News Category

Text

Text (7)

When you are drawing text into a PDF, you may need to define colorful brushes or pens in order to make the page more vivid. This article shows how to set the text string’s color space in a PDF document using Spire.PDF for Java.

Install Spire.PDF for Java

First, you need to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>10.3.4</version>
    </dependency>
</dependencies>
    

Set the Font Color for the Text String on PDF

Spire.PDF for Java offers PdfSolidBrush class to set the brush color for the text. It supports to define the brush color based on a particular RGB color space or a HTML color code.

  • Create a PdfDocument object.
  • Add a new page in the PDF using PdfDocument.getPages().add() method.
  • Create a PdfSolidBrush object based on a particular RGB color space or a HTML color code.
  • Create an object of PdfTrueTypeFont to set the font name, size and style.
  • Draw text on the page at the specified location using PdfPageBase.getCanvas().drawString() method.
  • Save the document to another PDF using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfRGBColor;
import com.spire.pdf.graphics.PdfSolidBrush;
import com.spire.pdf.graphics.PdfTrueTypeFont;

import java.awt.*;

       public class pdfBrush {
            public static void main(String[] args) throws Exception {


                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
                //Add a page
                PdfPageBase page = doc.getPages().add();

                //Set the location
                float y = 30;

                //Create solid brush object and define the color
                PdfRGBColor rgb1 = new PdfRGBColor(Color.green);
                PdfSolidBrush brush1 = new PdfSolidBrush(rgb1);

                //RGB Color
                PdfRGBColor rgb2 = new PdfRGBColor(0,197,205);
                PdfSolidBrush brush2 = new PdfSolidBrush(rgb2);

                //HTML code color
                Color color = Color.decode("#A52A2A");
                PdfSolidBrush brush3 = new PdfSolidBrush(new PdfRGBColor(color));

                //Create true type font object
                Font font = new Font("Arial", java.awt.Font.BOLD, 14);
                PdfTrueTypeFont trueTypeFont = new PdfTrueTypeFont(font);

                //Draw text
                page.getCanvas().drawString("Set the text color with brush", trueTypeFont, brush1, 0, (y = y + 30f));
                page.getCanvas().drawString("Set the text color with RGB", trueTypeFont, brush2, 0, (y = y + 50f));
                page.getCanvas().drawString("Set the text color with HTML code color", trueTypeFont, brush3, 0, (y = y + 60f));

                //Save to file
                doc.saveToFile("output/CreatePdf.pdf");

            }
        }

Java: Set the Font Color for the Text String on PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Finding and replacing text in PDF documents is essential for updating reports, legal contracts, or any other type of document where accurate and consistent information is crucial. The process involves identifying specific pieces of text and replacing them with new content, allowing users to update placeholder text, correct mistakes, customize document details, or undertake other modifications involving the written word.

This article introduces how to find and replace text in a PDF document in Java by using the Spire.PDF for Java library.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>10.3.4</version>
    </dependency>
</dependencies>
    

Replace Text in a Specific PDF Page in Java

In Spire.PDF for Java, the PdfTextReplacer class is designed to facilitate text replacement within PDF documents. One of its primary methods, replaceAllText(), enables developers to replace all instances of a specified text on a page with new text.

To replace text in a specific page in Java, follow these steps:

  • Create a PdfDocument object.
  • Load a PDF file for a specified path.
  • Get a specific page from the document.
  • Create a PdfTextReplaceOptions object, and specify the replace options using setReplaceType() method of the object.
  • Create a PdfTextReplacer object, and apply the replace options using setOptions() method of it.
  • Replace all instances of the target text in the page with new text using PdfTextReplacer.replaceAllText() method.
  • Save the document to a different PDF file.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextReplaceOptions;
import com.spire.pdf.texts.PdfTextReplacer;
import com.spire.pdf.texts.ReplaceActionType;

import java.util.EnumSet;

public class ReplaceTextInPage {

    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Create a PdfTextReplaceOptions object
        PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();

