Search code examples
pythonpdffontsaddition

How can I add custom font to an existing PDF file?


I have a font file "myfont.otf". And I have a pdf file "target.pdf". I want to add the font file to the pdf file. I try to ask chatgpt.

The code is as follows:

from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from fpdf import FPDF
from reportlab.lib.pagesizes import letter

packet = io.BytesIO()
pdf = FPDF()
pdf.add_page()

pdf.add_font('myfont', '', 'myfont.otf', uni=True)

pdf.set_font('myfont', '', 12)

pdf.text(10, 10, "Hello, world!")

pdf.output(packet, 'F')
packet.seek(0)

new_pdf = PdfFileReader(packet)

existing_pdf = PdfFileReader(open("target.pdf", "rb"))
output = PdfFileWriter()

page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)

outputStream = open("new_target.pdf", "wb")
output.write(outputStream)
outputStream.close()

But this code does not work correctly.

I am using the latest version of pypdf, and fpdf2.


Solution

  • How to add a custom font to a PDF using PyMuPDF.

    import fitz  # PyMuDPDF
    myfont = "myfont.otf"
    
    doc = fitz.open("input.pdf")
    page = doc[pno]  # load page with number pno (0-based)
    page.insert_font(fontname="F0", fontfile=myfont)
    
    # now start inserting text on the page. Use insertion point (100,100) at first
    page.insert_text((100,100), "Hello world", fontname="F0", fontsize=14, ...)
    
    # some text in a box
    rect = fitz.Rect(100, 120, 300, 200)  # a rectangle
    page.insert_textbox(rect, "this is text in a rectangle with auto line breaks",
        fontname="F0", ...)
    # etc.
    
    # Before saving, optionally build a subset of myfont:
    doc.subset_fonts()
    doc.save("output.pdf", garbage=4, deflate=True)