You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

macOS下Swift生成Hello World PDF出现空白页的解决方法

macOS端Swift使用PDFKit生成PDF无内容问题解决

问题描述

目前公开的Swift编写PDF内容的示例几乎都针对iOS平台,要实现macOS端的PDF生成功能时,无法使用UIGraphicsRenderer等iOS专属UI接口。
最初编写的仅输出「Hello World」文本的测试程序,生成的PDF可以正常创建保存,但没有任何内容,错误代码如下:

import Foundation
import PDFKit

func printPDF() {
    
    let localURL = FileManager.default.currentDirectoryPath
    let url = URL(fileURLWithPath: localURL).appendingPathComponent("tv-schedule-for-today.pdf")
 
    var pdfDoc: PDFDocument? = PDFDocument()
    
    let page: PDFPage? = PDFPage()
    var mediaBox: CGRect = page!.bounds(for: .mediaBox)
    
    guard let currentContext = CGContext(url as CFURL, mediaBox: &mediaBox, nil) else {
        return
    }
    var context: CGContext? = currentContext

    context!.beginPDFPage(nil)

    let attributes = [
          NSAttributedString.Key.font: NSFont.boldSystemFont(ofSize: 72)
        ]
    let text = "Hello World!"
    text.draw(at: CGPoint(x: 200, y: 300), withAttributes: attributes)

    context!.endPDFPage()

    pdfDoc!.insert(page!, at: 0)
        
    context!.closePDF()

    pdfDoc!.write(to: url as URL)
    
    context = nil

}

问题原因

实现时存在两处遗漏:

  • 没有将CGContext与NSGraphicsContext关联
  • 没有调用page.draw启动渲染

修复后可正常运行的代码

import Foundation
import PDFKit

func printPDF() {
    
    let localURL = FileManager.default.currentDirectoryPath
    let url = URL(fileURLWithPath: localURL).appendingPathComponent("tv-schedule-for-today.pdf")
 
    let pdfDoc: PDFDocument? = PDFDocument(url: url)
    //var pageCount = 0  // 后续自定义分页使用
    
    let page: PDFPage? = pdfDoc!.page(at: 0)!
    
    var mediaBox: CGRect = page!.bounds(for: .mediaBox)
    
    guard let currentContext = CGContext(url as CFURL, mediaBox: &mediaBox, nil) else {
        return
    }
    var context: CGContext? = currentContext
    
    let nscontext = NSGraphicsContext(cgContext: context!, flipped: false)
    NSGraphicsContext.current = nscontext

    context!.beginPDFPage(nil)
    
    do {
        page!.draw(with: .mediaBox, to: context!)

        let attributes = [
              NSAttributedString.Key.font: NSFont.boldSystemFont(ofSize: 36)
            ]
        let text = "I'm a simpler PDF!"
        text.draw(at: CGPoint(x: 100, y: 100), withAttributes: attributes)
    
    }

    context!.endPDFPage()

    NSGraphicsContext.current = nil

    context!.closePDF()
    
    context = nil

}

内容的提问来源于stack exchange,提问作者Joe Bell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 11:24:09