iOS PDF 添加图片

作者: 石显军 | 来源:发表于2016-08-16 17:32 被阅读1353次

上周公司交给我一个任务 在PDF文件中添加一张签名图片

发现中文搜索没有我想要的结果 所以才发布一篇文章 方便其他人开发这个需求时 查询资料

PDF文件添加图片代码:

-(void)addSignature:(UIImage *)imgSignature onPDFData:(NSData *)pdfData {

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) pdfData;

CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);

CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);

CGDataProviderRelease(provider);

CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1);

pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);

CGContextBeginPage(pdfContext, &pageRect);

CGContextDrawPDFPage(pdfContext, page);

// Draw the signature on pdfContext

pageRect = CGRectMake(0, 0,imgSignature.size.width , imgSignature.size.height);

CGImageRef pageImage = [imgSignature CGImage];

CGContextDrawImage(pdfContext, pageRect, pageImage);

// release the allocated memory

CGPDFContextEndPage(pdfContext);

CGPDFContextClose(pdfContext);

CGContextRelease(pdfContext);

// write new PDFData in "outPutPDF.pdf" file in document directory

NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *pdfFilePath =[NSString stringWithFormat:@"%@/outPutPDF.pdf",docsDirectory];

[outputPDFData writeToFile:pdfFilePath atomically:YES];

}

相关文章

网友评论

  • _小单:你好,请问可以在PDF某一页中添加一个图片水印么?
    石显军:另一篇文章里有demo 你看一下
  • 雨影:测试了一下.这种方式如果pdf存在电子签章的话,签章信息会被丢掉,不知道楼主有更好的pdf追加图片方式么?
  • ShineLing:您好, 求分享一份这个向PDF文件中添加图片的demo, 可以吗? 987410331@qq.com
    ShineLing:@石显军 非常感谢:heart:
    石显军:https://github.com/ShiXianjun-2016/PDFTest 这个是demo下载地址
    PDF 拆分 合并 添加图片 demo中都有
  • ea105108a443:我现在用mupdf在做在pdf文件中插入图片标签,请问你做过么,一直没有找到方法
    _小单:你好, 请问你实现了么?我想在PDF某一页中添加一个图片水印。
    石显军:MuPDF 没有用过 插入图片标签是什么意思 就是在PDF文件某一页的指定位置贴一张图片么
  • 雨影:请教一下,我想做 pdf 涂鸦,要保存到原文件当中.请问,怎么ios 中修改 pdf 文件呢?
    石显军:@雨影 有一些 不过好像只是基本的操作 之前查的Adobe公开的接口 只有基本操作的免费的 复杂操作都是收费的
    雨影:@石显军 ios 库中没有编辑修改 pdf 的接口么?我问了安卓那边好像是有增量更新的库的.
    石显军:我之前也没时间找到太好的方法 就是把PDF拆开 替换其中编辑的那一页 再整合到一起 PDF文件比较大的话 处理的时间也比较长

本文标题:iOS PDF 添加图片

本文链接:https://www.haomeiwen.com/subject/zjbpsttx.html