### Install fpdf2 with PIP Source: https://github.com/py-pdf/fpdf2/blob/master/tutorial/notebook.ipynb Use this command to install the fpdf2 library before running the examples. ```bash # Installation of fpdf2 with PIP: !pip install fpdf2 ``` -------------------------------- ### Install and Launch Jupyter Notebook Source: https://github.com/py-pdf/fpdf2/blob/master/tutorial/README.md Install the Jupyter notebook package and navigate to the tutorial directory to launch the notebook server. Access the notebook via the provided URL. ```bash pip install jupyter cd tutorial/ jupyter notebook ``` -------------------------------- ### Install mistletoe Source: https://github.com/py-pdf/fpdf2/blob/master/docs/CombineWithMarkdown.md Install the mistletoe library to parse Markdown according to the CommonMark specification. ```bash pip install mistletoe ``` -------------------------------- ### Install markdown-it-py Source: https://github.com/py-pdf/fpdf2/blob/master/docs/CombineWithMarkdown.md Install the markdown-it-py library for Markdown parsing that follows the CommonMark specification. ```bash pip install markdown-it-py ``` -------------------------------- ### Install fpdf2 from Local Git Repository Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Development.md Installs the fpdf2 package in editable mode, linking the installed package to the repository location. Changes to the code will be reflected directly in the environment. ```bash pip install --editable $path/to/fpdf/repo ``` -------------------------------- ### Install and Initialize Pre-commit Hooks Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Development.md Installs the pre-commit framework and initializes the git pre-commit hooks configured for this project. These hooks run checks like pylint and black before allowing a commit. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Install mistune Source: https://github.com/py-pdf/fpdf2/blob/master/docs/CombineWithMarkdown.md Install the mistune library, a fast Markdown parser that does not strictly follow the CommonMark specification. ```bash pip install mistune ``` -------------------------------- ### Generate PDF with Pygal Chart using svglib and reportlab Source: https://github.com/py-pdf/fpdf2/blob/master/docs/SVG.md This example uses Pygal to create a bar chart, then converts the SVG output to a JPEG using svglib and reportlab, and finally embeds it into a PDF with fpdf2. Requires installation of pygal, reportlab, svglib, and lxml. ```python import io import pygal from reportlab.graphics import renderPM from svglib.svglib import SvgRenderer from fpdf import FPDF from lxml import etree # Create a Pygal bar chart bar_chart = pygal.Bar() bar_chart.title = 'Sales by Year' bar_chart.x_labels = ['2016', '2017', '2018', '2019', '2020'] bar_chart.add('Product A', [500, 750, 1000, 1250, 1500]) bar_chart.add('Product B', [750, 1000, 1250, 1500, 1750]) svg_img = bar_chart.render() # Convert the SVG chart to a JPEG image in a BytesIO object drawing = SvgRenderer('').render(etree.fromstring(svg_img)) jpg_img_bytes = renderPM.drawToString(drawing, fmt='JPG', dpi=72) img_bytesio = io.BytesIO(jpg_img_bytes) # Set the position and size of the image in the PDF x = 50 y = 50 w = 100 h = 70 # Build the PDF pdf = FPDF() pdf.add_page() pdf.image(img_bytesio, x=x, y=y, w=w, h=h) pdf.output('sales-by-year-bar-chart.pdf') ``` -------------------------------- ### Install VeraPDF Script Source: https://github.com/py-pdf/fpdf2/blob/master/test/pdf-a/README.md Execute this shell script to install VeraPDF. Ensure you are in the repository root directory. ```shell scripts/install-verapdf.sh ``` -------------------------------- ### Install fpdf2 from Development Branch Source: https://github.com/py-pdf/fpdf2/blob/master/README.md Installs the latest development version of fpdf2 directly from the master branch of its GitHub repository. ```bash pip install git+https://github.com/py-pdf/fpdf2.git@master ``` -------------------------------- ### Include Python Tutorial Example Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Tutorial.md This snippet demonstrates how to include a Python tutorial file for generating a PDF. Ensure the tutorial file exists at the specified path. ```python {% include "../tutorial/tuto7.py" %} ``` -------------------------------- ### Generate a PDF with 'Hello World' Source: https://github.com/py-pdf/fpdf2/blob/master/tutorial/notebook.ipynb Creates a basic PDF document with 'hello world' text using the FPDF class. Ensure fpdf2 is installed. ```python # Generate a PDF: from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font('helvetica', size=48) pdf.cell(text="hello world") pdf_bytes = pdf.output() ``` -------------------------------- ### Install Python-Markdown Source: https://github.com/py-pdf/fpdf2/blob/master/docs/CombineWithMarkdown.md Install the Python-Markdown library, an older but active Markdown rendering library that does not follow the CommonMark specification. ```bash pip install markdown ``` -------------------------------- ### Complete Example: Multiple Page Label Styles Source: https://github.com/py-pdf/fpdf2/blob/master/docs/PageLabels.md Demonstrates creating a document with multiple sections, each having distinct page label styles and prefixes using `add_page()`. ```python from fpdf import FPDF pdf = FPDF() # Adding front matter with lowercase Roman numerals pdf.add_page(label_style="r", label_start=1) # Starts with "i", "ii", "iii", etc. # Adding main content with decimal numbers and a prefix pdf.add_page(label_style="D", label_prefix="Chapter-", label_start=1) # "Chapter-1", "Chapter-2", etc. # Adding an appendix section with uppercase letters pdf.add_page(label_style="A", label_prefix="Appendix-", label_start=1) # "Appendix-A", "Appendix-B", etc. pdf.output("labeled_document.pdf") ``` -------------------------------- ### Create a Basic PDF/A-4 Document Source: https://github.com/py-pdf/fpdf2/blob/master/docs/pdfa.md A simple example demonstrating the creation of a PDF/A-4 document with text content and saving it to a file. Ensure the compliance level is set during initialization. ```python pdf = FPDF(enforce_compliance=DocumentCompliance.PDFA_4) pdf.add_page() pdf.set_font("Helvetica", size=12) pdf.cell(0, 10, "Modern archival PDF, PDF 2.0 based.") pdf.output("example-4.pdf") ``` -------------------------------- ### Install Rough.js Dependencies Source: https://github.com/py-pdf/fpdf2/blob/master/docs/CombineWithRoughJS.md Install the necessary Node.js packages for Rough.js and xmldom. This is a prerequisite for generating SVG graphics. ```bash npm install roughjs xmldom ``` -------------------------------- ### Install Development Dependencies and Run Static Type Checkers Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Development.md Installs fpdf2 with development dependencies and runs mypy and pyright for static type checking. These tools enforce strict typing in the CI and can be run locally before pushing changes. ```bash pip install fpdf2[dev] mypy pyright ``` -------------------------------- ### Create PDF with fpdf2 and Load into borb Source: https://github.com/py-pdf/fpdf2/blob/master/docs/CombineWithBorb.md Use fpdf2 to generate a PDF, then load its output into a borb Document for further processing. Ensure fpdf2 and borb are installed. ```python from io import BytesIO from borb.pdf.pdf import PDF from fpdf import FPDF pdf = FPDF() pdf.set_title('Initiating a borb doc from a FPDF instance') pdf.set_font('helvetica', size=12) pdf.add_page() pdf.cell(text="Hello world!") doc = PDF.loads(BytesIO(pdf.output())) print(doc.get_document_info().get_title()) ``` -------------------------------- ### Convert Markdown to PDF with mistletoe Source: https://github.com/py-pdf/fpdf2/blob/master/docs/CombineWithMarkdown.md Use mistletoe to convert Markdown to PDF. This example assumes the existence of md2pdf_mistletoe.py. ```python {% include "../tutorial/md2pdf_mistletoe.py" %} ``` -------------------------------- ### Generate PDF in Bottle Route Source: https://github.com/py-pdf/fpdf2/blob/master/docs/UsageInWebAPI.md This example shows how to serve a PDF generated by fpdf2 from a Bottle web application. It correctly sets the Content-Type, status, and content length. ```python from bottle import route, run, response from fpdf import FPDF @route('/') def hello(): pdf = FPDF() pdf.add_page() pdf.set_font("Helvetica", size=24) pdf.cell(text="hello world") pdf_bytes = bytes(pdf.output()) response.set_header('Content-Type', 'application/pdf') response.status = 200 response.content_length = len(pdf_bytes) return pdf_bytes if __name__ == '__main__': run(host='localhost', port=8080, debug=True) ``` -------------------------------- ### Include fpdf2 library Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Tutorial.md Imports the necessary FPDF class from the fpdf2 library to start creating PDF documents. ```python from fpdf import FPDF ``` -------------------------------- ### Auto-format Code with Black Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Development.md Installs the Black code formatter and formats all code within the current directory. This tool ensures consistent code style across the project. ```bash pip install black black . ``` -------------------------------- ### Build PDF with Image using FPDF Source: https://github.com/py-pdf/fpdf2/blob/master/docs/SVG.md Generates a PDF and embeds an image. Ensure necessary libraries like Pygal and Cairo are installed for chart generation if applicable. ```python pdf = FPDF() pdf.add_page() pdf.image(img_bytesio, x=x, y=y, w=w, h=h) pdf.output('browser-usage-bar-chart.pdf') ``` -------------------------------- ### Subscript, Superscript, and Fractional Numbers Example Source: https://github.com/py-pdf/fpdf2/blob/master/docs/TextStyling.md Demonstrates the use of .char_vpos to control vertical positioning for subscripts, superscripts, and fractional numbers. ```python pdf = fpdf.FPDF() pdf.add_page() pdf.set_font("Helvetica", size=20) pdf.write(text="2") pdf.char_vpos = "SUP" pdf.write(text="56") pdf.char_vpos = "LINE" pdf.write(text=" more line text") pdf.char_vpos = "SUB" pdf.write(text="(idx)") pdf.char_vpos = "LINE" pdf.write(text=" end") pdf.ln() pdf.write(text="1234 + ") pdf.char_vpos = "NOM" pdf.write(text="5") pdf.char_vpos = "LINE" pdf.write(text="/") pdf.char_vpos = "DENOM" pdf.write(text="16") pdf.char_vpos = "LINE" pdf.write(text=" + 987 = x") ``` -------------------------------- ### Advanced Table Creation with fpdf2 Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Tutorial.md Generate tables with enhanced styling, including colors, custom widths, centered titles, and adjusted line heights. This example demonstrates using TableBordersLayout to control borders. ```python from fpdf import FPDF from fpdf.enums import TableBordersLayout class PDF(FPDF): def header(self): self.set_font('helvetica', 'B', 12) self.cell(0, 10, 'Advanced Table', 0, 1, 'C') def footer(self): self.set_y(-15) self.set_font('helvetica', 'I', 8) self.cell(0, 10, f'Page {self.page_no()}', 0, 0, 'C') pdf = PDF() pdf.add_page() pdf.set_font('times', '', 12) # Data for the table data = [ ['Country', 'Capital', 'Population'], ['France', 'Paris', '2.141 million'], ['Germany', 'Berlin', '3.748 million'], ['Spain', 'Madrid', '3.223 million'], ['Italy', 'Rome', '2.873 million'], ['United Kingdom', 'London', '8.799 million'], ] # Create the table with custom styling pdf.table( data=data, borders_layout=TableBordersLayout.NO_BORDERS, row_height=10, col_widths=[40, 40, 40], line_height=5, text_align='center', title_style={'font_weight': 'bold', 'text_align': 'center'}, header_style={'font_weight': 'bold', 'text_align': 'center'}, cell_style={'text_align': 'right'}, color=(220, 220, 220), header_color=(180, 180, 180) ) pdf.output('tuto5_advanced.pdf') ``` -------------------------------- ### Display PEM Certificate Details Source: https://github.com/py-pdf/fpdf2/blob/master/test/signing/README.md Use this command to display the details of a PEM certificate. This involves two steps: first, using a Python script to get information, and second, using OpenSSL for detailed output. ```bash python $opt/endesive/examples/cert-info-pem.py demo2_ca.crt.pem 1234 ``` ```bash openssl x509 -text -dates -noout -in demo2_ca.crt.pem ``` -------------------------------- ### Serve MkDocs Documentation Locally Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Development.md To preview the documentation locally, launch a rendering server using the `mkdocs serve` command. The `--open` flag will automatically open the documentation in your default web browser. ```bash mkdocs serve --open ``` -------------------------------- ### Generate API Documentation with pdoc3 Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Development.md Use this command to launch a local rendering server for the fpdf2 API documentation. It requires specifying the output directory, the source directory for fpdf, and the template directory. ```bash pdoc --html -o public/ fpdf --template-dir docs/pdoc --http : ``` -------------------------------- ### Generate Aztec Code Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Barcodes.md Generate an Aztec Code using the `aztec_code_generator` library. Install it via `pip install aztec_code_generator`. ```python {% include "../tutorial/aztec_code.py" %} ``` -------------------------------- ### Create a WSGI Application for PDF Generation Source: https://github.com/py-pdf/fpdf2/blob/master/docs/UsageInWebAPI.md This code demonstrates how to create a basic WSGI application that serves a PDF. It sets the appropriate Content-Type and Content-Length headers. ```python from fpdf import FPDF def app(environ, start_response): pdf = FPDF() pdf.add_page() pdf.set_font("Helvetica", size=12) pdf.cell(text="Hello world!") data = bytes(pdf.output()) start_response("200 OK", [ ("Content-Type", "application/pdf"), ("Content-Length", str(len(data))) ]) return iter([data]) ``` -------------------------------- ### Generate Code 128 Barcode with python-barcode Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Barcodes.md Generate a Code 128 barcode using the `python-barcode` library. Install it via `pip install python-barcode`. ```python {% include "../tutorial/code128_barcode.py" %} ``` -------------------------------- ### Generate a Simple PDF Source: https://github.com/py-pdf/fpdf2/blob/master/docs/index.md This snippet demonstrates the basic usage of fpdf2 to create a PDF file with a "Hello world!" message. Ensure the fpdf library is imported. ```python from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font('Helvetica', size=12) pdf.cell(text="Hello world!") pdf.output("hello_world.pdf") ``` -------------------------------- ### Install uharfbuzz package Source: https://github.com/py-pdf/fpdf2/blob/master/docs/TextShaping.md Install the uharfbuzz package using pip to enable text shaping capabilities in fpdf2. This is a prerequisite for using advanced text rendering features. ```bash pip install uharfbuzz ``` -------------------------------- ### Embed manipulated images using Pillow Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Images.md Perform image manipulations with the Pillow library and embed the processed image into the PDF. Ensure Pillow is installed (`pip install Pillow`). ```python from fpdf import FPDF from PIL import Image pdf = FPDF() pdf.add_page() img = Image.open("docs/fpdf2-logo.png") img = img.crop((10, 10, 490, 490)).resize((96, 96), resample=Image.NEAREST) pdf.image(img, x=80, y=100) pdf.output("pdf-with-image.pdf") ``` -------------------------------- ### Output PDF File Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Templates.md Writes the generated PDF content to a file named 'example.pdf'. This is the final step after all content has been added and rendered. ```python pdf.output("example.pdf") ``` -------------------------------- ### Generate Reference PDF for Testing Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Development.md Use assert_pdf_equal with generate=True to create a reference PDF file for a unit test. This function relies on qpdf for standardized PDF generation. ```python def test_some_feature(tmp_path): pdf = FPDF() pdf.add_page() pdf.rect(10, 10, 60, 80) assert_pdf_equal(pdf, HERE / "some_feature.pdf", tmp_path, generate=True) ``` -------------------------------- ### Create a Simple Table Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Tables.md Demonstrates the basic usage of the table() method to create a simple table with provided data. Ensure FPDF is imported and a page is added before creating the table. ```python from fpdf import FPDF TABLE_DATA = ( ("First name", "Last name", "Age", "City"), ("Jules", "Smith", "34", "San Juan"), ("Mary", "Ramos", "45", "Orlando"), ("Carlson", "Banks", "19", "Los Angeles"), ("Lucas", "Cimon", "31", "Angers"), ) pdf = FPDF() pdf.add_page() pdf.set_font("Times", size=16) with pdf.table() as table: for data_row in TABLE_DATA: row = table.row() for datum in data_row: row.cell(datum) pdf.output('table.pdf') ``` -------------------------------- ### Convert Markdown to PDF with Python-Markdown Source: https://github.com/py-pdf/fpdf2/blob/master/docs/CombineWithMarkdown.md Use Python-Markdown to convert Markdown to PDF. This example assumes the existence of md2pdf_markdown.py. ```python {% include "../tutorial/md2pdf_markdown.py" %} ``` -------------------------------- ### Convert Markdown to PDF with mistune Source: https://github.com/py-pdf/fpdf2/blob/master/docs/CombineWithMarkdown.md Use mistune to convert Markdown to PDF. This example assumes the existence of md2pdf_mistune.py. ```python {% include "../tutorial/md2pdf_mistune.py" %} ``` -------------------------------- ### Convert Markdown to PDF with markdown-it-py Source: https://github.com/py-pdf/fpdf2/blob/master/docs/CombineWithMarkdown.md Use markdown-it-py to convert Markdown to PDF. This example assumes the existence of md2pdf_markdown_it.py. ```python {% include "../tutorial/md2pdf_markdown_it.py" %} ``` -------------------------------- ### Run Renovate Locally with Docker Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Development.md To debug Renovate issues, you can invoke it locally using Docker. Ensure you provide your GitHub OAuth token for authentication. ```bash docker run -e LOG_LEVEL=debug docker.io/renovate/renovate:41-full --dry-run --token "$GITHUB_OAUTH_TOKEN" py-pdf/fpdf2 ``` -------------------------------- ### Generate PDF as Plone Browser View Source: https://github.com/py-pdf/fpdf2/blob/master/docs/UsageInWebAPI.md This example demonstrates creating a Plone browser view to generate and serve a PDF report. It accesses context data for the report content. Ensure the ZCML registration is correctly configured for the view. ```python from Products.Five import BrowserView from fpdf import FPDF class PDFReportView(BrowserView): """Generate and serve a PDF report""" def __call__(self): # Create PDF pdf = FPDF() pdf.add_page() pdf.set_font("Helvetica", size=24) pdf.cell(text="Hello from Plone!") # Add content from the context pdf.ln(10) pdf.set_font("Helvetica", size=12) pdf.cell(text=f"Title: {self.context.Title()}") # Generate PDF bytes pdf_bytes = bytes(pdf.output()) # Set response headers self.request.response.setHeader('Content-Type', 'application/pdf') self.request.response.setHeader( 'Content-Disposition', 'attachment; filename="report.pdf"' ) self.request.response.setHeader('Content-Length', len(pdf_bytes)) return pdf_bytes ``` ```xml ``` -------------------------------- ### Create and Use a Radial Gradient Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Patterns.md Shows how to create a radial gradient and fill a circle with it. The RadialGradient class must be imported. ```python from fpdf import FPDF from fpdf.pattern import RadialGradient pdf = FPDF() pdf.add_page() # Define a radial gradient radial_grad = RadialGradient( pdf, start_circle_x=30, start_circle_y=30, start_circle_radius=0, end_circle_x=50, end_circle_y=50, end_circle_radius=25, colors=["#FFFF00", "#FF0000"], ) with pdf.use_pattern(radial_grad): # Draw a circle filled with the radial gradient pdf.circle(x=50, y=50, radius=25, style="FD") pdf.output("pattern_radial_demo.pdf") ``` -------------------------------- ### Embed Matplotlib Figure as SVG Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Maths.md Embed a Matplotlib figure saved as an SVG file into a PDF. Ensure Matplotlib and fpdf2 are installed. ```python from fpdf import FPDF import matplotlib.pyplot as plt import numpy as np plt.figure(figsize=[2, 2]) x = np.arange(0, 10, 0.00001) y = x*np.sin(2* np.pi * x) plt.plot(y) plt.savefig("figure.svg", format="svg") pdf = FPDF() pdf.add_page() pdf.image("figure.svg") pdf.output("doc-with-figure.pdf") ``` -------------------------------- ### Render FlexTemplate with Offsets, Rotation, and Scale Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Templates.md Demonstrates rendering a FlexTemplate multiple times with different offset, rotation, and scale values. Ensure FPDF and FlexTemplate are imported. ```python from fpdf import FlexTemplate, FPDF pdf = FPDF() pdf.add_page() templ = FlexTemplate(pdf, [ {"name":"box", "type":"B", "x1":0, "y1":0, "x2":50, "y2":50,}, {"name":"d1", "type":"L", "x1":0, "y1":0, "x2":50, "y2":50,}, {"name":"d2", "type":"L", "x1":0, "y1":50, "x2":50, "y2":0,}, {"name":"label", "type":"T", "x1":0, "y1":52, "x2":50, "y2":57, "text":"Label",}, ]) templ["label"] = "Offset: 50 / 50 mm" templ.render(offsetx=50, offsety=50) templ["label"] = "Offset: 50 / 120 mm" templ.render(offsetx=50, offsety=120) templ["label"] = "Offset: 120 / 50 mm, Scale: 0.5" templ.render(offsetx=120, offsety=50, scale=0.5) templ["label"] = "Offset: 120 / 120 mm, Rotate: 30°, Scale=0.5" templ.render(offsetx=120, offsety=120, rotate=30.0, scale=0.5) pdf.output("example.pdf") ``` -------------------------------- ### Verify fpdf2 Package Provenance Source: https://github.com/py-pdf/fpdf2/blob/master/docs/index.md Use pypi-attestations to verify that a fpdf2 package was published from the py-pdf/fpdf2 GitHub repository. Ensure pypi-attestations is installed. ```shell $ pip install pypi-attestations $ pypi-attestations verify pypi --repository https://github.com/py-pdf/fpdf2 https://files.pythonhosted.org/packages/eb/46/7aae9cb2584dcac217e662ab6d4670ef4e447b73d624b6210f7155322411/fpdf2-2.8.2-py2.py3-none-any.whl OK: fpdf2-2.8.2-py2.py3-none-any.whl ``` -------------------------------- ### Create and Use a Linear Gradient Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Patterns.md Demonstrates creating a linear gradient and applying it to a rectangle. Ensure the LinearGradient class is imported. ```python from fpdf import FPDF from fpdf.pattern import LinearGradient pdf = FPDF() pdf.add_page() # Define a linear gradient linear_grad = LinearGradient( pdf, from_x=10, from_y=0, to_x=100, to_y=0, colors=["#C33764", "#1D2671"] ) with pdf.use_pattern(linear_grad): # Draw a rectangle that will be filled with the gradient pdf.rect(x=10, y=10, w=100, h=20, style="FD") pdf.output("pattern_linear_demo.pdf") ``` -------------------------------- ### Convert Profile Data to Flamegraph with flameprof Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Development.md Convert a .pstats file generated by cProfile into an SVG flamegraph for visualization. Requires flameprof to be installed. ```bash pip install flameprof flameprof profile.pstats > script-flamegraph.svg ``` -------------------------------- ### Combine Jinja and write_html in fpdf2 Source: https://github.com/py-pdf/fpdf2/blob/master/docs/TemplatingWithJinja.md Use this snippet to render a Jinja HTML template and convert it to PDF using fpdf2. Ensure Jinja2 is installed. ```python from fpdf import FPDF from jinja2 import Environment template = Environment().from_string("""

