如何在objective-c中编辑PDF?

Vya*_*hin 11 pdf objective-c

我正在使用objective-c(使用cocoa)编写应用程序.我有一个PDF模板,我需要将实际值替换为PDF中的占位符,然后将结果保存到新的PDF中.

我该怎么做?我应该使用哪个库?

Den*_*lov 25

我找到了解决方案!它连接了quartz2d的强大功能和UIGraphics的简单性.

NSString *newFilePath = @"path/to/your/newfile.pdf";
NSString *templatePath = @"path/to/your/template.pdf";

//create empty pdf file;
UIGraphicsBeginPDFContextToFile(newFilePath, CGRectMake(0, 0, 792, 612), nil);

CFURLRef url = CFURLCreateWithFileSystemPath (NULL, (CFStringRef)templatePath, kCFURLPOSIXPathStyle, 0);

//open template file
CGPDFDocumentRef templateDocument = CGPDFDocumentCreateWithURL(url);
CFRelease(url);

//get amount of pages in template
size_t count = CGPDFDocumentGetNumberOfPages(templateDocument);

//for each page in template
for (size_t pageNumber = 1; pageNumber <= count; pageNumber++) {
    //get bounds of template page
    CGPDFPageRef templatePage = CGPDFDocumentGetPage(templateDocument, pageNumber);
    CGRect templatePageBounds = CGPDFPageGetBoxRect(templatePage, kCGPDFCropBox);

    //create empty page with corresponding bounds in new document
    UIGraphicsBeginPDFPageWithInfo(templatePageBounds, nil);
    CGContextRef context = UIGraphicsGetCurrentContext();

    //flip context due to different origins
    CGContextTranslateCTM(context, 0.0, templatePageBounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    //copy content of template page on the corresponding page in new file
    CGContextDrawPDFPage(context, templatePage);

    //flip context back
    CGContextTranslateCTM(context, 0.0, templatePageBounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    /* Here you can do any drawings */
    [@"Test" drawAtPoint:CGPointMake(200, 300) withFont:[UIFont systemFontOfSize:20]];
}
CGPDFDocumentRelease(templateDocument);
UIGraphicsEndPDFContext();
Run Code Online (Sandbox Code Playgroud)

  • 我那么爱你 ! (3认同)

Ken*_*Ken 5

可能是PDFKit.对于某些任务,高级PDFKit API无法执行您想要的操作,您可能会被迫使用低级CG PDF解析库.不过他们的水平相当低.他们的意思是真正理解PDF文件格式.