News Category

Java: Compare PDF Documents

2023-10-16 01:30:33 Written by support iceblue

Comparison of PDF documents is essential for effective document management. By comparing PDF documents, users can easily identify differences in document content to have a more comprehensive understanding of them, which will greatly facilitate the user to modify and integrate the document content. This article will introduce how to use Spire.PDF for Java to compare PDF documents and find the differences.

Examples of the two PDF documents that will be used for comparison:

Java: Compare PDF Documents

Install Spire.PDF for Java

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

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

Compare Two PDF Documents

Spire.PDF for Java provides the PdfComparer class for users to create an object with two PDF documents for comparing. After creating the PdfComparer object, users can use PdfComparer.compare(String fileName) method to compare the two documents and save the result as a new PDF file.

The resulting PDF document displays the two original documents on the left and the right, with the deleted items in red and the added items in yellow.

The detailed steps for comparing two PDF documents are as follows:

  • Create two objects of PdfDocument class and load two PDF documents using PdfDocument.loadFromFile() method.
  • Create an object of PdfComparer class with the two documents.
  • Compare the two documents and save the result as a new PDF document using PdfComparer.compare() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.comparison.PdfComparer;

public class ComparePDFPageRange {
    public static void main(String[] args) {
        //Create an object of PdfDocument class and load a PDF document
        PdfDocument pdf1 = new PdfDocument();
        pdf1.loadFromFile("Sample1.pdf");

        //Create another object of PdfDocument class and load another PDF document
        PdfDocument pdf2 = new PdfDocument();
        pdf2.loadFromFile("Sample2.pdf");

        //Create an object of PdfComparer class
        PdfComparer comparer = new PdfComparer(pdf1,pdf2);

        //Compare the two PDF documents and save the compare results to a new document
        comparer.compare("ComparisonResult.pdf");
    }
}

Java: Compare PDF Documents

Compare a Specified Page Range of Two PDF Documents

Before comparing, users can use the PdfComparer.getOptions().setPageRanges() method to limit the page range to be compared. The detailed steps are as follows:

  • Create two objects of PdfDocument class and load two PDF documents using PdfDocument.loadFromFile() method.
  • Create an object of PdfComparer class with the two documents.
  • Set the page range to be compared using PdfComparer.getOptions().setPageRanges() method.
  • Compare the two documents and save the result as a new PDF document using PdfComparer.compare() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.comparison.PdfComparer;

public class ComparePDFPageRange {
    public static void main(String[] args) {
        //Create an object of PdfDocument class and load a PDF document
        PdfDocument pdf1 = new PdfDocument();
        pdf1.loadFromFile("G:/Documents/Sample6.pdf");

        //Create another object of PdfDocument class and load another PDF document
        PdfDocument pdf2 = new PdfDocument();
        pdf2.loadFromFile("G:/Documents/Sample7.pdf");

        //Create an object of PdfComparer class
        PdfComparer comparer = new PdfComparer(pdf1,pdf2);

        //Set the page range to be compared
        comparer.getOptions().setPageRanges(1, 1, 1, 1);

        //Compare the two PDF documents and save the compare results to a new document
        comparer.compare("ComparisonResult.pdf");
    }
}

Java: Compare PDF Documents

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.

A footer is text or other content located at the bottom of a page, usually including page numbers, dates, authors, and other information. Footers contribute to the overall professional appearance of the document by maintaining a consistent layout across all pages. By incorporating footers, PDF documents become more professional, user-friendly, and compliant with legal requirements. This article demonstrates how to add a footer to an existing PDF document in Java 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>
    

Background Knowledge

When using Spire.PDF for Java to process an existing PDF document, the origin of the coordinate system is located at the top left corner of the page, with the x-axis extending to the right and the y-axis extending downward. Adding a footer to a page means adding content, such as text, images, automatic fields and shapes, to a specified location in the bottom blank area of the page.

Java: Add a Footer to an Existing PDF Document

If the blank area is not large enough to accommodate the content you want to add, you can consider increasing the PDF page margins.

Add a Footer to an Existing PDF Document in Java

Spire.PDF for Java offers the PdfCanvas.drawString() method, PdfCanvas.drawImage() method, PdfCanvas.drawLine() method and its similar methods, allowing users to draw text, images and shapes on a PDF page at the specified location. To add dynamic data to the footer, such as page numbers, sections, dates, you need to use the automatic fields. Spire.PDF for Java provides the PdfPageNumberField class, PdfPageCountField calss, PdfSectionNumberField class etc. to achieve the addition of dynamic information.

