iOS PDF 替换一页
2017-03-04 本文已影响306人
石显军
1、把PDF厡文件拆开
- (void)splitPdfDataAndWriteToFile
{
for (NSInteger i = 1; i <= maximumPage; i++) {
NSMutableData* outputPDFData = [[NSMutableData alloc] init];
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)outputPDFData);
CFMutableDictionaryRef attrDictionary = NULL;
attrDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(attrDictionary, kCGPDFContextTitle, CFSTR("My Doc"));
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, NULL, attrDictionary);
CFRelease(dataConsumer);
CFRelease(attrDictionary);
CGRect pageRect;
// Draw the old "pdfData" on pdfContext
CFDataRef myPDFData = (__bridge CFDataRef) [NSData dataWithContentsOfURL:document.fileURL];
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
CGDataProviderRelease(provider);
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, i);
pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CGContextBeginPage(pdfContext, &pageRect);
CGContextDrawPDFPage(pdfContext, page);
// release the allocated memory
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);
CGContextRelease(pdfContext);
// write new PDFData in "outPutPDF.pdf" file in document directory
NSString *pdfFilePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@/filePages/outPutPDF_%ld.pdf",kDataProcessingPdf, (long)i];
[outputPDFData writeToFile:pdfFilePath atomically:YES];
}
}
2、上一篇文章 iOS PDF 添加图片会生成一页新的PDF 根据要替换的页码覆盖对应的文件
3、把所有页码的PDF再拼接到一起 形成一个新的PDF文件
/**
整合 PDF 文件
@param listOfPaths listOfPaths 需要整和文件路径数组
@param pdfPathOutput 整合后的文件输出
@return 整合后的文件输出
*/
- (NSString *)joinPDF:(NSArray *)listOfPaths pdfPathOutput:(NSString *)pdfPathOutput{
CFURLRef pdfURLOutput = ( CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:pdfPathOutput]);
NSInteger numberOfPages = 0;
CGContextRef writeContext = CGPDFContextCreateWithURL(pdfURLOutput, NULL, NULL);
for (NSString *source in listOfPaths) {
CFURLRef pdfURL = ( CFURLRef)CFBridgingRetain([[NSURL alloc] initFileURLWithPath:source]);
CGPDFDocumentRef pdfRef = CGPDFDocumentCreateWithURL((CFURLRef) pdfURL);
numberOfPages = CGPDFDocumentGetNumberOfPages(pdfRef);
CGPDFPageRef page;
CGRect mediaBox;
for (int i=1; i<=numberOfPages; i++) {
page = CGPDFDocumentGetPage(pdfRef, i);
mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CGContextBeginPage(writeContext, &mediaBox);
CGContextDrawPDFPage(writeContext, page);
CGContextEndPage(writeContext);
}
CGPDFDocumentRelease(pdfRef);
CFRelease(pdfURL);
}
CFRelease(pdfURLOutput);
CGPDFContextClose(writeContext);
CGContextRelease(writeContext);
return pdfPathOutput;
}
完结
这总方式个人感觉比较笨拙 但是还没有找到更好的方法 (在免费的接口里面)
如果有人知道更便捷的方式 希望可以给我留言 我也研究一下
DEMO:下载地址