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.


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