Some test text!

Search
Hamburger Icon

Xamarin / Guides

Convert HTML to PDF in Xamarin

This tutorial only applies to Xamarin.iOS. See Xamarin.Android equivalent here .
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:

pdftronprivate.PTConvert.ConvertHTMLStringToPDF(htmlString, baseURL, CGSize.Empty, (pathToPDF) => { 
    if (pathToPDF == null) {
        // Failed to convert HTML to PDF.
        return;
    }

    var documentDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

    var urlToPdf = new NSUrl(pathToPDF);
    var destinationURL = (new NSUrl(documentDirectory)).Append(urlToPdf.LastPathComponent, false);
    var destinationFileURL = NSUrl.CreateFileUrl(destinationURL.Path, null);

    NSError error = null;
    var result = NSFileManager.DefaultManager.Copy(urlToPdf, destinationFileURL, out 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.

Get the answers you need: Chat with us