Inappropriate scaling factor when editing PDF and displaying image in UIWebView

こ雲淡風輕ζ 提交于 2019-12-12 05:19:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!