首页 > 解决方案 > 将 UITableView 的 PDF 创建到 AirPrint Xcode 和 Swift

问题描述

寻找一种解决方案,以编程方式使用我的 UITabelView 的内容创建 pdf,顶部带有标签,并允许用户在标准 A4 纸上打印。

这是我不工作的代码:

        func createPdfFromView(aView: UIView, saveToDocumentsWithFileName fileName: String) {
     let pdfTitle = "\(pilotName)'s Past Duty"
    let pageSize = CGRect(x: 0, y: 0, width: 11 * 70, height: 8.5 * 70)
    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, pageSize, nil)
    UIGraphicsBeginPDFPage()
        let font = UIFont.preferredFont(forTextStyle: .largeTitle)
        let attributedPDFTitle = NSAttributedString(string: pdfTitle, attributes: [NSAttributedString.Key.font: font])
        let stringSize = attributedPDFTitle.size()
        let stringRect = CGRect(x: (pageSize.width / 2 - stringSize.width / 2), y: 20, width: stringSize.width, height: stringSize.height)
        attributedPDFTitle.draw(in: stringRect)
    aView.layer.render(in: UIGraphicsGetCurrentContext()!)
        UIGraphicsGetCurrentContext()!.translateBy(x: 0, y: 40)
    UIGraphicsEndPDFContext()

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

标签: swiftxcodeuitableviewpdfkitairprint

解决方案


推荐阅读