        // Specify the options for text replacement
        textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.IgnoreCase));
        textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.WholeWord));

        // Get a specific page
        PdfPageBase page = doc.getPages().get(0);

        // Create a PdfTextReplacer object based on the page
        PdfTextReplacer textReplacer = new PdfTextReplacer(page);

        // Set the replace options
        textReplacer.setOptions(textReplaceOptions);

        // Replace all instances of target text with new text
        textReplacer.replaceAllText("MySQL", "mysql");

        // Save the document to a different PDF file
        doc.saveToFile("output/ReplaceTextInPage.pdf");

        // Dispose resources
        doc.dispose();
    }
}

Java: Find and Replace Text in PDF

Replace Text in an Entire PDF Document in Java

You already know how to replace text in one page. To replace all instances of a specific text within a PDF document with new text, you just need to iterate through each page of the document and use the PdfTextReplacer.replaceAllText() method to update the text on every page.

The following are the steps to replace text in an entire PDF document using Java.

  • Create a PdfDocument object.
  • Load a PDF file for a specified path.
  • Create a PdfTextReplaceOptions object, and specify the replace options using setReplaceType() method of the object.
  • Iterate through the pages in the document.
    • Create a PdfTextReplacer object based on a specified page, and apply the replace options using setOptions() method.
    • Replace all instances of the target text in the page with new text using PdfTextReplacer.replaceAllText() method.
  • Save the document to a different PDF file.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextReplaceOptions;
import com.spire.pdf.texts.PdfTextReplacer;
import com.spire.pdf.texts.ReplaceActionType;

import java.util.EnumSet;

public class ReplaceTextInDocument {

    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Create a PdfTextReplaceOptions object
        PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();

        // Specify the options for text replacement
        textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.IgnoreCase));
        textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.WholeWord));

        for (int i = 0; i < doc.getPages().getCount(); i++) {

            // Get a specific page
            PdfPageBase page = doc.getPages().get(i);

            // Create a PdfTextReplacer object based on the page
            PdfTextReplacer textReplacer = new PdfTextReplacer(page);

            // Set the replace options
            textReplacer.setOptions(textReplaceOptions);

            // Replace all instances of target text with new text
            textReplacer.replaceAllText("MySQL", "mysql");
        }

        // Save the document to a different PDF file
        doc.saveToFile("output/ReplaceTextInDocument.pdf");

        // Dispose resources
        doc.dispose();
    }
}

Replace the First Instance of the Target Text in Java

To replace the first instance of the target text in a page, you can make use of the replaceText() method from the PdfTextReplacer class. Here are the steps to accomplish this task in Java.

  • Create a PdfDocument object.
  • Load a PDF file for a specified path.
  • Get a specific page from the document.
  • Create a PdfTextReplaceOptions object, and specify the replace options using replaceType method of the object.
  • Create a PdfTextReplacer object, and apply the replace options using setOptions() method.
  • Replace the first occurrence of the target text in the page with new text using PdfTextReplacer.replaceText() method.
  • Save the document to a different PDF file.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextReplaceOptions;
import com.spire.pdf.texts.PdfTextReplacer;
import com.spire.pdf.texts.ReplaceActionType;

import java.util.EnumSet;

public class ReplaceFirstInstance {

    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Create a PdfTextReplaceOptions object
        PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();

        // Specify the options for text replacement
        textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.IgnoreCase));
        textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.WholeWord));

        // Get a specific page
        PdfPageBase page = doc.getPages().get(0);

        // Create a PdfTextReplacer object based on the page
        PdfTextReplacer textReplacer = new PdfTextReplacer(page);

        // Set the replace options
        textReplacer.setOptions(textReplaceOptions);

        // Replace the first instance of target text with new text
        textReplacer.replaceText("MySQL", "mysql");

        // Save the document to a different PDF file
        doc.saveToFile("output/ReplaceFirstInstance.pdf");

        // Dispose resources
        doc.dispose();
    }
}

Java: Find and Replace Text in PDF

Replace Text Based on a Regular Expression in Java

Regular expressions are incredibly powerful and flexible patterns that are commonly used for matching text. When working with Spire.PDF for Java, you can harness the capabilities of regular expressions to search for specific text within a PDF document and replace it or them with new text.

