Add Text to PDF via Java

Add text to PDF document with Java. Use Aspose.PDF to modify PDF documents programmatically

How to Work with Text in PDF Using Java Library

To add Text into PDF File Aspose.PDF for Java API, which is a feature-rich, powerful, and easy-to-use conversion API for the Java platform. You can download its latest version directly from Maven and install it within your Maven-based project by adding the following configurations to the pom.xml.

Repository

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java AP</name>
    <url>https://releases.aspose.com/java/repo/</url>
</repository>

Dependency

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>

Add Text to PDF File via Java


You need Aspose.PDF for Java to try the code in your environment.

  1. Load the PDF with an instance of Document.
  2. Create a TextParagraph and define its properties.
  3. Add the TextParagraph to Page using TextBuilder.
  4. Save the file again.

Add Text to PDF - Java

This sample code shows how to add text into PDF document - Java


    public static void AddingText() {
    // Load the PDF file
    Document document = new Document(_dataDir + "sample.pdf");

    // get particular page
    Page pdfPage = document.getPages().get_Item(1);
    // create text fragment
    TextFragment textFragment = new TextFragment("Aspose.PDF");
    textFragment.setPosition(new Position(80, 700));

    // set text properties
    textFragment.getTextState().setFont(FontRepository.findFont("Verdana"));
    textFragment.getTextState().setFontSize(14);
    textFragment.getTextState().setForegroundColor(Color.getBlue());
    textFragment.getTextState().setBackgroundColor(Color.getLightGray());

    // create TextBuilder object
    TextBuilder textBuilder = new TextBuilder(pdfPage);
    // append the text fragment to the PDF page
    textBuilder.appendText(textFragment);

    // Save resulting PDF document.