Friday, 21 January 2022 06:16

Java: Change PDF Version

PDF is a file format developed by Adobe in 1992, and during the years, it has undergone a lot of changes. Sometimes you may find that some devices have strict requirements on the PDF version. In such a case, it's necessary to change the PDF file to a different version for compatibility purpose. This article will show how to programmatically change the PDF version using Spire.PDF for Java.

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.4.4</version>
    </dependency>
</dependencies>
    

Change PDF Version

Spire.PDF for Java supports the PDF versions from 1.0 to 1.7. The following are the detailed steps to change the PDF version.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.loadFromFile() method.
  • Change the PDF file to another version using PdfDocument.getFileInfo().setVersion() method.
  • Save the document to another file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.*;

public class ChangePdfVersion {

    public static void main(String[] args) {

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

        //Load a sample PDF file
        document.loadFromFile("sample.pdf");

        //Change the PDF to version 1.5
        document.getFileInfo().setVersion(PdfVersion.Version_1_5);

        //Save to file
        document.saveToFile("PdfVersion.pdf", FileFormat.PDF);
        document.close();
    }
}

Java: Change PDF Version

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.

Tuesday, 27 November 2018 09:47

Add header and footer to PDF in Java

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

Monday, 01 April 2024 07:02

Java: Find and Highlight Text in PDF

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.4.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.

Thursday, 30 June 2022 08:17

Java: Split a PDF File into Multiple PDFs

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>10.4.4</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.

Proper backgrounds can make different content elements of PDF documents better matched and improve the visual impression and reading experience of PDF documents. Besides, it's important to add different backgrounds to PDF documents for different usage scenarios to enhance the professionalism of the documents. This article will show how to use Spire.PDF for Java to set the background color and background image for PDF documents.

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>10.4.4</version>
    </dependency>
</dependencies>
    

Add Background Color to PDF Documents in Java

As setting the background of a PDF document needs to be done page by page, we can loop through all the pages in the document and use the PdfPageBase.setBackgroundColor() method to set the background color for each page. The following are the detailed steps:

  • Create an object of PdfDocument.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Loop through the pages in the PDF document and add a background color to each page using PdfPageBase.setBackgroundColor() method. You can also use the PdfPageBase.setBackgroudOpacity() method to set the opacity of the background.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

import java.awt.*;

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

        //Create an object of PdfDocument
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("Sample.pdf");

        //Loop through the pages in the PDF file
        for (PdfPageBase page : (Iterable) pdf.getPages()
             ) {
            //Set the background color for each page
            page.setBackgroundColor(Color.PINK);
            //Set the opacity of the background
            page.setBackgroudOpacity(0.2f);
        }

        //Save the PDF file
        pdf.saveToFile("BackgroundColor.pdf");
    }
}

Java: Set the Background Color or Background Image for PDF

Add Background Picture to PDF Documents in Java

Spire.PDF for Java provides the PdfPageBase.setBackgroundImage() to set a picture as the PDF page background. The detailed steps for adding an image background to a PDF document are as follows:

  • Create an object of PdfDocument.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Loop through the pages in the PDF document and add a background picture to each page using PdfPageBase.setBackgroundImage() method. You can also use the PdfPageBase.setBackgroudOpacity() method to set the opacity of the background.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class SetPDFBackgroundImage {
    public static void main(String[] args) throws IOException {

        //Create an object of PdfDocument
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("Sample.pdf");

        //Load an image
        BufferedImage background = ImageIO.read(new File("background.jpg"));

        //Loop through the pages in the PDF file
        for (PdfPageBase page : (Iterable) pdf.getPages()
             ) {
            //Set the loaded image as the background image of a page
            page.setBackgroundImage(background);
            //Set the opacity of the background
            page.setBackgroudOpacity(0.2f);
        }

        //Save the PDF file
        pdf.saveToFile("BackgroundImage.pdf");
    }
}

Java: Set the Background Color or Background Image for 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.

Wednesday, 08 February 2023 08:48

