将uiimageview转换为pdf - Swift

wixjitnu  于 2023-03-11  发布在  Swift
关注(0)|答案(5)|浏览(199)

我正在尝试使用swift创建一个iOS应用程序,它可以让用户拍摄照片或从图库中选择图像,并将其转换为pdf文件,以便保存到手机中。我的代码目前可以打开相机或图库并选择图像,但我无法将其转换为pdf。如有任何提示,我将不胜感激,谢谢!
相机视图控制器类

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

}

画廊视图控制器类

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

}
xam8gpfp

xam8gpfp1#

答案更新日期:
由于苹果在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上下文并将其推送到图形堆栈上。
1.创建一个页面。
1.使用UIKit或Core Graphics例程绘制页面的内容。
1.根据需要添加链接。
1.根据需要重复步骤2、3和4。
1.结束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内容

vfh0ocws

vfh0ocws2#

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

hof1towb

hof1towb3#

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)
3yhwsihp

3yhwsihp4#

在www.example.com中编写的PDF生成器swift.it将帮助生成包含图像路径、图像二进制、图像参考(CGImage)的PDF
https://github.com/sgr-ksmt/PDFGenerator

x6yk4ghg

x6yk4ghg5#

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)")
        }
        
       
    }
}

相关问题