【问题标题】:NSImages to PDFs and merge them in SwiftNSImages 到 PDF 并在 Swift 中合并它们
【发布时间】:2016-11-08 08:01:13
【问题描述】:

我有一个包含一些 NSImage 的数组。 我主要想将 NSImage 转换为 PDF。那么,谁能告诉我如何在 Swift 中做到这一点。

如果可能的话,你们能告诉我如何将 PDF 合并为一个并输出吗? 非常感谢。

【问题讨论】:

    标签: xcode macos pdf swift3 nsimage


    【解决方案1】:

    这在 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)
    
        }
    

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

    【讨论】:

      【解决方案2】:

      以下是从图像创建 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 来插入、删除和重新排序页面。

      【讨论】:

        猜你喜欢
        • 2015-06-11
        • 2015-09-20
        • 2018-07-16
        • 1970-01-01
        • 1970-01-01
        • 2016-01-10
        • 2017-11-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多