繁体   English   中英

iOS PDFKit无法编写

[英]iOS PDFKit will not write

import UIKit
import PDFKit

class ViewController: UIViewController {

    @IBOutlet weak var pdfView: PDFView!

    lazy var pdfDoc:PDFDocument? = {
        guard let path = Bundle.main.path(forResource: "6368", ofType: "pdf") else {return nil}
        let url = URL(fileURLWithPath: path)
        return PDFDocument(url: url)
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupPDFView()
        self.save()
    }

    func setupPDFView() {
        //Setup and put pdf on view
        pdfView.autoScales = true
        pdfView.displayMode = .singlePageContinuous
        pdfView.displayDirection = .horizontal
        pdfView.document = pdfDoc

        self.add(annotation: self.circleAnnotation(), to: 0)
    }

    func add(annotation: PDFAnnotation, to page:Int){
        self.pdfDoc?.page(at: page)?.addAnnotation(annotation)
    }

    func circleAnnotation()->PDFAnnotation {
        let bounds = CGRect(x: 20.0, y: 20.0, width:200.0, height: 200.0)
        let annotation = PDFAnnotation(bounds: bounds, forType: .circle, withProperties: nil)
        annotation.interiorColor = UIColor.black
        return annotation
    }

    func save() {
        //Save to file
        guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {return}
        let data = pdfView.document?.dataRepresentation()
        do {
            if data != nil{try data!.write(to: url)}
        } 
        catch {
            print(error.localizedDescription)
        }
    }
}

这只是简单的PDFKit代码,应将圆圈添加到pdf的第一页并将其保存到documents目录。 除保存外,所有工作均有效。 当我刚断点后, let data = .. 它表明有数据,但是有两个错误:

1)2018-12-18 05:10:28.887195-0500 PDFWriteTest [21577:1331197] [未知进程名称]无法加载/System/Library/PrivateFrameworks/CorePDF.framework/Versions/A/CorePDF

  • 无论我是否发现错误并打印,此内容都会显示

2)无法将“文档”文件保存在文件夹“ D3E23B05-92 ...”中。

  • 这是从error.localizedDescription打印的内容

可以使用PDFKit解决此问题(将PDF数据保存到文件)吗?

您可以这样打电话:

let data = NSMutableData()
UIGraphicsBeginPDFContextToData(data, .zero, nil)
// process view
UIGraphicsEndPDFContext()
data as Data
// now you get the data

苹果所说 ,使用此方法UIGraphicsBeginPDFContextToData(_:_:_:)保存PDF。

创建针对指定可变数据对象的基于PDF的图形上下文。

宣言

func UIGraphicsBeginPDFContextToData(_ data:NSMutableData,_ bounds:CGRect,_ documentInfo:[AnyHashable:Any]?)

参量

数据

数据对象,用于接收PDF输出数据。

您还可以使用UIGraphicsBeginPDFContextToFile(_:_:_:)将pdf视图写入磁盘。

UIGraphicsBeginPDFContextToFile(filePath, .zero, nil)
// do the view rendering
UIGraphicsEndPDFContext()

这是一个例子:

class ViewController: UIViewController {

//处理视图,并调用将其另存为PDF视图

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let v1 = UIScrollView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        v1.contentSize = CGSize(width: 100, height: 100)

        let v2 = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 200))
        let v3 = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 200))
        v1.backgroundColor = UIColor.red

        v2.backgroundColor = UIColor.green
        v3.backgroundColor = UIColor.blue

        let dst = NSHomeDirectory() + "/dng.pdf"

        UIGraphicsBeginPDFContextToFile(dst, .zero, nil)
        [v1, v2, v3].forEach{ (view : UIView)
            in
            autoreleasepool {
                self.renderPDFPage(view: view)
            }
        }
        UIGraphicsEndPDFContext()
    }

//开始渲染

    func renderPDFPage(view: UIView) {
        func renderScrollView(_ scrollView: UIScrollView) {
            let tmp = scrollView.tempInfo
            scrollView.transformForRender()
            _render(scrollView) { scrollView in
                if let scrollView = scrollView as? UIScrollView{
                    scrollView.restore(tmp)
                }
            }
        }


        if let scrollView = view as? UIScrollView {
            renderScrollView(scrollView)
        } else {
            _render(view)
        }
    }


    func getPageSize(_ view: UIView) -> CGSize {
        switch view {
        case (let scrollView as UIScrollView):
            return scrollView.contentSize
        default:
            return view.frame.size
        }
    }

    func _render(_ view: UIView, completion: (UIView) -> Void = { _ in }) {
        let size: CGSize = getPageSize(view)

        guard size.width > 0 && size.height > 0 else {
            return
        }
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }

        let renderFrame = CGRect(origin: CGPoint(x: 0.0 , y: 0.0),
                                 size: CGSize(width: size.width, height: size.height))
        autoreleasepool {
            let superView = view.superview
            view.removeFromSuperview()
            UIGraphicsBeginPDFPageWithInfo(CGRect(origin: .zero, size: renderFrame.size), nil)
            context.translateBy(x: -renderFrame.origin.x, y: -renderFrame.origin.y)
            view.layer.render(in: context)
            superView?.addSubview(view)
            superView?.layoutIfNeeded()
            completion(view)
        }
    }
}

// Util方法,用于处理UIScrollView

private extension UIScrollView {
    typealias TempInfo = (frame: CGRect, offset: CGPoint, inset: UIEdgeInsets)

    var tempInfo: TempInfo {
        return (frame, contentOffset, contentInset)
    }

    func transformForRender() {
        contentOffset = .zero
        contentInset = UIEdgeInsets.zero
        frame = CGRect(origin: .zero, size: contentSize)
    }

    func restore(_ info: TempInfo) {
        frame = info.frame
        contentOffset = info.offset
        contentInset = info.inset
    }

}

您不能将数据直接写到表示Documents文件夹的URL,必须指定(并附加)文件名。

func save(filename : String) {
    //Save to file
    guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
          let data = pdfView.document?.dataRepresentation() else {return}
    let fileURL = url.appendingPathComponent(filename)
    do {
        try data.write(to: fileURL)
    } catch {
        print(error.localizedDescription)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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