gpt4 book ai didi

java - iText PDF : How to create internal links to other sections in PDF

转载 作者:行者123 更新时间:2023-12-02 11:05:47 25 4
gpt4 key购买 nike

我使用 itext 5 生成 pdf 文件,并使用 Anchor 创建指向 pdf 内不同页面的内部链接。链接工作正常,但是,在 adobe PDF 阅读器中,当鼠标指针放置在链接的底部边缘时,“W”出现在“手形”工具的顶部,单击时会在 Web 浏览器中打开一个新文件,但不会重定向到链接页面。这是示例代码。请建议如何禁用在浏览器中打开内部链接。

import com.itextpdf.text.Anchor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;


public class AnchorExample {

public static void main(String[] args) {

Document document = new Document();

try {
PdfWriter.getInstance(document,
new FileOutputStream("Anchor2.pdf"));

document.open();


Anchor anchor =
new Anchor("Jump down to next paragraph");
anchor.setReference("#linkTarget");
Paragraph paragraph = new Paragraph();
paragraph.add(anchor);
document.add(paragraph);

document.newPage();

Anchor anchorTarget =
new Anchor("This is the target of the link above");
anchorTarget.setName("linkTarget");
Paragraph targetParagraph = new Paragraph();
targetParagraph.setSpacingBefore(50);

targetParagraph.add(anchorTarget);
document.add(targetParagraph);


document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

}
}

最佳答案

使用Anchor作为内部链接已经是过去的事了。我发现您使用的是 iText 的旧版本,因为 Anchor 类(iText 5 之前可用)已被 Link 类(在 iText 7 中引入)取代。请参阅overview of the iText 7 building block classes .

即使在 iText 5 中,使用 Anchor 定位本地目的地的情况也不常见。最好使用 Chunk 而不是 Anchor,使用 setLocalDestination() 方法定义目标,并使用 setLocalGoto() 方法来定义链接:

Chunk chunk = new Chunk("Contact information");
chunk.setLocalGoto("contact");
document.add(new Paragraph(chunk));
document.newPage();
chunk chunk1 = new Chunk("Contact information");
chunk1.setLocalDestination("contact");
Chapter chapter = new Chapter(new Paragraph(chunk1),1);
chapter.setNumberDepth(0);
document.add(chapter);

另请参阅几乎重复的问题 Add anchor to pdf using itext java 。就好像您从问题而不是答案中复制了代码(这真的很奇怪)。

关于java - iText PDF : How to create internal links to other sections in PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50970199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com