The following are the steps to add a footer consisting of an image and page number to a PDF document using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Load an image using PdfImage.fromFile() method.
  • Draw the image on the bottom blank area of a page using PdfPageBase.getCanvas().drawImage() method.
  • Create a PdfPageNumberField object, a PdfPageCountField object, and combine them in a PdfCompositefield object to return the string "Page X of Y".
  • Draw page number on the bottom blank area of a page using PdfCompositeField.draw() method.
  • Save the document to another PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.PdfBrush;
import com.spire.pdf.graphics.PdfBrushes;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.graphics.PdfTrueTypeFont;

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

public class AddFooterToPdf {

    public static void main(String[] args) {

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

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

        //Load an image
        PdfImage footerImage = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\bg.jpg");

        //Create a true type font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.BOLD, 12),true);

        //Create a brush
        PdfBrush brush = PdfBrushes.getWhite();

        //Create a page number field
        PdfPageNumberField pageNumberField = new PdfPageNumberField();

        //Create a page count field
        PdfPageCountField pageCountField = new PdfPageCountField();

        //Create a composite field to combine page count field and page number field in a single string
        PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);

        //Get the text size
        Dimension2D fontSize = font.measureString(compositeField.getText());

        //Get the page size
        Dimension2D pageSize = doc.getPages().get(0).getSize();

        //Set the position of the composite field
        compositeField.setLocation(new Point2D.Double((pageSize.getWidth() - fontSize.getWidth())/2,  pageSize.getHeight() - 45));

        //Loop through the pages in the document
        for (int i = 0; i < doc.getPages().getCount(); i++)
        {
            //Get a specific page
            PdfPageBase page = doc.getPages().get(i);

            //Draw the image on the bottom blank area
            page.getCanvas().drawImage(footerImage, 55, pageSize.getHeight() - 65, pageSize.getWidth() - 110, 50);

            //Draw the composite field on the bottom blank area
            compositeField.draw(page.getCanvas());
        }

        //Save to file
        doc.saveToFile("output/AddFooter.pdf");
        doc.dispose();
    }
}

Java: Add a Footer to an Existing 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.

Combining multiple images into a single PDF document is an efficient method for those who want to store or distribute their images in a more organized way. Converting these images into a single PDF file not only saves storage space but also ensures that all images are kept together in one place, making it easier and more convenient to share or transfer them. In this article, you will learn how to merge several images into a single PDF document in Java 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>
    

Convert Multiple Images into a Single PDF Document in Java

In order to convert all the images in a folder to a PDF, we iterate through each image, add a new page to the PDF with the same size as the image, and then draw the image onto the new page. The following are the detailed steps.

  • Create a PdfDocument object.
  • Set the page margins to zero using PdfDocument.getPageSettings().setMargins() method.
  • Get the folder where the images are stored.
  • Iterate through each image file in the folder, and get the width and height of a specific image.
  • Add a new page that has the same width and height as the image to the PDF document using PdfDocument.getPages().add() method.
  • Draw the image on 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.PdfImage;

import java.awt.*;
import java.io.File;

public class ConvertMultipleImagesIntoPdf {

    public static void main(String[] args) {

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

        //Set the page margins to 0
        doc.getPageSettings().setMargins(0);

        //Get the folder where the images are stored
        File folder = new File("C:/Users/Administrator/Desktop/Images");

        //Iterate through the files in the folder
        for (File file : folder.listFiles())
        {
            //Load a particular image
            PdfImage pdfImage = PdfImage.fromFile(file.getPath());

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

            //Add a page that has the same size as the image
            PdfPageBase page = doc.getPages().add(new Dimension(width, height));

            //Draw image at (0, 0) of the page
            page.getCanvas().drawImage(pdfImage, 0, 0, width, height);
        }

        //Save to file
        doc.saveToFile("CombineImagesToPdf.pdf");
        doc.dispose();
    }
}

Java: Combine Multiple Images into a Single 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.

Converting a PDF document to an image format like JPEG or PNG can be useful for a variety of reasons, such as making it easier to share the content on social media, embedding it into a website, or including it in a presentation. Converting PDF to images can also avoid printing issues caused by the printers that do not support PDF format well enough. In this article, you will learn how to convert PDF to JPEG or PNG 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.3.4</version>
    </dependency>
