Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python PDF generation libraries create PDF documents from code, templates, or HTML. An HTML renderer lays out each page from markup and CSS rather than from drawing commands at fixed coordinates. These libraries let apps generate invoices, reports, and certificates as PDF files.
Popularity
PyMuPDF has the most monthly downloads in this comparison, at 168.7M, a count that covers all its PDF work.
def showtable(self, ident, widths=None):
"""
Displays a table.
Parameters:
- ident: The identifier of the table.
- widths: The widths of the columns (optional).
"""
if self.table_ident == ident:
self._spacer()
tbl = Table(self.table_data, colWidths=widths, repeatRows=1)
tbl.setStyle(self.table_style)
self.contents.append(tbl)
self.table_ident = None
# Optional notes if data in columns truncated if len(self.note_data) > 0:
notes = ["<br/><u>Notes</u>"]
i = 1
for d in self.note_data:
notes.append(str(i) + ". " + d)
i += 1
self.paragraph("<br/>".join(notes))
self.note_data = []
self._spacer()
def render(self, output_path: Path) -> None:
"""Render page to PDF file.
Args:
output_path: Output PDF file path
"""
# Create PDF with custom page size pdf = FPDF(
unit="pt",
format=(
self.coord_transform.page_width_pt,
self.coord_transform.page_height_pt,
),
)
pdf.set_auto_page_break(auto=False)
# Enable text shaping for complex scripts pdf.set_text_shaping(True)
# Disable cell margin to ensure precise text positioning # fpdf2's cell() adds c_margin padding by default, which shifts text pdf.c_margin = 0
# Set text mode for invisible text if self.invisible_text:
pdf.text_mode = TextMode.INVISIBLE
else:
pdf.text_mode = TextMode.FILL
# Render content to PDF self.render_to_pdf(pdf)
# Write PDF pdf.output(str(output_path))
pdfkit
Converts HTML to PDF through wkhtmltopdf and the 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,
)
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 pathlib import Path
from borb.pdf import Document, Page, PageLayout, SingleColumnLayout, Paragraph, PDF
d: Document = Document()
p: Page = Page()
d.append_page(p)
l: PageLayout = SingleColumnLayout(p)
l.append_layout_element(Paragraph('Hello World!'))
PDF.write(what=d, where_to="assets/output.pdf")
FAQ
ReportLab suits reports with flowing layouts, tables, and page templates. WeasyPrint suits documents written as HTML and CSS. fpdf2 suits pages built from text, tables, and images in Python.
PyMuPDF creates, converts, and edits PDF documents and lays out HTML and CSS through its Story feature. It also extracts and analyzes content from existing PDFs.
WeasyPrint renders HTML and CSS to PDF, including paged media layout. It relies on system libraries for rendering.
ReportLab draws PDF pages on a canvas and builds flowing reports with tables, page templates, and styles through its Platypus layer.
xhtml2pdf generates PDF from HTML and CSS on top of ReportLab. It supports a documented subset of markup and styles rather than full browser CSS.
For coding agents
Found your PDF generation 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.