Java: Insert Image Watermarks to PDF

A PDF image watermark is a semi-transparent picture integrated into a PDF page as a fixed element. It is often used to protect the copyright and other rights of the document owner since it can't be removed easily. What's more, for famous PDF publishers, image watermarks are also used to increase the credibility of their documents. With an image watermark of their logo, the readers of documents can identify them at a glance. This article will show how to insert image watermarks into PDF documents using Spire.PDF for Java with simple code.

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.4.4</version>
    </dependency>
</dependencies>
    

Insert a Single Picture Watermark into PDF

A single image watermark is usually placed at the center of a PDF page. The detailed steps for inserting a single image watermark are as follows.

  • Create a PdfDocument class instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Load a picture using PdfImage.fromFile() method.
  • Get the width and height of the picture using PdfImage.getWidth() and PdfImage.getHeight() methods.
  • Loop through the pages in the PDF document to insert watermarks
  • Get a page using PdfDocument.getPages().get() method.
  • Get the width and height of the page using PdfPageBase.getActualSize().getWidth() and PdfPageBase.getActualSize().getHeight() methods.
  • Set the transparency of the watermark picture using PdfPageBase.getCanvas().setTransparency() method.
  • Draw the watermark picture at the center of the page using PdfPageBase.getCanvas().drawImage() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfBrush;
import com.spire.pdf.graphics.PdfImage;

import java.awt.*;
import java.awt.image.BufferedImage;

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

        //Create a PdfDocument class instance
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("Goodbye Pixel.pdf");

        //Load a picture
        PdfImage image = PdfImage.fromFile("Logo.png");

        //Get the width and height of the image
        int imageWidth = image.getWidth();
        int imageHeight = image.getHeight();

        //Loop through the pages to insert watermark
        for (int i = 0; i < pdf.getPages().getCount(); i++) {
            //Get a page
            PdfPageBase page = pdf.getPages().get(i);
            //Get the width and height of the page
            float pageWidth = (float) (page.getActualSize().getWidth());
            float pageHeight = (float) (page.getActualSize().getHeight());
            //Set the transparency of the watermark
            page.getCanvas().setTransparency(0.3f);
            //Draw the watermark picture at the middle of the page
            page.getCanvas().drawImage(image, pageWidth/2 - imageWidth/2, pageHeight/2 - imageHeight/2, imageWidth, imageHeight);
        }

        //Save the file
        pdf.saveToFile("SingleImageWatermark.pdf");
    }
}

Java: Insert Image Watermarks to PDF

Insert Tiled Picture Watermarks into PDF

Tiled image watermarks contain a picture that is displayed multiple times on one PDF page. When inserting a tiled image watermark, we can set the number of repetitions of its picture. The detailed steps for inserting a tiled image watermark are as follow.

  • Create a PdfDocument class instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Load a picture using PdfImage.fromFile() method.
  • Loop through the pages to insert watermarks.
  • Get a specific page using PdfDocument.getPages().get() method.
  • Use the custom method insertImageWatermark() to insert a tiled image watermark.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfBrush;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.graphics.PdfTilingBrush;

import java.awt.*;

public class insertTiledImageWatermark {
    public static void main(String[] args) {
        //Create a PdfDocument class instance
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("Goodbye Pixel.pdf");

        //Load a picture
        PdfImage image = PdfImage.fromFile("Logo.png");

        //Loop through the pages in the PDF document to insert watermark
        for (int i = 0; i < pdf.getPages().getCount(); i++ ) {
            //Get a Page
            PdfPageBase page = pdf.getPages().get(i);
            //Use the custom method to insert a tiled image watermark
            insertImageWatermark(page, image, 3, 3);
        }

        //Save the file
        pdf.saveToFile("TiledImageWatermark.pdf");
    }
    static void insertImageWatermark(PdfPageBase page, PdfImage image, int row, int column) {
        //Create a tile brush
        PdfTilingBrush brush = new PdfTilingBrush(new Dimension((int) (page.getActualSize().getWidth()/column), (int) (page.getActualSize().getHeight()/row)));
        brush.getGraphics().setTransparency(0.3f);
        brush.getGraphics().save();
        brush.getGraphics().translateTransform(brush.getSize().getWidth()/2 - image.getWidth()/2, brush.getSize().getHeight()/2 - image.getHeight()/2);
        //Draw the watermark image at the center of the page
        brush.getGraphics().drawImage(image, 0, 0);
        brush.getGraphics().restore();
        //Use the tile brush to draw the watermark picture
        page.getCanvas().drawRectangle(brush, new Rectangle(new Point(0, 0), new Dimension((int) (page.getActualSize().getWidth()), (int) (page.getActualSize().getHeight()))));
    }
}