</dependencies>
    

Convert PDF to JPEG in Java

The PdfDocument.saveAsImage() method provided by Spire.PDF for Java enables the conversion of a particular page from a PDF document into a BufferedImage object, which can be saved as a file in .jpg or .png format. The following are the steps to convert each page of a PDF document to a JPEG image file.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.loadFromFile() method.
  • Iterate through each page of the PDF document.
  • Convert a specific page into a BufferedImage object using PdfDocument.saveAsImage() method.
  • Re-create a BufferedImage in RGB type with the same width and height as the converted image.
  • Write the image data as a .jpg file using ImageIO.write() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.PdfImageType;

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

public class ConvertPdfToJpeg {

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

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

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

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

            //Save the current page as a buffered image
            BufferedImage image = pdf.saveAsImage(i, PdfImageType.Bitmap, 300, 300);

            //Re-create a buffered image in RGB type
            BufferedImage newImg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
            newImg.getGraphics().drawImage(image, 0, 0, null);

            //Write the image data as a .jpg file
            File file = new File("C:\\Users\\Administrator\\Desktop\\Output\\" + String.format(("ToImage-%d.jpg"), i));
            ImageIO.write(newImg, "JPEG", file);
        }
        pdf.close();
    }
}

Convert PDF to PNG in Java

The steps to convert PDF to PNG using Spire.PDF for Java are as follows.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.loadFromFile() method.
  • Iterate through each page of the PDF document.
  • Convert a specific page into a BufferedImage object using PdfDocument.saveAsImage() method.
  • Write the image data as a .png file using ImageIO.write() method.
  • Java
import com.spire.pdf.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ConvertPdfToPng {

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

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

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

        //Make the background of the generated PNG files transparent 
        //doc.getConvertOptions().setPdfToImageOptions(0);

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

            //Save the current page as a buffered image
            BufferedImage image = doc.saveAsImage(i);

            //Write the image data as a .png file
            File file = new File("C:\\Users\\Administrator\\Desktop\\Output\\" + String.format("ToImage-%d.png", i));
            ImageIO.write(image, "png", file);
        }
        doc.close();
    }
}

If the background of the PDF document is white and you want to make it transparent when converted to PNG, you can add following line of code before you save each page to a BufferedImage object.

  • Java
doc.getConvertOptions().setPdfToImageOptions(0);

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.

Adding a header to a PDF document is a useful way to display important information such as the document title, author, and page numbers. A header is a section of text or graphics that appears at the top of each page in a document and can be customized according to your needs. This feature is particularly helpful when creating reports, contracts, or other professional documents that require a consistent format. In this article, you will learn how to add a header to an existing PDF document in Java 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>
    

Background Knowledge

When an existing PDF document is manipulated by Spire.PDF for Java, the origin of the coordinate system is located at the top left corner of the page, with the x-axis extending to the right and the y-axis extending downward. Adding a header to a page means adding content, such as text, images, automatic fields and shapes, to a specified location in the upper blank area of the page.

Java: Add a Header to an Existing PDF Document

If the blank area is not large enough to accommodate the content you want to add, you can consider increasing the PDF page margins.

Add a Header to an Existing PDF Document in Java

Spire.PDF for Java allows users to draw text, images and shapes on a PDF page using PdfCanvas.drawString() method, PdfCanvas.drawImage() method, PdfCanvas.drawLine() method and other similar methods. To add dynamic information to the header, such as page numbers, sections, dates, you need to resort to automatic fields. Spire.PDF for Java provides the PdfPageNumberField class, PdfSectionNumberField class, PdfCreationDateField class, etc. to achieve the dynamic addition of these data.

The following are the steps to add a header consisting of text, an image, a date, and a line to a PDF document using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Create font, pen and brush objects that will be used to draw text or shapes.
  • Draw text on the top blank area of a page using PdfPageBase.getCanvas().drawString() method.
  • Draw a line on the top blank area of a page using PdfPageBase.getCanvas().drawLine() method.
  • Load an image using PdfImage.fromFile() method.
  • Draw the image on the top blank area of a page using PdfPageBase.getCanvas().drawImage() method.
  • Create a PdfCreationDateField object that reflects the creation time of the document.
  • Draw the creation time on the top blank area of a page using PdfCreationDateField.draw() method.
  • Save the document to another PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfCreationDateField;
