ScreenshotNeo

BlogHow-to

How to Convert HTML Content to PDF in Xamarin.Forms

Convert HTML strings, files, URLs, and WebView content to PDF in Xamarin.Forms with platform-specific code, validation steps, troubleshooting, and migration guidance.

By the ScreenshotNeo team30 September 20268 min read

How to Convert HTML Content to PDF in Xamarin.Forms

Direct answer: Xamarin.Forms WebView displays HTML but does not provide one portable HTML-to-PDF export call. For an existing Xamarin.Forms app, define a shared conversion service and implement it separately in the Android and iOS projects, or use a conversion SDK such as Apryse that supplies platform-specific APIs. Pass the correct base URL for relative images and stylesheets, persist the generated file, and validate remote assets, JavaScript, page breaks, and behavior on both platforms.

Microsoft says Xamarin.Forms support ended May 1, 2024. If you are starting substantial new work, evaluate .NET MAUI and Microsoft’s migration guidance before investing in more Xamarin.Forms-specific code. Existing maintenance projects can still use the patterns below, but verify every SDK version, target framework, license, and platform requirement before shipping.

1. Choose an HTML-to-PDF route

Route Best fit What you implement Important checks
Native platform APIs You want fewer third-party dependencies and can maintain Android/iOS code A shared interface plus separate render/export implementations Different APIs, rendering differences, JavaScript behavior, file persistence
Commercial conversion SDK You need URL, HTML-string, local-file, or WebView inputs behind a supported API Vendor initialization, licensing, platform adapters, conversion callbacks Current Xamarin support, minimum API levels, licensing, output and failure callbacks

Apryse documents separate Xamarin.Android and Xamarin.iOS conversion paths. Its Android guide supports HTTP/HTTPS URLs, UTF-8 HTML strings, and content loaded in an Android WebView; it states that local HTML does not need internet access while HTTP/HTTPS conversion does. The guide reports completion through ConversionFinished and failures through ConversionFailed. See the Apryse Xamarin HTML-to-PDF guide.

2. Put a shared service boundary in Xamarin.Forms

The following interface is application architecture. It keeps shared code independent from platform-specific converter classes and returns a path that the caller can open, share, or upload.

public sealed class HtmlPdfInput
{
    public string Html { get; init; }
    public string SourceUrl { get; init; }
    public string BaseUrl { get; init; }
    public string LocalFilePath { get; init; }
}

public interface IHtmlToPdfService
{
    Task<string> ConvertAsync(HtmlPdfInput input, CancellationToken cancellationToken = default);
}

Register one implementation per platform with Xamarin.Forms dependency injection or DependencyService. Reject ambiguous input (for example, both Html and SourceUrl) before invoking a native converter. Return a stable file in the app’s documents/cache policy and report conversion failures with enough context for diagnostics.

3. Android with an HTML-to-PDF SDK

Apryse’s Android examples use HTML2PDF. The documented converter accepts a URL, an HTML string with a base URL, or an existing Android WebView. The guide states availability from Android API 19 and above. Adapt names and initialization to the exact SDK version you install.

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Android.Webkit;
using pdftron.PDF;
using pdftron.PDF.Convert;

public sealed class AndroidHtmlToPdfService : IHtmlToPdfService
{
    public Task<string> ConvertAsync(HtmlPdfInput input, CancellationToken cancellationToken = default)
    {
        if (input == null) throw new ArgumentNullException(nameof(input));
        if (string.IsNullOrWhiteSpace(input.Html) &&
            string.IsNullOrWhiteSpace(input.SourceUrl) &&
            string.IsNullOrWhiteSpace(input.LocalFilePath))
            throw new ArgumentException("Provide HTML, a URL, or a local file.");

        var output = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.Personal),
            "converted-" + Guid.NewGuid().ToString("N") + ".pdf");

        var tcs = new TaskCompletionSource<string>();
        HTML2PDF converter;

        if (!string.IsNullOrWhiteSpace(input.SourceUrl))
        {
            converter = new HTML2PDF(input.SourceUrl, output);
        }
        else if (!string.IsNullOrWhiteSpace(input.Html))
        {
            // BaseUrl resolves relative images, CSS, fonts, and links.
            converter = HTML2PDF.FromHTMLDocument(
                input.BaseUrl ?? "file:///android_asset/", input.Html);
        }
        else
        {
            converter = new HTML2PDF(input.LocalFilePath, output);
        }

        converter.ConversionFinished += (sender, args) =>
        {
            try
            {
                // PdfOutput is provided by the converter on successful completion.
                args.PdfOutput.Save(output);
                tcs.TrySetResult(output);
            }
            catch (Exception ex) { tcs.TrySetException(ex); }
        };
        converter.ConversionFailed += (sender, args) =>
            tcs.TrySetException(new InvalidOperationException("HTML conversion failed."));

        converter.Convert();
        return tcs.Task;
    }
}

