简体   繁体   中英

How to fit a PDF from UIImage in PDFView in swift?

I have an app that captures an image and converts it to pdf. It is then displayed in a PDFView. However, the PDF does not fit into the dimensions of my PDFView. How do I scale the pdf to fit the PDFView?

When the image is selected from imagePickerController the following function is executed:

// OUTLETS
@IBOutlet weak var myPDFView: PDFView!


 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    print("image selected ...")
    // Get picked image info dictionary
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage

    // Add captured and selected image to your Photo Library
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

    // Create PDFDocument object and display in PDFView
    let document = createPDFDataFromImage(image: image)

    myPDFView.document = document
    myPDFView.scaleFactorForSizeToFit

    // Dimiss imagePicker
    dismiss(animated: true, completion: nil)

}


  func createPDFDataFromImage(image: UIImage) -> PDFDocument{

    let document = PDFDocument.init()
    let imagePDF = PDFPage.init(image: image)

    document.insert(imagePDF!, at: 0)
    return document
}

You can set autoScales to true

here is my code

pdfView.document = createPDF(image: #imageLiteral(resourceName: "Image-1"))

pdfView.minScaleFactor = 0.1
pdfView.maxScaleFactor = 5

pdfView.autoScales = true
pdfView.displayMode = .singlePageContinuous
pdfView.displayDirection = .vertical

And creating a PDFPage from the image like this:

func createPDF(image: UIImage) -> PDFDocument {
    let document = PDFDocument()

    guard let cgImage = image.cgImage else { return document }

    let image = UIImage(cgImage: cgImage, scale: image.scale, orientation: .downMirrored)

    guard let imagePDF = PDFPage(image: image) else { return document }

    document.insert(imagePDF, at: document.pageCount)

    return document
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM