How to create a PDF page with Transparent background?

228 views Asked by At

Here's the sample code used to create PDF data and then save it to the documents directory: Here the "self" is nothing but UIView

self.isOpaque = false
self.backgroundColor = UIColor.clear
let pdfPageFrame = self.bounds
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
UIGraphicsBeginPDFPageWithInfo(pdfPageFrame, nil)
let pdfContext = UIGraphicsGetCurrentContext()!
pdfContext.setFillColor(UIColor.clear.cgColor)
pdfContext.setAlpha(0)
self.layer.opacity = 0
self.layer.render(in: pdfContext)
UIGraphicsEndPDFContext()
return pdfData

When I save the PDFData, it result's in white background.

I want to use this pdf in PDFkit, not in image view or button. Two issues:

  1. How to generate a pdf with transparent background.
  2. How to ensure this transparency stays when I use it in pdfkit.
1

There are 1 answers

1
K J On

Most pdf viewers will use white background, even for transparent areas, Why do you think that may be (unlike in sci-fi movies our displays are solid 3 colours, with no holographic transparency)? However NO transparency is one requirement for PDF/A (archival) compatibility.

Note that PDFKit.org and many other JS Writers output in PDF editors will usually indicate the transparency, by simulation of a checked background. You can as user do that in Adobe Reader.

However, the convention for PDF display is a white background as shown in the Adobe Acrobat powered view in a browser extension (below), or in any standard PDF display such as top right.

The UIView class is a concrete class that you can instantiate and use to display a fixed background color.

Here is a supposed iOS PDFKit sample, however it is signed written by Adobe products

enter image description here