Organize Pages in PDF Documents in Java

When editing PDF documents, users often need to organize pages to make the documents fit their specific requirements. For instance, they may need to insert new pages to include additional information or graphics, rearrange pages to ensure that the content is presented in a logical order, or delete pages containing confidential or sensitive information to protect privacy. In this article, I will explain how to organize pages in a PDF document in Java.

The following topics will be covered in this article:

  • Insert Pages into a PDF Document in Java
  • Delete Pages from a PDF Document in Java
  • Rearrange Pages in a PDF Document in Java
  • Rotate Pages in a PDF Document in Java
  • Import Pages from Another PDF Document in Java
  • Extract Pages from a PDF Document in Java

Add Dependencies

To organize pages in pdf, this article uses Spire.PDF for Java library. If you are using Maven, you can install the jar of Spire.PDF for Java into your project by adding the following code to your project’s pom.xml file.

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

If you are not using Maven, you can download Spire.PDF for Java from the official website, extract the package and then import the Spire.Pdf.jar under the lib folder into your project as a dependency.

Insert Pages into a PDF Document in Java

You can insert a page at a specific position of a PDF document using the PdfDocument.getPages().insert(int index) method or add a page to the end of a PDF document using the PdfDocument.getPages().add() method.

The following are the detailed steps:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using the PdfDocument.loadFromFile() method.
  • Insert a page at a specific position of the document using the PdfDocument.getPages().insert(int index) method, or add a page to the end of a PDF document using the PdfDocument.getPages().add() method.
  • Save the result document using the PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;

