问题
I'm struggling with PDF editing so I'm starting with naive code trying to achieve the following :
- Display a PDF bundled with app
- Click on screen where I want to add my image (Signature for example)
- Reload the webview with the edited PDF
Here is my code on github : https://github.com/HRiffiod/PDFSignature.git
The problem is that my image does not display at the right position in the edited PDF. It is not random, but the farther I get from the (0,0) coordinates, the bigger the deviation, that's why I'm betting on a wrong scaling factor.
For example, this is what I get if I tap the first word and then click "Sign !" :
So this is pretty accurate. however, this is what happens if I click the last word from this PDF page (and I mean page, not this paragraph) :
That is not okay at all.
Any suggestion ? Thank you in advance
EDIT
Here is a piece of code (that you can find on github) where the context rendering kicks in and might be the place I am doing it wrong :
// 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);
// Get appropriate scale
//CGFloat scale = [[UIScreen mainScreen] scale];
// As suggested in SO, the (1, -1) scale might need to be changed but couldn't get it right. 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 == 1)
{
[self drawLogo];
}
}
UIGraphicsEndPDFContext();
回答1:
It looks like you are not using the appropriate scale for retina devices.
ViewController.m
CGContextScaleCTM(ctx, 1, -1);
This should be based off the device's scale.
e.g. (Assuming the y scale value needs to be negative for some reason)
CGFloat scale = [[UIScreen mainScreen] scale];
CGContextScaleCTM(ctx, scale, -scale);
来源:https://stackoverflow.com/questions/35019051/inappropriate-scaling-factor-when-editing-pdf-and-displaying-image-in-uiwebview