把UIImageView转换成PDF - Swift

11
我正在尝试使用Swift创建一个iOS应用程序,让用户拍照或从相册中选择图片,并将其转换为PDF文件,以便他们可以保存到手机。我的代码目前可以打开相机或相册并选择图像,但我无法将其转换为PDF。 如果您有任何提示,我将不胜感激,谢谢! CameraViewController类
import UIKit

class CameraViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate
 {

    @IBOutlet weak var myImg: UIImageView!

    @IBAction func takePhoto(_ sender: AnyObject) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.camera
            imagePicker.allowsEditing = false
            self.present(imagePicker, animated: true, completion: nil)
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            myImg.contentMode = .scaleToFill
            myImg.image = pickedImage
        }
        picker.dismiss(animated: true, completion: nil)
    }

    @IBAction func savePhoto(_ sender: AnyObject) {
        let imageData = UIImagePNGRepresentation(myImg.image!)
        let compressedImage = UIImage(data: imageData!)
        UIImageWriteToSavedPhotosAlbum(compressedImage!, nil, nil, nil)

        let alert = UIAlertController(title: "Saved", message: "Your image has been saved", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
        alert.addAction(okAction)
        self.present(alert, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

GalleryViewController 类

import UIKit

class GalleryViewController: UIViewController {

    @IBOutlet weak var myImg: UIImageView!

    @IBAction func pickPhoto(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate
            imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            imagePicker.allowsEditing = true
            self.present(imagePicker, animated: true, completion: nil)
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            myImg.contentMode = .scaleToFill
            myImg.image = pickedImage
        }
        picker.dismiss(animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
5个回答

28

答案已更新:

自从苹果在iOS 11.0引入PDFKit以来,您可以使用下面的代码将uiimage转换为PDF。我只尝试了以下的osx,但在iOS上应该以同样的方式工作。

// Create an empty PDF document
let pdfDocument = PDFDocument()

// Load or create your UIImage
let image = UIImage(....)

// 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与iOS中的绘制相似。

  1. 创建PDF上下文并将其推入图形堆栈。
  2. 创建页面。
  3. 使用UIKit或Core Graphics例程绘制页面内容。
  4. 如有需要,添加链接。
  5. 根据需要重复执行步骤2、3和4。
  6. 结束PDF上下文以从图形堆栈弹出上下文,并根据上下文的创建方式,将结果数据写入指定的PDF文件或存储到指定的NSMutableData对象中。

因此,最简单的方法可能是这样的:

func createPDF(image: UIImage) -> NSData? {

    let pdfData = NSMutableData()
    let pdfConsumer = CGDataConsumer(data: pdfData as CFMutableData)!

    var mediaBox = CGRect.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.cgImage!, in: mediaBox)
    pdfContext.endPage()

    return pdfData
}

那个创建了PDF文件的所有NSData,然后我们需要将数据保存到文件中:

let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let docURL = documentDirectory.appendingPathComponent("myFileName.pdf")

try createPDF(image: someUIImageFile)?.write(to: docURL, atomically: true)

阅读更多内容:生成PDF内容


7
在Swift 5中使用PDFKit: 首先导入PDFKit。 然后使用以下数组扩展:
import UIKit
import PDFKit


extension Array where Element: UIImage {
    
      func makePDF()-> PDFDocument? {
        let pdfDocument = PDFDocument()
        for (index,image) in self.enumerated() {
            let pdfPage = PDFPage(image: image)
            pdfDocument.insert(pdfPage!, at: index)
        }
        return pdfDocument
    }
}

并且 使用 这个:

let imageArray = [UIImage(named: "1")!, UIImage(named: "2")!] let yourPDF = imageArray.makePDF()


4

Swift 5 我们将使用UIGraphicsPDFRenderer()类,它将适用于iOS 10及以上版本

        let image = results.croppedScan.image
        let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let docURL = documentDirectory.appendingPathComponent("Scanned-Docs.pdf")
        let outputFileURL: URL = docURL
        let imageBounds = CGRect(origin: .zero, size: image.size)
        let pdfRenderer = UIGraphicsPDFRenderer(bounds: imageBounds)
        do {
            try pdfRenderer.writePDF(to: outputFileURL) { context in
                context.beginPage()
                results.croppedScan.image.draw(in: imageBounds)
            }
        } catch {
            print("Could not create PDF file: \(error)")
        }
        print("save at ===\(outputFileURL)")
        //Show PDF in Controller
        let dc = UIDocumentInteractionController(url: outputFileURL)
        dc.delegate = self
        dc.presentPreview(animated: true)

0

0
 func exportToPDF(_ uiImage:UIImage) {
    let outputFileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("testing" + ".pdf")
    let pageSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        
    let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(origin: .zero, size:  uiImage.size))
    DispatchQueue.main.async {
        do {
            let imageBounds = CGRect(origin: .zero, size: uiImage.size)
            try pdfRenderer.writePDF(to: outputFileURL, withActions: { (context) in
                context.beginPage()
                uiImage.draw(in: imageBounds)
              
            })
            print("wrote file to: \(outputFileURL.path)")
            var documentoPath = outputFileURL.path
            let fileManager = FileManager.default
            if fileManager.fileExists(atPath: documentoPath){
                            let documento = NSData(contentsOfFile: documentoPath)
                            let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [documento!], applicationActivities: nil)
                UIApplication.shared.windows.first?.rootViewController?.present(activityViewController, animated: true, completion: nil)
                        }
                        else {
                            print("wrote file to: No Document \(outputFileURL.path)")
                        }
        } catch {
            print("Could not create PDF file: \(error.localizedDescription)")
        }
        
       
    }
}

这基本上是一个现有答案的副本。 - HangarRash
这就是有效的代码。 - Adeyemi Seun
但是你的答案提供了什么之前的答案没有提供的呢?已经有一个回答展示了如何使用UIGraphicsPDFRenderer从图像创建PDF。 - HangarRash

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