Swift(iOS/macOS)中的PDF生成:UIGraphicsPDFRenderer、PDFKit 和 Core Graphics

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Swift(iOS/macOS)中的PDF生成:从简单到复杂



创建PDF文档是移动和桌面开发中的常见任务之一。在Apple平台(iOS/macOS)上,内置工具允许您无需第三方库即可生成高质量的PDF。在本文中,我们将介绍三种主要方法:UIGraphicsPDFRenderer(现代且简单)、PDFKit(用于处理现有PDF)和Core Graphics(用于完全控制)。所有示例均用Swift编写,适用于iOS和macOS(只需进行少量修改)。



1. UIGraphicsPDFRenderer — 现代标准



UIGraphicsPDFRenderer 在iOS 10和macOS 10.12中引入。它提供了一个用于创建多页PDF的高级API。主要优点包括:自动处理上下文、支持元数据以及易于使用。



基本示例:创建带文本的PDF



import UIKit

func generateSimplePDF() -> Data? { let pageWidth: CGFloat = 612 // A4 let pageHeight: CGFloat = 792 let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)) let data = renderer.pdfData { context in // 第一页 context.beginPage() let text = "你好,PDF世界!" let attributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 24), .foregroundColor: UIColor.black ] text.draw(at: CGPoint(x: 50, y: 50), withAttributes: attributes) // 第二页 context.beginPage() let secondText = "这是第二页" secondText.draw(at: CGPoint(x: 50, y: 50), withAttributes: attributes) } return data}

// 保存到文件if let pdfData = generateSimplePDF() { let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let pdfURL = documentsPath.appendingPathComponent("sample.pdf") try? pdfData.write(to: pdfURL) print("PDF已保存:\\(pdfURL)")}


高级示例:表格和图像



func generateInvoicePDF() -> Data {    let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 612, height: 792))        return renderer.pdfData { context in        context.beginPage()                // 绘制Logo(如果有)        if let logo = UIImage(named: "logo") {            logo.draw(in: CGRect(x: 50, y: 50, width: 100, height: 50))        }                // 标题        let titleAttributes: [NSAttributedString.Key: Any] = [            .font: UIFont.boldSystemFont(ofSize: 28),            .foregroundColor: UIColor.darkGray        ]        "发票号 #123".draw(at: CGPoint(x: 400, y: 50), withAttributes: titleAttributes)                // 表格        let items = [("商品", "价格"), ("笔记本电脑", "1200$"), ("鼠标", "25$")]        var yPosition: CGFloat = 200                for (name, price) in items {            let nameAttributes: [NSAttributedString.Key: Any] = [                .font: UIFont.systemFont(ofSize: 14),                .foregroundColor: UIColor.black            ]            name.draw(at: CGPoint(x: 100, y: yPosition), withAttributes: nameAttributes)            price.draw(at: CGPoint(x: 400, y: yPosition), withAttributes: nameAttributes)            yPosition += 30        }                // 总计        let totalAttributes: [NSAttributedString.Key: Any] = [            .font: UIFont.boldSystemFont(ofSize: 18),            .foregroundColor: UIColor.red        ]        "总计:1225$".draw(at: CGPoint(x: 350, y: yPosition + 20), withAttributes: totalAttributes)    }}


2. PDFKit — 处理现有PDF和注释



PDFKit 是一个更强大的框架,用

推荐