public class InsertPages {
    public static void main(String[] args) {
        //Initialize an instance of the PdfDocument class
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("Sample.Pdf");

        //Insert a page at the first index position
        pdf.getPages().insert(0);

        //Add a page to the end of the document
        //pdf.getPages().add();

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

Delete Pages from a PDF Document in Java

You can delete a specific page from a PDF document using the PdfDocument.getPages().removeAt(int index) method.

The following are the detailed steps:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using the PdfDocument.loadFromFile() method.
  • Delete a specific page by its index using the PdfDocument.getPages().removeAt(int index) method.
  • Save the result document using the PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;

public class DeletePages {
    public static void main(String[] args) {
        //Initialize an instance of the PdfDocument class
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("Sample.Pdf");

        //Delete the first page by page index
        pdf.getPages().removeAt(0);

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

Rearrange Pages in a PDF Document in Java

You can rearrange the pages in a PDF document using the PdfDocument.getPages().reArrange(int[] orderArray) method.

The following are the detailed steps:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using the PdfDocument.loadFromFile() method.
  • Create an int array for the new page order.
  • Rearrange the pages in the document according to the order specified in the int array using the PdfDocument.getPages().reArrange(int[] orderArray) method.
  • Save the result document using the PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;

public class RearrangePages {
    public static void main(String[] args) {
        //Initialize an instance of the PdfDocument class
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("Sample.Pdf");

        //Create an int array for new page order 
        //Original page order: 0, 1, 2, 3. Changed page order: 1, 0, 2, 3
        int[] orderArray = new int[] { 1, 0, 2, 3 };
        //Rearrange the pages according to the order specified in the array
        pdf.getPages().reArrange(orderArray);

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

Rotate Pages in a PDF Document in Java

You can rotate a PDF page using the PdfPageBase.setRotation(PdfPageRotateAngle rotateAngle) method.

The following are the detailed steps:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using the PdfDocument.loadFromFile() method.
  • Get the page that you want to rotate using the PdfDocument.getPages().get(int index) method.
  • Get the original rotation angle of the page using the PdfPageBase.getRotation().getValue() method.
  • Increase the original rotation angle by desired degrees.
  • Apply the new rotation angle to the page using the PdfPageBase.setRotation(PdfPageRotateAngle rotateAngle) method.
  • Save the result document using the PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageRotateAngle;

public class RotatePages {
    public static void main(String[] args) {
        //Initialize an instance of the PdfDocument class
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("Sample.pdf");

        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);

        //Get the original rotation angle of the page
        int rotation = (int)page.getRotation().getValue();

        //Rotate the page 180 degrees clockwise based on the original rotation angle
        rotation += PdfPageRotateAngle.Rotate_Angle_180.getValue();
        page.setRotation(PdfPageRotateAngle.fromValue(rotation));

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

Import Pages from Another PDF Document in Java

You can import a page or a range of pages from one PDF document to another PDF document using the PdfDocument.insertPage(PdfDocument doc, int pageIndex) or PdfDocument.insertPageRange(PdfDocument doc, int startIndex, int endIndex) method.

The detailed steps are as follows:

  • Initialize an instance of the PdfDocument class and load the first PDF document using the PdfDocument.loadFromFile() method.
  • Initialize an instance of the PdfDocument class and load the second PDF document using the PdfDocument.loadFromFile() method.
  • Import a specific page or a range of pages from the second PDF document to the first PDF document using the PdfDocument.insertPage(PdfDocument doc, int pageIndex) or PdfDocument.insertPageRange(PdfDocument doc, int startIndex, int endIndex) method.
  • Save the first PDF document to file using the PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;
public class ImportPages {
    public static void main(String[] args) {
        //Initialize an instance of the PdfDocument class
        PdfDocument pdf1 = new PdfDocument();
        //Load the first PDF document
        pdf1.loadFromFile("Sample.Pdf");

        //Initialize an instance of the PdfDocument class
        PdfDocument pdf2 = new PdfDocument();
        //Load the second PDF document
        pdf2.loadFromFile("test.Pdf");

        //Import the first page of the second PDF to the first PDF
        pdf1.insertPage(pdf2, 0);

        //Import a range of pages (page 1 - 4) of the second PDF to the first PDF
        //pdf1.insertPageRange(pdf2, 0, 3);

        //Save the first PDF document to file
        pdf1.saveToFile("ImportPages.pdf");
    }
}

Extract Pages from a PDF Document in Java

The PdfDocument.insertPage(PdfDocument doc, int pageIndex) and PdfDocument.insertPageRange(PdfDocument doc, int startIndex, int endIndex) methods can also be used to extract a specific page or a range of pages from a PDF document to a new PDF document.

The detailed steps are as follows:

  • Initialize an instance of the PdfDocument class and load the source PDF document using the PdfDocument.loadFromFile() method.
  • Initialize an instance of the PdfDocument class to create a new PDF document.
  • Extract a specific page or a range of pages from the source PDF document to the new PDF document using the PdfDocument.insertPage(PdfDocument doc, int pageIndex) or PdfDocument.insertPageRange(PdfDocument doc, int startIndex, int endIndex) method.
  • Save the new PDF document to file using the PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;

public class ExtractPages {
    public static void main(String[] args) {
        //Initialize an instance of the PdfDocument class
        PdfDocument pdf = new PdfDocument();
        //Load the source PDF document
        pdf.loadFromFile("Sample.Pdf");

        //Initialize an instance of the PdfDocument class to create a new PDF document
        PdfDocument newPdf = new PdfDocument();

        //Extract the first page of the source PDF to the new PDF
        newPdf.insertPage(pdf, 0);

        //Extract a range of pages (page 1 - 4) of the source PDF to the new PDF
        //newPdf.insertPageRange(pdf, 0, 3);

        //Save the new PDF document to file
        newPdf.saveToFile("ExtractPages.pdf");
    }
}

Create Tagged PDF in Java

A tagged PDF is a PDF document in which each content element is labeled with a tag. These tags are invisible on the document pages, but they can help assistive technologies understand the structure of the document and thereby enabling people with disabilities to access the information in the document. A tagged PDF can also provide a high-quality reading experience to users using smart mobile devices because it can re-flow to adapt its presentation to different screen sizes. In this article, I will demonstrate how to create tagged PDF documents in Java.

Add Dependencies

To create tagged PDFs, this article uses Spire.PDF for Java. If you are using maven, you can install the jar of Spire.PDF for Java into your project by adding the following code to your project’s pom.xml file.

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

If you are not using maven, you can download Spire.PDF for Java from this website, extract the package and then import the Spire.Pdf.jar under the lib folder into your project as a dependency.

Create Tagged PDF in Java

Spire.PDF provides the PdfTaggedContent class to generate tagged PDF documents. You can include various structural elements in a tagged PDF document, including heading, paragraph, figure, table, link, list, and many more.

The following are the main steps to create a tagged PDF with various structural elements using Java:

  • Initialize an instance of the PdfDocument class and add a page to it using PdfDocument.getPages().add() method.
  • Set the tab order of the page using PdfPageBase.setTabOrder(TabOrder) method.
  • Initialize an instance of the PdfTaggedContent class and pass the PdfDocument instance to the class constructor as a parameter.
  • Set the language and title of the document.
  • Add a document element which is the root element of a structure tree to the document using PdfTaggedContent.getStructureTreeRoot().appendChildElement() method.
  • Add a heading/paragraph/list/figure/table/ link element under the document element using PdfStructureElement.appendChildElement() method.
  • Add a start tag to indicate the beginning of the element using PdfStructureElement.beginMarkedContent() method.
  • Specify the element content and draw it onto the page.
  • Add an end tag to indicate the ending of the element using PdfStructureElement.endMarkedContent() method.
  • Save the result document to a PDF file using PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageSize;
import com.spire.pdf.TabOrder;
import com.spire.pdf.annotations.PdfTextWebLink;
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.lists.PdfMarker;
import com.spire.pdf.lists.PdfUnorderedList;
import com.spire.pdf.lists.PdfUnorderedMarkerStyle;
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 {
        //Initialize an instance of the PdfDocument class
        PdfDocument doc = new PdfDocument();

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

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

        //Initialize an instance of the PdfTaggedContent class
        PdfTaggedContent taggedContent = new PdfTaggedContent(doc);

        //Set language and title
        taggedContent.setLanguage("en-US");
        taggedContent.setTitle("Tagged PDF");

        //Set PDF/UA-1 compliance
        taggedContent.setPdfUA1Identification();

        //Create font and brush
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN,14), true);
        PdfBrush brush = PdfBrushes.getBlack();

        //Add a document element which is the root element of a structure tree
        PdfStructureElement document = taggedContent.getStructureTreeRoot().appendChildElement(PdfStandardStructTypes.Document);

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

        //Add a paragraph element
        PdfStructureElement paragraph = document.appendChildElement(PdfStandardStructTypes.Paragraph);
        paragraph.beginMarkedContent(page);
        String paragraphText = "Java is a computer programming language that was first released in 1995. It is owned by Oracle, and more than 3 billion devices run Java. It can be used for:";
        Rectangle2D rect = new Rectangle2D.Float(10, 30, (float)page.getCanvas().getClientSize().getWidth(), (float)page.getCanvas().getClientSize().getHeight());
        page.getCanvas().drawString(paragraphText, font, brush, rect);
        paragraph.endMarkedContent(page);

        //Add a list element
        PdfStructureElement listElement = document.appendChildElement(PdfStandardStructTypes.List);
        listElement.beginMarkedContent(page);
        String listContent = "Mobile applications (specially Android apps)\n"
                + "Desktop applications\n"
                + "Web applications\n"
                + "Web servers and application servers\n"
                + "Database connection\n"
                + "Games\n"
                + "And many more!";
        PdfMarker marker = new PdfMarker(PdfUnorderedMarkerStyle.Asterisk);
        PdfTrueTypeFont markerFont = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN,6), true);
        marker.setFont(markerFont);
        PdfUnorderedList list = new PdfUnorderedList(listContent);
        list.setFont(font);
        list.setIndent(2);
        list.setTextIndent(4);
        list.setBrush(brush);
        list.setMarker(marker);
        list.draw(page,  10, 70);
        listElement.endMarkedContent(page);

        //Add a figure element
        PdfStructureElement figure = document.appendChildElement(PdfStandardStructTypes.Figure);
        figure.beginMarkedContent(page);
        PdfImage image = PdfImage.fromFile("JavaLogo.png");
        page.getCanvas().drawImage(image, 10, 190);
        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);

        //Define data
        String[] data = {"Year; Product; Sales",
                "2020; Components; $20,000",
                "2021; Bikes; $6,300"};
        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
        pdfTable.setDataSource(dataSource);

        pdfTable.getStyle().setShowHeader(true);
        pdfTable.draw(page.getCanvas(), new Point2D.Float(10, 280), 270f);
        table.endMarkedContent(page);

        //Add a link element
        PdfStructureElement link = document.appendChildElement(PdfStandardStructTypes.Link);
        link.beginMarkedContent(page);
        PdfTextWebLink link2 = new PdfTextWebLink();
        link2.setText("www.google.com");
        link2.setUrl("https://www.google.com");
        link2.setFont(font);
        link2.setBrush(brush);
        link2.drawTextWebLink(page.getCanvas(), new Point2D.Float(10, 340));
        link.endMarkedContent(page);

        //Save the result document
        doc.saveToFile("CreateTaggedPdf.pdf");
    }
}
Create Tagged PDF in Java

Add, Remove, Replace or Extract Images in PDF in Java

In some cases, you may need to add images to a PDF, for example, when you produce a brochure or other publication that contains vivid images. In some other cases, you may need to remove images from a PDF, for example, if you want to remove useless images from the PDF to reduce its file size. This article will demonstrate how to add, remove, replace or extract images in PDF in Java using Spire.PDF for Java.

Add Dependencies

To manipulate images in PDF, this article uses Spire.PDF for Java. If you are using maven, you can install the jar of Spire.PDF for Java into your project by adding the following code to your project’s pom.xml file.

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

If you are not using maven, you can download Spire.PDF for Java from this website, extract the package and then import the Spire.Pdf.jar under the lib folder into your project as a dependency.

Add an Image to a PDF in Java

The following are the main steps to add an image to a PDF document:

