Convert HTML to PDF on iOS
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:
PTConvert.convertHTMLString(toPDF: htmlString, baseURL: baseURL, paperSize: .zero) { (pathToPDF) in
guard let pathToPDF = pathToPDF else {
// Failed to convert HTML to PDF.
return
}
// Copy temporary PDF to persistent location.
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, false)[0]
let urlToPDF = URL(fileURLWithPath: pathToPDF)
let destinationURL = URL(fileURLWithPath: documentDirectory).appendingPathComponent(urlToPDF.lastPathComponent)
do {
try FileManager.default.copyItem(at: urlToPDF, to: destinationURL)
} catch {
// Failed to copy item to persistent location.
}
// Do something with PDF output.
}[PTConvert convertHTMLStringToPDF:htmlString baseURL:baseURL paperSize:CGSizeZero completion:^(NSString *pathToPDF) {
if (!pathToPDF) {
// Failed to convert HTML to PDF.
return;
}
NSString *documentDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO)[0];
// Copy temporary PDF to persistent location.
NSURL *urlToPDF = [NSURL fileURLWithPath:pathToPDF];
NSURL *destinationURL = [[NSURL fileURLWithPath:documentDirectory] URLByAppendingPathComponent:urlToPDF.lastPathComponent];
NSError *error = nil;
BOOL result = [NSFileManager.defaultManager copyItemAtURL:urlToPDF toURL:destinationURL error:&error];
if (!result) {
// Failed to copy PDF to persistent location.
}
// Do something with PDF output.
}];where baseURL is the URL to use as the page's base URL for resolving relative links in the document.
Last updated
Was this helpful?