Converting HTML to PDF
HTML content can render differently across browsers, devices, and viewport sizes. Converting HTML to PDF gives you a fixed output format for sharing, archiving, and printing.
Use this workflow to:
- Preserve layout and styling in a stable document format
- Distribute web content for offline access
- Archive rendered pages for audit or compliance workflows
How Nutrient supports this workflow
Nutrient Python SDK converts HTML to PDF through a single API call. Nutrient renders the HTML through Chrome, so the PDF preserves the page layout, fonts, images, and styling.
HTML-to-PDF conversion on Linux relies on Chrome for rendering. If you run this workflow in Docker on Linux, make sure the container includes Chrome and runs as a non-root user. For the packaged Docker setup, refer to the running Chrome-based conversions in Docker guide.
You don’t need to handle:
- HTML parsing and layout
- Rendering fonts, images, and CSS styling
- Page sizing and pagination
Use the SDK API to handle the conversion in your application.
Complete implementation
The following example converts a local input.html file to PDF.
Import the required Nutrient classes:
from nutrient_sdk import Documentfrom nutrient_sdk import NutrientExceptionThen open the HTML file with a Python context manager(opens in a new tab). The context manager closes the document automatically:
def main(): try: with Document.open("input.html") as document:Export the file to PDF and handle conversion errors with NutrientException:
document.export_as_pdf("output.pdf") print("Successfully converted to output.pdf") except NutrientException as e: print(f"Error: {e}")
if __name__ == "__main__": main()Summary
The conversion has two steps:
- Open the HTML file.
- Export it as PDF.
Nutrient renders the HTML through Chrome and writes the result to output.pdf, so you don’t need to implement format-specific rendering logic.
To run the example locally, download the sample package.