  • Initialize an instance of the PdfDocument instance.
  • Load a PDF document from file using PdfDocument.loadFromFile() method.
  • Get a specific page by its index using PdfDocument.getPages().get(int) method.
  • Load an image using PdfImage.fromFile() method.
  • Draw the image to a specific location on the page using PdfPageBase.getCanvas().drawImage() method.
  • Save the result document using PdfDocument.SaveToFile() method.
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;

public class AddImage {
    public static void main(String []args){
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("input.pdf");

        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);

        //Load an image
        PdfImage image = PdfImage.fromFile("image.jpg");

        //Set the width and height of image
        float width = image.getWidth() * 0.50f;
        float height = image.getHeight() * 0.50f;

        //Define a position to draw image
        double x = (page.getCanvas().getClientSize().getWidth() - width) / 2;
        float y = 60f;

        //Draw the image onto a speicific position on the page
        page.getCanvas().drawImage(image, x, y, width, height);

        //Save the result document
        pdf.saveToFile("addImage.pdf", FileFormat.PDF);
    }
}

Remove a Specific Image from a PDF in Java

The following are the steps to remove a specific image from a PDF document:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the desired page in the PDF document by its index using PdfDocument.getPages().get(int) method.
  • Delete a specific image on the page by its index using PdfPageBase.deleteImage(int) method.
  • Save the result document using PdfDocument.saveToFile() method.
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

public class RemoveImage {
    public static void main(String []args){
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("addImage.pdf");

        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);

        //Delete the first image on the page
        page.deleteImage(0);

