Search code examples
objective-cannotationspdf-generationcore-graphicsquartz-2d

Get graphics context after saving in PDF - Objective C


How to get the core graphics context from PDF after saving? For example I am creating a rectangle inside PDF pages, I need to edit, update or delete that rectangle inside PDF pages after saving it.

Here is the code I used to save rectangle inside PDF pages in objective c.

CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)[[NSBundle mainBundle] URLForResource:@"tutorial" withExtension:@"pdf"]);

const size_t numberOfPages = CGPDFDocumentGetNumberOfPages(pdf);

NSMutableData* data = [NSMutableData data];
UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);

for(size_t page = 1; page <= numberOfPages; page++)
{
    //  Get the current page and page frame
    CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf, page);
    const CGRect pageFrame = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);

    UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);

    //  Draw the page (flipped)
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -pageFrame.size.height);
    CGContextDrawPDFPage(ctx, pdfPage);
    CGContextRestoreGState(ctx);

    //  Draw a red box
    [[UIColor redColor] set];
    UIRectFill(CGRectMake(20, 20, 100, 100));
}

UIGraphicsEndPDFContext();

CGPDFDocumentRelease(pdf);
pdf = nil;

Now I need to edit or delete the rectangle created above. Please advice !!!


Solution

  • It is not possible to remove content from the PDF file using the CoreGraphics API.
    You need to redesign your code to draw or not the rectangle in the PDF file based on some condition.