在 itext 7 的行之间添加 canvas 没有重叠页面

Add canvas between line in itext 7 Without Overlapping Page

是否可以将 canvas 与 addParagraph 一起添加到文档中?我有很长的文字(1000 页)。

我需要在某些地方(图形、形状等)的文本之间添加 canvas。

比如文中有一个词"graph_add"

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
PageSize ps = PageSize.A4;;
Document doc = new Document(pdfDoc, ps);
BufferedReader br = new BufferedReader(new FileReader("bigfileWithText.txt"));
while ((line = br.readLine()) != null) {
if("graph_add".equals(line))
//Add canvas in document in this place!!doc.add(Canvas)
doc.add(new Paragraph(line)
}
doc.close();

这是示例文件:

本文 https://itextpdf.com/ru/resources/books/itext-7-building-blocks/chapter-2-adding-content-canvas-or-document 不适合,这里我需要在单独的页面上创建。我在文本后的某个时刻添加了一个数字(Canvas),然后再次添加了一个文本。 像这样:

添加什么

首先,你不能简单地添加一个Canvas到一个东西,因为Canvas只是一个帮助,将内容直接添加到指定的PdfCanvas,不同API 级别,cf.它的 JavaDoc:

/**
 * This class is used for adding content directly onto a specified {@link PdfCanvas}.
 * {@link Canvas} does not know the concept of a page, so it can't reflow to a 'next' {@link Canvas}.
 *
 * This class effectively acts as a bridge between the high-level <em>layout</em>
 * API and the low-level <em>kernel</em> API.
 */
public class Canvas extends RootElement<Canvas>

出于类似的原因,您不能添加 PdfCanvas,因为它也仅仅是将内容直接添加到页面内容流或表单 XObject 中的帮助程序:

/**
 * PdfCanvas class represents an algorithm for writing data into content stream.
 * To write into page content, create PdfCanvas from a page instance.
 * To write into form XObject, create PdfCanvas from a form XObject instance.
 * Make sure to call PdfCanvas.release() after you finished writing to the canvas.
 * It will save some memory.
 */
public class PdfCanvas implements Serializable

不过,您可以将 XObject 包装成 Image.

后添加到其中。

因此,您应该首先创建一个表单 XObject,然后创建一个 PdfCanvas,然后创建一个 Canvas,并用您的内容填充 Canvas

PdfFormXObject pdfFormXObject = new PdfFormXObject(XOBJECT_SIZE);
PdfCanvas pdfCanvas = new PdfCanvas(pdfFormXObject, pdfDoc);
try (Canvas canvas = new Canvas(pdfCanvas, pdfDoc, pdfFormXObject.getBBox().toRectangle())) {
    ADD CONTENT TO canvas AS REQUIRED FOR THE USE CASE IN QUESTION
}

然后您可以将表单 XObject 包装在 Image 中并将其添加到文档中:

doc.add(new Image(pdfFormXObject));

一个例子

我使用了您的示例文本和图形图像(存储为 "Graph.png"):

String text = "Until recently, increasing dividend yields grabbed the headlines. However, increasing\n" + 
        "yields were actually more a reflection of the market capitalisation challenge than of the\n" + 
        "fortunes of mining shareholders. The yields mask a complete u-turn from boom-time\n" + 
        "dividend policies. More companies have now announced clear percentages of profit\n" + 
        "distribution policies. The big story today is the abandonment of progressive dividends\n" + 
        "by the majors, confirming that no miner was immune from a sustained commodity\n" + 
        "cycle downturn, however diversified their portfolio. \n" +
        "\ngraph_add\n\n" +
        "Shareholders were not fully rewarded for the high commodity prices and huge\n" + 
        "profits experienced in the boom, as management ploughed cash and profits into\n" + 
        "bigger and more marginal assets. During those times, production was the main\n" + 
        "game and shareholders were rewarded through soaring stock prices. However,\n" + 
        "this investment proposition relied on prices remaining high. ";

final Image img;
try (InputStream imageResource = getClass().getResourceAsStream("Graph.png")) {
    ImageData data = ImageDataFactory.create(StreamUtil.inputStreamToArray(imageResource));
    img = new Image(data);
}

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
PageSize ps = PageSize.A4;;
Document doc = new Document(pdfDoc, ps);

Rectangle effectivePageSize = doc.getPageEffectiveArea(ps);
img.scaleToFit(effectivePageSize.getWidth(), effectivePageSize.getHeight());
PdfFormXObject pdfFormXObject = new PdfFormXObject(new Rectangle(img.getImageScaledWidth(), img.getImageScaledHeight()));
PdfCanvas pdfCanvas = new PdfCanvas(pdfFormXObject, pdfDoc);
try (Canvas canvas = new Canvas(pdfCanvas, pdfDoc, pdfFormXObject.getBBox().toRectangle())) {
    canvas.add(img);
}

BufferedReader br = new BufferedReader(new StringReader(text));
String line;
while ((line = br.readLine()) != null) {
    if("graph_add".equals(line)) {
        doc.add(new Image(pdfFormXObject));
    } else {
        doc.add(new Paragraph(line));
    }
}
doc.close();

(AddCanvasToDocument 测试 testAddCanvasForRuslan)

结果:


顺便说一句:如果仅像本例那样向 Canvas 添加一个位图,显然可以将 Image img 直接添加到 Document doc 而不是通过表单XObject...