        //Save the result document
        pdf.saveToFile("removeImage.pdf", FileFormat.PDF);
    }
}

Replace an Image in a PDF in Java

The following are the steps to replace an image with another image in a PDF document:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the desired page in the PDF document by its index using PdfDocument.getPages().get(int) method.
  • Load an image using PdfImage.fromFile() method.
  • Replace a specific image with the loaded image using PdfPageBase.replaceImage(int, PdfImage) method.
  • Save the result document using PdfDocument.saveToFile() method.
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;

public class ReplaceImage {
    public static void main(String []args){
        //Create a PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Load a pdf document
        doc.loadFromFile("addImage.pdf");

        //Get the first page
        PdfPageBase page = doc.getPages().get(0);

        //Load an image
        PdfImage image = PdfImage.fromFile("newImage.jpg");

        //Replace the first image with the loaded image
        page.replaceImage(0, image);

        //Save the result document
        doc.saveToFile("replaceImage.pdf", FileFormat.PDF);
    }
}

Extract All Images from a PDF in Java

The following are the main steps to extract all images from a PDF document:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Loop through all pages in the document.
  • Extract images from each page using PdfPageBase.extractImages() method.
  • Save the extracted images to a specific file path.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

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

public class ExtractImage {
    public static void main(String []args) throws IOException {
        //Create a PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Load a pdf document
        doc.loadFromFile("addImage.pdf");

        //Declare an int variable
        int index = 0;
        //Loop through the pages
        for (PdfPageBase page : (Iterable<PdfPageBase>) doc.getPages()) {
            //Extract images from the current page
            for (BufferedImage image : page.extractImages()) {
                //Specify the output file path
                File output = new File("images/" + String.format("image_%d.jpg", index++));
                //Save image as .jpg file
                ImageIO.write(image, "JPG", output);
            }
        }
    }
}

Java: Change PDF Page Margins

For various reasons, you may need to change page margins of a PDF document. For instance, you want to add additional information such as a stamp to a PDF page, but the page is full of content and has no extra margin spaces for you to do so. This article will demonstrate how to change PDF page margins using Java.

The following topics will be discussed:

  • Change PDF Page Margins without Changing Page Size
  • Change PDF Page Margins and Also Change Page Size

Add Dependencies

To change PDF page margins, this article uses Spire.PDF for Java. If you are using maven, you can install the jar of Spire.PDF for Java into your project by adding the following code to your project’s pom.xml file.

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

If you are not using maven, you can download Spire.PDF for Java from this website, extract the package and then import the Spire.Pdf.jar under the lib folder into your project as a dependency.

Change PDF Page Margins without Changing Page Size in Java

It is possible to change the margins without changing the page size, but the page content may be scaled. The following steps show how to increase the page margins of a PDF document without changing page size using Java:

  • Load the source PDF document using PdfDocument class.
  • Create a new PDF document using PdfDocument class. Then set the increasing or decreasing value of margins as margins of the new PDF document.
  • Loop through the pages in the source PDF document.
  • Add a page that has the same page size with the source page to the new PDF document.
  • Create a new instance of PdfTextLayout class and specify the layout type as one page using PdfTextLayout.setLayout(PdfLayoutType.One_Page) method (if not set the content will not scale to fit page size).
  • Create a template based on the source page using PdfPageBase.createTemplate() method.
  • Draw the template on the page of the new PDF document with one page layout using PdfTemplate.draw() method.
  • Save the new PDF document to file using PdfDocument.saveToFile() method.

Code example:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfLayoutType;
import com.spire.pdf.graphics.PdfTemplate;
import com.spire.pdf.graphics.PdfTextLayout;

import java.awt.geom.Point2D;

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

        //Load the source PDF document
        PdfDocument sourcePdf = new PdfDocument("Input.pdf");

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

        //Set increasing value of page margins as page margins of the new PDF document
        //if you want to decrease the margins, set the value as negative
        newPdf.getPageSettings().getMargins().setLeft(40);
        newPdf.getPageSettings().getMargins().setRight(40);
        newPdf.getPageSettings().getMargins().setTop(40);
        newPdf.getPageSettings().getMargins().setBottom(40);

        //Loop through the pages in the source PDF document
        for (PdfPageBase sourcePage : (Iterable<PdfPageBase>) sourcePdf.getPages())
        {
            //Add a page with the same page size to the new PDF document
            PdfPageBase newPage = newPdf.getPages().add(sourcePage.getSize());

            //Set text layout as 1 page, if not set the content will not scale to fit page size
            PdfTextLayout layout = new PdfTextLayout();
            layout.setLayout(PdfLayoutType.One_Page);

            //Create a template based on the source page and draw it on the page of the new PDF document
            PdfTemplate template = sourcePage.createTemplate();
            template.draw(newPage, new Point2D.Float(0, 0), layout);
        }

        //Save the new PDF document to file
        newPdf.saveToFile("ChangeMargins1.pdf");
    }
}

The source PDF:

The source PDF document

The result PDF:

The result PDF document after changing page margins

Change PDF Page Margins and Also Change Page Size in Java

The page size can be adjusted accordingly if you don’t want to scale the page content when changing margins.

