在没有重叠页面的itext 7中的行之间添加画布

时间:2019-03-17 15:03:42

标签: java pdf itext itext7

是否可以将画布和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不适合,我需要在单独的页面上创建。我在文本之后的某个时刻添加了一个图形(画布),然后再次添加了文本。 像这样的东西:example image

1 个答案:

答案 0 :(得分:0)

要添加的内容

首先,您不能简单地将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

结果:

screen shot


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