首页 > 解决方案 > PDF阅读器夜间模式

问题描述

我正在使用 pdf 阅读器,但在为 PDF 文档创建夜间模式时遇到问题。我已经成功创建了具有黑色背景和白色前景的新 PDF 文档。但不能为已经创建的文档做我为新的 PDF 文档做的是

func show(text:NSAttributedString) {


       // let attributedString = NSAttributedString(string: text, attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
   // text.attribute(NSAttributedString.Key.foregroundColor, at: 0, effectiveRange: NSRange(location: 0, length: text.length))

        let printFormatter = UISimpleTextPrintFormatter(attributedText: text)
        let renderer = UIPrintPageRenderer()
        renderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)
        // A4 size
        let pageSize = CGSize(width: 595.2, height: 841.8)
        // Use this to get US Letter size instead
        // let pageSize = CGSize(width: 612, height: 792)

        // create some sensible margins
        let pageMargins = UIEdgeInsets(top: 72, left: 72, bottom: 72, right: 72)

        // calculate the printable rect from the above two
        let printableRect = CGRect(x: pageMargins.left, y: pageMargins.top, width: pageSize.width - pageMargins.left - pageMargins.right, height: pageSize.height - pageMargins.top - pageMargins.bottom)

        // and here's the overall paper rectangle
        let paperRect = CGRect(x: 0, y: 0, width: pageSize.width, height: pageSize.height)

        renderer.setValue(NSValue(cgRect: paperRect), forKey: "paperRect")
        renderer.setValue(NSValue(cgRect: printableRect), forKey: "printableRect")
        let pdfData = NSMutableData()

        UIGraphicsBeginPDFContextToData(pdfData, paperRect, nil)
        renderer.prepare(forDrawingPages: NSMakeRange(0, renderer.numberOfPages))

        let bounds = UIGraphicsGetPDFContextBounds()
        for i in 0  ..< renderer.numberOfPages {
            UIGraphicsBeginPDFPage()
            let currentContext = UIGraphicsGetCurrentContext()
            currentContext?.setFillColor(UIColor.yellow.cgColor)
            currentContext?.fill(bounds)
            renderer.drawPage(at: i, in: bounds)

        }

        UIGraphicsEndPDFContext()

        var pdfUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
        pdfUrl?.appendPathComponent("text")
        pdfUrl?.appendPathExtension("pdf")
        do {
            try pdfData.write(to: pdfUrl!)
        } catch {
            print(error.localizedDescription)
        }
    let pdfdocemrnt = PDFDocument(url: pdfUrl!)
    self.baseView.document = pdfdocemrnt!
    }

如果有人知道这个问题,请帮忙。

标签: iosswiftpdfios-pdfkit

解决方案


推荐阅读