Java: Insert Image Watermarks to 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.

Tuesday, 20 November 2018 09:08

Java: Add Stamps to a PDF Document

When it comes to PDF documents, stamps offer an indispensable feature for adding contextual information and visual elements. These stamps can range from simple notes to complex graphics, enabling users to annotate, emphasize, or personalize their PDF content. With the ability to place stamps strategically, businesses can streamline workflows, indicate approvals, or provide concise feedback.

In this article, you will learn how to programmatically add dynamic stamps and image stamps to a PDF document using Spire.PDF for Java.

Install Spire.PDF for Java

To start, make sure to add the Spire.Pdf.jar file as a dependency in your Java program. You can download Spire.PDF for Java from our website and manually import the JAR file into your application. If you are using Maven, simply add the following code to your project's pom.xml file to include the JAR file effortlessly.

<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.4.4</version>
    </dependency>
</dependencies>
    

Prior Knowledge

In PDF, a stamp refers to an annotation or graphical element that can be added to a document to provide additional information. Spire.PDF for Java introduces the PdfRubberStampAnnotation class, which serves as a representation of a rubber stamp. To create the visual representation of a rubber stamp, the PdfTemplate class is employed. This class acts as a canvas allowing you to draw various types of information, including text, images, shapes, and date/time elements.

Add a Dynamic Stamp to PDF in Java

A dynamic stamp refers to a customizable annotation that can be added to a PDF document to indicate a specific status, approval, or other information. Unlike static stamps, dynamic stamps contain variables or fields that can be dynamically updated, such as the current date, time, username, or any other custom data.

The following are the steps to add a dynamic stamp to PDF using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.loadFromFile() method.
  • Create a PdfTemplate object with desired size.
  • Draw strings (including dynamic information such as date and time) on the template using PdfTemplate.getGraphics().drawString() method.
  • Create a PdfRubberStampAnnotation object, and set the template as its appearance.
  • Add the stamp to a specific PDF page using PdfPageBase.getAnnotationsWidget().add() method.
  • Save the document to a different PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.annotations.PdfRubberStampAnnotation;
import com.spire.pdf.annotations.appearance.PdfAppearance;
import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.SimpleDateFormat;

public class AddDynamicStampToPdf {

