Swift - 在当前PDF文档上叠加文本

时间:2018-01-30 04:02:12

标签: swift macos pdf

我一直试图简单地将文本叠加到当前基本上是时间卡的PDF文档上。我将文件复制到downloads文件夹,工作正常,但是当我尝试使用CGContext添加文本时,它会导出一个白色的PDF文档。谁能看到我出错的地方?

do {
        try fileManager.copyItem(at: pdfURL!, to: destinationURL)
    } catch let error as NSError {
        print("Copy failed :( with error: \(error)")

    }


    if let pdf: CGPDFDocument = CGPDFDocument(destinationURL as CFURL) { // Create a PDF Document


        if pdf.numberOfPages == 1 {

            let pdfPage: CGPDFPage = pdf.page(at: 1)!

            let pageRect = pdfPage.getBoxRect(CGPDFBox.mediaBox)
            //print(pageRect)

            let context = CGContext.init(destinationURL as CFURL, mediaBox: nil, nil)

            let font = NSFont(name: "Helvetica Bold", size: 20.0)

            let textRect = CGRect(x: 250, y: 250, width: 500, height: 40)

            let paragraphStyle: NSParagraphStyle = NSParagraphStyle.default

            let textColor = NSColor.black

            let textFontAttributes = [
                NSAttributedStringKey.font: font!,
                NSAttributedStringKey.foregroundColor: textColor,
                NSAttributedStringKey.paragraphStyle: paragraphStyle
            ]

            let text: NSString = "Hello world"

            text.draw(in: textRect, withAttributes: textFontAttributes)

            context?.addRect(textRect)

            context?.closePDF()

        }




}

1 个答案:

答案 0 :(得分:0)

以下代码是我用来在macOS上覆盖文本的代码。我一直试图找到我从中得到的答案的链接。如果找到它,我将使用链接编辑该答案。

// Confirm there is a document there
if let doc: PDFDocument = PDFDocument(url: srcURL) {
    
    // Create a document, get the first page, and set the size of the page
    let page: PDFPage = doc.page(at: 0)!
    var mediaBox: CGRect = CGRect(x: 0, y: 0, width: 792, height: 612)
    
    // This is where the magic happens.  Create the drawing context on the PDF
    let context = CGContext(dstURL as CFURL, mediaBox: &mediaBox, nil)
    let graphicsContext = NSGraphicsContext(cgContext: context!, flipped: false)
    NSGraphicsContext.current = graphicsContext
    
    context!.beginPDFPage(nil)
    
    // Draws the PDF into the context
    page.draw(with: .mediaBox, to: context!)
    
    // Parse and Draw Text on the context
    drawText()
    
    context!.saveGState()
    
    context!.restoreGState()
    
    context!.endPDFPage()
    NSGraphicsContext.current = nil
    context?.closePDF()
}