首页 > 解决方案 > 在itext 7中的行之间添加画布而不重叠页面

问题描述

是否可以将画布与 addParagraph 一起添加到文档中?我有长文本(1000 页)。

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

例如,如果文本中有一个单词“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();

这是示例文件: bigfileWithText.txt

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

标签: javapdfitextitext7

解决方案


添加什么

首先,您不能简单地将 a 添加Canvas到某物,因为 aCanvas只是将内容直接添加到指定的助手,PdfCanvas不同 API 级别之间的桥梁,参见。它的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>

出于类似的原因,您不能添加 a 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,然后是 a PdfCanvas,然后是a ,然后用您的内容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 包装在 an 中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...


推荐阅读