renderer.writePDF 无法正常工作

renderer.writePDF doesn't work without error

我学习 swift 并遇到问题:当我尝试在文档目录中写入 pdf 文件时,没有任何反应。 代码:

func createPDF() {
        // MARK: - create path
        let documentDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
        let path = documentDir.appendingPathComponent("\(clientCompanyName + UUID().uuidString).pdf")

        // MARK: - create meta
        let pdfMetaData = [
            kCGPDFContextCreator: "something",
            kCGPDFContextAuthor: "https://bla-bla.com"
        ]
        let format = UIGraphicsPDFRendererFormat()
        format.documentInfo = pdfMetaData as [String: Any]
        
        // MARK: - set page size
        let pageWidth = 8.5 * 72.0
        let pageHeight = 11 * 72.0
        let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
        
        // MARK: - render
        let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
        try? renderer.writePDF(to: path) { (context) in
            let attributes = [
                NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 72)
            ]
            let text = clientCompanyName + " " + formattedDate
            text.draw(at: CGPoint(x: 0, y: 0), withAttributes: attributes)
        }
    }

当我启动这段代码时,我在终端中没有看到任何错误。但是如果我打开文件,我的文档没有保存

所以我认为问题是不允许您写入 cachesDirectory。所以用那个替换所有东西,它应该可以工作。此外,使用 pageDatas,您现在可以在 CGRects 中打印多页,只需附加数组,不客气:)

    func createPDF() -> URL {
            // MARK: - create path
        let documentDir = FileManager.default.temporaryDirectory
            let path = documentDir.appendingPathComponent("\("clientCompanyName" + UUID().uuidString).pdf")
        
            // MARK: - create meta
            let pdfMetaData = [
                kCGPDFContextCreator: "something",
                kCGPDFContextAuthor: "https://bla-bla.com"
            ]
        let format = UIGraphicsPDFRendererFormat()
        format.documentInfo = pdfMetaData as [String: Any]
        
        // MARK: - set page size
        let pageWidth = 8.5 * 72.0
        let pageHeight = 11 * 72.0
        let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)
        
        // MARK: - render
        let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
        let attributes = [
                NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 72)
            ]
        let text = "clientCompanyName" + " " + "formattedDate"
        let myAttributedString = NSAttributedString(string: text, attributes: attributes)
        let pageDatas = [[[pageRect, myAttributedString]]]
        let pdfData = createCustomPdfDataa(renderer: renderer, pageDatas: pageDatas)
        do {
            try pdfData.write(to: path)
        } catch {
            fatalError("Sorry this does not work, because \(error)")
        }
        return path
    }

    func createCustomPdfDataa(renderer: UIGraphicsPDFRenderer, pageDatas: [[[Any?]]]) -> Data {
        // render context to pdfData
        let data = renderer.pdfData { (context) in
            // create pages
            for pageNumber in 0..<pageDatas.count {
                context.beginPage()
                let pageData = pageDatas[pageNumber]
                for textIndex in 0..<pageData.count {
                    drawAttributedText(inFrame: pageData[textIndex][0] as! CGRect, pageData[textIndex][1] as! NSAttributedString)
                }
            }
        }
        return data
    }


    func drawAttributedText(inFrame: CGRect, _ text: NSAttributedString) {
        text.draw(in: inFrame)
    }
}

createPDF 函数 returns 您要保存到 url,如果您想在 PDFView 中显示它,请使用下面的代码调用它:

    let documentDir = createPDF()
    let data = readDataFromUrl(with: documentDir)
    pdfView.document = PDFDocument(data: data)


func readDataFromUrl(with url: URL) -> Data {
    // PathUrl
    let fileURL = url
    // Read
    var readData = Data()
    do {
        readData = try Data(contentsOf: fileURL)
    } catch let jsonErr {
        print("Error read file:", jsonErr)
    }
    return readData
}