    public static void main(String[] args) {

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

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

        // Get the last page
        PdfPageBase page = document.getPages().get(document.getPages().getCount() - 1);

        // Create a PdfTemplate object
        PdfTemplate template = new PdfTemplate(195, 50);

        // Create two fonts
        PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Elephant", Font.ITALIC, 15), true);
        PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", Font.ITALIC, 10), true);

        // Create a solid brush and a gradient brush
        PdfSolidBrush solidBrush = new PdfSolidBrush(new PdfRGBColor(Color.black));
        Rectangle2D rect1 = new Rectangle2D.Float();
        rect1.setFrame(new Point2D.Float(0, 0), template.getSize());
        PdfLinearGradientBrush linearGradientBrush = new PdfLinearGradientBrush(rect1, new PdfRGBColor(Color.white), new PdfRGBColor(Color.orange), PdfLinearGradientMode.Horizontal);

        // Create rounded rectangle path
        int CornerRadius = 10;
        PdfPath path = new PdfPath();
        path.addArc(template.getBounds().getX(), template.getBounds().getY(), CornerRadius, CornerRadius, 180, 90);
        path.addArc(template.getBounds().getX() + template.getWidth() - CornerRadius, template.getBounds().getY(), CornerRadius, CornerRadius, 270, 90);
        path.addArc(template.getBounds().getX() + template.getWidth() - CornerRadius, template.getBounds().getY() + template.getHeight() - CornerRadius, CornerRadius, CornerRadius, 0, 90);
        path.addArc(template.getBounds().getX(), template.getBounds().getY() + template.getHeight() - CornerRadius, CornerRadius, CornerRadius, 90, 90);
        path.addLine(template.getBounds().getX(), template.getBounds().getY() + template.getHeight() - CornerRadius, template.getBounds().getX(), template.getBounds().getY() + CornerRadius / 2);

        // Draw path on the template
        template.getGraphics().drawPath(linearGradientBrush, path);
        template.getGraphics().drawPath(PdfPens.getRed(), path);

        // Draw dynamic text on the template
        String s1 = "APPROVED\n";
        String s2 = "By Manager at " + dateToString(new java.util.Date(), "yyyy-MM-dd HH:mm:ss");
        template.getGraphics().drawString(s1, font1, solidBrush, new Point2D.Float(5, 5));
        template.getGraphics().drawString(s2, font2, solidBrush, new Point2D.Float(2, 28));

        // Create a rubber stamp, specifying its size and location
        Rectangle2D rect2 = new Rectangle2D.Float();
        rect2.setFrame(new Point2D.Float(50, (float) (page.getActualSize().getHeight() - 300)), template.getSize());
        PdfRubberStampAnnotation stamp = new PdfRubberStampAnnotation(rect2);

        // Create a PdfAppearance object and apply the template as its normal state
        PdfAppearance appearance = new PdfAppearance(stamp);
        appearance.setNormal(template);

        // Apply the appearance to stamp
        stamp.setAppearance(appearance);

        // Add the stamp annotation to annotation collection
        page.getAnnotationsWidget().add(stamp);

        // Save the file
        document.saveToFile("output/DynamicStamp.pdf");
        document.close();
    }

    // Convert date to string
    public static String dateToString(java.util.Date date, String dateFormat) {
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        return format.format(date);
    }
}

Java: Add Stamps to a PDF Document

Add an Image Stamp to PDF in Java

An image stamp in PDF refers to a graphical element that is added to a document as an annotation or overlay. It involves placing an image onto a specific location within a PDF page.

The steps to add an image stamp to PDF using Spire.PDF for Java are as follows.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.loadFromFile() method.
  • Load an image that you want to stamp on PDF using PdfImage.fromFile() method.
  • Create a PdfTemplate object based on the size of the image.
  • Draw the image on the template using PdfTemplate.getGraphics().drawImage() method.
  • Create a PdfRubberStampAnnotation object, and set the template as its appearance.
  • Add the stamp to a specific PDF page using PdfPageBase.getAnnotationsWidget().add() method.
  • Save the document to a different PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.annotations.PdfRubberStampAnnotation;
import com.spire.pdf.annotations.appearance.PdfAppearance;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.graphics.PdfTemplate;

import java.awt.geom.Rectangle2D;

public class AddImageStampToPdf {

    public static void main(String[] args) {

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

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

        // Get the last page
        PdfPageBase page = document.getPages().get(document.getPages().getCount() - 1);

        // Load an image file
        PdfImage image = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\stamp-image.png");

        // Get the width and height of the image
        int width = image.getWidth();
        int height = image.getHeight();

        // Create a PdfTemplate object based on the size of the image
        PdfTemplate template = new PdfTemplate(width, height);

        // Draw image on the template
        template.getGraphics().drawImage(image, 0, 0, width, height);

        // Create a rubber stamp annotation, specifying its location and position
        Rectangle2D rect = new Rectangle2D.Float((float) (page.getActualSize().getWidth() - width - 50), (float) (page.getActualSize().getHeight() - 400), width, height);
        PdfRubberStampAnnotation stamp = new PdfRubberStampAnnotation(rect);

        // Create a PdfAppearance object
        PdfAppearance pdfAppearance = new PdfAppearance(stamp);

        // Set the template as the normal state of the appearance
        pdfAppearance.setNormal(template);

        // Apply the appearance to the stamp
        stamp.setAppearance(pdfAppearance);

        // Add the stamp annotation to PDF
        page.getAnnotationsWidget().add(stamp);

        // Save the file
        document.saveToFile("output/ImageStamp.pdf");
        document.close();
    }
}

