0

I am trying to draw an image over an existing PDF (displayed on the screen). The final goal would be to sign the pdf anywhere.

My sample code is here on Github

The code (basic) works like this :

  • The user clicks where he wants to draw the image
  • The PDF editing occurs and the final PDF appears on screen

However the problem is that my image appears upside down. While working with PDF, I learned that you have to flip context to render, it may be related.

- (void)editPDFWithName:(NSString*)pdfName
{
// grab reference to bundled PDF
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)[[NSBundle mainBundle] URLForResource:pdfName withExtension:@"pdf"]);

const size_t numberOfPages = CGPDFDocumentGetNumberOfPages(pdf);

// Begin PDF context
NSMutableData* data = [NSMutableData data];
UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);

// loop over PDF pages to render it
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);

    // Y axis is negative in order to render PDF (mandatory)
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -pageFrame.size.height);
    CGContextDrawPDFPage(ctx, pdfPage);
    CGContextRestoreGState(ctx);

    if(page == [self getCurrentPage])
    {
        // 0.75f factor to convert pixel/points
        CGContextDrawImage(ctx, CGRectMake(self.xTouchCoord*0.75f, self.yTouchCoord*0.75f, self.logo.size.width, self.logo.size.height), self.logo.CGImage);
    }

}
UIGraphicsEndPDFContext();

CGPDFDocumentRelease(pdf);
pdf = nil;

//  Save PDF
[self savePDF:data];

}

I tried multiple ways to flip image as suggested on this post

But the image is still flipped.

One thing I noticed is if I use the method drawAtPoint method on the image, it appears not flipped but does not appear at the specified position, like there is an offset (see other post here)

Can someone please suggest any idea ? I'm betting on the Save and Restore context methods but cannot get it working.

Community
  • 1
  • 1
H4Hugo
  • 2,570
  • 3
  • 16
  • 32

1 Answers1

0

Well I finally found the solution :

  • use drawInRectinstead of CGContextDrawImage
  • for better precision, don't forget to subtract half of the width and height to the coordinates to adjust the center :

        // 0.75f factor to convert pixel/points
        [self.logo drawInRect:CGRectMake(self.xTouchCoord*0.75f - self.logo.size.width/2, self.yTouchCoord*0.75f - self.logo.size.width/2, self.logo.size.width, self.logo.size.height)];
    
H4Hugo
  • 2,570
  • 3
  • 16
  • 32