在iOS上将HTML转换为PDF? [英] HTML to PDF conversion on iOS?

查看:459
本文介绍了在iOS上将HTML转换为PDF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道要获取UIWebView的屏幕截图并将其转换为PDF,但是我需要生成适当的pdf(文本为文本而不是屏幕截图). Save2PDF是一个可以创建正确的PDF的应用程序.有谁知道如何做到这一点?

I am aware of taking the screenshot of UIWebView and converting it to PDF but I need to generate a proper pdf (text as text and not screenshot). Save2PDF is an application which creates proper PDF. Does anybody have an idea how do they do it?

推荐答案

我根据周围发现的每个好的建议创建了一个类.我一直在努力学习,希望我的课程对尝试直接从HTML源代码创建多页PDF的任何人提供一个良好的开端.

I created a class based on every good advice I found around. I've been digging a lot and I hope my class will offer some good start for anyone trying to create multi-page PDF directly out of some HTML source.

您将在这里找到带有一些基本示例代码的完整代码: https://github.com/iclems/iOS-htmltopdf

You'll find the whole code here with some basic sample code : https://github.com/iclems/iOS-htmltopdf

我遇到了与您相同的问题,我的要求是: -完整的PDF(纯文本,无位图) -智能多页(相比于每X像素剪切全高的Webview ...)

I had just the same issue as you and my requirements were: - full PDF (real text, no bitmap) - smart multi-pages (compared to cutting a full height webview every X pixels...)

因此,我使用的解决方案非常不错,因为它诉诸于iOS用于分割页面以进行打印的相同工具.

Thus, the solution I use is pretty nice as it resorts to the same tools iOS uses to split pages for print.

让我解释一下,我基于Web视图打印格式化程序设置了一个UIPrintPageRenderer(第一个技巧):

Let me explain, I setup a UIPrintPageRenderer based on the web view print formatter (first tip) :

UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];

[render addPrintFormatter:webView.viewPrintFormatter startingAtPageAtIndex:0];

CGRect printableRect = CGRectMake(self.pageMargins.left,
                              self.pageMargins.top,
                              self.pageSize.width - self.pageMargins.left - self.pageMargins.right,
                              self.pageSize.height - self.pageMargins.top - self.pageMargins.bottom);

CGRect paperRect = CGRectMake(0, 0, self.pageSize.width, self.pageSize.height);

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

NSData *pdfData = [render printToPDF];

[pdfData writeToFile: self.PDFpath  atomically: YES];

同时,我在UIPrintPageRenderer上创建了一个类别来支持:

In the meantime, I have created a category on UIPrintPageRenderer to support:

- (NSData*) printToPDF
{
    NSMutableData *pdfData = [NSMutableData data];

    UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, 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;
}

这篇关于在iOS上将HTML转换为PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