pythonpdfpymupdf

PyMuPDF add bold & italics & underline & stikrethrough text


I was looking at the PyMuPDF package and it says

enter image description here

https://pymupdf.readthedocs.io/en/latest/recipes-text.html#how-to-insert-text

However I cannot find documentation on how to do this?

My end goal is being to able text dynamically that can be bold, underline, strikethrough and italic (including a scenario where the text is bold & underline & strikethrough & italic).

Is PyMuPdf able to handle this? Edit: Yes you can see answer


Solution

  • This code that is able to bold, underline, italics, and strikethrough:

    black= (0, 0, 0)
    
    font_name = 'courier'
    
    if bold and italic:
        font_name += '-boldoblique'
    elif bold:
        font_name += '-bold'
    elif italic:
        font_name += '-oblique'
    
    # Add the text as a textbox
    page.insert_textbox(
        rect=page.rect,
        buffer=text,
        fontname=font_name,
        fontsize=12,
        align=0)
        
    # Search for the newly added text
    rl = page.search_for(text, quads=True)
    
    # add strikeout if applicable
    if strikeout:
        annot = page.add_strikeout_annot(rl[0])
        annot.set_colors(stroke=black)
        annot.update() # **Edit** - this line required to update annot.
    
    # add underline if applicable
    if underline:
        page.add_underline_annot(rl[0])
        annot.set_colors(stroke=black)
        annot.update() # **Edit** - this line required to update annot.