To replace text in a PDF based on a regular expression, you can follow these steps:

  • Create a PdfDocument object.
  • Load a PDF file for a specified path.
  • Get a specific page from the document.
  • Create a PdfTextReplaceOptions object.
  • Specify the replace type as Regex using PdfTextReplaceOptions.setReplaceType() method.
  • Create a PdfTextReplacer object, and apply the replace options using setOptions() method.
  • Find and replace the text that matches a specified regular expression using PdfTextReplacer.replaceAllText() method.
  • Save the document to a different PDF file.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextReplaceOptions;
import com.spire.pdf.texts.PdfTextReplacer;
import com.spire.pdf.texts.ReplaceActionType;

import java.util.EnumSet;

public class ReplaceBasedOnRegularExpression {

    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Create a PdfTextReplaceOptions object
        PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();

        // Set the replace type as Regex
        textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.Regex));

        // Get a specific page
        PdfPageBase page = doc.getPages().get(0);

        // Create a PdfTextReplacer object based on the page
        PdfTextReplacer textReplacer = new PdfTextReplacer(page);

        // Set the replace options
        textReplacer.setOptions(textReplaceOptions);

        // Specify the regular expression
        String regularExpression = "\\bS\\w*L\\b";

        // Replace all instances that match the regular expression with new text
        textReplacer.replaceAllText(regularExpression, "NEW");

        // Save the document to a different PDF file
        doc.saveToFile("output/ReplaceWithRegularExpression.pdf");

        // Dispose resources
        doc.dispose();
    }
}

Java: Find and Replace Text in PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

This article will show you how to use Spire.PDF for Java to draw superscript and subscript text to PDF file in Java applications.

Draw Superscript Text

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;

public class PdfSuperscriptText {
    public static void main(String[] args) {

        //Create a new PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Add a page to pdf
        PdfPageBase page = doc.getPages().add();

        //Set the font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,14),true);
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));

        //Set initial (x, y) coordinate
        float x = 120f;
        float y = 100f;

        //Draw text string
        String text = "Sample Text";
        page.getCanvas().drawString(text, font, brush, new Point2D.Float(x, y));

        //Measure the string
        Dimension2D size = font.measureString(text);
        x += size.getWidth();

        //Draw the text string and set the format as Superscript
        PdfStringFormat format = new PdfStringFormat();
        format.setSubSuperScript(PdfSubSuperScript.Super_Script);
        text = "Superscrip";
        page.getCanvas().drawString(text, font, brush, new Point2D.Float(x, y), format);

        //Save the document to file
        String result="output/superScript.pdf";
        doc.saveToFile(result);
    }
}

Effective screenshot:

Java draw Superscript and Subscript Text in PDF

Draw Subscript Text

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;

public class PdfSubscriptText {
    public static void main(String[] args) {

        //Create a new PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Add a page to pdf
        PdfPageBase page = doc.getPages().add();

        //Set the font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,14),true);
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));

        //Set initial (x, y) coordinate
        float x = 120f;
        float y = 100f;

        //Draw text string
        String text = "Sample Text";
        page.getCanvas().drawString(text, font, brush, new Point2D.Float(x, y));

        //Measure the string
        Dimension2D size = font.measureString(text);
        x += size.getWidth();

        //Draw the text string and set the format as Subscript
        PdfStringFormat format = new PdfStringFormat();
        format.setSubSuperScript(PdfSubSuperScript.Sub_Script);
        text = "Subscrip";
        page.getCanvas().drawString(text, font, brush, new Point2D.Float(x, y), format);

        //Save the document to file
        String result="output/subScript.pdf";
        doc.saveToFile(result);
    }
}

Output:

Java draw Superscript and Subscript Text in PDF

This article demonstrates how to find the text that matches a specific regular expression in a PDF document using Spire.PDF for Java.

import com.spire.pdf.general.find.PdfTextFind;
import java.awt.*;

public class FindByRegularExpression {