import com.spire.pdf.graphics.*;

import java.awt.*;

public class AddHeaderToPdf {

    public static void main(String[] args) {

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

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

        //Load an image for the header
        PdfImage headerImage = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\logo.png");

        //Get image width in pixel
        float width = headerImage.getWidth();

        //Convert pixel to point
        PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
        float pointWidth = unitCvtr.convertUnits(width, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);

        //Specify text for the header
        String headerText = "E-iceblue Tech\nwww.e-iceblue.com";

        //Create a true type font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.BOLD, 12),true);

        //Create a brush
        PdfBrush brush = PdfBrushes.getPurple();

        //Create a pen
        PdfPen pen = new PdfPen(brush, 1.0f);

        //Create a creation date field
        PdfCreationDateField creationDateField = new PdfCreationDateField(font, brush);
        creationDateField.setDateFormatString("yyyy-MM-dd");

        //Create a composite field to combine static string and date field
        PdfCompositeField compositeField = new PdfCompositeField(font, brush, "creation time: {0}", creationDateField);
        compositeField.setLocation(new Point(55, 48));

        //Loop through the pages in the document
        for (int i = 0; i < doc.getPages().getCount(); i++)
        {
            //Get specific page
            PdfPageBase page = doc.getPages().get(i);

            //Draw the image on the top blank area
            page.getCanvas().drawImage(headerImage, page.getActualSize().getWidth() - pointWidth - 55, 20);

            //Draw text on the top blank area
            page.getCanvas().drawString(headerText, font, brush, 55, 20);

            //Draw a line on the top blank area
            page.getCanvas().drawLine(pen, new Point(55, 70), new Point((int)page.getActualSize().getWidth() - 55, 70));

            //Draw the composite field on the top blank area
            compositeField.draw(page.getCanvas());
        }

        //Save to file
        doc.saveToFile("output/AddHeader.pdf");
        doc.dispose();
    }
}

Java: Add a Header to an Existing 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.

PDF is a popular and widely used file format, but when it comes to giving presentations to others in meetings, classes or other scenarios, PowerPoint is always preferred over PDF files because it contains rich presentation effects that can better capture the attention of your audience. In this article, you will learn how to convert an existing PDF file to a PowerPoint presentation 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>
    

Convert PDF to PowerPoint Presentation in Java

From Version 9.2.1, Spire.PDF for Java supports converting PDF to PPTX using PdfDocument.saveToFile() method. With this method, each page of your PDF file will be converted to a single slide in PowerPoint. Below are the steps to convert a PDF file to an editable PowerPoint document.

  • Create a PdfDocument instance.
  • Load a sample PDF document using PdfDocument.loadFromFile() method.
  • Save the document as a PowerPoint document using PdfDocument.saveToFile(String filename, FileFormat.PPTX) method.
  • Java
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;

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

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

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

        //Convert PDF to PPTX document
        pdfDocument.saveToFile("PDFtoPowerPoint.pptx", FileFormat.PPTX);
    }
}

Java: Convert PDF to PowerPoint Presentation

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.

A tagged PDF is a PDF document that contains tags that are pretty similar to HTML code. Tags provide a logical structure that governs how the content of the PDF is presented through assistive technology. Each tag identifies the associated content element, for example heading level 1 <H1>, paragraph <P>, image <Figure>, or table <Table>. In this article, you will learn how to create a tagged PDF document in Java 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>
    

Create a Tagged PDF in Java

To add structure elements in a tagged PDF document, we must first create an object of PdfTaggedContent class. Then, add an element to the root using PdfTaggedContent.getStructureTreeRoot().appendChildElement() method. The following are the detailed steps to add a "heading" element to a tagged PDF using Spire.PDF for Java.

  • Create a PdfDocument object and add a page to it using PdfDocument.getPages().add() method.
  • Create an object of PdfTaggedContent class.
  • Make the document compliance to PDF/UA identification using PdfTaggedContent.setPdfUA1Identification() method.
  • Add a "document" element to the root of the document using PdfTaggedContent.getStructureTreeRoot().appendChildElement() method.
  • Add a "heading" element under the "document" element using PdfStructureElement.appendChildElement() method.
  • Add a start tag using PdfStructureElement.beginMarkedContent() method, which indicates the beginning of the heading element.
  • Draw heading text on the page using PdfPageBase.getCanvas().drawString() method.
  • Add an end tag using PdfStructureElement.beginMarkedContent() method, which implies the heading element ends here.
  • Save the document to a PDF file using PdfDocument.saveToFile() method.

