Convert HTML to PDF on iOS

Internet connection is not required when converting local HTML files. However, it is required for converting HTTP/HTTPS links.

The platform-specific conversion API also supports HTML to PDF conversion, either with the +convertOfficeToPDF:paperSize:completion: method for .html files or the +convertHTMLStringToPDF:baseURL:paperSize:completion: for raw HTML text.

The following code shows how to convert an HTML string to PDF:

1PTConvert.convertHTMLString(toPDF: htmlString, baseURL: baseURL, paperSize: .zero) { (pathToPDF) in
2 guard let pathToPDF = pathToPDF else {
3 // Failed to convert HTML to PDF.
4 return
5 }
6
7 // Copy temporary PDF to persistent location.
8 let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, false)[0]
9
10 let urlToPDF = URL(fileURLWithPath: pathToPDF)
11 let destinationURL = URL(fileURLWithPath: documentDirectory).appendingPathComponent(urlToPDF.lastPathComponent)
12
13 do {
14 try FileManager.default.copyItem(at: urlToPDF, to: destinationURL)
15 } catch {
16 // Failed to copy item to persistent location.
17 }
18
19 // Do something with PDF output.
20}

where baseURL is the URL to use as the page's base URL for resolving relative links in the document.

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales