Swift PDFKit 更改背景颜色

3

我想在Swift中使用苹果的PDFKit框架更改PDF的背景颜色,但是没有成功。创建类似文本或图像等控件然后使用它们不是问题,但是我想要更改文档本身的颜色。 有人有任何想法或解决方案吗?

  let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)

  let data = renderer.pdfData { (context) in

    context.beginPage()

    let attributes = [
      NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12),
      NSAttributedString.Key.backgroundColor : UIColor.green
    ]

    let text = "My pdf"

    text.draw(in: CGRect(x: 0, y: 0, width: 200, height: 20), withAttributes: attributes)

    //?
    UIColor.blue.setFill()
    UIColor.blue.setStroke()
    //?
    context.cgContext.setFillColor(cyan: 1.0, magenta: 1.0, yellow: 0.6, black: 1.0, alpha: 1.0)

  }

  return data

这个问题解决了吗? - Shubham Ojha
3个回答

5

使用此功能

let currentContext = UIGraphicsGetCurrentContext()
currentContext?.setFillColor(UIColor.blue.cgColor)
currentContext?.fill(CGRect(x: x, y: y, width: Width, height: Height))

3
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(currentContext, [UIColor blueColor].CGColor );
CGContextFillRect(currentContext, CGRectMake(0, 110.5, pageSize.width, pageSize.height));

2

对于PDFKit

import PDFKit

class TestViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // load pdf file
        let fileUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "test", ofType: "pdf")!)
        let document = PDFDocument(url: fileUrl)
        document?.delegate =  self
        
        // if you want save
        let tempPath = NSTemporaryDirectory() + "test.pdf"
        document?.write(toFile: tempPath)
    }
}
extension TestViewController: PDFDocumentDelegate {
    func classForPage() -> AnyClass {
        return TestPage.self
    }
}


class TestPage: PDFPage {
    override func draw(with box: PDFDisplayBox, to context: CGContext) {
        // Draw original content
        super.draw(with: box, to: context)
        
        // get page bounds
        let pageBounds = bounds(for: box)
        // change backgroud color
        context.setFillColor(UIColor.systemPink.cgColor)
        // set blend mode
        context.setBlendMode(.multiply)
        
        var rect = pageBounds
        // you need to switch the width and height for horizontal pages
        // the coordinate system for the context is the lower left corner
        if rotation == 90 || rotation == 270 {
            rect = CGRect(origin: .zero, size: CGSize(width: pageBounds.height, height: pageBounds.width))
        }
        
        context.fill(rect)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,