Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python HTML to PDF libraries render a web page or an HTML string as a PDF document. A dedicated renderer lays out HTML and CSS itself rather than printing the page from a headless browser. These libraries let apps generate invoices, reports, and receipts from the same templates they show on the web.
Popularity
PyMuPDF has the most monthly downloads in this comparison, at 168.7M, a count that covers all its PDF work.
import pymupdf
HTML = """
<p style="font-family: sans-serif;color: blue">Hello World!</p>
"""
MEDIABOX = pymupdf.paper_rect("letter") # output page format: Letter
WHERE = MEDIABOX + (36, 36, -36, -36) # leave borders of 0.5 inches
story = pymupdf.Story(html=HTML) # create story from HTML
writer = pymupdf.DocumentWriter("output.pdf") # create the writer
more = 1 # will indicate end of input once it is set to 0
while more: # loop outputting the story
device = writer.begin_page(MEDIABOX) # make new page
more, _ = story.place(WHERE) # layout into allowed rectangle
story.draw(device) # write on page
writer.end_page() # finish page
writer.close() # close output file
async def export_pdf(self, page: Page) -> bytes:
"""
Exports the current page as a PDF.
Args:
page (Page): The Playwright page object
Returns:
bytes: The PDF data
"""
pdf_data = await page.pdf(print_background=True)
return pdf_data
WeasyPrint
Turns HTML pages into PDF documents.
Downloads / mo
44.5M
Stars
9.8K
Last release
70.0
License
BSD-3-Clause
Strengths
Supports paged print styles.Use CSS page rules, margins, and page counters for print layouts.
Renders HTML without browser automation.Generate PDFs with WeasyPrint’s own layout engine.
Limitations
JavaScript content needs another renderer.Render script-generated content before passing HTML to WeasyPrint.
Relative assets need a base.Set base_url for relative image and stylesheet paths in HTML strings.
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/web-form.html")
@logger.catch
def _enrich_full_page_pdf(self, sb: SB, to_enrich: Metadata):
"""
Enriches the full page PDF of the Metadata object.
This method is called by the enrich method.
"""
result = sb.driver.execute_cdp_cmd("Page.printToPDF", {"printBackground": True, "landscape": False})
pdf_data = base64.b64decode(result["data"])
pdf_filename = os.path.join(self.tmp_dir, f"pdf{random_str(6)}.pdf")
with open(pdf_filename, "wb") as f:
f.write(pdf_data)
to_enrich.add_media(Media(filename=pdf_filename), id="pdf")
PDFKit
Converts HTML to PDF through wkhtmltopdf and its WebKit rendering engine.
def md_to_pdf(self, jarvis):
jarvis.say('')
jarvis.say('This option will help you convert Markdown files to PDF')
while True:
md_file = jarvis.input('Enter the full path of the Markdown file (or type "quit" to exit): ').strip()
if md_file.lower() in ['q', 'quit', 'exit']:
jarvis.say("Goodbye!", Fore.CYAN)
break
if not os.path.isfile(md_file):
jarvis.say('The file does not exist. Please try again.', Fore.RED)
continue
if not md_file.lower().endswith('.md'):
jarvis.say('The file must be a Markdown (.md) file.', Fore.RED)
continue
try:
with open(md_file, 'r', encoding='utf-8') as f:
md_content = f.read()
# Convert Markdown to HTML html_content = markdown.markdown(md_content, extensions=['fenced_code', 'tables', 'toc'])
# Process HTML to convert relative image paths to absolute paths html_content = self.convert_image_paths(html_content, os.path.dirname(os.path.abspath(md_file)))
pdf_file = os.path.splitext(md_file)[0] + '.pdf'
options = {
'enable-local-file-access': None,
}
config = pdfkit.configuration()
# Convert HTML to PDF pdfkit.from_string(html_content, pdf_file, options=options, configuration=config)
jarvis.say(f"Converted '{md_file}' to '{pdf_file}'.", Fore.GREEN)
except Exception as e:
jarvis.say(f"An error occurred: {e}", Fore.RED)
break
def add_download_pdf(
name, text, button_text="Download PDF", is_markdown=True, disabled=False
):
if not name.endswith(".pdf"):
name += ".pdf"
# Convert text to HTML if it's in Markdown format text = markdown2.markdown(text) if is_markdown else text
text = f"<style>{style_pdf}</style> \n\n {text} <hr>{text_label}"
# Generate PDF from HTML string config_pdf = config_pdfkit()
with st.spinner("Preparing PDF download..."):
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_file:
pdfkit.from_string(
text, temp_file.name, options=pdfkit_options, configuration=config_pdf
)
# Provide download button for the generated PDF with open(temp_file.name, "rb") as f:
st.download_button(
button_text,
f,
file_name=name,
mime="application/pdf",
disabled=disabled,
)
xhtml2pdf
Converts HTML and CSS into PDF documents through Python.
Downloads / mo
4.3M
Stars
2.4K
Last release
0.2.28
License
Apache-2.0
Strengths
Defines reusable page frames.Place fixed headers and footers in static frames.
Writes PDF into memory.Write PDF data into a BytesIO destination.
Limitations
Table rows split at boundaries.Split long content across rows when a cell exceeds its page space.
import io
from xhtml2pdf import pisa
output = io.BytesIO()
pisa.CreatePDF(
"<html><body><p>To PDF or not to PDF</p></body></html>", # page data
dest=output, # destination "file"
)
# You can get the PDF file bytes with `.getbuffer()`print(len(output.getbuffer()))
from seleniumbase import sb_cdp
sb = sb_cdp.Chrome(fast=True)
sb.goto("https://hn.algolia.com/?query=seleniumbase")
elements = sb.find_elements("div.Story_title > a")
for element in elements:
print("--> " + element.text)
sb.save_as_pdf("sb_news.pdf", folder="./downloaded_files/")
print("*** PDF saved to: ./downloaded_files/sb_news.pdf")
pyppeteer
Automates headless Chrome or Chromium through an unofficial port of Puppeteer.
async def main(temp_file):
"""Run main pyppeteer script."""
args = ["--no-sandbox"] if self.disable_sandbox else []
browser = await self._check_launch_reqs()(
handleSIGINT=False, handleSIGTERM=False, handleSIGHUP=False, args=args
)
page = await browser.newPage()
await page.emulateMedia("print")
await page.waitFor(100)
await page.goto(f"file://{temp_file.name}", waitUntil="networkidle0")
await page.waitFor(100)
pdf_params = {"printBackground": True}
if not self.paginate:
# Floating point precision errors cause the printed # PDF from spilling over a new page by a pixel fraction. dimensions = await page.evaluate(
"""() => {
const rect = document.body.getBoundingClientRect();
return {
width: Math.ceil(rect.width) + 1,
height: Math.ceil(rect.height) + 1,
}
}"""
)
width = dimensions["width"]
height = dimensions["height"]
# 200 inches is the maximum size for Adobe Acrobat Reader. pdf_params.update(
{
"width": min(width, 200 * 72),
"height": min(height, 200 * 72),
}
)
pdf_data = await page.pdf(pdf_params)
await browser.close()
return pdf_data
FAQ
WeasyPrint suits invoices, reports, and other documents styled with print CSS. Playwright suits pages that need JavaScript to render. xhtml2pdf suits basic layouts converted without a browser.
WeasyPrint turns HTML and CSS into PDF documents with print features such as page sizes, headers, and footers. It does not execute JavaScript.
Open the page in headless Chromium with Playwright and call page.pdf. The call supports print CSS, backgrounds, page sizes, and headers and footers.
WeasyPrint is a maintained HTML and CSS renderer for paged documents. wkhtmltopdf, which PDFKit wraps, carries a deprecation warning along with PDFKit itself.
For coding agents
Found your HTML to PDF library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.