I have an array with some NSImages in it. I mainly want to convert NSImage to PDF. So, can anyone show me how to do it in Swift.
If possible, could you guys show me how to merge PDFs into one and output it as well? Thank you so much.
Here are some rough steps to create a PDF document from images, this should get you started.
Use PDFKit (import Quartz) framework.
// Create an empty PDF document
let pdfDocument = PDFDocument()
// Load or create your NSImage
let image = NSImage(....)
// Create a PDF page instance from your image
let pdfPage = PDFPage(image: image!)
// Insert the PDF page into your document
pdfDocument.insert(pdfPage!, at: 0)
// Get the raw data of your PDF document
let data = pdfDocument.dataRepresentation()
// The url to save the data to
let url = URL(fileURLWithPath: "/Path/To/Your/PDF")
// Save the data to the url
try! data!.write(to: url)
You may need to tinker with the page's bounds and image size's to get the exact PDF page sizes you need.
You can use other PDFDocument/PDFPage API to insert, remove and reorder pages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With