将uiimageview转换为pdf-Swift [英] Converting uiimageview to pdf - Swift

查看:104
本文介绍了将uiimageview转换为pdf-Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用swift创建一个iOS应用程序,该应用程序将允许用户拍摄照片或从图库中选择图像,然后将其转换为pdf文件,然后将其保存到手机中.我的代码当前可以打开相机或图库并选择图像,但是无法将其转换为pdf. 任何提示将不胜感激,谢谢!

I am trying to create an iOS app using swift that will let the user either take a photo or choose an image from their gallery, and convert it to a pdf file that they are able to save to their phone. My code currently works to open either the camera or the gallery and choose an image, but I'm unable to convert it to pdf. Any tips would be really appreciated, thanks!

CameraViewController类

CameraViewController class

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类

GalleryViewController class

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.
    }

}

推荐答案

答案已更新:

自从Apple在iOS 11.0中引入PDFKit以来,您可以使用下面的代码将uiimage转换为pdf,我只尝试了下面的osx,但是在iOS上应该以相同的方式工作.

Since Apple introduced PDFKit to iOS 11.0, you can use the code below to convert uiimage to pdf, I only tried the osx below, but it should work the same way on 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)

================================================ =

================================================

实际上,有很多类似的问题和足够好的答案.让我再试一次.

Actually there're a lot similar questions and good enough answers. Let me try to answer this again.

基本上生成PDF类似于iOS中的图形.

Basically generating PDF is similar to the drawing in iOS.

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

所以最简单的方法是这样的:

So the most simple way would be something like this:

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,然后我们需要将数据保存到文件:

That created all the NSData for the PDF file, then we need to save the data to file:

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)

在此处了解更多信息:

Read more here: Generating PDF Content

这篇关于将uiimageview转换为pdf-Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