Java: Add Stamps to a PDF Document

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.

Monday, 19 November 2018 08:31

Align Text in PDF in Java

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

Tuesday, 01 November 2022 07:17

Java: Create Tables in a PDF Document

A table represents information or data in the form of horizontal rows and vertical columns. Creating tables is often more efficient than describing the data in the paragraph text, especially when the data is numerical or large. The tabular data presentation makes it easier to read and understand. In this article, you will learn how to create tables in a PDF document in Java using Spire.PDF for Java.

Spire.PDF for Java offers the PdfTable and the PdfGrid class to work with the tables in a PDF document. The PdfTable class is used to quickly create simple, regular tables without too much formatting, while the PdfGrid class is used to create more complex tables.

The table below lists the differences between these two classes.

PdfTable PdfGrid
Formatting
Row Can be set through events. No API support. Can be set through API.
Column Can be set through API. Can be set through API.
Cell Can be set through events. No API support. Can be set through API.
Others
Column span Not support. Can be set through API.
Row span Can be set through events. No API support. Can be set through API.
Nested table Can be set through events. No API support. Can be set through API.
Events BeginCellLayout,  EndCellLayout, BeginRowLayout, EndRowLayout, BeginPageLayout, EndPageLayout. BeginPageLayout, EndPageLayout.

The following sections demonstrate how to create a table in PDF using the PdfTable class and the PdfGrid class, respectively.

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.4.4</version>
    </dependency>
</dependencies>
    

Create a Table in PDF Using PdfTable Class

The following are the steps to create a table using the PdfTable class using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.getPages().add() method.
  • Create a Pdftable object.
  • Set the table style using the methods under PdfTableStyle object which is returned by PdfTable.getTableStyle() method.
  • Insert data to table using PdfTable.setDataSource() method.
  • Set row height and row color through BeginRowLayout event.
  • Draw table on the PDF page using PdfTable.draw() method.
  • Save the document to a PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.data.table.DataTable;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageSize;
import com.spire.pdf.graphics.*;
import com.spire.pdf.tables.*;

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

public class CreateTable {

