将uiimageview转换为pdf - Swift

时间:2017-05-11 10:25:13

标签: ios swift xcode pdf uiimageview

我正在尝试使用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.
    }

}

4 个答案:

答案 0 :(得分:8)

答案已更新:

由于Apple将PDFKit引入iOS 11.0,您可以使用下面的代码将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对象中。
  7. 所以最简单的方法就是这样:

    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)
    

    在此处阅读更多内容:Generating PDF Content

答案 1 :(得分:0)

用swift.it编写的PDF生成器将有助于生成带图像路径,图像二进制,图像参考(CGImage)的PDF

https://github.com/sgr-ksmt/PDFGenerator

答案 2 :(得分:0)

swift 5 中使用PDFKit: 首次导入 PDFKit

tan使用此数组扩展名:

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()

答案 3 :(得分:0)

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)