Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSImages to PDFs and merge them in Swift

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.

like image 549
user2367447 Avatar asked Jan 05 '23 02:01

user2367447


1 Answers

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.

like image 86
danielv Avatar answered Jan 09 '23 09:01

danielv