Search code examples
javaitext7

How do I create a forward link to a specific page which does not yet exists when I generate the link


How do I generate some text, which links forward to an other page in the pdf file I am generating?

I have the code below which generate working pdf links, bit it require that the page I link to, exists in the pdf file at the time I generate the link. Is there any way to avoid this problem?

My use case is that I am generating the table of content, which is in the beginning of the pdf file, but it need to link to the content pages, which don't yet exists when I generate the table of content.

int linkToPdfPage=42;
PdfArray array = new PdfArray();
array.add(pdfDocument.getPage(linkToPdfPage).getPdfObject());
array.add(PdfName.Fit);
PdfDestination dest2 = PdfDestination.makeDestination(array);
Link newLink=new Link("Link text", PdfAction.createGoTo(dest2));
newLink.getLinkAnnotation().setBorder(new PdfArray(new int[]{0,0,0}));

Solution

  • You can use named destinations for this task. You can create a link to a PdfStringDestination with a name of your choice and later, when you have the target page, create an explicit destination and add it to the document for your chosen name using PdfDocument.addNamedDestination.

    For example:

    try (   PdfDocument pdfDocument = new PdfDocument(new PdfWriter(...));
            Document document = new Document(pdfDocument)   )
    {
        String destinationName = "MyForwardDestination";
    
        for (int page = 1; page <= 50; page++) {
            document.add(new Paragraph().setFontSize(100).add(String.valueOf(page)));
            switch (page) {
            case 1:
                document.add(new Paragraph(new Link("Click here for a forward jump", new PdfStringDestination(destinationName)).setFontSize(20)));
                break;
            case 42:
                pdfDocument.addNamedDestination(destinationName, PdfExplicitDestination.createFit(pdfDocument.getLastPage()).getPdfObject());
                break;
            }
            if (page < 50)
                document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        }
    }
    

    (CreateLink test testCreateForwardLink)

    This generates a 50 page PDF with a link on page 1 targeting page 42, and the link was added to page 1 long before page 42 was created.