GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Drawing Text to a CGContext for Quartz PDF not working

Forums > macOS

This is for Swift 5 on macOS

I am trying to write some text to a generated PDF.

I am able to load a background image onto the pages, but when I call my drawText method, it is not making it onto either of the pages.

I tried drawing an NSString to the context via the .draw() method and that would not work either. I hoping to get this to work so I can add more text, including text boxes, etc.

What am I doing wrong? Thanks for any pointers.

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, y: 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)
        ("Some text on a page" as NSString).draw(at: NSMakePoint(295, 300), withAttributes: attr as [NSAttributedString.Key : Any])
        attrText.draw(with: textRect)
        pdfContext?.restoreGState()
    }
}

3      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until February 9th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.