    public static void main(String[] args) throws Exception {

        //Load a PDF document
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\test.pdf");

        //Create a object of PdfTextFind collection
        PdfTextFind[] results;

        //Loop through the pages
        for (Object page : (Iterable) pdf.getPages()) {
            PdfPageBase pageBase = (PdfPageBase) page;

            //Define a regular expression
            String pattern = "\\#\\w+\\b";

            //Find all results that match the pattern
            results = pageBase.findText(pattern).getFinds();

            //Highlight the search results with yellow
            for (PdfTextFind find : results) {
                find.applyHighLight(Color.yellow);
            }
        }

        //Save to file
        pdf.saveToFile("FindByPattern.pdf");
    }
}

Find Text in PDF by Regular Expression in Java

Finding and highlighting text within a PDF document is a crucial task for many individuals and organizations. Whether you're a student conducting research, a professional reviewing contracts, or an archivist organizing digital records, the ability to quickly locate and emphasize specific information is invaluable.

In this article, you will learn how to find and highlight text in a PDF document in Java using the Spire.PDF for Java library.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>10.3.4</version>
    </dependency>
</dependencies>
    

Find and Highlight Text in a Specific Page in Java

In Spire.PDF for Java, you can utilize the PdfTextFinder class to locate specific text within a page. Prior to executing the find operation, you can set the search options such as WholeWord and IgnoreCase by utilizing the PdfTextFinder.getOptions.setTextFindParameter() method. Once the text is located, you can apply highlighting to visually differentiate the text.

The following are the steps to find and highlight text in a specific page in PDF using Java.

  • Create a PdfDocument object.
  • Load a PDF file from a given path.
  • Get a specific page from the document.
  • Create a PdfTextFinder object based on the page.
  • Specify search options using PdfTextFinder.getOptions().setTextFindParameter() method.
  • Find all instance of searched text using PdfTextFinder.find() method.
  • Iterate through the find results, and highlight each instance using PdfTextFragment.highlight() method.
  • Save the document to a different PDF file.
  • Java
import com.spire.ms.System.Collections.Generic.List;
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextFinder;
import com.spire.pdf.texts.PdfTextFragment;
import com.spire.pdf.texts.TextFindParameter;

import java.awt.*;
import java.util.EnumSet;

public class FindAndHighlightTextInPage {

    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Get a specific page
        PdfPageBase page = doc.getPages().get(0);

        // Create a PdfTextFinder object based on the page
        PdfTextFinder finder = new PdfTextFinder(page);

        // Specify the find options
        finder.getOptions().setTextFindParameter(EnumSet.of(TextFindParameter.WholeWord));
        finder.getOptions().setTextFindParameter(EnumSet.of(TextFindParameter.IgnoreCase));

        // Find the instances of the specified text
        List results  = finder.find("MySQL");

        // Iterate through the find results
        for (PdfTextFragment textFragment: results)
        {
            // Highlight text
            textFragment.highLight(Color.LIGHT_GRAY);
        }

        // Save to a different PDF file
        doc.saveToFile("output/HighlightTextInPage.pdf", FileFormat.PDF);

        // Dispose resources
        doc.dispose();
    }
}

Java: Find and Highlight Text in PDF

Find and Highlight Text in a Rectangular Area in Java

To draw attention to a specific section or piece of information within a document, users can find and highlight specified text within a rectangular area of a page. The rectangular region can be defined by utilizing the PdfTextFinder.getOptions().setFindArea() method.

The following are the steps to find and highlight text in a rectangular area of a PDF page using Java.

  • Create a PdfDocument object.
  • Load a PDF file from a given path.
  • Get a specific page from the document.
  • Create a PdfTextFinder object based on the page.
  • Specify search options using PdfTextFinder.getOptions().setTextFindParameter() method.
  • Find all instance of searched text within the rectangular area using PdfTextFinder.find() method.
  • Iterate through the find results, and highlight each instance using PdfTextFragment.fighlight() method.
  • Save the document to a different PDF file.
  • Java
import com.spire.ms.System.Collections.Generic.List;
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextFinder;
import com.spire.pdf.texts.PdfTextFragment;
import com.spire.pdf.texts.TextFindParameter;

