1

我在 iText 7 中遇到了一个非常奇怪的问题,我希望其他人过去已经处理过。我基本上只是试图通过将一系列 Link 对象添加到 Paragraph 对象中来创建目录,然后将 Paragraph 放入 Canvas 对象中。这是简化代码的示例:

    PdfCanvas pdfCanvas = new PdfCanvas(document.getPdfDocument().addNewPage());
    Rectangle rectangle = new Rectangle(36, 650, 100, 100);
    pdfCanvas.rectangle(rectangle);
    pdfCanvas.stroke();
    Canvas canvas = new Canvas(pdfCanvas, document.getPdfDocument(), rectangle);
    canvas.add(new Paragraph(new Link("Google", PdfAction.createGoToR("HELLO", "www.google.com"))));

正如你所看到的,这是非常简单的骨头。但是,当我这样做时,我得到一个空指针异常。我可以毫无问题地添加简单的文本,但是在我添加链接的那一刻,事情就变得混乱了。任何帮助将不胜感激。

4

1 回答 1

4

这就是你如何在 a 上绘制一个矩形(或者在这种情况下是一个正方形)PdfCanvas

PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfPage page = pdf.addNewPage();
PdfCanvas pdfCanvas = new PdfCanvas(page);
Rectangle rectangle = new Rectangle(36, 650, 100, 100);
pdfCanvas.rectangle(rectangle);
pdfCanvas.stroke();
pdf.close();

你不需要一个Document对象。您只需创建一个PdfCanvas并绘制一个矩形形状,其左下角x = 36; y = 360为 100 x 100 个用户单位。

您引入一个Document对象,因为您还想创建一个Link. 这也没有必要。你可以试试这个(但那是错误的):

Canvas canvas = new Canvas(pdfCanvas, pdf, rectangle);
canvas.add(new Paragraph().add("Google"));
canvas.add(new Paragraph(new Link("Google", PdfAction.createGoToR("HELLO", "www.google.com"))));
pdf.close();

如您所见,我们单独使用pdf(a PdfDocument) 。pdf没有Document涉及。但是,您正在尝试向Canvas对象添加链接。如果要将 PDF 语法添加到内容流Canvas可以使用A。链接不是内容流的一部分。链接是存储在页面字典条目中的注释。简而言之:您正在使用它不能使用的东西。/AnnotsCanvas

我认为您正在尝试将链接放在绝对位置,并且您想在该链接周围放置一个矩形。使用Canvas. 如果您只是将 aParagraph放在绝对位置,那就容易多了。

例如:

public void createPdf(String dest) throws IOException {
    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    Document document = new Document(pdf);
    Paragraph p = new Paragraph()
        .add(new Link("Google", PdfAction.createGoToR("HELLO", "www.google.com")))
        .setFixedPosition(36, 650, 80)
        .setBorder(new SolidBorder(0.5f));
    document.add(p);
    document.close();
}

这将添加一个Paragraphat 位置(x = 36; y = 650)和 80 个用户单位的宽度。我们在Paragraph.

这也不起作用,因为链接都是错误的。您正在使用GoToR(转到远程)操作,该操作旨在转到另一个 PDF 文件中的特定目标。我认为您需要一个 URI 操作:

public void createPdf(String dest) throws IOException {
    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    Document document = new Document(pdf);
    Paragraph p = new Paragraph()
        .add(new Link("Google", PdfAction.createURI("www.google.com")))
        .setFixedPosition(36, 650, 80)
        .setBorder(new SolidBorder(0.5f));
    document.add(p);
    document.close();
}

如果您想在文本周围获得更多空间,可以更改填充:

public void createPdf(String dest) throws IOException {
    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    Document document = new Document(pdf);
    Paragraph p = new Paragraph()
        .add(new Link("Google", PdfAction.createURI("www.google.com")))
        .setFixedPosition(36, 650, 80)
        .setPadding(10)
        .setBorder(new SolidBorder(0.5f));
    document.add(p);
    document.close();
}

这比您尝试实现的要直观得多。

于 2016-08-09T07:01:38.257 回答