The following steps show how to change PDF page margins and also change page size using Java:

  • Load the source PDF document using PdfDocument class.
  • Create a new PDF document using PdfDocument class. Then set the increasing or decreasing value of margins as margins of the new PDF document.
  • Loop through the pages in the source PDF document.
  • Create an instance of Dimension class which will then be used as the page size of the new PDF document. Then set its size using Dimension.setSize() method.
  • Add a page with the specified size to the new PDF document.
  • Create a template based on the source page using PdfPageBase.createTemplate() method.
  • Draw the template on the page of the new PDF document using PdfTemplate.draw() method.
  • Save the new PDF document to file using PdfDocument.saveToFile() method.

Code example:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfTemplate;

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

public class ChangePageMargins {
    public static void main(String[] args) {
        //Load the source PDF document
        PdfDocument sourcePdf = new PdfDocument("Input.pdf");

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

        //Set increasing value of margins as margins of the new PDF document 
        //if you want to decrease the margins, set the value as negative
        newPdf.getPageSettings().getMargins().setLeft(40);
        newPdf.getPageSettings().getMargins().setRight(40);
        newPdf.getPageSettings().getMargins().setTop(40);
        newPdf.getPageSettings().getMargins().setBottom(40);

        //Loop through the pages in the source PDF document
        for (PdfPageBase sourcePage : (Iterable<PdfPageBase>) sourcePdf.getPages())
        {
            double width = sourcePage.getSize().getWidth() + newPdf.getPageSettings().getMargins().getLeft() + newPdf.getPageSettings().getMargins().getRight();
            double height = sourcePage.getSize().getHeight() + newPdf.getPageSettings().getMargins().getTop() + newPdf.getPageSettings().getMargins().getBottom();
            //Create a SizeF instance which will then be used as the page size of the new PDF document
            Dimension2D size = new Dimension();
            //Set its width and height 
            size.setSize(width, height);
            //Add a page with larger page size to the new PDF document
            PdfPageBase newPage = newPdf.getPages().add(size);
            //Create a template based on the source page and draw it on the page of the new PDF document
            PdfTemplate template = sourcePage.createTemplate();
            template.draw(newPage, new Point2D.Float(0, 0));
        }

        //Save the new PDF document to file
        newPdf.saveToFile("ChangeMargins2.pdf");
    }
}

The result PDF:

The result PDF after changing page margins and page size

Making PDF Forms Non-Editable in Java

When a PDF form is made non-editable, its interactive capability is removed, so the field data appears as regular text and cannot be edited. This is very useful when we want to archive or distribute PDF documents containing forms. In this article, I will demonstrate how to make PDF forms non-editable in Java using Free Spire.PDF for Java.

Add Dependencies

If you are using maven, you can install the jar of Free Spire.PDF for Java into your project by adding the following code to your project’s pom.xml file.

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

If you are not using maven, you can download Free Spire.PDF for Java from this website, unzip the package and then import the Spire.Pdf.jar under the lib folder into your project as a dependency.

Making PDF Forms Non-Editable in Java

There are two ways to make PDF forms non-editable, they are: flatten the forms and make the forms read only.

Example 1. Flatten PDF Forms in Java

The following are the steps to flatten all the forms in a PDF document:

  • Load a PDF document by initializing an instance of PdfDocument class and passing the file path to the class’s constructor as a parameter.
  • Flatten all the forms in the document using PdfDocument.getForm().isFlatten(true) method.
  • Save the result document using PdfDocument.saveToFile() method.

Code example:

import com.spire.pdf.PdfDocument;

public class FlattenForms {
    public static void main(String[] args){
        //Load a PDF document
        PdfDocument doc = new PdfDocument("FormFields.pdf");

        //Flatten all the form fields in the document 
        doc.getForm().isFlatten(true);

        //Save the result document
        doc.saveToFile("Flatten.pdf");
    }
}

The input PDF:

The input PDF document with forms

The result PDF:

Flatten PDF forms using Java

If you only want to flatten a specific form, you can use the following code:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.widget.PdfFormWidget;

public class FlattenSpecificForm {
    public static void main(String[] args){
        //Load a PDF document
        PdfDocument doc = new PdfDocument("FormFields.pdf");

        //Access the first form
        PdfFormWidget formWidget = (PdfFormWidget)doc.getForm();
        PdfField form = (PdfField) formWidget.getFieldsWidget().getList().get(0);
        //Flatten the first form
        form.setFlatten(true);

        //Save the result document
        doc.saveToFile("FlattenSpecificForm.pdf");
    }
}

Example 2. Make PDF forms Read Only in Java

The following are the steps to make all the forms in a PDF document as read only:

  • Load a PDF document by initializing an instance of PdfDocument class and passing the file path to the class’s constructor as a parameter.
  • Make all the forms in the document as read only using PdfDocument.getForm().setReadOnly(true) method.
  • Save the result document using PdfDocument.saveToFile() method.

Code example:

import com.spire.pdf.PdfDocument;

public class MakeFormsReadOnly {
    public static void main(String[] args){
        //Load a PDF document
        PdfDocument doc = new PdfDocument("FormFields.pdf");

        //Make all forms in the document as read only
        doc.getForm().setReadOnly(true);

        //Save the result document
        doc.saveToFile("ReadOnly.pdf");
    }
}