import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.EnumSet;

public class FindAndHighlightTextInRectangle {

    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Get a specific page
        PdfPageBase page = doc.getPages().get(0);

        // Create a PdfTextFinder object based on the page
        PdfTextFinder finder = new PdfTextFinder(page);

        // Specify a rectangular area for searching text
        finder.getOptions().setFindArea(new Rectangle2D.Float(0,0,841,180));

        // Specify other options
        finder.getOptions().setTextFindParameter(EnumSet.of(TextFindParameter.WholeWord));
        finder.getOptions().setTextFindParameter(EnumSet.of(TextFindParameter.IgnoreCase));

        // Find the instances of the specified text in the rectangular area
        List results  = finder.find("MySQL");

        // Iterate through the find results
        for (PdfTextFragment textFragment: results)
        {
            // Highlight text
            textFragment.highLight(Color.LIGHT_GRAY);
        }

        // Save to a different PDF file
        doc.saveToFile("output/HighlightTextInRectangle.pdf", FileFormat.PDF);

        // Dispose resources
        doc.dispose();
    }
}

Java: Find and Highlight Text in PDF

Find and Highlight Text in an Entire PDF Document in Java

The first code example provides a demonstration of how to highlight text on a specific page. To highlight text throughout the entire document, you can traverse each page of the document, perform the search operation, and apply the highlighting to the identified text.

The steps to find and highlight text in an entire PDF document using Java are as follows.

  • Create a PdfDocument object.
  • Load a PDF file from a given path.
  • Iterate through each page in the document.
    • Create a PdfTextFinder object based on a certain page.
    • Specify search options using PdfTextFinder.getOptions().setTextFindParameter() method.
    • Find all instance of searched text using PdfTextFinder.find() method.
    • Iterate through the find results, and highlight each instance using PdfTextFragment.fighlight() method.
  • Save the document to a different PDF file.
  • Java
import com.spire.ms.System.Collections.Generic.List;
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextFinder;
import com.spire.pdf.texts.PdfTextFragment;
import com.spire.pdf.texts.TextFindParameter;

import java.awt.*;
import java.util.EnumSet;

public class FindAndHighlightTextInDocument {

    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");
        
        // Iterate through the pages in the PDF file
        for (Object pageObj : doc.getPages()) {

            // Get a specific page
            PdfPageBase page = (PdfPageBase) pageObj;

            // Create a PdfTextFinder object based on the page
            PdfTextFinder finder = new PdfTextFinder(page);

            // Specify the find options
            finder.getOptions().setTextFindParameter(EnumSet.of(TextFindParameter.WholeWord));
            finder.getOptions().setTextFindParameter(EnumSet.of(TextFindParameter.IgnoreCase));

            // Find the instances of the specified text
            List results  = finder.find("MySQL");

            // Iterate through the find results
            for (PdfTextFragment textFragment: results)
            {
                // Highlight text
                textFragment.highLight(Color.LIGHT_GRAY);
            }
        }

        // Save to a different PDF file
        doc.saveToFile("output/HighlightTextInDocument.pdf", FileFormat.PDF);

        // Dispose resources
        doc.dispose();
    }
}

Find and Highlight Text in PDF Using a Regular Expression in Java

When you're looking for specific text within a document, regular expressions offer enhanced flexibility and control over the search criteria. To make use of a regular expression, you'll need to set the TextFindParameter as Regex and supply the desired regular expression pattern as input to the find()method.

The following are the steps to find and highlight text in PDF using a regular expression using Java.

  • Create a PdfDocument object.
  • Load a PDF file from a given path.
  • Iterate through each page in the document.
    • Create a PdfTextFinder object based on a certain page.
    • Set the TextFindParameter as Regex using PdfTextFinder.getOptions().setTextFindParameter() method.
    • Create a regular expression pattern that matches the specific text you are searching for.
    • Find all instance of the searched text using PdfTextFinder.find() method.
    • Iterate through the find results, and highlight each instance using PdfTextFragment.fighlight() method.
  • Save the document to a different PDF file.
  • Java
