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

Monday, 12 November 2018 07:34

Spire.PDF for Java Program Guide Content

Spire.PDF for Java is a PDF API that enables Java applications to read, write and save PDF documents without using Adobe Acrobat. Using this Java PDF component, developers and programmers can implement rich capabilities to create PDF files from scratch or process existing PDF documents entirely on Java applications (J2SE and J2EE).

Many rich features can be supported by it, such as security settings, extract text/image from the PDF, merge/split PDF, draw text/image/shape/barcode to the PDF, create and fill in form fields, add and delete PDF layers, overlay PDF, insert text/image watermark to the PDF, add/update/delete PDF bookmarks, add tables to the PDF, compress PDF document etc.

Monday, 12 November 2018 06:52

Draw Barcode on PDF in Java

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

Wednesday, 29 June 2022 07:04

Java: Encrypt or Decrypt PDF Files

For PDF documents that contain confidential or sensitive information, you may want to password protect these documents to ensure that only the designated person can access the information. This article will demonstrate how to programmatically encrypt a PDF document and decrypt a password-protected document 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.3.4</version>
    </dependency>
</dependencies>
    

Encrypt a PDF File with Password

There are two kinds of passwords for encrypting a PDF file - open password and permission password. The former is set to open the PDF file, while the latter is set to restrict printing, contents copying, commenting, etc. If a PDF file is secured with both types of passwords, it can be opened with either password.

The PdfDocument.getSecurity().encrypt(java.lang.String openPassword, java.lang.String permissionPassword, java.util.EnumSet<PdfPermissionsFlags> permissions, PdfEncryptionKeySize keySize) method offered by Spire.PDF for Java allows you to set both open password and permission password to encrypt PDF files. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a sample PDF file using PdfDocument.loadFromFile() method.
  • Set open password, permission password, encryption key size and permissions.
  • Encrypt the PDF file using PdfDocument.getSecurity().encrypt(java.lang.String openPassword, java.lang.String permissionPassword, java.util.EnumSet<PdfPermissionsFlags> permissions, PdfEncryptionKeySize keySize) method.
  • Save the result file using PdfDocument.saveToFile () method.
  • Java
import java.util.EnumSet;

import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;

public class EncryptPDF {

    public static void main(String[] args) {

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

        //Load a sample PDF file
        pdf.loadFromFile("E:\\Files\\sample.pdf");

        //Encrypt the file
        PdfEncryptionKeySize keySize = PdfEncryptionKeySize.Key_128_Bit;
        String openPassword = "e-iceblue";
        String permissionPassword = "test";
        EnumSet flags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Fill_Fields);
        pdf.getSecurity().encrypt(openPassword, permissionPassword, flags, keySize);

        //Save and close
        pdf.saveToFile("Encrypt.pdf");
        pdf.close();

    }

}

Java: Encrypt or Decrypt PDF Files

Remove Password to Decrypt a PDF File

When you need to remove the password from a PDF file, you can set the open password and permission password to empty while calling the PdfDocument.getSecurity().encrypt(java.lang.String openPassword, java.lang.String permissionPassword, java.util.EnumSet<PdfPermissionsFlags> permissions, PdfEncryptionKeySize keySize, java.lang.String originalPermissionPassword) method. The detailed steps are as follows.

  • Create a PdfDocument object.
  • Load the encrypted PDF file with password using PdfDocument.loadFromFile(java.lang.String filename, java.lang.String password) method.
  • Decrypt the PDF file by setting the open password and permission password to empty using PdfDocument.getSecurity().encrypt(java.lang.String openPassword, java.lang.String permissionPassword, java.util.EnumSet<PdfPermissionsFlags> permissions, PdfEncryptionKeySize keySize, java.lang.String originalPermissionPassword) method.
  • Save the result file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;

public class DecryptPDF {

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

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        
        //Load the encrypted PDF file with password
        pdf.loadFromFile("Encrypt.pdf", "e-iceblue");

        //Decrypt the file
        pdf.getSecurity().encrypt("", "", PdfPermissionsFlags.getDefaultPermissions(), PdfEncryptionKeySize.Key_256_Bit, "test");

        //Save and close
        pdf.saveToFile("Decrypt.pdf");
        pdf.close();
    }
}

Java: Encrypt or Decrypt PDF Files

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, 06 February 2023 07:02

Java: Insert Text Watermarks to PDF

Text watermarks are digital marks consisting of formatted text displayed semi-transparently on PDF pages. They are often used to show copyright, author, company, or other document attributes. Unlike comments or stamps, text watermarks are integrated into PDF documents and can’t be removed easily. Therefore, they are also used to protect copyright or ownership of documents. This article will show how to use Spire.PDF for Java to insert text watermarks into PDF documents.

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>
    

Insert a Single Text Watermark to a PDF Document

