Last active
February 23, 2024 10:21
-
-
Save KrisYu/83d7d97cae35a0b10fd238e5c86d288f to your computer and use it in GitHub Desktop.
convert NSImage to pdf, basically the same as UIImage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
let a = #imageLiteral(resourceName: "hot.png") | |
extension NSImage { | |
var toCGImage: CGImage { | |
var imageRect = NSRect(x: 0, y: 0, width: size.width, height: size.height) | |
guard let image = cgImage(forProposedRect: &imageRect, context: nil, hints: nil) else { | |
abort() | |
} | |
return image | |
} | |
} | |
func createPDF(image: NSImage) -> NSData? { | |
let pdfData = NSMutableData() | |
let pdfConsumer = CGDataConsumer(data: pdfData as CFMutableData)! | |
var mediaBox = NSRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height) | |
let pdfContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)! | |
pdfContext.beginPage(mediaBox: &mediaBox) | |
pdfContext.draw(image.toCGImage , in: mediaBox) | |
pdfContext.endPage() | |
return pdfData | |
} | |
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! | |
let docURL = documentDirectory.appendingPathComponent("myFileName.pdf") | |
print(docURL) | |
try createPDF(image: a)?.write(to: docURL, atomically: true) | |
================================== | |
This also works, using PDFKit | |
=================================== | |
//: Playground - noun: a place where people can play | |
import Cocoa | |
import Quartz | |
// Create an empty PDF document | |
let pdfDocument = PDFDocument() | |
// Load or create your NSImage | |
let image = #imageLiteral(resourceName: "hot.png") | |
// 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 documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! | |
let docURL = documentDirectory.appendingPathComponent("myFileName.pdf") | |
try data?.write(to: docURL) | |
// Save the data to the url | |
print(docURL) | |
I had to add pdfContext.closePDF()
after endPage() to make it generate a PDF that I can open.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! This helped me!