将NSImages转换为PDF并在Swift中合并它们

4

我有一个包含一些NSImage的数组。我主要想将NSImage转换为PDF。请问有人可以向我展示如何在Swift中实现吗?

如果可能的话,你们能否向我展示如何合并PDF并将其输出呢?非常感谢。

2个回答

4
这里提供从图片创建PDF文档的大致步骤,帮助你入门。
使用 PDFKit (导入 Quartz)框架。
// 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来插入、删除和重新排序页面。


4
这对我来说在Swift(iOS 9或更高版本)上运行良好:
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)

    }

希望这能对某个人有所帮助 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接