Greetings,
this may be an odd question but I was not able to find an answer to this.
So I am developing this pure MacOS program for a client and one thing he wants is to create some PDFs along the way. Great chance I thought to try out this fancy Swift 5 with SwiftUI and so far it's going great, most of the program is up and running but I've hit a wall with the PDF generation, which I thought would be one of the easiest parts.
Since it's a pure MacOS program, UIKit is not available but there is not a single tutorial out there for generating PDFs which is not using UIKit to do it. It seems people only want to create PDFs on iOS.
Can someone give me a small breakdown or starter or tutorial or skeleton on how I would do that?
Thanks and have a nice day
PDFKit is available in macOS 10.4+. Here's the first tutorial I found Create PDF view programmatically using PDFKit in swift. - Mobikul
FYI, Apple platform development questions should be directed to Apple Developer Forums
This page of documentation probably has what you're looking for: Apple Developer Documentation
Additionally, when you ask this question on Apple Developer Forums, it might help if you provide some details of what you're trying to create a PDF from.
Hey, I have found this tutorial, it is for iOS, not MacOS. I had no idea, I am new here. It just said newbie questions welcome
Hi Halest,
It appears no one has answered your question.
How to create a PDF from a SwiftUI MacOS program where UIKit is not available.
Did you find a way to do it?
I want to do the same thing.
no, Sample is for iOS.
You can use Core Graphics and PDFKit on both macOS and iOS to create/manipulate PDFs. There isn’t a shortage of guides online for either of them.
There’s also the ImageRenderer class added to SwiftUI this year, although supposedly it’s quite limited. The official documentation looks to be quite thorough.
Depending on the kind of documents you’re trying to create it may be worth using something like Weasy Print or wkhtmltopdf instead, which render HTML as PDFs. They aren’t written in Swift, but they’re simple enough to use if you have some understanding of HTML and CSS.
Try GitHub - atrbx5/PdfBuilder at macos
there is some bugs, but gonna be fixed soon
I highly recommend checking out the Swift package that I just released: swift-html-to-pdf, if you want to create your PDF using HTML.
- Convert HTML strings to PDF documents on both iOS and macOS.
- Handle thousands of documents quickly with lightweight and fast performance.
- Customize PDF document margins to fit your needs.
- Swift 6 language mode enabled for complete concurrency checks.
let htmlString = "<html><body><h1>Hello, World!</h1></body></html>"
try await htmlString.print(
to: URL(fileURLWithPath: "path/to/output.pdf"),
configuration: .a4
)
This package should save you a lot of time and hassle. Plus, it’s open-source, so feel free to contribute or customize it to fit your needs.
Check it out on GitHub: swift-html-to-pdf