-1

I am creating a pdf certificate using fitz python. because it contains paragraph. in the middle of paragraph I have some name age and other. I need to make it bold, how?

My code:

import fitz

def add_paragraph_to_pdf(input_pdf_path, output_pdf_path, paragraph,bold_words):

    doc = fitz.open(input_pdf_path)

    rect = fitz.Rect(70,230,550,500)

    page = doc[0]
    textbox = page.insert_textbox(rect, "")  # Create an empty textbox

    words = paragraph.split()

    for word in words:
        if word in bold_words:
            font = textbox.insert_text(word)
            font.set_font("Helvetica-Bold", size=12)
        else:
            font = textbox.insert_text(word)
            font.set_font("Helvetica", size=12)

    doc.save(output_pdf_path)
    doc.close()
    print("Paragraph with bold words added to the PDF successfully!")
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958

1 Answers1

0

Don't set font after inserting text, you have to specify it in the insert command like this:

import fitz

def add_paragraph_to_pdf(input_pdf_path, output_pdf_path, paragraph, bold_words):
    doc = fitz.open(input_pdf_path)
    rect = fitz.Rect(70, 230, 550, 500)
    page = doc[0]
    textbox = page.insert_textbox(rect, "")  # Create an empty textbox
    font = textbox.insert_text("")  # Create a font object
    
    words = paragraph.split()

    for word in words:
        if word in bold_words:
            font.insert_text(word, "Helvetica-Bold")
        else:
            font.insert_text(word, "Helvetica")
        
        font.insert_text(" ")  # Add space after each word
    
    doc.save(output_pdf_path)
    doc.close()
    print("Paragraph with bold words added to the PDF successfully!")

# Example usage
add_paragraph_to_pdf("input.pdf", "output.pdf", "This is a test paragraph with some bold words", ["test", "bold"])
Omid Roshani
  • 1,083
  • 4
  • 15
  • Thanks for the reply but i got error Traceback (most recent call last): add_paragraph_to_pdf("Certificate_Input.pdf", "output.pdf", "This is a test paragraph with some bold words", ["test", "bold"]) 43, in add_paragraph_to_pdf font = textbox.insert_text("") # Create a font object ^^^^^^^^^^^^^^^^^^^ AttributeError: 'float' object has no attribute 'insert_text – Sanjay Sujir Jul 17 '23 at 05:29