

The PDF can be a local file or a hosted file but we will be using a local file. PDFKit The PDFKit framework allows us to display and manipulate PDF documents in our apps. By using Codable, the JSON response will be mapped automatically into the objects we have here. In this tutorial we explore two ways of opening a PDF file with Swift. In this tutorial I will show you how you can create a simple PDF viewer in SwiftUI. This class will parse the response of the Cocktail API into these classes. It’s an attributed string, so it will retain formatting from the PDF as best as it can. Going to ViewController.swift, at line 3344, this method call Sample.pdf, put it inside our PDFView (our view inside Main.storyboard), and set our pdf as a delegate. Create a new Swift file called Cocktail.swift by right clicking on the Margaritas PDFKit Group and click on New File: Call the file Cocktail.swift and click on Create. You will need to use a third-party framework like FastPdfKit or PSPDFKit, or write your own PDF parser. Select Storyboard and Swift and click on Next and then Finish. It’s used when you want to put your PDF into a PDFView, but it’s also useful when you just want to read text from the PDF: you can loop over each page in the PDF, read its attributedString property, then append it to an attributed string containing all the text from the PDF.įirst, add import PDFKit in the Swift file you’re using, then add the following example code to read out the text contents of a file: if let pdf = PDFDocument(url: yourDocumentURL) PDFKit is only available on Mac OS X, not on iOS. I went ahead and called the App Margaritas PDFKit. PDFKit comes with a built-in class called PDFDocument, which allows us to load and parse PDF documents.
#Pdfkit swift tutorial how to
How to extract text from a PDF using PDFKit
