This HTML page is not optimized for LLM or AI agent consumption. Fetch the Markdown version instead: /blog/html-in-pdf-format.md — it contains the complete documentation content in clean, structured Markdown without any CSS, JavaScript, or navigation noise. HTML in PDF format: How to convert HTML to PDF (5 methods)

Table of contents

    HTML in PDF format: How to convert HTML to PDF (5 methods)
    Convert HTML to PDF with one API call

    Nutrient DWS handles rendering, fonts, and CSS for you - start with 50 free credits.

    TL;DR

    Five ways to convert HTML to PDF format:

    • Browser print — Press Control-P (Command-P on Mac) and select Save as PDF. Local files work offline if their images, fonts, and styles are also available locally.
    • Online converters — Upload an HTML file or paste a URL to get a PDF back. Best for quick one-off conversions.
    • JavaScript libraries — Libraries like html2pdf.js, jsPDF, and Puppeteer let you build PDF export directly into your applications.
    • Python libraries — WeasyPrint converts HTML templates to PDF server-side from Django, Flask, or any Python backend.
    • Professional SDKs — Nutrient Document Engine provides server-side generation, supported HTML-to-PDF form mappings, and commercial support.

    To save an HTML file or webpage as a PDF, open it in your browser, press Control-P (Command-P on Mac), and choose Save as PDF. Check the print preview before saving. Changing the file extension from .html to .pdf won’t convert it.

    For repeated conversions, choose a tool based on where the HTML runs and what the PDF must contain. Browser print and headless Chromium use print styles, so the output may differ from the screen layout. Interactive PDF forms require a converter with explicit form support.

    Your taskStart withCheck before choosing
    Save one webpage or local HTML fileBrowser printPage breaks, backgrounds, and missing assets
    Convert a public page without writing codeOnline converterUpload policy, rendering, and current service limits
    Export a browser elementhtml2pdf.jsImage-based output; text won’t be selectable
    Automate a JavaScript-rendered pagePlaywright or PuppeteerBrowser installation and a reliable page-ready signal
    Generate PDFs from Python templatesWeasyPrintSystem dependencies and supported CSS; no JavaScript execution
    Generate documents with PDF form fieldsA form-capable converter such as Nutrient Document EngineSupported field types and deployment requirements

    Method 1: Use your browser (print to PDF)

    Your browser’s built-in print function can save a webpage or local HTML file to PDF.

    Chrome

    1. Open the HTML file or webpage in Chrome
    2. Press Control-P (Windows) or Command-P (Mac)
    3. Change Destination to Save as PDF
    4. Adjust settings (margins, scale, and background graphics)
    5. Click Save and choose a location

    Firefox

    1. Open the HTML file or webpage in Firefox
    2. Press Control-P (Windows) or Command-P (Mac)
    3. Select Microsoft Print to PDF or Save to PDF
    4. Adjust layout options as needed
    5. Click Save

    Safari

    1. Open the HTML file or webpage in Safari
    2. Press Command-P to open the print dialog
    3. Open the PDF menu
    4. Select Save as PDF
    5. Choose a location and click Save

    Edge

    1. Open the HTML file or webpage in Edge
    2. Press Control-P (Windows)
    3. Change Printer to Microsoft Print to PDF or Save as PDF
    4. Adjust settings and click Save

    Tips for better output

    • Enable Background graphics to include colors and images
    • Set Margins to None or Minimum for more content per page
    • Use Scale to fit wide content on the page
    • Remove Headers and footers for cleaner output
    ProsCons
    Free, no software neededLimited control over output
    Local assets work offlineMay break complex layouts
    Built into common browsersManual process for each page

    Method 2: Free online HTML-to-PDF converters

    Online converters handle quick conversions without installing software. Upload an HTML file or enter a URL, and the service returns a PDF.

    Check the converter’s limits

    Before uploading a file, check whether the service accepts a URL, an HTML file, or both. Confirm its current free allowance, watermark policy, asset support, and file retention policy. A service that accepts a public URL may not be able to access a page behind a login.

    When to use online converters

    Online converters make sense when you need a quick PDF and don’t want to install anything. They’re useful for one-off conversions of public webpages or simple HTML files where exact formatting isn’t critical.

    Avoid them for anything automated or sensitive, or where you need consistent results across multiple conversions.

    Limitations to consider

    • Privacy — Your HTML content is uploaded to third-party servers, which may not be suitable for confidential documents.
    • File size limits — Upload size and usage limits vary by service and plan.
    • Internet required — These tools require an active internet connection and can’t work offline.
    • Inconsistent rendering — CSS support varies significantly between tools, so complex layouts may not convert accurately.

    For sensitive documents, avoid online converters. Use browser print or local tools instead.

    Method 3: JavaScript libraries (for developers)

    Several JavaScript libraries can add PDF export to your applications. These run either client-side (in the browser) or server-side (on your backend).

    Client-side: html2pdf.js

    html2pdf.js combines html2canvas and jsPDF to convert HTML elements to PDF in the browser. Load the bundled script before this code and run it after the element with ID content exists:

    // Include via CDN.
    // <script src="https://unpkg.com/html2pdf.js@0.14.0/dist/html2pdf.bundle.min.js"></script>
    const element = document.getElementById('content');
    html2pdf().from(element).save('document.pdf');

    This works for simple documents but produces image-based PDFs with limited CSS support.

    Client-side: jsPDF

    jsPDF can create PDFs by drawing text and graphics directly. This example demonstrates that API; it doesn’t convert an HTML page. Load the UMD bundle before running it:

    // Include via CDN.
    // <script src="https://unpkg.com/jspdf@4.2.1/dist/jspdf.umd.min.js"></script>
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF();
    doc.text('Hello World', 10, 10);
    doc.save('document.pdf');

    Use this approach for structured documents like invoices when you want to specify the layout yourself.

    Server-side: Puppeteer and Playwright

    Puppeteer and Playwright automate Chromium to render HTML with browser CSS and JavaScript support. For the Playwright example, install the package and its Chromium browser:

    Terminal window
    npm install playwright
    npx playwright install chromium

    Save this as convert.cjs and run node convert.cjs to create invoice.pdf:

    const { chromium } = require('playwright');
    async function main() {
    const browser = await chromium.launch();
    try {
    const page = await browser.newPage();
    await page.setContent('<h1>Invoice</h1><p>Details here...</p>');
    await page.pdf({ path: 'invoice.pdf', format: 'A4', printBackground: true });
    } finally {
    await browser.close();
    }
    }
    main().catch((error) => {
    console.error('HTML to PDF conversion failed:', error.message);
    process.exitCode = 1;
    });

    Playwright’s PDF export(opens in a new tab) uses print CSS by default. For a live application, navigate to its URL and wait for the required content, images, and fonts before exporting. The example uses inline HTML without external assets.

    Server-side: Prince (CSS-first)

    Prince(opens in a new tab) is a commercial command-line tool that renders HTML and XML to PDF using CSS — including advanced print stylesheets, paged media, and complex CSS layouts. Unlike browser-based renderers, Prince is built specifically for print, so headers, footers, page numbers, and cross-references work without scripting:

    Terminal window
    prince input.html -o output.pdf

    It’s a good fit when your priority is precise CSS-driven print output (books, technical manuals, regulatory documents) rather than matching exactly what a browser displays.

    When to use JavaScript libraries

    • Building apps with PDF export features
    • Automated report generation
    • Custom PDF workflows in your codebase

    For a detailed comparison of JavaScript libraries, refer to our blog post on how to convert HTML to PDF with JavaScript.

    Method 4: Python libraries (for developers)

    Python has several libraries for converting HTML to PDF server-side. These integrate directly with web frameworks like Django and Flask, so you can generate PDFs from templates without spinning up a headless browser.

    WeasyPrint

    WeasyPrint(opens in a new tab) renders HTML and CSS to PDF with a layout engine designed for print. It doesn’t execute JavaScript and it requires system libraries, including Pango. CSS support differs from browsers, so test your templates and page breaks:

    from weasyprint import HTML
    # From an HTML string.
    HTML(string="<h1>Invoice</h1><p>Details here...</p>").write_pdf("invoice.pdf")
    # From a URL.
    HTML(url="https://example.com").write_pdf("page.pdf")
    # From a local file.
    HTML(filename="template.html").write_pdf("output.pdf")

    Follow the platform installation instructions(opens in a new tab) to install its system dependencies. Then install the Python package with pip install weasyprint. Use from weasyprint import HTML before calling HTML(...).write_pdf(...), as shown above.

    pdfkit (wkhtmltopdf)

    The wkhtmltopdf repository is archived and the project is no longer maintained. Don’t use pdfkit or wkhtmltopdf with untrusted HTML. For new projects, use WeasyPrint or Playwright instead.

    pdfkit(opens in a new tab) wraps the wkhtmltopdf(opens in a new tab) command-line tool, converting HTML to PDF via the QtWebKit engine. It’s still widely referenced in existing codebases but shouldn’t be used in new projects:

    import pdfkit
    # From a URL.
    pdfkit.from_url("https://example.com", "output.pdf")
    # From an HTML string.
    pdfkit.from_string("<h1>Hello</h1>", "output.pdf")
    # From a local file.
    pdfkit.from_file("template.html", "output.pdf")

    If you have an existing pdfkit dependency, the recommended migration path is WeasyPrint for Python stacks not requiring JavaScript execution, or Playwright for full browser rendering.

    When to use Python libraries

    • Flask or Django apps with PDF export features
    • Server-side report generation from HTML templates
    • Data pipelines that produce PDFs without a Node.js dependency

    For a broader comparison of Python PDF tools, see our Python PDF libraries guide.

    Method 5: Professional SDKs (for production apps)

    Both open source tools and commercial SDKs can power production workflows. Choose based on output requirements, deployment constraints, and the support your team needs.

    Why use a professional SDK?

    A commercial SDK can combine conversion with other document operations and vendor support. Test rendering and resource use with representative files for any converter. Form support isn’t exclusive to commercial products: WeasyPrint also offers PDF form generation(opens in a new tab).

    Nutrient solutions

    Nutrient offers several options for HTML-to-PDF conversion: Document Engine for server-side processing, native SDKs for mobile and desktop platforms, a cloud API for zero-infrastructure setups, and no-code integrations for automated workflows.

    Document Engine

    Document Engine is a server-side toolkit that powers document processing, rendering, and automation behind the scenes of web, mobile, and desktop apps. It handles more than just HTML-to-PDF conversion: You can use it for document viewing, generation, conversion, OCR, redaction, and real-time collaboration at scale.

    Preview templates in Chrome’s print view. Then test the generated PDF. Supply the required CSS, images, and fonts according to the HTML generation schema; JavaScript assets aren’t supported. Supported HTML form controls can become fillable PDF fields, but not every HTML input type has a PDF equivalent.

    You can run document workflows entirely on the backend, or pair Document Engine with a frontend SDK. Size the backend and limit concurrency for the documents you process. Features like form filling, annotation, and signing work through frontend and backend syncing, so users interact with documents in the browser while the server handles processing.

    Document Engine can serve applications built with .NET, Node.js, Java, iOS, Android, React Native, and Flutter. The following request requires a running Document Engine instance, an API token, and a local HTML file:

    Terminal window
    curl --fail-with-body -X POST http://localhost:5000/api/build \
    -H "Authorization: Token token=<API token>" \
    -F page.html=@/path/to/page.html \
    -F instructions='{ "parts": [{ "html": "page.html" }] }' \
    -o result.pdf

    Three deployment options:

    OptionConversion infrastructureApplication responsibilities
    Self-hosted Document EngineYou run the serverDeployment, scaling, authentication, and document handling
    Cloud APINutrient runs the serviceAPI credentials, requests, retries, and document handling
    Managed Document EngineNutrient operates the instanceIntegration, access controls, and document handling

    Self-hosted means you run the Docker container on your own servers. You control the infrastructure, updates, and scaling. This option works for air-gapped environments or when regulations require data to stay on-premises.

    Nutrient Processor API is the fastest way to get started. You send HTTP requests to Nutrient’s servers and receive PDFs back. No infrastructure to manage, and you pay based on credits consumed. The API supports multiple languages, including JavaScript, Python, Java, C#, and PHP:

    Install axios and form-data with npm install axios form-data. Save the following as convert-api.cjs, place index.html beside it, and set NUTRIENT_API_KEY in your server environment. Run node convert-api.cjs from that directory. This example uses the documented build endpoint and HTML part schema:

    const axios = require('axios');
    const FormData = require('form-data');
    const fs = require('node:fs/promises');
    async function main() {
    const apiKey = process.env.NUTRIENT_API_KEY;
    if (!apiKey) throw new Error('Set NUTRIENT_API_KEY before running this script.');
    const formData = new FormData();
    formData.append('page.html', await fs.readFile('index.html'), {
    filename: 'index.html',
    contentType: 'text/html',
    });
    formData.append('instructions', JSON.stringify({
    parts: [{ html: 'page.html' }],
    }));
    const response = await axios.post('https://api.nutrient.io/build', formData, {
    headers: formData.getHeaders({ Authorization: `Bearer ${apiKey}` }),
    responseType: 'arraybuffer',
    });
    await fs.writeFile('result.pdf', response.data);
    }
    main().catch((error) => {
    const detail = error.response?.data;
    console.error(detail ? Buffer.from(detail).toString('utf8') : error.message);
    process.exitCode = 1;
    });

    For a template with separate stylesheets, images, or fonts, upload those files and list their multipart names in the HTML part’s assets array. Keep the API key on your server.

    Managed gives you a dedicated Document Engine instance that Nutrient operates on your behalf. You get the isolation of self-hosting without the operational overhead. Check the deployment and data-handling requirements for your organization before choosing a managed service.

    .NET SDK

    The .NET SDK brings HTML-to-PDF conversion to .NET applications. It uses Chrome-based rendering for consistent output.

    The SDK integrates with C# and other .NET languages. You pass an HTML string or file path to the conversion method, and it returns a PDF document. Since it runs locally, your HTML content never leaves your servers.

    Android and iOS SDKs

    Our Android SDK and iOS SDK generate PDFs directly on mobile devices. Android uses the system WebView for rendering, while iOS uses WebKit. Local HTML can be converted without an external conversion server. Remote images, stylesheets, or fonts still require network access.

    On-device conversion keeps sensitive data on the device instead of sending it to a server. You can convert HTML strings or local HTML files (including file and content URIs on Android).

    React Native and Flutter SDKs

    Our React Native SDK and Flutter SDK provide HTML-to-PDF conversion for cross-platform mobile development. Both SDKs use native implementations under the hood (WebView on Android, WebKit on iOS), so you write one codebase that works on both platforms.

    In Flutter SDK 6, HTML generation uses the deprecated legacy method-channel API; it isn’t part of the bindings API yet. Follow the Flutter guide for the required import and platform options. The React Native SDK also provides PDF generation methods.

    Beyond conversion, Nutrient’s mobile SDKs include viewing, annotation, form filling, and digital signature features.

    Zapier and Power Automate

    Zapier integration and Power Automate connectors bring HTML-to-PDF conversion to no-code workflows. You can trigger PDF generation from events in other apps without writing any code.

    These integrations let you automate HTML-to-PDF generation as part of larger workflows — for example, generating documents from templates or form submissions. The PDF generation happens on Nutrient’s servers, and you receive the finished document in your workflow.

    What you can build with Nutrient

    Invoices — Generate branded invoices from HTML templates with dynamic data, watermarks, and automatic delivery to customers.

    Reports — Generate a PDF from a report template. Then apply supported signing or encryption operations as needed.

    Contracts — Convert HTML contracts to PDF with fillable signature fields.

    Customer exports — Let users download reports, statements, or receipts as PDFs from your web app.

    Document pipelines — Chain HTML conversion with OCR, redaction, and merging in a single API call.

    Start a free trial to evaluate rendering, form conversion, and processing with your own documents.

    HTML-to-PDF conversion methods compared

    MethodBest forMain tradeoff
    Browser printOne-off savesManual export; print layout can differ from the screen
    Online toolsOccasional public-page conversionsService limits and third-party data handling
    JavaScript librariesBrowser exports or automated Chromium renderingOutput and deployment depend on the library
    Python librariesServer-side templatesWeasyPrint needs system libraries and doesn’t execute JavaScript
    NutrientConversion combined with document workflowsCommercial licensing and product-specific deployment requirements

    Common issues when converting HTML to PDF

    IssueCauseSolution
    Formatting breaksCSS not supportedTest a renderer that supports your styles
    Images not appearingRelative pathsProvide assets using the converter’s supported paths or uploads
    CSS not renderingModern CSS unsupportedCheck the renderer’s supported CSS
    Large file sizesUncompressed imagesOptimize images before conversion
    Page breaks wrongNo CSS page rulesTest break-before and break-inside rules

    FAQ

    How do I save an HTML file as a PDF?

    Open the HTML file in any browser, press Control-P (Windows) or Command-P (Mac), select Save as PDF as the destination, and click Save. This works in Chrome, Firefox, Safari, and Edge. For better results, enable Background graphics in the print settings to preserve colors and images.

    How do I open an HTML file in PDF format?

    HTML and PDF are different file formats, so you can’t open an HTML file directly as a PDF. First, convert the HTML to PDF using one of these methods: browser print (Control-P), an online converter, or a PDF generation tool. Once converted, open the resulting PDF file in any PDF reader.

    Can I convert HTML to PDF for free?

    Yes. Use your browser’s print to PDF feature (Control-P or Command-P), or open source libraries like html2pdf.js for basic use cases. Nutrient’s Cloud API offers 50 free credits monthly for testing.

    How do I convert HTML to PDF without losing formatting?

    Use print preview to check page size, margins, backgrounds, and page breaks. Ensure the converter can access your fonts and images. Test the actual PDF: Browser layout and paginated PDF layout can differ even when both use Chromium.

    What’s the best HTML-to-PDF converter?

    For a single page, start with browser print. For automated browser content, evaluate Playwright or Puppeteer. For Python templates without JavaScript, evaluate WeasyPrint. Choose Nutrient when its document operations, form support, and deployment options fit your application.

    How do I convert HTML to PDF in JavaScript?

    Client-side: html2pdf.js or jsPDF for simple documents. Server-side: Puppeteer, Playwright, or Nutrient’s Cloud API. See our JavaScript guide for code examples.

    Can I convert HTML forms to fillable PDF forms?

    Yes, with a converter that supports PDF forms. Nutrient maps supported HTML controls to PDF fields. WeasyPrint can also generate PDF forms(opens in a new tab). Check the supported control types and test the fields in a PDF viewer.

    How do I convert HTML to PDF on mobile devices?

    On iOS and Android, you can use the browser’s share or print function for basic conversions. For in-app PDF generation, Nutrient provides native SDKs for iOS, Android, React Native, and Flutter. These SDKs generate PDFs on-device without requiring a server connection.

    How do I convert HTML to PDF in Python?

    Install WeasyPrint and its system dependencies(opens in a new tab), import HTML from weasyprint, and call HTML(filename="template.html").write_pdf("output.pdf"). It renders HTML/CSS without executing JavaScript. For a hosted service, Nutrient’s Cloud API accepts HTTP requests from Python.

    How do I convert HTML to PDF with CSS preserved?

    CSS support depends on the renderer and its print rules. Playwright and Puppeteer use Chromium; WeasyPrint uses its own print layout engine. Make fonts and images available to the converter and test pagination instead of assuming the PDF will match the screen.

    How do I convert HTML to PDF from the command line?

    Use weasyprint input.html output.pdf after installing WeasyPrint(opens in a new tab), or prince input.html -o output.pdf with Prince(opens in a new tab) installed. Prince is commercial. The older wkhtmltopdf project is archived, so evaluate maintained tools for new projects.

    Conclusion

    For one-off conversions, your browser’s print function works. For production applications that need consistent output and automated workflows, Nutrient provides self-hosted, cloud, and SDK options with Chromium-based rendering and enterprise security.

    Start your free trial to test HTML-to-PDF conversion with your own templates.

    Hulya Masharipov

    Hulya Masharipov

    Technical Writer

    Hulya is a frontend web developer and technical writer who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

    Explore related topics

    50 free credits Start converting HTML to PDF