Skip to content

Instantly share code, notes, and snippets.

@leoleozhu
Created August 5, 2021 10:49
Show Gist options
  • Save leoleozhu/9c51a8a38e372d3eb2d755f72fc514c5 to your computer and use it in GitHub Desktop.
Save leoleozhu/9c51a8a38e372d3eb2d755f72fc514c5 to your computer and use it in GitHub Desktop.
Reuse page in PDF
@Test
public void testReusePage() throws Exception {
String original = resourceFile("PdfWithImage.pdf");
String destination = targetFile("image-reuse-ReusePage.pdf");
try (
PdfDocument input = new PdfDocument(new PdfReader(original));
PdfDocument output = new PdfDocument(new PdfWriter(destination))
) {
PdfPage page = input.getPage(1);
for (int i = 0; i < 100; i++) {
PdfPage newPage = output.addNewPage(new PageSize(page.getPageSize()));
// copy boxes
newPage.setMediaBox(page.getMediaBox());
newPage.setTrimBox(page.getTrimBox());
newPage.setBleedBox(page.getBleedBox());
newPage.setArtBox(page.getArtBox());
newPage.setCropBox(page.getCropBox());
PdfCanvas newCanvas = new PdfCanvas(newPage);
newCanvas.addXObject(page.copyAsFormXObject(output));
newCanvas.release();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment