iOS PDFKit不会写

问题描述 投票:1回答:2
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的第一页上添加一个圆圈并将其保存到文档目录中。所有工作,除了保存。当我在let data = ..之后断断续续。它表明有数据,但有两个错误:

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

  • 这个显示无论我是否捕获错误和打印

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

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

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

ios swift pdf
2个回答
2
投票

您不能将数据直接写入表示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)
    }
}

2
投票

你可以这样打电话:

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

作为apple says,使用此方法UIGraphicsBeginPDFContextToData(_:_:_:)来保存PDF。

创建基于PDF的图形上下文,该上下文以指定的可变数据对象为目标。

Declaration

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

Parameters

数据

用于接收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
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.