NEW: Master Swift design patterns with my latest book! >>

How to display PDFs using PDFView

Written by Paul Hudson    @twostraws

Apple’s PDFKit framework provides a huge range of code to help us work with PDFs, and one of the most useful is PDFView – it renders PDFs to the screen and lets users interact with them.

To try it out, start by importing the PDFKit framework:

import PDFKit

Next, add this code to your viewDidLoad() method to create a PDFView and make it fill all available space:

let pdfView = PDFView()

pdfView.translatesAutoresizingMaskIntoConstraints = false

pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
pdfView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor.topAnchor).isActive = true

Finally, create a URL pointing to a PDF you have in your bundle somewhere (or one in your documents directory), then create a PDFDocument object from that and pass it to the PDF view:

guard let path = Bundle.main.url(forResource: "example", withExtension: "pdf") else { return }

if let document = PDFDocument(url: path) {
    pdfView.document = document


Available from iOS 11.0 – learn more in my book Practical iOS 11

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Hacking with watchOS

Transfer your Swift skills to watchOS the easy way, and learn to build real-world apps in the process!

Click here to visit the Hacking with Swift store >>