The following code snippet provides an example on how to create various elements including document, heading, paragraph, figure and table in a tagged PDF document in Java.

  • Java
import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import com.spire.pdf.interchange.taggedpdf.PdfStandardStructTypes;
import com.spire.pdf.interchange.taggedpdf.PdfStructureElement;
import com.spire.pdf.interchange.taggedpdf.PdfTaggedContent;
import com.spire.pdf.tables.PdfTable;

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

public class CreateTaggedPdf {

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

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

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

        //Set tab order
        page.setTabOrder(TabOrder.Structure);

        //Create an object of PdfTaggedContent class
        PdfTaggedContent taggedContent = new PdfTaggedContent(doc);

        //Set language and title for the document
        taggedContent.setLanguage("en-US");
        taggedContent.setTitle("Create Tagged PDF in Java");

        //Set PDF/UA1 identification
        taggedContent.setPdfUA1Identification();

        //Create font and brush
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman",Font.PLAIN,14), true);
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK));

        //Add a "document" element
        PdfStructureElement document = taggedContent.getStructureTreeRoot().appendChildElement(PdfStandardStructTypes.Document);

        //Add a "heading" element
        PdfStructureElement heading1 = document.appendChildElement(PdfStandardStructTypes.HeadingLevel1);
        heading1.beginMarkedContent(page);
        String headingText = "What Is a Tagged PDF?";
        page.getCanvas().drawString(headingText, font, brush, new Point2D.Float(0, 0));
        heading1.endMarkedContent(page);

        //Add a "paragraph" element
        PdfStructureElement paragraph = document.appendChildElement(PdfStandardStructTypes.Paragraph);
        paragraph.beginMarkedContent(page);
        String paragraphText = "Tagged PDF doesn’t seem like a life-changing term. But for some, it is. For people who are " +
                "blind or have low vision and use assistive technology (such as screen readers and connected Braille displays) to " +
                "access information, an untagged PDF means they are missing out on information contained in the document because assistive " +
                "technology cannot “read” untagged PDFs.  Digital accessibility has opened up so many avenues to information that were once " +
                "closed to people with visual disabilities, but PDFs often get left out of the equation.";
        Rectangle2D.Float rect = new Rectangle2D.Float(0, 30, (float) page.getCanvas().getClientSize().getWidth(), (float) page.getCanvas().getClientSize().getHeight());
        page.getCanvas().drawString(paragraphText, font, brush, rect);
        paragraph.endMarkedContent(page);

        //Add a "figure" element
        PdfStructureElement figure = document.appendChildElement(PdfStandardStructTypes.Figure);
        figure.beginMarkedContent(page);
        PdfImage image = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\pdfua.png");
        page.getCanvas().drawImage(image, new Point2D.Float(0, 150));
        figure.endMarkedContent(page);

        //Add a "table" element
        PdfStructureElement table = document.appendChildElement(PdfStandardStructTypes.Table);
        table.beginMarkedContent(page);
        PdfTable pdfTable = new PdfTable();
        pdfTable.getStyle().getDefaultStyle().setFont(font);
        String[] data = {"Name;Age;Sex",
                "John;22;Male",
                "Katty;25;Female"
        };
        String[][] dataSource = new String[data.length][];
        for (int i = 0; i < data.length; i++) {
            dataSource[i] = data[i].split("[;]", -1);
        }
        pdfTable.setDataSource(dataSource);
        pdfTable.getStyle().setShowHeader(true);
        pdfTable.draw(page.getCanvas(), new Point2D.Float(0, 280), 300f);
        table.endMarkedContent(page);

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

Java: Create a Tagged 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.

PDF documents can be secured in several ways. When PDFs are protected with a permission password, readers can open the document without needing to enter a password, but they may not have permission to further manipulate the document, such as printing or copying the content. In this article, you will learn how to set security permissions for a PDF document in Java using Spire.PDF for Java library.

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>
    

Add Security Permissions to a PDF Document in Java

