### 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