NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills 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
    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 {
        return image

class PDFText {

     Create a non-nil CGContext
     Credit - hmali - 3/15/2019
    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)
        drawText("This is page 1")
        drawText("This is page 1")

    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?.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)


Hacking with Swift is sponsored by MadMachine

SPONSORED Want to explore your Swift skill outside of the Apple world? Join the MadMachine community and start to program microcontrollers in Swift.

Get it 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.