coskukoz coskukoz - 2 months ago 65
Swift Question

Insert an Image into PDF file Swift

I have searched a lot of pages but haven't seen any good explanation for making image to pdf. Also there are many never answered question. So it's looks helpful to ask here. The app has 'Camera', 'Photo Library' and 'Create PDF' buttons. After taken/choosing picture I want to attach this image into pdf file by 'Create PDF' button

Main Storyboard:

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




}

Answer

Use the following function to convert your image into 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)
    }
}

I create pdf of a view, so I pass a UIView to this function. Pass your UIImageView to this function and it should work fine.

Comments