In the article, I will discuss about the PDFKit framework and how we use PDFView in our swift project.
The PDFKit is a framework available in AppKit since iOS 11.0 and macOS 10.4. Please click here to read more about PDFKit.
PDFView is mainly used to show the pdf file in our application and also it allows users to set zoom level, select content, navigate through a document, and copy the textual content to the Pasteboard, and also keeps track of page history.
Declaration
iOS, Mac Catalyst
1 |
class PDFView : UIView |
macOS
1 |
class PDFView : NSView |
Getting Started
Swift version: 5
iOS version: 13
Xcode: 11.3
First Create a project from Xcode.
File ▸ New ▸ Project…. Choose the iOS ▸ Application ▸ Single View App template and create a new project.
Then, we will create an object of PDFView and we will add this view inside the super view.
1 2 3 |
let pdfView = PDFView(frame: self.view.bounds) pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.view.addSubview(pdfView) |
Now we load a pdf file from the app bundle.
1 2 |
let fileURL = Bundle.main.url(forResource: "Demo", withExtension: "pdf") pdfView.document = PDFDocument(url: fileURL!) |
We can Fit content in the pdfview set autoScales true
1 |
pdfView.autoScales = true |
Now run code and it will display Demo.pdf file in our app.
Now we will add a watermark in the PDFView.
First we have to initializes a PDFDocument instance and sets its delegate to self.
1 2 3 |
let document = PDFDocument(url: fileURL!) document?.delegate = self pdfView.document = document |
Now, the delegate, of type PDFDocumentDelegate, implements a classForPage() method.
1 2 3 |
func classForPage() -> AnyClass { return WatermarkPage.self } |
Now, implement WatermarkPage class and draw the watermark.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class WatermarkPage : PDFPage{ override func draw(with box: PDFDisplayBox, to context: CGContext) { // Draw original content super.draw(with: box, to: context) // Draw rotated overlay string UIGraphicsPushContext(context) context.saveGState() let pageBounds = self.bounds(for: box) context.translateBy(x: 0.0, y: pageBounds.size.height) context.scaleBy(x: 1.0, y: -1.0) context.rotate(by: CGFloat.pi / 4.0) let string: NSString = "U s e r 3 1 4 1 5 9" let attributes: [NSAttributedString.Key: Any] = [ NSAttributedString.Key.foregroundColor: colorLiteral(red: 0.4980392157, green: 0.4980392157, blue: 0.4980392157, alpha: 0.5), NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 64) ] string.draw(at: CGPoint(x: 250, y: 40), withAttributes: attributes) context.restoreGState() UIGraphicsPopContext() } } |
I hope this article helps you to display the pdf file in the project.