This class processes links from imported pages so that they may be active. The following example code reads a group
of files and places them all on the output PDF, four pages in a single page, keeping the links active.
String[] files = new String[] {"input1.pdf", "input2.pdf"};
String outputFile = "output.pdf";
int firstPage=1;
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
document.setPageSize(PageSize.A4);
float W = PageSize.A4.getWidth() / 2;
float H = PageSize.A4.getHeight() / 2;
document.open();
PdfContentByte cb = writer.getDirectContent();
for (int i = 0; i < files.length; i++) {
PdfReader currentReader = new PdfReader(files[i]);
currentReader.consolidateNamedDestinations();
for (int page = 1; page <= currentReader.getNumberOfPages(); page++) {
PdfImportedPage importedPage = writer.getImportedPage(currentReader, page);
float a = 0.5f;
float e = (page % 2 == 0) ? W : 0;
float f = (page % 4 == 1 || page % 4 == 2) ? H : 0;
ArrayList links = currentReader.getLinks(page);
cb.addTemplate(importedPage, a, 0, 0, a, e, f);
for (int j = 0; j < links.size(); j++) {
PdfAnnotation.PdfImportedLink link = (PdfAnnotation.PdfImportedLink)links.get(j);
if (link.isInternal()) {
int dPage = link.getDestinationPage();
int newDestPage = (dPage-1)/4 + firstPage;
float ee = (dPage % 2 == 0) ? W : 0;
float ff = (dPage % 4 == 1 || dPage % 4 == 2) ? H : 0;
link.setDestinationPage(newDestPage);
link.transformDestination(a, 0, 0, a, ee, ff);
}
link.transformRect(a, 0, 0, a, e, f);
writer.addAnnotation(link.createAnnotation(writer));
}
if (page % 4 == 0)
document.newPage();
}
if (i < files.length - 1)
document.newPage();
firstPage += (currentReader.getNumberOfPages()+3)/4;
}
document.close();