TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Draw text on all pages of PDF using PDFKit

Forums > macOS

I'm using the following code to draw text on a PDF Document.This seems to draw the text only on a single page.I'm trying to iterate through each page,draw string on it and finally display the PDF document from the MutableData. How do I draw the string on all pages?

var pdffile=PDFDocument(url: input)
let data = NSMutableData()
let consumer = CGDataConsumer(data: data as CFMutableData)!
for y in stride(from: 0, to: pdffile!.pageCount, by: 1)
    let page: PDFPage = pdffile!.page(at: y)!
    let outputBounds = page.bounds(for: PDFDisplayBox.mediaBox)
    var mediaBox = CGRect(x: 0, y: 0, width: outputBounds.size.width, height: outputBounds.size.height)
    let context = CGContext(consumer: consumer, mediaBox: &mediaBox, nil)!
    NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)

    page.draw(with: .mediaBox, to: context)
let anotherDocument = PDFDocument(data:data as Data)


Does the PDF contain only the last page of text? That's what I expect to see from the code you showed.

You are creating a new context each time you go through the for loop.

let context = CGContext(consumer: consumer, mediaBox: &mediaBox, nil)!

When you call beginPDFPage and endPDFPage to create a new PDF page, you end up adding only one page to the context because there's a new context each time you go through the loop. Instead of creating X number of pages, you create X number of contexts with one page each.

Declare the context before the for loop. Now the new pages you add inside the for loop will be added to the same context.

You should also call closePDF after the for loop. With your current code, you're saving a PDF every time through the loop. Wait until you create all the pages before saving the PDF.

There may be other problems with the code. If you are still getting only a single page, set a breakpoint and step through the code line by line, making sure the variables contain the data you expect. The following article may help you if you still have problems:

Creating PDFs with Core Text and Quartz


Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.