The result PDF:

Make PDF forms read only using Java

If you only want to make a specific form read only, you can use the following code:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.widget.PdfFormWidget;

public class MakeSpecificFormReadOnly {
    public static void main(String[] args){
        //Load a PDF document
        PdfDocument doc = new PdfDocument("FormFields.pdf");

        //Access the first form
        PdfFormWidget formWidget = (PdfFormWidget)doc.getForm();
        PdfField form = (PdfField) formWidget.getFieldsWidget().getList().get(0);

        //Make the first form read only
        form.setReadOnly(true);

        //Save the result document
        doc.saveToFile("MakeSpecificFormReadOnly.pdf");
    }
}

Java: Convert PDF to PDF/A and Determine if a PDF is PDF/A

PDF/A is an archiving format of PDF that ensures a document with text, vector graphics, raster images and related metadata can be faithfully reproduced after a long-term preservation. Under certain circumstances, you may need to convert a regular PDF file to PDF/A or determine if a PDF is already a PDF/A file. In this article, I will demonstrate how to convert PDF to PDF/A, to be more specific, PDF/A-1a, PDF/A-1b, PDF/A-2a, PDF/A-2b, PDF/A-3a, PDF/A-3b, and how to determine if a PDF is PDF/A in java.

Add Dependencies

In order to convert PDF to PDF/A, I will be using Spire.PDF for Java, which is an easy-to-use and multi-functional PDF library.

The jar file of Spire.PDF for Java can be downloaded from this link or installed from Maven by adding the following code to your maven-based 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>5.1.0</version>
    </dependency>
</dependencies>

Convert PDF to PDF/A

The following are the steps to convert a PDF file to PDF/A:

  • Create a PdfStandardsConverter instance, within the constructor, pass in the file path of the sample PDF file as a parameter.
  • Convert the sample file to PdfA1A conformance level using PdfStandardsConverter.toPdfA1A() method.
  • Convert the sample file to PdfA1B conformance level using PdfStandardsConverter. toPdfA1B() method.
  • Convert the sample file to PdfA2A conformance level using PdfStandardsConverter. toPdfA2A() method.
  • Convert the sample file to PdfA2B conformance level using PdfStandardsConverter. toPdfA2B() method.
  • Convert the sample file to PdfA3A conformance level using PdfStandardsConverter. toPdfA3A() method.
  • Convert the sample file to PdfA3B conformance level using PdfStandardsConverter. toPdfA3B() method.
import com.spire.pdf.conversion.PdfStandardsConverter;

public class ConvertPdfToPdfA {
    public static void main(String[] args) {
        //Load a PDF file using PdfStandardsConverter class
        PdfStandardsConverter converter = new PdfStandardsConverter("Input.pdf");

        //Convert to PdfA1A
        converter.toPdfA1A("output/ToPdfA1A.pdf");

        //Convert to PdfA1B
        converter.toPdfA1B("output/ToPdfA1B.pdf");

        //Convert to PdfA2A
        converter.toPdfA2A( "output/ToPdfA2A.pdf");

        //Convert to PdfA2B
        converter.toPdfA2B("output/ToPdfA2B.pdf");

        //Convert to PdfA3A
        converter.toPdfA3A("output/ToPdfA3A.pdf");

        //Convert to PdfA3B
        converter.toPdfA3B("output/ToPdfA3B.pdf");
    }
}

The converted PDF/A-1a document:

Convert PDF to PDF/A in Java

Determine if a PDF is PDF/A

You can use the getConformance() method of the PdfDocument class to get the PDF/A version and the conformance level of a PDF file. If it’s a PDF/A file, let’s say, PDF/A-1a, it returns “Pdf_A_1_A”. If it’s a regular PDF file, it returns “None”.

The following are the steps to determine if a PDF file is PDF/A:

  • Create a PdfDocument instance, within the constructor, pass in the file path of the sample PDF file as a parameter.
  • Get the PDF/A version and conformance level of the file using PdfDocument.getConformance() method.
import com.spire.pdf.PdfConformanceLevel;
import com.spire.pdf.PdfDocument;

public class DetectIfAPdfIsPdfa {
    public static void main(String[] args){
        //Load a Pdf document
        PdfDocument pdf = new PdfDocument("ToPdfA1A.pdf");
        //Get the PDF/A version and conformance level
        PdfConformanceLevel conformanceLevel = pdf.getConformance();
        System.out.println(conformanceLevel.toString());
    }
}

Output:

Determine if a PDF is PDF/A in Java

Conclusion

In this article, I have demonstrated how to convert PDF to PDF/A using Spire.PDF for Java library. Besides the PDF to PDF/A conversion, the library can also be used to convert PDF to Word, Excel, HTML, images and many more. You can explore more about it by visiting the documentation.

In case you have any question, you can post it on the forum.

Split a PDF into Multiple Files in Java

You might need to split a PDF into more than one file in certain circumstances, like if you have a big PDF and you want to send just a few pages to others. In this article, I will introduce how to split a PDF file into multiple files programmatically using Java.