Below are the steps to apply security permissions to a PDF document using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.loadFileFile() method.
  • Specify open password and permission password. The open password can be set to empty so that the generated document will not require a password to open.
  • Encrypt the document with the open password and permission password, and set the security permissions using PdfDocument.getSecurity().encypt() method. This method takes PdfPermissionsFlags enumeration as a parameter, which defines user access permissions for an encrypted document.
  • Save the document to another PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;

import java.util.EnumSet;

public class ChangeSecurityPermissions {

    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\\sample.pdf");

        //Specify open password
        String openPsd = "";

        //Specify permission password
        String permissionPsd = "e-iceblue";

        //Specify permissions
        EnumSet permissionsFlags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Full_Quality_Print);

        //Encrypt the document with open password and permission password, and set the permissions and encryption key size
        doc.getSecurity().encrypt(openPsd, permissionPsd, permissionsFlags, PdfEncryptionKeySize.Key_128_Bit);

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

Java: Add Security Permissions 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.

Java: Convert Text Files to PDF

2022-08-02 01:17:45 Written by support iceblue

Text files can be easily edited by any text editing program. If you want to prevent changes when others view the files, you can convert them to PDF. In this article, we will demonstrate how to convert text files to PDF in Java 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>
    

Convert Text Files to PDF in Java

The following are the main steps to convert a text file to PDF using Spire.PDF for Java:

  • Read the text in the text file into a String object.
  • Create a PdfDocument instance and add a page to the PDF file using PdfDocument.getPages().add() method.
  • Create a PdfTextWidget instance from the text.
  • Draw the text onto the PDF page using PdfTextWidget.draw() method.
  • Save the result file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;

import java.awt.geom.Rectangle2D;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ConvertTextToPdf {
    public static void main(String[] args) throws Exception {
        //Read the text from the text file
        String text = readTextFromFile("Input.txt");

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

        //Create a PdfFont instance
        PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 11);

        //Create a PdfTextLayout instance
        PdfTextLayout textLayout = new PdfTextLayout();
        textLayout.setBreak(PdfLayoutBreakType.Fit_Page);
        textLayout.setLayout(PdfLayoutType.Paginate);

        //Create a PdfStringFormat instance
        PdfStringFormat format = new PdfStringFormat();
        format.setLineSpacing(20f);

        //Create a PdfTextWidget instance from the text
        PdfTextWidget textWidget = new PdfTextWidget(text, font, PdfBrushes.getBlack());
        //Set string format
        textWidget.setStringFormat(format);

        //Draw the text at the specified location of the page
        Rectangle2D.Float bounds = new Rectangle2D.Float();
        bounds.setRect(0,25,page.getCanvas().getClientSize().getWidth(),page.getCanvas().getClientSize().getHeight());
        textWidget.draw(page, bounds, textLayout);

        //Save the result file
        pdf.saveToFile("TextToPdf.pdf", FileFormat.PDF);
    }
    public static String readTextFromFile(String fileName) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String content = null;
        while ((content = br.readLine()) != null) {
            sb.append(content);
            sb.append("\n");
        }
        return sb.toString();
    }
}

Java: Convert Text Files 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.

Java: Change PDF Page Size

2022-07-26 00:59:47 Written by support iceblue

In some circumstances, you may need to change the page size of a PDF. For example, if you have a combined PDF file with pages of different sizes, you may want to resize the pages to the same size for easier reading and printing. In this article, we will introduce how to change the page size of a PDF file in Java 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>
    

Change PDF Page Size to a Standard Paper Size in Java

The way to change the page size of a PDF file is to create a new PDF file and add pages of the desired size to it, next, create templates from the pages in the original PDF file, then draw the templates onto the pages in the new PDF file. This process will preserve text, images, and other elements present in the original PDF.

Spire.PDF for Java supports a variety of standard paper sizes like letter, legal, A0, A1, A2, A3, A4, B0, B1, B2, B3, B4 and many more. The following steps show you how to change the page size of a PDF file to a standard paper size.

  • Initialize a PdfDocument instance and load the original PDF file using PdfDocument.loadFromFile() method.
  • Initialize another PdfDocument instance to create a new PDF file.
  • Loop through the pages in the original PDF.
  • Add pages of the desired size to the new PDF file using PdfDocument.getPages().add() method.
  • Initialize a PdfTextLayout instance and set the text layout as one page using PdfTextLayout.setLayout() method.
  • Create templates based on the pages in the original PDF using PdfPageBase.createTemplate() method.
  • Draw the templates onto the pages in the new PDF file with the specified text layout using PdfTemplate.draw() method.
  • Save the result file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageSize;
