使用Swift生成PDF [英] Generate PDF with Swift

查看:281
本文介绍了使用Swift生成PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Swift中的UITableView创建一个PDF。我发现了Objective C的一些教程,并尝试了它,但是这个代码仍然没有生成文件。

I would like to create a PDF from a UITableView in Swift. Ill found some tutorials for Objective C, and tried it out but there is still no file generated by this code.

        // get a temprorary filename for this PDF

        var path = NSTemporaryDirectory();
        var pdfFilePath = path.stringByAppendingPathComponent("mypdfdocument.pdf")

        UIGraphicsBeginPDFContextToFile(pdfFilePath, CGRectMake(0, 0, self.tableView.contentSize.width, self.tableView.contentSize.height), nil)
        UIGraphicsBeginPDFPage();
        self.view.layer.renderInContext(UIGraphicsGetCurrentContext())
        self.tableView.scrollRectToVisible(CGRectMake(0, 0, 1, 1), animated: false)
        self.tableView.layer.renderInContext(UIGraphicsGetCurrentContext())

        var screensInTable = Int(self.tableView.contentSize.width) / Int(self.tableView.contentSize.height)

        for i in 1...screensInTable {

            var point = CGFloat(CGFloat(i) * self.tableView.bounds.height)
            var contentOffset:CGPoint = CGPointMake(0, point)
            self.tableView.setContentOffset(contentOffset, animated: false)
            self.tableView.layer.renderInContext(UIGraphicsGetCurrentContext())
        }

        UIGraphicsEndPDFContext();

并且:我有一个包含4个部分的表和不同的行高和单元格模板。是否有机会使用此类代码轻松生成PDF?或者用CoreText创建Row by Row会更好吗?

And: I have a Table with 4 Sections and different Row Heights and Cell Templates. Is there a Chance that the generated PDF easily with this type of code? Or would it be better to create Row by Row with CoreText?

提前致谢。

推荐答案

这是我的方法。使用模板视图。它具有所有静态文本和图像。然后对于pdf中的每个页面使用此模板视图。这是我使用的函数:

Here is my approach. Use a template view. It has all the static texts and images. And then for every page in pdf use this template view. Here is the function that I use:

func renderAsPDF(demandEntry: ParsedDemandEntry, inView view: UIView) -> NSData? {
    let entries = demandEntry.demands
    let pageCount = Int(ceil(Double(entries.count) / Double(demandCountForPage)))
    if pageCount != 0 {
        let views = (1...pageCount).map { (pageNumber: Int) -> UIView in
            let pdfPageView = createTemplatePageViewWithParsedEntry(demandEntry, inView: view)

            let pageRange = ((pageNumber - 1) * demandCountForPage)..<(min(pageNumber * demandCountForPage, entries.count))
            let entriesForPage = Array(entries[pageRange])

            addEntries(entriesForPage, toView: pdfPageView)

            pdfPageView.removeFromSuperview()

            return pdfPageView
        }

        return toPDF(views)
    } else {
        return nil
    }
}

ParsedDemandEntry 是我的模型对象。 视图参数是一个容器视图,用于在其中准备pdf视图。这是必要的,因为我使用自动布局来定位pdf视图中的所有标签。没有超级视图布局过程将无法正常工作。

The ParsedDemandEntry is my model object. The view parameter is a container view to prepare pdf view in it. This is necessary because I use auto layout to position all labels in pdf view. Without a super view layout process won't work.

让我们进入功能。首先,我从模型对象中获取条目。认为这些是需要以pdf填充的行。之后我计算了我需要的页数。然后循环开始。在每个循环中,我创建一个tamplate视图。 ( pdfPageView )。然后填入条目。 ( addEntries(_:toView :) 函数调用)。

Let's walk into function. First I get entries from model object. Think these are rows that needs to populate in pdf. After that I calculate how many pages I need. Then the loop begins. In every loop I create a tamplate view. (pdfPageView). And then fill it with entries. (addEntries(_:toView:) function call).

循环后我将所有视图都提供给 toPDF 功能。它创建表示pdf的 NSData 。以下是 toPDF 函数的样子:

After the loop I give all views to toPDF function. It creates NSData that represents pdf. Here is how toPDF function look like:

private func toPDF(views: [UIView]) -> NSData? {

    if views.isEmpty {
        return nil
    }

    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, CGRect(x: 0, y: 0, width: 612, height: 792), nil)

    let context = UIGraphicsGetCurrentContext()

    for view in views {
        UIGraphicsBeginPDFPage()
        view.layer.renderInContext(context)
    }

    UIGraphicsEndPDFContext()

    return pdfData
}

这很简单。首先我创建pdf上下文。然后循环遍历 views 数组。对于每个视图它将视图呈现为pdf上下文。

It is fairly simple. First I create pdf context. And then loop through views array. For each view It renders view into pdf context.

我希望这会有所帮助。

这篇关于使用Swift生成PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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