DEV Community

CodeSharing
CodeSharing

Posted on

Duplicate a Page in PDF Using Java

PDF is a stable file format, and it is difficult for us to duplicate a PDF page by simply copying and pasting. This article will introduce how I duplicate a page within a PDF document using a free Java library (Free Spire.PDF for Java).

Import jar dependency (2 Methods)
● Download the free library and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.
● Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<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>4.3.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Relevant Code

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

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

public class DuplicatePage {

    public static void main(String[] args) {

        //Load a sample PDF document
        PdfDocument pdf = new PdfDocument("C:\\Users\\Administrator\\Desktop\\The Scarlet Letter.pdf");

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

        //Get the page size
        Dimension2D size = page.getActualSize();

        //Create a template based on the page
        PdfTemplate template = page.createTemplate();

        for (int i = 0; i < 5; i++) {

            //Add a new page to the document
            page = pdf.getPages().add(size, new PdfMargins(0));

            //Draw template on the new page
            page.getCanvas().drawTemplate(template, new Point2D.Float(0, 0));
        }

        //Save the file
        pdf.saveToFile("output/DuplicatePage.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
Duplicate

Top comments (0)