iOS PDF 添加圖片

上周公司交給我一個任務 在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];

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容