Last Updated: July 25, 2019
·
11.64K
· jfsagasti

How to save a pdf file with its annotations in Objective-C

Here is the way I saved a pdf with all the drawings or annotations made on a UIView layer. I show this UIView layer on top of the pdf reader view, so it lets the user to draw things on it. This code is about how to save both layers (pdf and annotations) in a new pdf file.

NSError *error;
//Load original pdf data:
NSData *pdfData = [NSData dataWithContentsOfFile:OriginalPdfPath    options:NSDataReadingUncached error:&error];

if (error) 
{
    NSLog(@"%@", [error localizedDescription]);
    return;
} 
else 
    NSLog(@"Data has loaded successfully.");

//If fails to create the new file, returns
if (![[NSFileManager defaultManager] createFileAtPath:NewPdfPath contents:pdfData attributes:nil])
{
    return;
}

NSURL *url = [NSURL fileURLWithPath:OriginalPdfPath];
CGPDFDocumentRef document = CGPDFDocumentCreateWithURL ((__bridge_retained CFURLRef) url);
size_t count = CGPDFDocumentGetNumberOfPages(document);

if (count == 0)
{
    NSLog(@"PDF needs at least one page");
    return;
}

CGRect paperSize = CGRectMake(0, 0, 1190, 842);

 UIGraphicsBeginPDFContextToFile(NewPdfPath , paperSize, nil);
// CGPDFPageRef page = CGPDFDocumentGetPage(document, 1); 
 UIGraphicsBeginPDFPageWithInfo(paperSize, nil);
 CGContextRef currentContext = UIGraphicsGetCurrentContext();

// flip context so page is right way (landscape app)
CGContextScaleCTM(currentContext, 1, -1);
// Rotate the coordinate system (rotation = M_PI or -M_PI for landscape)
CGContextRotateCTM(currentContext, rotation/ 2);

CGPDFPageRef page = CGPDFDocumentGetPage (document, 1); // grab page 1 of the PDF 
CGContextDrawPDFPage (currentContext, page); // draw page 1 into graphics context

 //flip context so annotations are right way
CGContextScaleCTM(currentContext, 1, -1);
CGContextRotateCTM(currentContext, rotation / 2);
//Render the layer of the annotations view in the context
[drawingView.layer renderInContext:currentContext];
UIGraphicsEndPDFContext();
CGPDFDocumentRelease (document);

3 Responses
Add your response

Thank you for the utility function.
But can you tell where are you exactly saving the layer that you draw back to pdf? Is it just displayed on the context or being drawn on the pdf an saved in File Manager?

Thank you for clarifying!!

over 1 year ago ·

Draw the original pdf page in a graphic context and then draw the drawings layer in the same context ([drawingView.layer renderInContext:currentContext]). Then you can save the context as a new pdf document and you are done :)

over 1 year ago ·

Yes it worked , great renderInContext works like magic, perhaps I gave a call to drawAnnots before as to draw in that view context before rendering it on pdf context. If there some other it would be great to hear from you!!

over 1 year ago ·