iOS swift开发--- 加载PDF文件并显示内容

iOS开发采用pdfkit ,可以很方便的读取pdf的内容。以下是简易的显示pdf内容的代码

Swift 复制代码
import UIKit
import PDFKit
 
 
class ViewController: UIViewController, UIDocumentPickerDelegate {
 
    var pdfView: PDFView!  //创建一个控件显示内容
    
    let selectPDFButton = UIButton(type: .system)  //点击按钮选择打开pdf文件
 
   
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        selectPDFButton.setTitle("Select PDF", for: .normal)
        selectPDFButton.addTarget(self, action: #selector(selectPDF), for: .touchUpInside)
        selectPDFButton.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(selectPDFButton)
        pdfView = PDFView()
        pdfView.backgroundColor = .red
        pdfView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(pdfView)

 
        selectPDFButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 120).isActive = true
        selectPDFButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
        selectPDFButton.widthAnchor.constraint(equalToConstant: 100).isActive = true
        selectPDFButton.heightAnchor.constraint(equalToConstant: 50).isActive = true

        // 设置 pdfView 的约束
           pdfView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
           pdfView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
           pdfView.topAnchor.constraint(equalTo: selectPDFButton.bottomAnchor, constant: 120).isActive = true
           pdfView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true

 

        
    }
    

    @objc func selectPDF() {
   
        let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.pdf])
        documentPicker.delegate = self
        present(documentPicker, animated: true, completion: nil)
    }
    
 
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let url = urls.first else { return }
        selectedPDFURL = url
        
        // 请求安全范围内的资源访问,这个startAccessingSecurityScopedResource很关键,否则可能打不开文件
        guard url.startAccessingSecurityScopedResource() else {
            print("Failed to start accessing security-scoped resource.")
            showErrorMessage("Failed to access the selected file.")
            return
        }
        
        defer {
            url.stopAccessingSecurityScopedResource()
        }
        

        // 尝试加载 PDF 文档
            guard let pdfDocument = PDFDocument(url: url) else {
                // 如果无法加载 PDF 文档,打印错误信息
                print("Failed to load PDF document at URL: \(url)")
                showErrorMessage("Failed to load PDF document.")
                return
            }
        print("load PDF document  success ")
        pdfView.document = pdfDocument
        pdfView.autoScales = true
        pdfView.layoutSubviews()
     
        print("load PDF document  success ")
        // 可以在这里显示一些提示,告知用户文件已选择
        let alertController = UIAlertController(title: "Info", message: "PDF file selected successfully.", preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        present(alertController, animated: true, completion: nil)
        
    // 显示 PDF 文件
   
    }
    
    private func showErrorMessage(_ message: String) {
            let alertController = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            present(alertController, animated: true, completion: nil)
        }
        
        private func showSuccessMessage(_ message: String) {
            let alertController = UIAlertController(title: "Success", message: message, preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            present(alertController, animated: true, completion: nil)
        }

    
}
相关推荐
周末zm3 小时前
golang将word、excel转换为pdf
pdf·word·excel
wjg10244 小时前
连接数据库导出数据库信息支持excel pdf html markdown
pdf
lu_rong_qq7 小时前
分享 pdf 转 word 的免费平台
pdf
郝晨妤7 小时前
HarmonyOS和OpenHarmony区别是什么?鸿蒙和安卓IOS的区别是什么?
android·ios·harmonyos·鸿蒙
Hgc558886667 小时前
iOS 18.1,未公开的新功能
ios
Hamm7 小时前
先别急着喷,没好用的iOS-Ollama客户端那就自己写个然后开源吧
人工智能·llm·swift
CocoaKier9 小时前
苹果商店下载链接如何获取
ios·apple
一只小白菜~10 小时前
web浏览器环境下使用window.open()打开PDF文件不是预览,而是下载文件?
前端·javascript·pdf·windowopen预览pdf
zhlx283511 小时前
【免越狱】iOS砸壳 可下载AppStore任意版本 旧版本IPA下载
macos·ios·cocoa
XZHOUMIN1 天前
网易博客旧文----编译用于IOS的zlib版本
ios