在Swift中从UIScrollView创建PDF文件

问题描述:

我想根据UIScrollView的内容创建PDF文件.

I want to create a PDF file from the contents of a UIScrollView.

func createPdfFromView(aView: UIView, saveToDocumentsWithFileName fileName: String) {
    let pdfData = NSMutableData()
    let height = 1754.0
    let width = 1240.0
    UIGraphicsBeginPDFContextToData(pdfData, CGRect(x:-30, y:15,width:width,height:height) , nil)
    UIGraphicsBeginPDFPage()
    guard let pdfContext = UIGraphicsGetCurrentContext() else { return }

    aView.layer.render(in: pdfContext)
    UIGraphicsEndPDFContext()

    if let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
        let documentsFileName = documentDirectories + "/" + fileName
        debugPrint(documentsFileName)
        pdfData.write(toFile: documentsFileName, atomically: true)
    }
}

我希望代码会生成一个基于滚动视图中内容大小的PDF.

I would expect that the code generates a PDF oriented on the size of the content in the scrollview.

该代码当前仅生成静态PDF.如果滚动视图中的内容大于PDF页面,则该内容将被剪切.

The code currently only generates a static PDF. If the content in the scrollview is bigger than the PDF page, the content is cut off.

我可以使用此Cocoapods框架实现此目的.就我而言,我想从Spreadsheet制作一个PDF,以便该框架帮助我添加具有不同列大小的表以及我希望从数据中获取的更多功能.

I could achieve this using this Cocoapods framework. In my case I wanted to make a PDF from Spreadsheet , so that this framework help me to add table with different column size and many more features which I had wanted from my data.

https://cocoapods.org/pods/SimplePDF