Combine with pypdf¶
fpdf2
cannot parse existing PDF files.
However, other Python libraries can be combined with fpdf2
in order to add new content to existing PDF files.
This page provides several examples of doing so using pypdf
, an actively-maintained library formerly known as PyPDF2
.
Adding content onto an existing PDF page¶
In this code snippet, new content will be added on top of existing content:
#!/usr/bin/env python3
# USAGE: ./add_on_page_with_pypdf.py src_file.pdf dest_file.pdf
import io, sys
from contextlib import contextmanager
# Before 2.8.2 use: from fpdf.util import get_scale_factor
from fpdf import FPDF, get_scale_factor
from pypdf import PdfReader, PdfWriter
IN_FILEPATH = sys.argv[1]
OUT_FILEPATH = sys.argv[2]
ON_PAGE_INDEX = 0 # Index of the target page (starts at zero)
@contextmanager
def add_to_page(reader_page, unit="mm"):
k = get_scale_factor(unit)
format = (reader_page.mediabox[2] / k, reader_page.mediabox[3] / k)
pdf = FPDF(format=format, unit=unit)
pdf.add_page()
yield pdf
page_overlay = PdfReader(io.BytesIO(pdf.output())).pages[0]
reader_page.merge_page(page2=page_overlay)
reader = PdfReader(IN_FILEPATH)
with add_to_page(reader.pages[0]) as pdf:
pdf.set_font("times", style="B", size=30)
pdf.text(50, 150, "Hello World!")
writer = PdfWriter()
writer.append_pages_from_reader(reader)
writer.write(OUT_FILEPATH)
Adding a page to an existing PDF¶
#!/usr/bin/env python3
# USAGE: ./add_new_page_with_pypdf.py src_file.pdf dest_file.pdf
import io, sys
from fpdf import FPDF
from pypdf import PdfReader, PdfWriter
IN_FILEPATH = sys.argv[1]
OUT_FILEPATH = sys.argv[2]
ON_PAGE_INDEX = 2 # Index at which the page will be inserted (starts at zero)
def build_page():
pdf = FPDF()
pdf.add_page()
pdf.set_font("times", style="B", size=19)
pdf.text(50, 10, "Hello World!")
return io.BytesIO(pdf.output())
writer = PdfWriter(clone_from=IN_FILEPATH)
new_page = PdfReader(build_page()).pages[0]
writer.insert_page(new_page, index=ON_PAGE_INDEX)
writer.write(OUT_FILEPATH)
Altering with pypdf a document generated with fpdf2¶
A document created with fpdf2
can the be edited with pypdf
by passing its .output()
to a pypdf.PdfReader
:
import io
from fpdf import FPDF
from pypdf import PdfReader
pdf = FPDF()
pdf.add_page()
pdf.set_font('times', style='B', size=19)
pdf.text(50, 10, 'Hello World!')
reader = PdfReader(io.BytesIO(pdf.output()))