In the following section, you will learn two scenarios to split a PDF file, they are:

  • Split a PDF File by Each Page
  • Split a PDF File by Page Ranges

Add Dependencies

In order to split PDF files, I will be using Spire.PDF for Java, which is an easy-to-use and multi-functional PDF library.

The jar file of Spire.PDF for Java can be downloaded from this link or installed from Maven by adding the following code to your maven-based 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>5.1.0</version>
    </dependency>
</dependencies>

Split a PDF File by Each Page in Java

To split a PDF file by each page, you just need to add two lines of code. The following are the steps to split a PDF file by each page:

  • Load a PDF file using PdfDocument class.
  • Split each page of the PDF into a separate file using the PdfDocument.split(String destFilePattern, int startNumber) method.

The following code example shows how to split a 5 pages PDF file by each page in Java:

import com.spire.pdf.PdfDocument;

public class SplitPdfByEachPage {
    public static void main(String []args){
        //Load a PDF file using PdfDocument class
        PdfDocument doc = new PdfDocument("Sample.pdf");

        //Split every page of the PDF into a separate file
        doc.split("Output/Split-{0}.pdf", 1);
        doc.close();
    }
}

Output:

Split a PDF file by each page in Java

Split a PDF File by Page Ranges in Java

Sometimes, you might want to split a PDF file by page ranges instead of each page. Let’s follow the following steps to split a PDF file by page ranges:

  • Load a PDF file using PdfDocument class.
  • Create a new PDF file using PdfDocument class
  • Import desired pages of the source PDF file to the new PDF file using PdfDocument.insertPageRange(PdfDocument doc, int startIndex, int endIndex) method.
  • Save the result PDF file using PdfDocument.saveToFile() method.

The following code shows how to split a 5 pages PDF file into two files – one with 2 pages, another with 3 pages:

import com.spire.pdf.PdfDocument;

public class SplitPdfByCertainPages {
    public static void main(String []args){
        //Load a PDF file using PdfDocument class
        PdfDocument doc = new PdfDocument("sample.pdf");

        //Create a new PDF file
        PdfDocument newDoc1 = new PdfDocument();
        //Import 1-2 pages of the source PDF to the new PDF
        newDoc1.insertPageRange(doc, 0, 1);
        //Save the PDF file
        newDoc1.saveToFile("Output/Doc1.pdf");

        //Create a new PDF file
        PdfDocument newDoc2 = new PdfDocument();
        //Import 3-5 pages of the source PDF to the new PDF
        newDoc2.insertPageRange(doc, 2, 4);
        //Save the PDF file
        newDoc2.saveToFile("Output/Doc2.pdf");
    }
}

Output:

Split a PDF file by certain pages in Java

Conclusion

In this article, I have demonstrated how to split PDF files in Java using Spire.PDF for Java library. Besides splitting PDF, the library can also be used to merge, convert, print, protect PDF files and many more. You can explore more about it by visiting the documentation.

Convert PDF to Word or Excel in Java

PDF is one of the most commonly used file formats, however it’s much more difficult to edit a PDF document comparing with editing Word or Excel documents. In some cases, we may need to convert PDF documents to Word or Excel. In this article, I am going to demonstrate how to achieve this task programmatically using Java.

Add Dependencies

In order to convert PDF to Word or Excel, I will use Spire.PDF for Java which is a powerful and multifunctional API for creating, manipulating and converting PDF documents.

You can either download the API’s jar from this link or install it from Maven by adding the following code to your maven-based 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>4.10.2</version>
    </dependency>
</dependencies>

Convert PDF to Word or Excel

Converting PDF to Word or Excel is pretty easy with Spire.PDF for Java API. You just need to follow two steps below:

1. Load a PDF document using PdfDocument class.
2. Save the PDF document to Word or Excel using PdfDocument.saveToFile(String, FileFormat) method.

The following code example demonstrates how to convert a PDF document to Word and Excel:

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;

public class ConvertPdfToWord {
    public static void main(String[] args) {
        //Load a sample PDF document
        PdfDocument pdf = new PdfDocument("Sample.pdf");

        //Save the PDF document as Word DOCX format
        pdf.saveToFile("ToWord.docx", FileFormat.DOCX);

        //Save the PDF document as Excel XLSX format
        pdf.saveToFile("ToExcel.xlsx", FileFormat.XLSX);
    }
}

The input PDF:

The Input PDF

The converted Word:

The Word Document Converted from PDF

The converted Excel:

The Excel document converted from PDF

Extract Table Data from PDF in Java

PDF invoices often contain tabular data, in some circumstance, you may want to extract the tabular data to perform data analysis. In this article, you will learn how to achieve this task programmatically using Java.

Install Spire.PDF for Java

In order to extract PDF table data, I will use Spire.PDF for Java which is a powerful and multifunctional API for creating, manipulating, converting and printing PDF documents.

You can either download the API’s jar from this link or install it from Maven by adding the following code to your maven-based 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>4.10.2</version>
    </dependency>
</dependencies>

Extract Table Data from PDF Document

Spire.PDF for Java uses the PdfTableExtractor.extractTable(int pageIndex) method to detect and extract tables from a desired PDF page.

The following are the steps to extract table data from a PDF file:

