当前位置: 首页 > article >正文

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

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


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

    
}


http://www.kler.cn/a/396758.html

相关文章:

  • 存储过程及练习
  • Spring boot + Vue2小项目基本模板
  • Linux之vim全选,全部复制,全部删除
  • aws ses 设置发件人昵称
  • Selective attention improves transformer详细解读
  • c#————委托Action使用例子
  • 聊聊Flink:Flink的运行时架构
  • 【含开题报告+文档+PPT+源码】基于Spring Boot智能综合交通出行管理平台的设计与实现
  • 除了 TON, 哪些公链在争夺 Telegram 用户?数据表现如何?
  • 【IEEE出版 | 中国石油大学(华东)主办】第六届信息与计算机前沿术国际学术会议(ICFTIC 2024,12月13-15日)
  • 两部手机的IP地址:是否会相同?全面探讨
  • K8S 查看pod节点的磁盘和内存使用情况
  • 【364】基于springboot的高校科研信息管理系统
  • Python 如何通过 cron 或 schedule 实现爬虫的自动定时运行
  • Flink_DataStreamAPI_源算子Source
  • Java进阶 - 并发编程
  • 帽子矩阵--记录
  • SQL 中 BETWEEN AND 用于字符串的理解
  • Element UI如何实现按需导入--Vue3篇
  • Kotlin jetpack MVP
  • sql server 查看io资源使用
  • Docker环境搭建Cloudreve网盘服务(附shell脚本一键搭建)
  • 【从零开始的LeetCode-算法】3270. 求出数字答案
  • 使用阿里云远程访问 Synology Web Station 的指南
  • JMeter初体验:从入门到入门的性能测试之旅
  • 万字长文解读机器学习——KNN