pdf-annotate
pdf-annotate copied to clipboard
Can we add text on the PDF?
I want to add a text on the PDF at a particular location. Is it possible using pdf-annotate?
Yes, we do this currently @hyangda any chance you can help, since you did this most recently.
Hi @devildani,
Please see this example code for adding a text annotation:
from pdf_annotate import Appearance
from pdf_annotate import Location
from pdf_annotate import PdfAnnotator
from pdf_annotate.config.constants import TEXT_BASELINE_BOTTOM
path = '/path/to/file.pdf'
pdf_file = PdfAnnotator(path)
# These are pixel coordinates with (0, 0) as bottom left.
# Note PDF coordinates define (0, 0) as the top left, so you may have to perform a
# transform depending on how you're getting these coordinates.
x1_pixel, y1_pixel, x2_pixel, y2_pixel = 50, 50, 100, 100
# This is the 0-indexed page index, not the 1-indexed page number
page_idx = 0
text_string = 'your annotation text'
pdf_file.add_annotation(
'text',
Location(x1=x1_pixel, y1=y2_pixel, x2=x2_pixel, y2=y2_pixel, page=page_idx),
Appearance(
fill=(1, 0, 0), # solid fill
font_size=40,
content=text_string,
text_baseline=TEXT_BASELINE_BOTTOM,
),
)
out_path = '/path/to/new_file.pdf'
pdf_file.write(out_path)
I usually add some padding to y2 to get the text to display exactly how I want. I find that a percentage of the document height works well.
Good luck, and if you have any further questions let me know 😄