上周公司交給我一個(gè)任務(wù) 在PDF文件中添加一張簽名圖片
發(fā)現(xiàn)中文搜索沒有我想要的結(jié)果 所以才發(fā)布一篇文章 方便其他人開發(fā)這個(gè)需求時(shí) 查詢資料
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];
}