Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to edit a PDF in objective-c?

i'm writing an application in objective-c (using cocoa). i have a PDF template, i need to substitute actual values into placeholders in PDF and then save the result into new PDF.

how can i do it? which library should i use?

like image 257
Vyacheslav Karpukhin Avatar asked Aug 26 '09 10:08

Vyacheslav Karpukhin


2 Answers

I've found the solution! It connects the power of quartz2d and simplicity of 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();
like image 108
Denis Mikhaylov Avatar answered Oct 03 '22 21:10

Denis Mikhaylov


Probably PDFKit. For some tasks, the high level PDFKit API cannot do what you want, and you might be forced to use the low level CG PDF parsing libraries. They're quite low level, though. They mean really understanding the PDF file format.

like image 37
Ken Avatar answered Oct 03 '22 21:10

Ken