iOS PDFKit无法编写

时间:2018-12-18 10:31:48

标签: ios swift pdf

PDFKit

这只是简单的let data = ..代码,应该在pdf的第一页上添加一个圆圈并将其保存到documents目录。除保存外,所有工作均有效。当我在{ "@type": "ActionCard", "name": "Comment", "inputs": [ { "@type": "TextInput", "id": "comment", "isMultiline": true, "title": "Input's title property" } ], "actions": [ { "@type": "HttpPOST", "name": "Action's name prop.", "target": "https://yammer.com/comment?postId=123", "body": "comment={{comment.value}}" } ] } 之后断点时。它表明有数据,但是有两个错误:

  

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数据保存到文件)吗?

2 个答案:

答案 0 :(得分:2)

您可以这样拨打电话:

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

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

  

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

     

声明

     

func UIGraphicsBeginPDFContextToData(_ data:NSMutableData,                                      _范围: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
    }

}

答案 1 :(得分: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)
    }
}