To add Text into PDF File, we’ll use Aspose.PDF for Python a powerful and easy-to-use API. Open PyPI, search for aspose-pdf
, and install it. Alternatively, run the command:
Add Text to PDF File via Python
To try the code in your environment, you need Aspose.PDF for Python.
- Load the PDF with an instance of Document.
- Create a TextParagraph and define its properties.
- Add the TextParagraph to Page using TextBuilder.
- Save the file again.
Add Text to PDF - Python
import aspose.pdf as apdf
from os import path
path_infile = path.join(self.data_dir, infile)
path_outfile = path.join(self.data_dir, outfile)
document = apdf.Document(path_infile)
# Get particular page
page = document.pages[1]
# Create text fragment
text_fragment = apdf.text.TextFragment("Hello, world!")
text_fragment.position = apdf.text.Position(100, 600)
# Set text properties
text_fragment.text_state.font_size = 12
text_fragment.text_state.font = apdf.text.FontRepository.find_font("TimesNewRoman")
text_fragment.text_state.background_color = apdf.Color.light_gray
text_fragment.text_state.foreground_color = apdf.Color.red
# Create TextBuilder object
builder = apdf.text.TextBuilder(page)
# Append the text fragment to the PDF page
builder.append_text(text_fragment)
# Save resulting PDF document.
document.save(path_outfile )