import com.spire.pdf.graphics.*;

import java.awt.geom.Point2D;

public class ChangePageSizeToStandardPaperSize {
    public static void main(String []args){
        //Load the original PDF document
        PdfDocument originPdf = new PdfDocument();
        originPdf.loadFromFile("Sample.pdf");

        //Create a new PDF document
        PdfDocument newPdf = new PdfDocument();

        //Loop through the pages in the original PDF
        for(int i = 0; i< originPdf.getPages().getCount(); i++)
        {
            //Add pages of size A1 to the new PDF
            PdfPageBase newPage = newPdf.getPages().add(PdfPageSize.A1, new PdfMargins((0)));
            //Create a PdfTextLayout instance
            PdfTextLayout layout = new PdfTextLayout();
            //Set text layout as one page (if not set the content will not scale to fit page size)
            layout.setLayout(PdfLayoutType.One_Page);
            //Create templates based on the pages in the original PDF
            PdfTemplate template = originPdf.getPages().get(i).createTemplate();
            //Draw templates onto the pages in the new PDF
            template.draw(newPage, new Point2D.Float(0,0), layout);
        }

        //Save the result document
        newPdf.saveToFile("ChangePageSizeToA1.pdf");
    }
}

Java: Change PDF Page Size

Change PDF Page Size to a Custom Paper Size in Java

Spire.PDF for Java uses point (1/72 of an inch) as the unit of measure. If you want to change the page size of a PDF to a custom paper size in other units of measure like inches or millimeters, you can use the PdfUnitConvertor class to convert them to points.

The following steps show you how to change the page size of a PDF file to a custom paper size in inches:

  • Initialize a PdfDocument instance and load the original PDF file using PdfDocument.loadFromFile() method.
  • Initialize another PdfDocument instance to create a new PDF file.
  • Initialize a PdfUnitConvertor instance, then convert the custom size in inches to points using PdfUnitConvertor.convertUnits() method.
  • Initialize a Dimension2D instance from the custom size.
  • Loop through the pages in the original PDF.
  • Add pages of the custom size to the new PDF file using PdfDocument.getPages().add() method.
  • Create a PdfTextLayout instance and set the text layout as one page using PdfTextLayout.setLayout() method.
  • Create templates based on the pages in the original PDF using PdfPageBase.createTemplate() method.
  • Draw the templates onto the pages in the new PDF file with the specified text layout using PdfTemplate.draw() method.
  • Save the result file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;

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

public class ChangePageSizeToCustomPaperSize {
    public static void main(String []args){
        //Load the original PDF document
        PdfDocument originPdf = new PdfDocument();
        originPdf.loadFromFile("Sample.pdf");

        //Create a new PDF document
        PdfDocument newPdf = new PdfDocument();

        //Create a PdfUnitConvertor instance
        PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
        //Convert the custom size in inches to points
        float width = unitCvtr.convertUnits(6.5f, PdfGraphicsUnit.Inch, PdfGraphicsUnit.Point);
        float height = unitCvtr.convertUnits(8.5f, PdfGraphicsUnit.Inch, PdfGraphicsUnit.Point);

        //Create a Dimension2D instance from the custom size, then it will be used as the page size of the new PDF
        Dimension2D size = new Dimension();
        size.setSize(width, height);

        //Loop through the pages in the original PDF
        for(int i = 0; i< originPdf.getPages().getCount(); i++)
        {
            //Add pages of the custom size (6.5*8.5 inches) to the new PDF
            PdfPageBase newPage = newPdf.getPages().add(size, new PdfMargins((0)));
            //Create a PdfTextLayout instance
            PdfTextLayout layout = new PdfTextLayout();
            //Set text layout as one page (if not set the content will not scale to fit page size)
            layout.setLayout(PdfLayoutType.One_Page);
            //Create templates based on the pages in the original PDF
            PdfTemplate template = originPdf.getPages().get(i).createTemplate();
            //Draw templates onto the pages in the new PDF
            template.draw(newPage, new Point2D.Float(0,0), layout);
        }

        //Save the result document
        newPdf.saveToFile("ChangePageSizeToCustomSize.pdf");
    }
}

Java: Change PDF Page Size

Apply for a Temporary License

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

Page 1 of 9