HTML Files to PDF
Convert an entire HTML file into a pixel-perfect PDF with IronPDF for Python's RenderHtmlFileAsPdf
method.
Getting Started
To convert an HTML file to PDF, you can use the RenderHtmlFileAsPdf
method. This method requires only the path to the local HTML file and returns a PdfDocument
object. This object contains the content from the HTML file, rendered as if viewed in a web browser. Ensure your HTML contains valid markup to avoid rendering issues.
Here's a simple example of how to use the method:
from ironpdf import ChromePdfRenderer
# Initialize a ChromePdfRenderer object
renderer = ChromePdfRenderer()
# Path to the local HTML file you want to convert
html_file_path = "path/to/your/file.html"
# Render the HTML file as a PDF document
pdf_document = renderer.render_html_file_as_pdf(html_file_path)
# Save the resulting PDF to a file
pdf_output_path = "output.pdf"
pdf_document.save_as(pdf_output_path)
# Print success message
print(f"PDF successfully created at {pdf_output_path}")
from ironpdf import ChromePdfRenderer
# Initialize a ChromePdfRenderer object
renderer = ChromePdfRenderer()
# Path to the local HTML file you want to convert
html_file_path = "path/to/your/file.html"
# Render the HTML file as a PDF document
pdf_document = renderer.render_html_file_as_pdf(html_file_path)
# Save the resulting PDF to a file
pdf_output_path = "output.pdf"
pdf_document.save_as(pdf_output_path)
# Print success message
print(f"PDF successfully created at {pdf_output_path}")
Understanding the Code
ChromePdfRenderer: This object serves as the point of interaction with the rendering process. It allows adjustments to the PDF output by setting properties like headers, footers, and more.
render_html_file_as_pdf: This method takes a path to an HTML file and converts it into a
PdfDocument
. The generated PDF will closely match the HTML file as it appears in a web browser.- save_as: This method saves the newly created PDF document to the specified path on your file system.
Customizing the PDF Output
ChromePdfRenderer
comes with various options for customization, including setting headers, footers, margins, backgrounds, page numbers, etc. For more advanced features and customization, see this code example and learn how to customize PDF output.