Automate beginPage() for PDF using PDFKit – Swift 5

In my app, I want to print large, paragraph-length Strings onto a PDF (like if you wrote a huge paper in Microsoft Word and then printed it to a PDF). Where I'm struggling is in figuring out how to make it know when to call beginPage() and bleed onto a new page (at a certain distance down the page)? For example, imagine opening a Word Document and typing until the first page is completely full, then notice how it automatically goes to a new page when necessary. I would imagine Xcode would need to know where to print down to (pageBottom + certain amount of pixels off the bottom), then it would need to cut the rest of the String still needing to be printed, create a new page, know where to start printing at, then continue printing the string where it left off, on the second page.

Essentially:
Code Block
//1
let paragraphFont = UIFont.systemFont(ofSize: 12.0, weight: .regular)
//2
let paragraphAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: paragraphFont]
//3
let attributedParagraph = NSAttributedString(
string: "\(paragraphToBePrinted)",
attributes: paragraphAttributes
)
//4
let paragraphStringSize = attributedParagraph.size()
//5
let paragraphStringRect = CGRect(
x: (pageRect.width - pageRect.width) + 20,
y: paragraphTop,
width: paragraphStringSize.width,
height: paragraphStringSize.height
)
//6
attributedParagraph.draw... if while printing the paragraph you come to a certain point near the bottom
of the page (pageBottom + 50 [example]), then create a new page, and continue printing at startPoint (pageTop - 50).


Any ideas? I'm using PDFKit, of course. Please explain your answers.

Thanks!
It won't let me edit the article, so I'll put it here instead:

I'm actually creating the PDF with CoreGraphics and saving it with PDFKit.
Using the Core Text framework is going to be the easiest way to create a PDF with large amounts of text. Core Text has a function to determine how much text can fit on a page, CTFramesetterSuggestFrameSizeWithConstraints.

It's been a while since I used Core Text, but the following article shows how to create a PDF with Core Text and Quartz (Core Graphics):

meandmark.com/blog/2016/08/creating-pdfs-with-core-text-and-quartz/


Automate beginPage() for PDF using PDFKit – Swift 5
 
 
Q