{{ title | escape }}

""") title = "HTML & Jinja demo" items = [ "FIRST", "SECOND", "LAST" ] pdf = FPDF() pdf.add_page() pdf.write_html(template.render(**globals())) pdf.output("templating_with_jinja.pdf") ``` -------------------------------- ### Text Mode Example Source: https://github.com/py-pdf/fpdf2/blob/master/docs/TextStyling.md Illustrates different text modes (STROKE, CLIP) and their application using local context managers. ```python from fpdf import FPDF pdf = FPDF(orientation="landscape") pdf.add_page() pdf.set_font("Helvetica", size=100) with pdf.local_context(text_mode="STROKE", line_width=2): pdf.cell(text="Hello world") # Outside the local context, text_mode & line_width are reverted # back to their original default values pdf.ln() with pdf.local_context(text_mode="CLIP"): pdf.cell(text="CLIP text mode") for r in range(0, 250, 2): # drawing concentric circles pdf.circle(x=130-r/2, y=70-r/2, radius=r) pdf.output("text-modes.pdf") ``` -------------------------------- ### Configure Table and Column Widths Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Tables.md Shows how to set the overall table width and individual column widths. `col_widths` can be a single number for fixed width or an array of numbers representing fractions of the page width. ```python with pdf.table(width=150, col_widths=(30, 30, 10, 30)) as table: ... ``` -------------------------------- ### Render Unicode characters with mistletoe Source: https://github.com/py-pdf/fpdf2/blob/master/docs/CombineWithMarkdown.md Convert Markdown to PDF while correctly rendering Unicode characters using mistletoe. This example assumes the existence of md2pdf_mistletoe_unicode.py. ```python {% include "../tutorial/md2pdf_mistletoe_unicode.py" %} ``` -------------------------------- ### Using FlexTemplate Class Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Templates.md Illustrates the FlexTemplate class for more flexible template usage. Requires an existing FPDF instance and allows rendering templates on specific pages, resetting after each render. ```python from fpdf import FlexTemplate, FPDF pdf = FPDF() pdf.add_page() # One template for the first page fp_tmpl = FlexTemplate(pdf, elements=fp_elements) fp_tmpl["item_key_01"] = "Text 01" fp_tmpl["item_key_02"] = "Text 02" ... fp_tmpl.render() # add template items to first page # add some more non-template content to the first page pdf.polyline(point_list, fill=False, polygon=False) # second page pdf.add_page() # header for the second page h_tmpl = FlexTemplate(pdf, elements=h_elements) h_tmpl["item_key_HA"] = "Text 2A" h_tmpl["item_key_HB"] = "Text 2B" ... h_tmpl.render() # add header items to second page # footer for the second page f_tmpl = FlexTemplate(pdf, elements=f_elements) f_tmpl["item_key_FC"] = "Text 2C" f_tmpl["item_key_FD"] = "Text 2D" ... f_tmpl.render() # add footer items to second page # other content on the second page pdf.set_dash_pattern(dash=1, gap=1) pdf.line(x1, y1, x2, y2): pdf.set_dash_pattern() # third page pdf.add_page() # header for the third page, just reuse the same template instance after render() h_tmpl["item_key_HA"] = "Text 3A" h_tmpl["item_key_HB"] = "Text 3B" ... h_tmpl.render() # add header items to third page # footer for the third page f_tmpl["item_key_FC"] = "Text 3C" f_tmpl["item_key_FD"] = "Text 3D" ... f_tmpl.render() # add footer items to third page # other content on the third page pdf.rect(x, y, w, h, style=None) # possibly more pages pdf.add_page() ... ``` -------------------------------- ### Lint Code with Pylint Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Development.md Installs Pylint, a static code analyzer, and runs it on the fpdf/ and test/ directories. Pylint helps detect potential issues in the code. ```bash pip install pylint pylint fpdf/ test/ ``` -------------------------------- ### Display P12 Certificate Details Source: https://github.com/py-pdf/fpdf2/blob/master/test/signing/README.md Use this command to display the details of a P12 certificate. Ensure the path to the script and the certificate file are correct, and provide the correct password. ```bash python $opt/endesive/examples/cert-info-p12.py certs.p12 1234 ``` -------------------------------- ### Apply Compositing Operation to Paths Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Drawing.md Applies a compositing operation (DESTINATION_ATOP) to control how two paths blend. This example uses the `PaintComposite` class and `CompositingOperation` enum. ```python from fpdf import FPDF from fpdf.drawing import PaintedPath, PaintComposite from fpdf.enums import CompositingOperation from pathlib import Path pdf = FPDF() pdf.add_page() with pdf.drawing_context() as gc: blue_square = PaintedPath() blue_square.rectangle(10, 10, 50, 50) blue_square.style.fill_color = "#0000ff" red_square = PaintedPath() red_square.rectangle(35, 35, 50, 50) red_square.style.fill_color = "#ff0000" composite = PaintComposite(backdrop=red_square, source=blue_square, operation=CompositingOperation.DESTINATION_ATOP) gc.add_item(composite) pdf.output('compositing-demo.pdf') ``` -------------------------------- ### Add Launch Action to PDF Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Annotations.md Use `LaunchAction` to create an action that launches an application or opens a document. Requires FPDF and LaunchAction imports. ```python from fpdf import FPDF from fpdf.actions import LaunchAction pdf = FPDF() pdf.set_font("Helvetica", size=24) pdf.add_page() x, y, text = 80, 140, "Launch action" pdf.text(x=x, y=y, text=text) pdf.add_action( LaunchAction("another_file_in_same_directory.pdf"), x=x, y=y - pdf.font_size, w=pdf.get_string_width(text), h=pdf.font_size, ) pdf.output("launch_action.pdf") ``` -------------------------------- ### Run zizmor Locally for Static Analysis Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Development.md Use the `zizmor` tool locally to perform static analysis on your GitHub Actions workflow definition files. ```bash zizmor .github/workflows/*.yml ``` -------------------------------- ### Encrypt PDF with AES-128 and Deny All Permissions Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Encryption.md Encrypt your PDF using the AES-128 algorithm and deny all user permissions by specifying `AccessPermission.none()`. This requires the `cryptography` package to be installed. ```python from fpdf import FPDF from fpdf.enums import AccessPermission, EncryptionMethod pdf = FPDF() pdf.add_page() pdf.set_font("helvetica", size=12) pdf.cell(text="hello world") pdf.set_encryption( owner_password="123", encryption_method=EncryptionMethod.AES_128, permissions=AccessPermission.none() ) pdf.output("output.pdf") ``` -------------------------------- ### Configure Per-Page Backgrounds and Formats Source: https://github.com/py-pdf/fpdf2/blob/master/docs/PageFormatAndOrientation.md Dynamically set page backgrounds and formats within a loop. Backgrounds can be images, colors, or None to remove. Page formats can be standard or custom dimensions, changing with each page. ```python from fpdf import FPDF pdf = FPDF() pdf.set_font("Helvetica") pdf.set_page_background((252,212,255)) for i in range(9): if i == 6: pdf.set_page_background('image_path.png') pdf.add_page(format=(210 * (1 - i/10), 297 * (1 - i/10))) pdf.cell(text=str(i)) pdf.set_page_background(None) pdf.add_page(same=True) pdf.cell(text="9") pdf.output("varying_format.pdf") ``` -------------------------------- ### Using Template Class Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Templates.md Demonstrates the traditional approach to using the Template class for applying predefined elements to each page of a document. The Template class manages its own FPDF instance. ```python tmpl = Template(elements=elements) # first page and content tmpl.add_page() tmpl[item_key_01] = "Text 01" tmpl[item_key_02] = "Text 02" ... # second page and content tmpl.add_page() tmpl[item_key_01] = "Text 11" tmpl[item_key_02] = "Text 12" ... # possibly more pages ... # finalize document and write to file tmpl.render(outfile="example.pdf") ``` ```python Template["company_name"] = "Sample Company" ``` -------------------------------- ### Manage Graphics State Stack in fpdf2 Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Internals.md This example demonstrates how to manage a stack of graphics states using the GraphicsStateMixin. Use _push_local_stack() to save the current state and _pop_local_stack() to restore it. Ensure proper nesting to avoid unexpected behavior. ```python from fpdf import FPDF class PDF(FPDF): def header(self): # Enclose header content in a graphics state self._push_local_stack() self.set_font('helvetica', 'B', 16) self.cell(0, 10, 'My Header', 0, 1, 'C') # Restore graphics state self._pop_local_stack() def footer(self): # Enclose footer content in a graphics state self._push_local_stack() self.set_y(-15) self.set_font('helvetica', 'I', 8) self.cell(0, 10, f'Page {self.page_num}', 0, 0, 'C') # Restore graphics state self._pop_local_stack() doc = PDF() doc.add_page() doc.set_font('helvetica', '', 12) doc.cell(0, 10, 'This is the main content.', 0, 1) doc.output('graphics_state_example.pdf') ``` -------------------------------- ### Using Optional Content Groups (Layers) Source: https://github.com/py-pdf/fpdf2/blob/master/docs/OptionalContent.md Demonstrates how to use the `optional_content()` context manager to create layers. Content within `with pdf.optional_content(on_print=False):` will not be printed, while content within `with pdf.optional_content(on_view=False):` will not be shown on screen. Content outside these blocks is always visible. This feature requires PDF version 1.5 or higher. ```python from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font("helvetica", size=24) # Shown on screen but not printed: with pdf.optional_content(on_print=False): pdf.image("background.png", x=0, y=0, w=pdf.epw) # Printed but not shown on screen: with pdf.optional_content(on_view=False): pdf.text(20, 50, "Printed copy only") pdf.text(20, 70, "Always visible") pdf.output("optional_content.pdf") ``` -------------------------------- ### HTML Tag Styling Example Source: https://github.com/py-pdf/fpdf2/blob/master/docs/TextStyling.md Shows how to use the write_html() method to apply bold, italic, and underlined text using HTML tags. ```python pdf.write_html("""bold italic underlined all at once!""") ``` -------------------------------- ### Mirror Text Horizontally Source: https://github.com/py-pdf/fpdf2/blob/master/docs/Transformations.md Applies a horizontal mirror transformation using the `mirror()` context manager. The transformation is applied over a line defined by a starting coordinate and the direction 'EAST'. ```python x, y = 100, 100 pdf.text(x, y, text="mirror this text") with pdf.mirror((x, y), "EAST"): pdf.set_text_color(r=255, g=128, b=0) pdf.text(x, y, text="mirror this text") ```