0

下午好,我想在按钮中调用一个函数来将图像页面添加到文档中。这里在下面提供的这个方法中。

@IBAction func mergeButton(_ sender: Any) {
  
  
        let newDocument = PDFDocument()
        let image = UIImage(systemName: "image")
      
        let page = PDFPage(image: image!)
        
        newDocument.insert(page!, at: 0)
        newPDF.document = newDocument
      
    }

这是我的全部代码。我打算通过选择器上传图像,然后将其添加到 pdf 文档中。谁能帮我纠正错误?下面是我的整个代码

import UIKit
import PDFKit
import MobileCoreServices

class ViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate,PDFViewDelegate {
  
    
    let pdf = PDFView()
    let newPDF = PDFView()
    
    @IBOutlet weak var pdfImage: UIView!
    
   
    
    @IBOutlet weak var imageGallery: UIImageView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
      pdfImage.addSubview(pdf)
        mergeFile.addSubview(newPDF)
        guard let url = Bundle.main.url(forResource: "foglio", withExtension: "pdf") else {
            return
        }
        
        
        guard let document = PDFDocument(url: url) else {return }
        
        pdf.document = document
        pdf.autoScales = true
        pdf.delegate = self
        newPDF.delegate = self
            
        
        
    }
  
    
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        pdf.frame = pdfImage.bounds
        pdf.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        newPDF.frame = mergeFile.bounds
        newPDF.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        
    }

   
    @IBOutlet weak var mergeFile: UIView!
    
    
    @IBAction func mergeButton(_ sender: Any) {
  
  
        let newDocument = PDFDocument()
        let image = UIImage(systemName: "image")
      
        let page = PDFPage(image: image!)
        
        newDocument.insert(page!, at: 0)
        newPDF.document = newDocument
      
    }
    
    @IBAction func ImageUpdate(_ sender: Any) {
        let picker = UIImagePickerController()
            picker.delegate = self
            picker.sourceType = .photoLibrary

        present(picker, animated: true, completion: nil)
    }
    
    
     private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

        if let image = info[UIImagePickerController.InfoKey.originalImage.rawValue] as? UIImage {
           
            imageGallery.image = image

        }
         self.dismiss(animated: true, completion: nil)
    }


     func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

         self.dismiss(animated: true, completion: nil)
    }

  

   
}
4

1 回答 1

0

尝试这样的事情:

    let newDocument = PDFDocument()
    if let image = UIImage(named: "image"),
       let page = PDFPage(image: image) {
        newDocument.insert(page, at: 0)
        newPDF.document = newDocument
    }
于 2022-01-19T08:01:58.137 回答