    public static void main(String[] args) {

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

        //Add a page
        PdfPageBase page = doc.getPages().add(PdfPageSize.A4, new PdfMargins(40));

        //Create a PdfTable object
        PdfTable table = new PdfTable();

        //Set font for header and the rest cells
        table.getStyle().getDefaultStyle().setFont(new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 12), true));
        table.getStyle().getHeaderStyle().setFont(new PdfTrueTypeFont(new Font("Times New Roman", Font.BOLD, 12), true));

        //Define data
        String[] data = {"ID;Name;Department;Position;Level",
                "1; David; IT; Manager; 1",
                "3; Julia; HR; Manager; 1",
                "4; Sophie; Marketing; Manager; 1",
                "7; Wickey; Marketing; Sales Rep; 2",
                "9; Wayne; HR; HR Supervisor; 2",
                "11; Mia; Dev; Developer; 2"};
        String[][] dataSource = new String[data.length][];
        for (int i = 0; i < data.length; i++) {
            dataSource[i] = data[i].split("[;]", -1);
        }

        //Set data as the table data
        table.setDataSource(dataSource);

        //Set the first row as header row
        table.getStyle().setHeaderSource(PdfHeaderSource.Rows);
        table.getStyle().setHeaderRowCount(1);

        //Show header(the header is hidden by default)
        table.getStyle().setShowHeader(true);

        //Set font color and background color of header row
        table.getStyle().getHeaderStyle().setBackgroundBrush(PdfBrushes.getGray());
        table.getStyle().getHeaderStyle().setTextBrush(PdfBrushes.getWhite());

        //Set text alignment in header row
        table.getStyle().getHeaderStyle().setStringFormat(new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));

        //Set text alignment in other cells
        for (int i = 0; i < table.getColumns().getCount(); i++) {
            table.getColumns().get(i).setStringFormat(new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));
        }

        //Register with BeginRowLayout event
        table.beginRowLayout.add(new BeginRowLayoutEventHandler() {

            public void invoke(Object sender, BeginRowLayoutEventArgs args) {
                Table_BeginRowLayout(sender, args);

            }
        });

        //Draw table on the page
        table.draw(page, new Point2D.Float(0, 30));

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

    }

    //Event handler
    private static void Table_BeginRowLayout(Object sender, BeginRowLayoutEventArgs args) {

        //Set row height
        args.setMinimalHeight(20f);

        //Alternate color of rows except the header row
        if (args.getRowIndex() == 0) {
            return;
        }
        if (args.getRowIndex() % 2 == 0) {
            args.getCellStyle().setBackgroundBrush(PdfBrushes.getLightGray());
        } else {
            args.getCellStyle().setBackgroundBrush(PdfBrushes.getWhite());
        }
    }
}

Java: Create Tables in a PDF Document

Create a Table in PDF Using PdfGrid Class

Below are the steps to create a table in PDF using the PdfGrid class using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.getPages().add() method.
  • Create a PdfGrid object.
  • Set the table style using the methods under the PdfGridStyle object which is returned by PdfGrid.getStyle() method.
  • Add rows and columns to the table using PdfGrid.getRows().add() method and PdfGrid.getColumns().add() method.
  • Insert data to specific cells using PdfGridCell.setValue() method.
  • Span cells across columns or rows using PdfGridCell.setRowSpan() method or PdfGridCell.setColumnSpan() method.
  • Set the formatting of a specific cell using PdfGridCell.setStringFormat() method and the methods under PdfGridCellStyle object.
  • Draw table on the PDF page using PdfGrid.draw() method.
  • Save the document to a PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import com.spire.pdf.grid.PdfGrid;
import com.spire.pdf.grid.PdfGridRow;

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

public class CreateGrid {

    public static void main(String[] args) {

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

        //Add a page
        PdfPageBase page = doc.getPages().add(PdfPageSize.A4,new PdfMargins(40));

        //Create a PdfGrid
        PdfGrid grid = new PdfGrid();

        //Set cell padding
        grid.getStyle().setCellPadding(new PdfPaddings(1, 1, 1, 1));

        //Set font
        grid.getStyle().setFont(new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 13), true));

        //Add rows and columns
        PdfGridRow row1 = grid.getRows().add();
        PdfGridRow row2 = grid.getRows().add();
        PdfGridRow row3 = grid.getRows().add();
        PdfGridRow row4 = grid.getRows().add();
        grid.getColumns().add(4);

        //Set column width
        for (int i = 0; i < grid.getColumns().getCount(); i++) {

            grid.getColumns().get(i).setWidth(120);
        }

        //Write data into specific cells
        row1.getCells().get(0).setValue("Order and Payment Status");
        row2.getCells().get(0).setValue("Order number");
        row2.getCells().get(1).setValue("Date");
        row2.getCells().get(2).setValue ("Customer");
        row2.getCells().get(3).setValue("Paid or not");
        row3.getCells().get(0).setValue("00223");
        row3.getCells().get(1).setValue("2022/06/02");
        row3.getCells().get(2).setValue("Brick Lane Realty");
        row3.getCells().get(3).setValue("Yes");
        row4.getCells().get(0).setValue("00224");
        row4.getCells().get(1).setValue("2022/06/03");
        row4.getCells().get(3).setValue("No");

        //Span cell across columns
        row1.getCells().get(0).setColumnSpan(4);

        //Span cell across rows
        row3.getCells().get(2).setRowSpan(2);

        //Set text alignment of specific cells
        row1.getCells().get(0).setStringFormat(new PdfStringFormat(PdfTextAlignment.Center));
        row3.getCells().get(2).setStringFormat(new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle));

        //Set background color of specific cells
        row1.getCells().get(0).getStyle().setBackgroundBrush(PdfBrushes.getOrange());
        row4.getCells().get(3).getStyle().setBackgroundBrush(PdfBrushes.getLightGray());

        //Format cell border
        PdfBorders borders = new PdfBorders();
        borders.setAll(new PdfPen(new PdfRGBColor(Color.ORANGE), 0.8f));
        for (int i = 0; i < grid.getRows().getCapacity(); i++) {

            PdfGridRow gridRow = grid.getRows().get(i);
            gridRow.setHeight(20f);
            for (int j = 0; j < gridRow.getCells().getCount(); j++) {
                gridRow.getCells().get(j).getStyle().setBorders(borders);
            }

        }

        //Draw table on the page
        grid.draw(page, new Point2D.Float(0, 30));

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

