将文本绘制到CGContext的Quartz PDF不起作用

问题描述

这是针对macOS上的Swift 5

我正在尝试将一些文本写入生成的PDF。

我能够将背景图像加载到页面上,但是当我调用drawText方法时,它并没有将其加载到任何页面上。

我尝试通过.draw()方法将Nsstring绘制到上下文,这也不起作用。我希望此功能可以正常工作,以便添加更多文本,包括文本框等。

我在做什么错?感谢您的指导。

import Cocoa
import CoreText
import Quartz

extension NSImage {
    /*
        Converts an NSImage to a CGImage for rendering in a CGContext
        Credit - Xue Yu
        - https://gist.github.com/KrisYu/83d7d97cae35a0b10fd238e5c86d288f
     */
    var tocgImage: CGImage {
        var imageRect = NSRect(x: 0,y: 0,width: pageWidth,height: pageHeight)
        guard let image =  cgImage(forProposedRect: &imageRect,context: nil,hints: nil) else {
            abort()
        }
        return image
    }
}

class PDFText {

    /*
     Create a non-nil CGContext
     Credit - hmali - 3/15/2019
        https://stackoverflow.com/questions/41100895/empty-cgcontext
     */
    var pdfContext = CGContext(data: nil,width: 0,height: 0,bitsPerComponent: 1,bytesPerRow: 1,space: CGColorSpace.init(name: CGColorSpace.sRGB)!,bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)

    let textRect = CGRect(x: 295,y: 350,width: 100,height: 100)
    
    func createPDF() {
        let filePath = "/Users/Shared/Text.pdf"
        let fileURL = NSURL(fileURLWithPath: filePath)
        pdfContext = CGContext(fileURL,mediaBox: &backgroundRect,nil)
        pdfContext!.beginpdfpage(nil)
        drawBackground()
        drawText("This is page 1")
        pdfContext!.endpdfpage()
        pdfContext!.beginpdfpage(nil)
        drawBackground()
        drawText("This is page 1")
        pdfContext!.endpdfpage()
        pdfContext!.closePDF()
    }
    
    func drawBackground() {
        
        let cgImage = NSImage(contentsOfFile: "/Users/Shared/background.png")?.tocgImage
        pdfContext?.draw(cgImage!,in: CGRect(x: 0,width: Int(72*8.5),height: Int(72*11)))
    }
    
    func drawText(_ text:String) {
    
        let style = NSMutableParagraphStyle()
        style.alignment = .center
        let attr = [NSAttributedString.Key.font: NSFont(name: "Helvetica",size: 16.0),NSAttributedString.Key.foregroundColor: NSColor.purple,NSAttributedString.Key.backgroundColor: NSColor.clear,NSAttributedString.Key.paragraphStyle: style]
        let attrText = NSAttributedString(string: text,attributes: attr as [NSAttributedString.Key : Any])
        pdfContext?.saveGState()
        pdfContext?.translateBy(x: attrText.size().width,y: attrText.size().height)
        attrText.draw(with: textRect)
        pdfContext?.restoreGState()
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)