0

因此,似乎几乎所有在 swift 应用程序中编写 PDF 内容的示例都是针对 ios 的。但我需要这个在macos下运行。例如,我不能使用任何 UI 功能,如 UIGraphicsRenderer 等。我试图拼凑一个测试应用程序,它的唯一功能是打印“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

}

更新:

这里有一个答案可以解决我的问题。感谢@Willeke 向我指出这一点。

[https://stackoverflow.com/questions/44640022/draw-on-a-pdf-using-swift-on-macos][1]

原来我之前看过它,但在实现它时出错了。再看一遍,我意识到我没有将 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  // for future use with custom pagination
    
    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

}
4

0 回答 0