import com.spire.ms.System.Collections.Generic.List;
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextFinder;
import com.spire.pdf.texts.PdfTextFragment;
import com.spire.pdf.texts.TextFindParameter;

import java.awt.*;
import java.util.EnumSet;

public class FindAndHighlightTextUsingRegex {

    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Iterate through the pages in the PDF file
        for (Object pageObj : doc.getPages()) {

            // Get a specific page
            PdfPageBase page = (PdfPageBase) pageObj;

            // Create a PdfTextFinder object based on the page
            PdfTextFinder finder = new PdfTextFinder(page);

            // Specify the search model as Regex
            finder.getOptions().setTextFindParameter(EnumSet.of(TextFindParameter.Regex));

            // Define a regular expression pattern that matches a letter starting with 'R' and ending with 'S'
            String pattern = "\\bR\\w*S\\b";

            // Find the text that conforms to a regular expression
            List results  = finder.find(pattern);

            // Iterate through the find results
            for (PdfTextFragment textFragment: results)
            {
                // Highlight text
                textFragment.highLight(Color.LIGHT_GRAY);
            }
        }

        // Save to a different PDF file
        doc.saveToFile("output/HighlightTextUsingRegex.pdf", FileFormat.PDF);

        // Dispose resources
        doc.dispose();
    }
}

Java: Find and Highlight Text in PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Align Text in PDF in Java

2018-11-19 08:31:13 Written by support iceblue

When drawing text on PDF page, you can align text horizontally and vertically. This tutorial will show you how to align text in a line and a rectangle by using Spire.PDF for Java.

Align Text in Line

import com.spire.pdf.graphics.*;

import java.awt.*;

public class AlignTextInLine {

    public static void main(String[] args) {

        //create a PdfDocument object 
        PdfDocument doc = new PdfDocument();

        //add a page 
        PdfPageBase page = doc.getPages().add();

        //create a true type font
        PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Times New Roman",Font.PLAIN,15));

        //create a brush 
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));

        //create a PdfStringFormat object, specifying PdfTextAlignment to Left
        PdfStringFormat leftAlignment = new PdfStringFormat(PdfTextAlignment.Left);

        //draw text at left 
        page.getCanvas().drawString("Left", font , brush, 0, 20, leftAlignment);

        //draw text at right 
        PdfStringFormat rightAlignment = new PdfStringFormat(PdfTextAlignment.Right);
        page.getCanvas().drawString("Right", font , brush, page.getCanvas().getClientSize().getWidth(), 20, rightAlignment);

        //draw text in center 
        PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center);
        page.getCanvas().drawString("Center", font , brush, page.getCanvas().getClientSize().getWidth() / 2, 20, centerAlignment);

        //save the file 
        doc.saveToFile("AlignTextInLine.pdf");
    }
}

Output:

Align Text on PDF in Java

Align Text in Rectangle

import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Rectangle2D;

public class AlignTextInRectangle {

    public static void main(String[] args) {

        //create a PdfDocument object 
        PdfDocument doc = new PdfDocument();

        //add a page 
        PdfPageBase page = doc.getPages().add();

        //create a true type font
        PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Times New Roman",Font.PLAIN,15));

        //craete a pen 
        PdfPen pen = new PdfPen(new PdfRGBColor(Color.black));

        //create a brush 
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));

        //draw a rectangle 
        Rectangle2D.Float rect = new Rectangle2D.Float();
        rect.setRect(0, 20, page.getCanvas().getClientSize().getWidth() / 2, 100);
        page.getCanvas().drawRectangle(pen, rect);

        //create a PdfStringFormat object, specifying PdfTextAlignment to Top and Left
        PdfStringFormat topLeft = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Top);

        //draw text at top left
        page.getCanvas().drawString("TopLeft", font, brush, rect, topLeft);

        //draw text at top right 
        PdfStringFormat topRight = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top);
        page.getCanvas().drawString("TopRight", font, brush, rect, topRight);

        //draw text in center 
        PdfStringFormat center = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
        page.getCanvas().drawString("Center", font, brush, rect, center);

        //draw text at bottom left 
        PdfStringFormat bottomLeft = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Bottom);
        page.getCanvas().drawString("BottomLeft", font, brush, rect, bottomLeft);

        //draw text at bottom right 
        PdfStringFormat bottomRight = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Bottom);
        page.getCanvas().drawString("BottomRight", font, brush, rect, bottomRight);

        //save the file 
        doc.saveToFile("AlignTextInRectangle.pdf");
    }
}

