Add header and footer to PDF in Java

2018-11-27 09:47:53 Written by Koohji

This article demonstrates how to use Spire. PDF for Java to add header and footer when creating new PDF document in Java applications.

Spire.PDF has a class named PdfPageTemplateElement, which represents a page template element that can be used as header, footer, watermark or stamp. The template can contain text, image as well as dynamic fields like PdfPageCountField, PdfPageNumberField, etc. We use text string for the header and dynamic fields for the footer in the following example.

import java.awt.*;
import java.awt.geom.Dimension2D;
import com.spire.pdf.*;
import com.spire.pdf.automaticfields.PdfAutomaticField;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.*;

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

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

        //Set margins
        PdfMargins margin = new PdfMargins(60,60,40,40);

        //Call the method addHeaderAndFooter() to add header and footer
        addHeaderAndFooter(doc, PdfPageSize.A4, margin);

        //Add two pages to the PDF document and draw string to it.
        PdfPageBase page1 = doc.getPages().add();
        PdfPageBase page2 = doc.getPages().add();
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN, 14));
        String text1 = "Demo of Spire.PDF";
        String text2 = "How to add header and footer to PDF in JAVA";
        page1.getCanvas().drawString(text1, font, PdfBrushes.getBlack(),0,0);
        page2.getCanvas().drawString(text2, font, PdfBrushes.getBlack(),0,0);
      
        //Save the document
        doc.saveToFile("output/headerFooter.pdf");
        doc.close();

    }
static void addHeaderAndFooter(PdfDocument doc, Dimension2D pageSize, PdfMargins margin) {

      PdfPageTemplateElement header = new PdfPageTemplateElement(margin.getLeft(), pageSize.getHeight());
      doc.getTemplate().setLeft(header);

      PdfPageTemplateElement topSpace = new PdfPageTemplateElement(pageSize.getWidth(), margin.getTop());
      topSpace.setForeground(true);
      doc.getTemplate().setTop(topSpace);

      //Draw header label
      PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Arial",Font.PLAIN,12));

      PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
      String label = "E-iceblue Co.,Ltd";
      Dimension2D dimension2D = new Dimension();
      dimension2D.setSize(font.measureString(label, format));
      float y = topSpace.getHeight() - font.getHeight() - 1;
      PdfPen pen = new PdfPen(new PdfRGBColor(Color.black), 0.75f);
      topSpace.getGraphics().setTransparency(0.5f);
      topSpace.getGraphics().drawLine(pen, margin.getLeft(), y, pageSize.getWidth() - margin.getRight(), y);
      y = y - 1 - (float) dimension2D.getHeight();
      topSpace.getGraphics().drawString(label, font, PdfBrushes.getBlack(), margin.getLeft(), y, format);

      PdfPageTemplateElement rightSpace = new PdfPageTemplateElement(margin.getRight(), pageSize.getHeight());
      doc.getTemplate().setRight(rightSpace);


      //Draw dynamic fields as footer
      PdfPageTemplateElement footer = new PdfPageTemplateElement(pageSize.getWidth(), margin.getBottom());
      footer.setForeground(true);
      doc.getTemplate().setBottom(footer);

      y = font.getHeight() + 1;
      footer.getGraphics().setTransparency(0.5f);
      footer.getGraphics().drawLine(pen, margin.getLeft(), y, pageSize.getWidth() - margin.getRight(), y);
      y = y + 1;
      PdfPageNumberField pageNumber = new PdfPageNumberField();
      PdfPageCountField pageCount = new PdfPageCountField();
      PdfCompositeField pageNumberLabel = new PdfCompositeField();
      pageNumberLabel.setAutomaticFields(new PdfAutomaticField[]{pageNumber, pageCount});
      pageNumberLabel.setBrush(PdfBrushes.getBlack());
      pageNumberLabel.setFont(font);
      format = new PdfStringFormat(PdfTextAlignment.Right);
      pageNumberLabel.setStringFormat(format);
      pageNumberLabel.setText("page {0} of {1}");
      pageNumberLabel.setBounds(footer.getBounds());
      pageNumberLabel.draw(footer.getGraphics(), - margin.getLeft(), y);
  }

}

Effective screenshot after adding header and footer to the new PDF document in JAVA application:

Add header and footer to PDF in JAVA

Java: Find and Highlight Text in PDF

2024-04-01 07:02:00 Written by Koohji

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>11.11.11</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<PdfTextFragment> 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<PdfTextFragment> 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<PdfTextFragment> 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<PdfTextFragment> 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.

By splitting PDF pages into separate files, you get smaller PDF documents that have one or some pages extracted from the original. A split file contains less information and is naturally smaller in size and easier to share over the internet. In this article, you will learn how to split PDF into single-page PDFs and how to split PDF by page ranges in Java using Spire.PDF for Java.

Install Spire.PDF for Java

First, 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>11.11.11</version>
    </dependency>
</dependencies>

Split a PDF File into Multiple Single-Page PDFs in Java

Spire.PDF for Java offers the split() method to divide a multipage PDF document into multiple single-page files. The following are the detailed steps.

  • Create a PdfDcoument object.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Split the document into one-page PDFs using PdfDocument.split(string destFilePattern, int startNumber) method.
  • Java
import com.spire.pdf.PdfDocument;

public class SplitPdfByEachPage {

    public static void main(String[] args) {

        //Specify the input file path
        String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

        //Specify the output directory
        String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

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

        //Load a PDF file
        doc.loadFromFile(inputFile);

        //Split the PDF to one-page PDFs
        doc.split(outputDirectory + "output-{0}.pdf", 1);
    }
}

Java: Split a PDF File into Multiple PDFs

Split a PDF File by Page Ranges in Java

No straightforward method is offered for splitting PDF documents by page ranges. To do so, we create two or more new PDF documents and import the selected page or page range from the source document into them. Here are the detailed steps.

  • Load the source PDF file while initialing the PdfDocument object.
  • Create two additional PdfDocument objects.
  • Import the first page from the source file to the first document using PdfDocument.insertPage() method.
  • Import the remaining pages from the source file to the second document using PdfDocument.insertPageRange() method.
  • Save the two documents as separate PDF files using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;

public class SplitPdfByPageRange {

    public static void main(String[] args) {

        //Specify the input file path
        String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

        //Specify the output directory
        String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

        //Load the source PDF file while initialing the PdfDocument object
        PdfDocument sourceDoc = new PdfDocument(inputFile);

        //Create two additional PdfDocument objects
        PdfDocument newDoc_1 = new PdfDocument();
        PdfDocument newDoc_2 = new PdfDocument();

        //Insert the first page of source file to the first document
        newDoc_1.insertPage(sourceDoc, 0);

        //Insert the rest pages of source file to the second document
        newDoc_2.insertPageRange(sourceDoc, 1, sourceDoc.getPages().getCount() - 1);

        //Save the two documents as PDF files
        newDoc_1.saveToFile(outputDirectory + "output-1.pdf");
        newDoc_2.saveToFile(outputDirectory + "output-2.pdf");
    }
}

Java: Split a PDF File into Multiple PDFs

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.

page 77