在Swift中生成PDF报告:iOS/macOS的库与框架

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

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

开始课程

在Swift中生成PDF报告 (iOS/macOS)



在Apple平台上创建PDF文档是开发商业应用、财务报告或文档管理系统时的关键任务之一。与使用众多第三方库的Web技术栈不同,在Swift生态系统中,既有强大的内置框架,也有专门的第三方解决方案用于处理PDF。本文将详细解析在Swift中为iOS和macOS生成PDF报告的所有主要工具。



Apple内置框架



Apple提供了两种创建PDF文档的主要方式:UIGraphicsPDFRenderer(用于UIKit)和PDFKit(用于处理现有PDF)。此外,macOS还提供了支持PDF的NSGraphicsContext。



UIGraphicsPDFRenderer (iOS 10+)



这是从UIKit内容生成PDF的主要工具。它允许在PDF页面的上下文中绘制文本、图像、表格和任意图形。



import UIKit

func generateReport(data: String) -> Data { let pageSize = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4 let renderer = UIGraphicsPDFRenderer(bounds: pageSize) return renderer.pdfData { context in context.beginPage() // 标题 let title = "销售报告" let attributes: [NSAttributedString.Key: Any] = [ .font: UIFont.boldSystemFont(ofSize: 24), .foregroundColor: UIColor.darkGray ] title.draw(at: CGPoint(x: 50, y: 50), withAttributes: attributes) // 内容 let textAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 14) ] data.draw(at: CGPoint(x: 50, y: 100), withAttributes: textAttributes) // 分隔线 context.cgContext.setStrokeColor(UIColor.lightGray.cgColor) context.cgContext.setLineWidth(1) context.cgContext.move(to: CGPoint(x: 50, y: 90)) context.cgContext.addLine(to: CGPoint(x: 545, y: 90)) context.cgContext.strokePath() }}


PDFKit (iOS 11+, macOS 10.13+)



PDFKit是一个更高级的框架,不仅允许创建PDF,还可以编辑现有的PDF。它支持注释、表单、书签以及多页文档的处理。



import PDFKit

func createPDFWithText() -> PDFDocument { let page = PDFPage() let pdfDocument = PDFDocument() // 创建带文本的页面 let text = "PDFKit可以轻松添加文本和注释" let textAnnotation = PDFAnnotation( bounds: CGRect(x: 50, y: 700, width: 500, height: 100), forType: .freeText, withProperties: nil ) textAnnotation.contents = text textAnnotation.font = UIFont.systemFont(ofSize: 18) page.addAnnotation(textAnnotation) pdfDocument.insert(page, at: 0) return pdfDocument}


Swift的第三方库



尽管内置工具涵盖了大多数需求,但在某些情况下需要专门的功能:处理模板、从SwiftUI导出PDF或支持复杂排版。



SwiftUI 和 PDF (iOS 14+, macOS 11+)



从iOS 14开始,可以使用ImageRenderer将SwiftUI视图转换为PDF:



import SwiftUI

struct ReportView: View { var body: some View { VStack(alignment: .leading) { Text("月度报告") .font(.largeTitle) .foregroundColor(.blue) Text("2024年8月数据") .font(.headline) Divider() Text("收入:1,234,567 ₽") .font(.body) } .padding() }}

func generatePDFFromSwiftUI() -> Data { let vie

推荐