3

I'd like to change the background color of a pdf with apples PDFKit framework in Swift, but it doesn't work. It's not a problem to create some controls like a text or image and then use it but I want to change the color of the document itself. Does anyone have any idea or solution?

  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
Asperi
  • 228,894
  • 20
  • 464
  • 690
Niels
  • 375
  • 5
  • 15

3 Answers3

5

Use this

let currentContext = UIGraphicsGetCurrentContext()
currentContext?.setFillColor(UIColor.blue.cgColor)
currentContext?.fill(CGRect(x: x, y: y, width: Width, height: Height))
vrat2801
  • 538
  • 2
  • 13
3
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(currentContext, [UIColor blueColor].CGColor );
CGContextFillRect(currentContext, CGRectMake(0, 110.5, pageSize.width, pageSize.height));
2

for 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)
    }
}
TW520
  • 86
  • 6