1. Load a sample PDF document using PdfDocument class.
2. Create a StringBuilder instance and a PdfTableExtractor instance.
3. Loop through the pages in the PDF, extract tables from each page into a PdfTable array using PdfTableExtractor.extractTable(int pageIndex) method.
4. Loop through the tables in the array.
5. Loop through the rows and columns in each table, after that extract data from each table cell using PdfTable.getText(int rowIndex, int columnIndex) method, then append the data to the StringBuilder instance using StringBuilder.append() method.
6. Write the extracted data to a txt document using Writer.write() method.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.utilities.PdfTable;
import com.spire.pdf.utilities.PdfTableExtractor;

import java.io.FileWriter;

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

        //Load a sample PDF document
        PdfDocument pdf = new PdfDocument("Table.pdf");

        //Create a StringBuilder instance
        StringBuilder builder = new StringBuilder();
        //Create a PdfTableExtractor instance
        PdfTableExtractor extractor = new PdfTableExtractor(pdf);

        //Loop through the pages in the PDF
        for (int pageIndex = 0; pageIndex < pdf.getPages().getCount(); pageIndex++) {
            //Extract tables from the current page into a PdfTable array
            PdfTable[] tableLists = extractor.extractTable(pageIndex);
            
            //If any tables are found
            if (tableLists != null && tableLists.length > 0) {
                //Loop through the tables in the array
                for (PdfTable table : tableLists) {
                    //Loop through the rows in the current table
                    for (int i = 0; i < table.getRowCount(); i++) {
                        //Loop through the columns in the current table
                        for (int j = 0; j < table.getColumnCount(); j++) {
                            //Extract data from the current table cell and append to the StringBuilder 
                            String text = table.getText(i, j);
                            builder.append(text + " | ");
                        }
                        builder.append("\r\n");
                    }
                }
            }
        }

        //Write data into a .txt document
        FileWriter fw = new FileWriter("ExtractTable.txt");
        fw.write(builder.toString());
        fw.flush();
        fw.close();
    }
}

The input PDF:

The Input PDF with Table

The output .txt document with extracted table data:

The TXT Document with Data Extracted from PDF Table

See Also

C#/VB.NET: Read or Extract Table Data from PDF File

Convert PDF to Images (JPG, PNG, TIFF, SVG) in Java

Images are used almost everywhere in our daily life. In some circumstances, you may need to convert documents in other format like PDF to images. In this article, I am going to describe how to convert PDF document to image formats such as PNG, JPG, TIFF and SVG programmatically using Java.

Add Dependencies

To convert PDF to Images, this article uses Spire.PDF for Java, which is a multi-functional third-party API for creating, manipulating and converting PDF documents.

You can either download the API’s jar from here or install it from maven by adding the following configurations to your maven-based project’s pom.xml file.

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

Convert PDF to PNG/JPG

Spire.PDF for Java uses the PdfDocument.saveAsImage() method to convert PDF document to PNG/JPG images. This method accepts an int parameter which specifies the index of a desired PDF page.

To convert a PDF document to PNG/JPG images, you can follow the following steps:

1. Create a PdfDocument instance.
2. Load a PDF document using PdfDocument.loadFromFile() method.
3. Traverse through the pages in the PDF, and then save every page to image using PdfDocument.saveAsImage() method.

import com.spire.pdf.PdfDocument;

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

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

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("sample.pdf");
        
        BufferedImage image;
        //Traverse through the pages in the PDF
        for (int i = 0; i < pdf.getPages().getCount(); i++) {
            //Save every page as PNG image
            image = pdf.saveAsImage(i);
            File file = new File( "output/" + String.format(("ToImage-img-%d.png"), i));
            ImageIO.write(image, "PNG", file);
        }
        pdf.close();
    }
}

The input PDF:

The input PDF

Converted PNG images:

PNG images converted from PDF

Convert PDF to TIFF

Spire.PDF for Java provides the ability to convert PDF document to multi-page TIFF by using the PdfDocument.saveToTiff() method. You can convert particular PDF page(s) to TIFF or convert a whole PDF document to TIFF, furthermore, you can also specify the resolution of the TIFF when performing conversion.

The following example shows how to convert all pages in a PDF document to TIFF with specified resolution.

import com.spire.pdf.PdfDocument;

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

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("sample.pdf");
        
        //Save the document to Tiff
        //pdf.saveToTiff("output/page1toTiff.tiff");
        
        //Save all PDF pages to Tiff with specified resolution
        pdf.saveToTiff("output/page2toTiff.tiff", 0, pdf.getPages().getCount() - 1,200, 200);
    }
}

The converted TIFF:

Converted TIFF from PDF

Convert PDF to SVG

To convert PDF to SVG, you can use the PdfDocument.saveToFile method. This method accepts the following parameters:

String: specifies the file path of the converted SVG.

FileFormat: Specifies the desired file format that the PDF document will be saved to.

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;

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

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("sample.pdf");

        //Save the document to Svg
        pdf.saveToFile("output/toSVG_result.svg", FileFormat.SVG);
        pdf.close();
    }
}

The converted SVG:

Converted SVG from PDF
Design a site like this with WordPress.com
Get started