ios - UIWebView 到 PDF 的 Objective-C 问题

标签 ios objective-c pdf uiwebview

我这里有这种方法,可以将我的 UIWebView 转换为 PDF,并且运行良好。但是当我打印此 PDF 或通过电子邮件发送它时,它被切断了。它就像它只生成我设置的 UIWebView 的大小(宽度:688 和高度:577)如果我将 UIWebView 的大小增加到可以说 900 或 1024,我的 PDF 是空的。我的 UIWebView 大于 577,但在我的应用中,我可以滚动。

这是方法....

-(void)webViewDidFinishLoad:(UIWebView *)webViewPDF
{
    CGRect origframe = webViewPDF.frame;
    NSString *heightStr = [webViewPDF stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"]; // Get the height of our webView
    int height = [heightStr intValue];

    CGFloat maxHeight   = kDefaultPageHeight - 2*kMargin;
    int pages = floor(height / maxHeight);

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];

    self.pdfPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"Purchase Order.pdf"]];

    UIGraphicsBeginPDFContextToFile(self.pdfPath, CGRectZero, nil);

    for (int i = 0; i < pages; i++)
    {
        if (maxHeight * (i+1) > height) {
            CGRect f = [webViewPDF frame];
            f.size.height -= (((i+1) * maxHeight) - height);
            [webViewPDF setFrame: f];
        }

        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
        CGContextRef currentContext = UIGraphicsGetCurrentContext();

        CGContextTranslateCTM(currentContext, kMargin, kMargin);

        [webViewPDF.layer renderInContext:currentContext];
    }

    UIGraphicsEndPDFContext();

    [webViewPDF setFrame:origframe];
    [[[webViewPDF subviews] lastObject] setContentOffset:CGPointMake(0, 0) animated:NO];
}

我希望这是有道理的....有没有人对如何解决这个问题有任何建议,这样 PDF 就不会被截断?

我忘了提到这些变量:

#define kDefaultPageHeight 850
#define kDefaultPageWidth  850
#define kMargin 50

这是我的分享按钮:

- (IBAction)Share:(id)sender {

    NSData *pdfData = [NSData dataWithContentsOfFile:self.pdfPath];

    UIActivityViewController * activityController = [[UIActivityViewController alloc] initWithActivityItems:@[pdfData] applicationActivities:nil];

    UIPopoverController *popup = [[UIPopoverController alloc] initWithContentViewController:activityController];

    [popup presentPopoverFromRect:CGRectMake(self.view.frame.size.width - 36, 60, 0, 0)inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];

}

最佳答案

我过去使用 UIPrintPageRenderer 完成过此操作。这是一种从 UIWebView 创建 PDF 的更通用的方法,到目前为止它对我来说效果很好。我已经用 Xcode 6 和 iOS 8.2 测试了这个解决方案。此外,尝试打印生成的 PDF,一切都打印出来了。

当我阅读 OP 时,我对各种页面大小进行了一些测试,以查看是否可以获得空白 PDF。我确定了一些关键项目,它们可能有助于生成空白 PDF 文件。我已在代码中识别出它们。

调用 webViewDidFinishLoad() 时, View 可能未 100% 加载。有必要进行检查,以查看 View 是否仍在加载。这很重要,因为它可能是您问题的根源。如果不是,那么我们就可以开始了。这里有一个非常重要的注意事项。一些网页是动态加载的(在页面本身中定义)。以 youtube.com 为例。该页面几乎立即显示,并带有“正在加载”屏幕。这将欺骗我们的 web View ,并且它的“isLoading”属性将设置为“false”,而网页仍在动态加载内容。不过这种情况很少见,而且在一般情况下,此解决方案会运行良好。如果您需要从这样的动态加载网页生成 PDF 文件,您可能需要将实际生成移动到不同的位置。即使使用动态加载网页,您最终也会得到一个显示加载屏幕的 PDF,而不是一个空的 PDF 文件。

另一个关键方面是设置 printableRect 和 pageRect。请注意,这些是单独设置的。如果 printableRect 小于 paperRect,您最终会在内容周围添加一些填充 - 例如,请参见代码。这是一个link到 Apple 的 API 文档,其中包含对两者的一些简短描述。

下面的示例代码将一个类别添加到 UIPrintPageRenderer 以创建实际的 PDF 数据。这个示例中的代码是过去使用各种在线资源组合在一起的,我无法找到使用了哪些资源来正确地归功于它们。

@interface UIPrintPageRenderer (PDF)
- (NSData*) createPDF;
@end

@implementation UIPrintPageRenderer (PDF)
- (NSData*) createPDF
{
    NSMutableData *pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData( pdfData, self.paperRect, nil );
    [self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)];
    CGRect bounds = UIGraphicsGetPDFContextBounds();
    for ( int i = 0 ; i < self.numberOfPages ; i++ )
    {
        UIGraphicsBeginPDFPage();
        [self drawPageAtIndex: i inRect: bounds];
    }
    UIGraphicsEndPDFContext();
    return pdfData;
}
@end

这是我在 webViewDidFinishLoad() 中的内容

- (void)webViewDidFinishLoad:(UIWebView *)webViewIn {
    NSLog(@"web view did finish loading");

    // webViewDidFinishLoad() could get called multiple times before
    // the page is 100% loaded. That's why we check if the page is still loading
    if (webViewIn.isLoading)
        return;

    UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
    [render addPrintFormatter:webViewIn.viewPrintFormatter startingAtPageAtIndex:0];

    // Padding is desirable, but optional
    float padding = 10.0f;

    // Define the printableRect and paperRect
    // If the printableRect defines the printable area of the page
    CGRect paperRect = CGRectMake(0, 0, PDFSize.width, PDFSize.height);
    CGRect printableRect = CGRectMake(padding, padding, PDFSize.width-(padding * 2), PDFSize.height-(padding * 2));

    [render setValue:[NSValue valueWithCGRect:paperRect] forKey:@"paperRect"];
    [render setValue:[NSValue valueWithCGRect:printableRect] forKey:@"printableRect"];

    // Call the printToPDF helper method that will do the actual PDF creation using values set above
    NSData *pdfData = [render createPDF];

    // Save the PDF to a file, if creating one is successful
    if (pdfData) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [paths objectAtIndex:0];

        NSString *pdfPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"Purchase Order.pdf"]];

        [pdfData writeToFile:pdfPath atomically:YES];
    }
    else
    {
        NSLog(@"error creating PDF");
    }
}

PDFSize 被定义为一个常量,设置为标准的 A4 页面大小。可以对其进行编辑以满足您的需要。

#define PDFSize CGSizeMake(595.2,841.8)

关于ios - UIWebView 到 PDF 的 Objective-C 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30201970/

相关文章:

objective-c - 为什么我的 xmlTextReaderConstValue 会发生内存泄漏?

java - 如何使用 APV PDF 查看器

python-3.x - 如何在JupyterLab中解决 'nbconvert failed: Inkscape svg to pdf conversion failed`

pdf - 如何从 Qt 应用程序创建 pdf 文件?

ios - 计算 Twitter 字符数

ios - 如何将 CLCircularRegion 保存到 NSUserDefaults

objective-c - 无法访问 Pod 内的 Pod lib 依赖项,只能在客户端 App 内访问

ios - 仅获取下一次 iOS 本地通知的时间

ios - UIButton Action 不在 Swift 中调用?

ios - UIPageViewController 中的奇怪约束行为