将图像插入PDF文件Swift

时间:2016-09-29 06:06:41

标签: ios swift xcode pdf-generation

我搜索了很多页面,但没有看到任何关于将图像制作成pdf的好解释。还有很多从未回答的问题。所以在这里问问看起来很有帮助。该应用程序有“相机”,“照片库”和“创建PDF”按钮。拍摄/选择图片后,我想通过“创建PDF”按钮将此图像附加到pdf文件中

主要故事板:

my scrreen

的ViewController:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var PhotoLibrary: UIButton!
@IBOutlet weak var Camera: UIButton!
@IBOutlet weak var ImageDisplay: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


//MARK: Photo Library Button Action
@IBAction func PhotoLibraryAction(sender: UIButton) {
    let picker = UIImagePickerController()
    picker.delegate = self
    picker.sourceType = .PhotoLibrary

    presentViewController(picker, animated: true, completion: nil)
}




//MARK: Camera Button Action
@IBAction func CameraAction(sender: UIButton) {
    let picker = UIImagePickerController()
    picker.delegate = self
    picker.sourceType = .Camera

    presentViewController(picker, animated: true, completion: nil)
}




//MARK: Adding Texts on Selected/Taken Image
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    if var image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        ImageDisplay.image = image

    }
    dismissViewControllerAnimated(true, completion: nil)
}




}

1 个答案:

答案 0 :(得分:4)

使用以下功能将图像转换为pdf

func createPdfFromView(imageView: UIImageView, saveToDocumentsWithFileName fileName: String)
{
    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, imageView.bounds, nil)
    UIGraphicsBeginPDFPage()

    let pdfContext = UIGraphicsGetCurrentContext()

    if (pdfContext == nil)
    {
        return
    }

    imageView.layer.renderInContext(pdfContext!)
    UIGraphicsEndPDFContext()

    if let documentDirectories: AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first
    {
        let documentsFileName = (documentDirectories as! String)  + ("/\myPDFImage.pdf")
        debugPrint(documentsFileName, terminator: "")
        pdfData.writeToFile(documentsFileName, atomically: true)
    }
}

我创建了一个视图的pdf,所以我将UIView传递给了这个函数。将你的UIImageView传递给这个函数,它应该可以正常工作。