我有一个包含一些NSImage的数组。我主要想将NSImage转换为PDF。请问有人可以向我展示如何在Swift中实现吗?
如果可能的话,你们能否向我展示如何合并PDF并将其输出呢?非常感谢。
// 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)
你可能需要调整页面边界和图像大小,以获取所需的PDF页面尺寸。
你可以使用其他PDFDocument/PDFPage API来插入、删除和重新排序页面。
func createPDF(images: [UIImage]) {
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
for image in images {
let imgView = UIImageView.init(image: image)
UIGraphicsBeginPDFPageWithInfo(imgView.bounds, nil)
let context = UIGraphicsGetCurrentContext()
imgView.layer.render(in: context!)
}
UIGraphicsEndPDFContext()
//try saving in doc dir to confirm:
let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
let path = dir?.appendingPathComponent("file.pdf")
do {
try pdfData.write(to: path!, options: NSData.WritingOptions.atomic)
} catch {
print("error catched")
}
let documentViewer = UIDocumentInteractionController(url: path!)
documentViewer.name = "Vitul"
documentViewer.delegate = self
documentViewer.presentPreview(animated: true)
}