【问题标题】:How do I create a forward link to a specific page which does not yet exists when I generate the link如何在生成链接时创建指向尚不存在的特定页面的转发链接
【发布时间】:2021-10-13 14:15:03
【问题描述】:

如何生成一些文本,这些文本链接到我正在生成的 pdf 文件中的其他页面?

我有下面的代码生成有效的 pdf 链接,它要求我链接到的页面在我生成链接时存在于 pdf 文件中。有什么办法可以避免这个问题?

我的用例是我正在生成目录,它位于 pdf 文件的开头,但它需要链接到内容页面,当我生成目录时,这些页面还不存在。

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}));

【问题讨论】:

  • 您可以先创建内容,然后再返回内容并插入这些页面吗?

标签: java itext7


【解决方案1】:

您可以为此任务使用命名目的地。您可以使用您选择的名称创建指向PdfStringDestination 的链接,然后,当您拥有目标页面时,创建一个明确的目标并使用PdfDocument.addNamedDestination 将其添加到您选择的名称的文档中。

例如:

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 测试testCreateForwardLink)

这会生成一个 50 页的 PDF,其中第 1 页上的链接指向第 42 页,并且该链接早在第 42 页创建之前就已添加到第 1 页。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2022-01-27
    • 2020-06-17
    相关资源
    最近更新 更多