// For already-rendered WebView content, the documented route is:
// var converter = new HTML2PDF(webView);
// converter.DoHtml2Pdf();

Do not assume that displaying a page in WebView automatically creates a PDF. WebView is a display component. Android’s documentation also notes that JavaScript is disabled by default; enable it only when the page requires scripts and your app’s security model permits it.

4. iOS with an HTML-to-PDF SDK

Apryse documents iOS conversion for HTML files and raw HTML strings. Its raw-string API accepts a baseURL, which resolves relative resources. The completion callback supplies a generated path; copy that file to the app’s documents directory before returning it to shared code.

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Foundation;
using UIKit;
using pdftron.PDF;

public sealed class IosHtmlToPdfService : IHtmlToPdfService
{
    public Task<string> ConvertAsync(HtmlPdfInput input, CancellationToken cancellationToken = default)
    {
        if (input == null) throw new ArgumentNullException(nameof(input));
        if (string.IsNullOrWhiteSpace(input.Html) && string.IsNullOrWhiteSpace(input.LocalFilePath))
            throw new ArgumentException("Provide HTML or a local file.");

        var tcs = new TaskCompletionSource<string>();
        var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var destination = Path.Combine(documents, "converted-" + Guid.NewGuid().ToString("N") + ".pdf");

        if (!string.IsNullOrWhiteSpace(input.Html))
        {
            var baseUrl = new NSUrl(input.BaseUrl ?? "about:blank");
            PTDocumentConvertor.ConvertHTMLStringToPDF(
                input.Html, baseUrl, PTSize.PTSizeLetter,
                generatedPath =>
                {
                    try
                    {
                        if (string.IsNullOrEmpty(generatedPath))
                            throw new InvalidOperationException("Converter returned no PDF path.");
                        File.Copy(generatedPath, destination, true);
                        tcs.TrySetResult(destination);
                    }
                    catch (Exception ex) { tcs.TrySetException(ex); }
                });
        }
        else
        {
            PTDocumentConvertor.ConvertOfficeToPDF(
                input.LocalFilePath, PTSize.PTSizeLetter,
                generatedPath =>
                {
                    try
                    {
                        if (string.IsNullOrEmpty(generatedPath))
                            throw new InvalidOperationException("Converter returned no PDF path.");
                        File.Copy(generatedPath, destination, true);
                        tcs.TrySetResult(destination);
                    }
                    catch (Exception ex) { tcs.TrySetException(ex); }
                });
        }

        return tcs.Task;
    }
}

Use the exact method signatures exposed by your installed Apryse binding; the documented iOS guide shows the concepts as convertHTMLStringToPDF:baseURL:paperSize:completion: and convertOfficeToPDF:paperSize:completion:. The sample above illustrates the Xamarin service boundary and output-copying pattern, not a guarantee that every binding uses these C# names.

5. Handle each input type correctly

HTML string

Encode the string as UTF-8. Supply a meaningful base URL when markup contains relative references such as <img src="images/logo.png"> or @import url("styles/site.css"). Without it, those assets may disappear or resolve against the wrong location.

Local HTML file

Use a file URL or the SDK’s file conversion method. Bundle CSS, images, and fonts in a predictable directory. Local conversion can work without internet access, but remote assets referenced by the document still require network access.

HTTP or HTTPS URL

Confirm the device can reach the URL, TLS certificates are trusted, authentication is available, and the page has finished loading before conversion. Redirects, bot checks, login screens, and script-generated content can change the resulting PDF.

Already-loaded WebView

Wait for navigation completion and any application-specific readiness signal. A WebView can show content while images, fonts, or JavaScript requests are still pending. Use the SDK’s WebView conversion constructor where supported.