Java: Create Tables in a PDF Document

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.

If you are having trouble handling a great many PDF files, you might want to merge all of those files into one. Combining multiple files into one PDF lets you store, share and review them more easily. In this article, you will learn how to merge PDF documents in Java by 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>10.4.4</version>
    </dependency>
</dependencies>
    

Merge Multiple PDFs into a Single PDF

Spire.PDF for Java offers the PdfDocument.mergeFiles() method to merge multiple PDF documents into a single document. The detailed steps are as follows.

  • Get the paths of the documents to be merged and store them in a String array.
  • Call PdfDocument.mergeFiles() method to merge these files. This method also accepts an array of InputStream as the parameter.
  • Save the result to a PDF document using PdfDocumentBase.save() method.
  • Java
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfDocumentBase;

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

        //Get the paths of the documents to be merged
        String[] files = new String[] {
                "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-1.pdf",
                "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-2.pdf",
                "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-3.pdf"};

        //Merge these documents and return an object of PdfDocumentBase
        PdfDocumentBase doc = PdfDocument.mergeFiles(files);

        //Save the result to a PDF file
        doc.save("output.pdf", FileFormat.PDF);
    }
}

Java: Merge Multiple PDFs into a Single PDF

Merge the Selected Pages of Different PDFs into One PDF

Spire.PDF for Java offers the PdfDocument.insertPage() method and the PdfDocument.insertPageRange() method to import a page or a page range from one PDF document to another. The following are the steps to combine the selected pages of different PDF documents into a new PDF document.

  • Get the paths of the source documents and store them in a String array.
  • Create an array of PdfDocument, and load each source document to a separate PdfDocument object.
  • Create another PdfDocument object for generating a new document.
  • Insert the selected page or page range of the source documents to the new document using PdfDocument.insertPage() method and PdfDocument.insertPageRange() method.
  • Save the new document to a PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;

public class MergeSelectedPages {

    public static void main(String[] args) {

        //Get the paths of the documents to be merged
        String[] files = new String[] {
                "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-1.pdf",
                "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-2.pdf",
                "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-3.pdf"};

        //Create an array of PdfDocument
        PdfDocument[] docs = new PdfDocument[files.length];

        //Loop through the documents
        for (int i = 0; i < files.length; i++)
        {
            //Load a specific document
            docs[i] = new PdfDocument(files[i]);
        }

        //Create a PdfDocument object for generating a new PDF document
        PdfDocument doc = new PdfDocument();

        //Insert the selected pages from different documents to the new document
        doc.insertPage(docs[0], 0);
        doc.insertPageRange(docs[1], 1,3);
        doc.insertPage(docs[2], 0);

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

Java: Merge Multiple PDFs into a Single 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.