A single text watermark is a text watermark that is displayed only once in the middle of a PDF page. The steps for inserting a single text watermark into a PDF document using Spire.PDF for Java are as follows.

  • Create a PdfDocument class instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Loop through the pages to insert watermarks.
  • Get a specific page using PdfDocument.getPages().get() method.
  • Set the transparency of the watermark using PdfPageBase.getCanvas().setTransparency() method.
  • Set the translation amount of the coordinate using PdfPageBase.getCanvas().translateTransform() method.
  • Set the rotation angle of the watermark using PdfPageBase.getCanvas().rotateTransform() method.
  • Draw the watermark on the page using PdfPageBase.getCanvas().drawString() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.*;
import com.spire.pdf.graphics.*;

import java.awt.*;

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

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

        //Load a PDF document
        pdf.loadFromFile("We’ve Always Been Distracted.pdf");

        //Loop through all pages in the PDF document to insert watermarks
        String text = "DRAFT";
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 50));
        float set1 = (float) (font.measureString(text).getWidth() * Math.sqrt(2)/4);
        float set2 = (float) (font.measureString(text).getHeight() * Math.sqrt(2)/4);
        for (int i = 0; i < pdf.getPages().getCount(); i++){
            //Get a page
            PdfPageBase page = pdf.getPages().get(i);
            //Set the transparency of the watermark
            page.getCanvas().setTransparency(0.8f);
            //Set translation amount of the coordinate
            page.getCanvas().translateTransform(page.getCanvas().getSize().getWidth()/2 - set1 - set2, page.getCanvas().getSize().getHeight()/2 + set1 - set2);
            //Set the rotation angle
            page.getCanvas().rotateTransform(-45);
            //Draw the watermark text on the page
            page.getCanvas().drawString(text, font, PdfBrushes.getDarkGray(), 0, 0);
        }

        //Save the document
        pdf.saveToFile("SingleTextWatermark.pdf");
    }
}

Java: Insert Text Watermarks to PDF

Insert a Tiled Text Watermark to a PDF Document

Tiled watermarks are displayed multiple times on one page. They are used more often to protect the copyright and ownership of documents. We can create a custom method insertTextWatermark() based on classes and methods of Spire.PDF for Java to insert tiled text watermarks into a PDF document. The detailed steps are as follows.

  • Create a PdfDocument class instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Loop through the pages in the document to insert watermarks.
  • Get a page in the document using PdfDocument.getPages().get() method.
  • Insert a text watermark using the custom method insertTextWatermark().
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import com.spire.pdf.htmlconverter.qt.Size;

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


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

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

        //Load a PDF file
        pdf.loadFromFile("We’ve Always Been Distracted.pdf");

        //Loop through the pages to insert watermarks
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 20));
        for (int i = 0; i < pdf.getPages().getCount(); i++){
            PdfPageBase pageBase = pdf.getPages().get(i);
            insertTextWatermark(pageBase, font, "CONFIDENTIAL", 3, 3);
        }

        //Save the document
        pdf.saveToFile("TiledTextWatermark.pdf");
    }

    static void insertTextWatermark(PdfPageBase page, PdfTrueTypeFont font, String watermark, int row, int column) {

        //Calculate the values of two offset variables to be used to calculate the translation amount of the coordinate
        float set1 = (float)(font.measureString(watermark).getWidth() * Math.sqrt(2)/4);
        float set2 = (float)(font.measureString(watermark).getHeight() * Math.sqrt(2)/4);

        //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 - set1 - set2, brush.getSize().getHeight()/2 + set1 - set2);
        brush.getGraphics().rotateTransform(-45);

        //Draw watermark text on the tile brush
        brush.getGraphics().drawString(watermark, font, PdfBrushes.getViolet(), 0, 0);
        brush.getGraphics().restore();

        //Draw watermark with the tile brush
        page.getCanvas().drawRectangle(brush, new Rectangle(new Point(0, 0), new Dimension((int)(page.getActualSize().getWidth()), (int)(page.getActualSize().getHeight()))));
    }
}

Java: Insert Text 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, 30 October 2018 00:52

Delete Images in PDF in Java

This article shows how to delete a particular picture on a PDF page and how to delete all pictures of the entire document by using Spire.PDF for Java.

Delete a particular image

import com.spire.pdf.PdfDocument;

public class DeleteImage {

	public static void main(String[] args) {

		//create a PdfDocument object
		PdfDocument doc = new PdfDocument();
		
		//load a sample PDF file
		doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Images.pdf");

		//get the specified page
		PdfPageBase page = doc.getPages().get(0);
		
		//delete a particular image by its index
		page.deleteImage(1);

		//save the file
		doc.saveToFile("DeleteSpecificImage.pdf", FileFormat.PDF);
	}

}

Delete all images

import com.spire.pdf.exporting.PdfImageInfo;

public class DeleteAllImages {

    public static void main(String[] args) {

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

        //load a sample PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\asda.pdf");

        //loop through the pages
        for (int i = 0; i < doc.getPages().getCount(); i++) {

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

            //get the image information of the page
            PdfImageInfo[] imageInfo = page.getImagesInfo();

            //loop through the image information collection
            for (int j = imageInfo.length; j > 0; j--) {

                //delete image by its index
                page.deleteImage(j - 1);
            }
        }

        //save the file
        doc.saveToFile("DeleteAllImages.pdf", FileFormat.PDF);
    }
}