Output:

Align Text on PDF in Java

Draw Barcode on PDF in Java

2018-11-12 06:52:18 Written by support iceblue

Spire.PDF for Java supports the creation of Codebar, Code11, Code128A, Code128B, Code32, Code39, Code39 Extended, Code93 and Code93 Extended barcodes in PDF. This tutorial give you an example of how to add Codebar, Code128A and Code39 in PDF.

import com.spire.pdf.barcode.*;
import com.spire.pdf.graphics.*;
import static com.spire.pdf.graphics.PdfFontStyle.Bold;

import java.awt.*;
import java.awt.geom.Point2D;
import java.util.EnumSet;

public class DrawBarcode {

    public static void main(String[] args) {

        //create a PdfDocument instance 
        PdfDocument doc = new PdfDocument();

        //add a page 
        PdfPageBase page = doc.getPages().add();

        //declare a double variable 
        double y = 15;

        //create font 
        PdfFont font= new PdfFont(PdfFontFamily.Helvetica, 12, EnumSet.of(Bold));

        //draw text "Codebar:" on PDF 
        PdfTextWidget text = new PdfTextWidget();
        text.setFont(font);
        text.setText("Codebar:");
        PdfLayoutResult result = text.draw(page, 0, y);
        y =(float)(result.getBounds().getY()+ result.getBounds().getHeight() + 2);

        //draw Codebar barcode on PDF 
        PdfCodabarBarcode codebar= new PdfCodabarBarcode("00:12-3456/7890");
        codebar.setBarcodeToTextGapHeight(1f);
        codebar.setBarHeight(50f);
        codebar.setEnableCheckDigit(true);
        codebar.setShowCheckDigit(true);
        codebar.setTextDisplayLocation(TextLocation.Bottom);
        PdfRGBColor blue = new PdfRGBColor(Color.blue);
        codebar.setTextColor(blue);
        Point2D.Float point = new Point2D.Float();
        point.setLocation(0,y);
        codebar.draw(page,point);
        y = codebar.getBounds().getY()+ codebar.getBounds().getHeight() + 5;

        //draw text "Code128-A:" on PDF 
        text.setText("Code128-A:");
        result = text.draw(page, 0, y);
        page = result.getPage();
        y =result.getBounds().getY()+ result.getBounds().getHeight() + 2;

        //draw Code128 barcode on PDF 
        PdfCode128ABarcode code128 = new PdfCode128ABarcode("HELLO 00-123");
        code128.setBarcodeToTextGapHeight(1f);
        code128.setBarHeight(50f);
        code128.setTextDisplayLocation(TextLocation.Bottom);
        code128.setTextColor(blue);
        point.setLocation(point.x,y);
        code128.draw(page, point);
        y =code128.getBounds().getY()+ code128.getBounds().getHeight() + 5;

        //draw text "Code39:" on PDF 
        text.setText("Code39:");
        result = text.draw(page, 0, y);
        page = result.getPage();
        y =result.getBounds().getY()+ result.getBounds().getHeight() + 2;

        //draw Code39 barcode on PDF 
        PdfCode39Barcode code39 = new PdfCode39Barcode("16-273849");
        code39.setBarcodeToTextGapHeight(1f);
        code39.setBarHeight(50f);
        code39.setTextDisplayLocation(TextLocation.Bottom);
        code39.setTextColor(blue);
        point.setLocation(point.x,y);
        code39.draw(page, point);

        //save to file 
        doc.saveToFile("DrawBarcode.pdf");
    }
}

Draw Barcode in PDF in Java