6. Rendering and validation checklist

  • Check every relative image, stylesheet, font, and link with the intended base URL.
  • Decide whether JavaScript is required; Android WebView disables it by default.
  • Test authenticated pages, redirects, CSP, mixed content, and offline behavior.
  • Inspect page breaks, long tables, fixed headers, background colors, SVGs, and print CSS.
  • Confirm the PDF is fully written before opening or sharing it.
  • Use a unique output name and clean temporary files after upload or sharing.
  • Validate both Android and iOS outputs because native renderers may differ.
  • Test large documents for memory pressure and cancellation behavior.

7. Troubleshooting

Symptom Likely cause Fix
Images or CSS are missing No base URL or incorrect relative paths Pass the directory or HTTPS origin that resolves every relative asset.
Blank or partially rendered PDF Conversion started before navigation, scripts, or fonts completed Wait for navigation and an app-level ready signal; avoid arbitrary short delays.
Remote URL fails only on device DNS, TLS, authentication, redirect, or network permission issue Open the URL in the device WebView, inspect the final URL, and verify credentials and certificates.
JavaScript content is absent WebView scripting is disabled or the converter does not execute scripts Enable JavaScript when required and permitted, or render a server-produced HTML snapshot.
PDF path is null or cannot be opened Conversion failed or generated file was temporary Handle the failure callback, check for a non-empty path, then copy into app documents before use.
App freezes during export Conversion or file I/O runs on the UI thread Use asynchronous callbacks/tasks and marshal only final UI updates to the main thread.
Android and iOS layouts differ Different engines, fonts, print CSS, or default margins Bundle fonts, define print styles, set explicit dimensions, and review each platform’s output.
Large reports crash High memory use from DOM, images, or concurrent conversions Reduce image size, process one job at a time, dispose WebViews/documents, and cancel safely.

8. Performance, reliability, and cost considerations

Conversion time depends on document size, JavaScript, remote assets, image decoding, and device resources. Measure on representative low-memory devices instead of assuming desktop timing. Cache stable source data, avoid converting the same document concurrently, and record conversion duration and failure reason. Retry only transient network failures; do not blindly retry malformed HTML or authentication errors.

Native APIs avoid a service request cost but increase platform maintenance. A commercial SDK introduces licensing and compatibility costs; verify the current Xamarin.Forms support statement, Android API floor, iOS targets, and redistribution terms with the vendor. The cited sources do not establish comparative speed, reliability, or pricing.

9. Or skip the browser setup

If your requirement is a clean screenshot or PDF of a web URL rather than in-app HTML rendering, ScreenshotNeo provides a single HTTP request. Its capture API accepts URL, viewport, full-page, PDF, waiting, blocking, headers, cookies, user-agent, timezone, geolocation, custom CSS/JavaScript, and other options; see the ScreenshotNeo documentation.

A capture pipeline can remove distracting consent and overlay elements before producing an asset.
A capture pipeline can remove distracting consent and overlay elements before producing an asset.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners, popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are never billed, and the response identifies the page verdict and billing status. An MCP server lets AI agents take screenshots, inspect pages, and capture PDFs. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

10. Xamarin.Forms lifecycle and migration

Microsoft’s Xamarin.Forms lifecycle page states: “Support for Xamarin.Forms ended May 1, 2024.” Microsoft describes .NET MAUI as its evolution and points to the upgrade assistant. For a maintained application, isolate PDF conversion behind the service interface now; that makes replacing Xamarin platform projects or the converter easier during migration.

FAQ

Can Xamarin.Forms WebView export a PDF by itself?

No. It renders HTML. Use a platform PDF API or a conversion SDK.

Does local HTML require internet access?

The Apryse Android guide says local HTML conversion does not; remote assets referenced by that HTML still need access.

Why is a base URL necessary?

It tells the converter where to resolve relative images, stylesheets, fonts, and links.

Can I use the same converter call on Android and iOS?

The cited Apryse documentation provides separate platform APIs. Keep a shared app interface, but implement each platform separately.

Should a new app still use Xamarin.Forms?

Plan around .NET MAUI or another supported target because Xamarin.Forms support ended May 1, 2024.

When is ScreenshotNeo a better fit?

Use it when the source is a web URL and you want an API or MCP workflow instead of maintaining mobile WebView and PDF conversion code.