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
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 = 0 # Index of the target page (starts at zero)
def new_content():
pdf = FPDF()
pdf.add_page()
pdf.set_font("times", "B", 30)
pdf.text(50, 150, "Hello World!")
return io.BytesIO(pdf.output())
reader = PdfReader(IN_FILEPATH)
page_overlay = PdfReader(new_content()).pages[0]
reader.pages[ON_PAGE_INDEX].merge_page(page2=page_overlay)
writer = PdfWriter()
writer.append_pages_from_reader(reader)
writer.write(OUT_FILEPATH)
Adding a page to an existing PDF¶
#!/usr/bin/env python3
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", "B", 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', 'B', 19)
pdf.text(50, 10, 'Hello World!')
reader = PdfReader(io.BytesIO(pdf.output()))