如何在swift中使用PDFView中的UIImage来装入PDF?

时间:2018-02-19 16:15:13

标签: ios swift pdfkit pdfview

我有一个应用程序捕获图像并将其转换为PDF格式。然后它以PDFView显示。但是,PDF不适合我的PDFView的尺寸。如何缩放pdf以适合PDFView?

从imagePickerController中选择图像时,执行以下功能:

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

1 个答案:

答案 0 :(得分:1)

您可以将autoScales设置为true

这是我的代码

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

pdfView.minScaleFactor = 0.1
pdfView.maxScaleFactor = 5

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

从图像中创建PDFPage:

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
}