java 如何使用 iText 将图形绘制为 PDF?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7830928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:36:24  来源:igfitidea点击:

How do I draw graphics to PDF using iText?

javaspring-mvcpdf-generationitextgraphics2d

提问by jimdrang

I am trying to complete an example that draws graphics and writes them to PDF, but I keep getting errors that the PDF has no pages. if I add something simple with document.add() after opening it works fine, I just never see the graphics. Here is my code:

我正在尝试完成一个绘制图形并将它们写入 PDF 的示例,但我不断收到 PDF 没有页面的错误。如果我在打开后用 document.add() 添加一些简单的东西,它工作正常,我只是看不到图形。这是我的代码:

Document document = new Document();
PdfWriter writer = new PdfWriter();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition",
    " attachment; filename=\"Design.pdf\"");

writer = PdfWriter.getInstance(document, response.getOutputStream());

document.open();    
PdfContentByte cb = writer.getDirectContent();
Graphics2D graphics2D = cb.createGraphics(36, 54);
graphics2D.drawString("Hello World", 36, 54);
graphics2D.dispose();   
document.close();

Do I have to do something else to add the graphic to the document or is my syntax incorrect?

我是否必须执行其他操作才能将图形添加到文档中,还是我的语法不正确?

采纳答案by styken

Does Document doc = new Document(PageSize.A4);make any difference?

Document doc = new Document(PageSize.A4);什么区别吗?

I don't know if you need to add a Paragraphlike this:

我不知道你是否需要添加Paragraph这样的:

doc.add(new Paragraph(...));

Also we use doc.add(ImgRaw);to add images.

我们也doc.add(ImgRaw);用来添加图像。

回答by Ralph

I am not an expert in IText, but last week I tryed to draw some circles with it. So this is what I have noticed during my tests:

我不是 IText 的专家,但上周我试着用它画了一些圆圈。所以这就是我在测试中注意到的:

If you draw graphics, you must (or lets say I must when I tryed it) "wrap" the graphics commands in a section starting with saveState()and ending with restoreState(), es well as I needed to invoke fillStroke()-- if I do not invoke fillStroke()then nothing was drawn.

如果您绘制图形,则必须(或者说我尝试时必须)将图形命令“包装”在以 开头saveState()和结尾的部分中restoreState(),以及我需要调用的部分fillStroke()- 如果我不调用,fillStroke()则什么都没有画。

Example

例子

private void circle(float x, float y, PdfWriter writer) {
    PdfContentByte canvas = writer.getDirectContent();

    canvas.saveState();
    canvas.setColorStroke(GrayColor.BLACK);
    canvas.setColorFill(GrayColor.BLACK);
    canvas.circle(x, y, 2);
    canvas.fillStroke();

    canvas.restoreState();
}

@Test
public void testPossition() throws DocumentException, IOException {
    OutputStream outputStream = FileUtil.openOutputStream("testPosition.pdf");
    //this is my personal file util, but it does not anything more
    //then creating a file and opening the file stream.

    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();

    markPosition(100, 100, writer);
    document.add(new Paragraph("Total: 595 x 842 -- 72pt (1 inch)"));

    document.close();
    outputStream.flush();
    outputStream.close();
}

private void markPosition(float x, float y, PdfWriter writer)
        throws DocumentException, IOException {
    placeChunck("x: " + x + " y: " + y, x, y, writer);
    circle(x, y, writer);
}

 private void placeChunck(String text, float x, float y, PdfWriter writer)
       throws DocumentException, IOException {
    PdfContentByte canvas = writer.getDirectContent();
    BaseFont font = BaseFont.createFont(BaseFont.HELVETICA,
                  BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    canvas.saveState();
    canvas.beginText();
    canvas.moveText(x, y);
    canvas.setFontAndSize(font, 9);
    canvas.showText(text);
    canvas.endText();
    canvas.restoreState();
}

But PdfContentByte(canvas) has much more functions, for example rectangle.

但是PdfContentByte(canvas) 有更多的功能,例如rectangle.

回答by Carles Company

I think the problem is that directcontent writes directly to the page object. This way you can add backgrounds or backdrop images. Try adding a new page (doc.newPage()) before writing to the directcontent.

我认为问题是直接内容直接写入页面对象。通过这种方式,您可以添加背景或背景图像。doc.newPage()在写入直接内容之前尝试添加一个新页面 ( )。

回答by Kevin Day

Have you tried drawing operations on the g2d object that just use shapes instead of text? That would eliminate the possibility of something odd going on with font selection or something like that.

您是否尝试过仅使用形状而不是文本的 g2d 对象的绘图操作?这将消除字体选择或类似事情发生奇怪的可能性。

iText In Action Chapter 12 has exactly what you are looking for - it really is worth picking up. Preview of Chapter 12

iText 实战第 12 章正是您要寻找的内容 - 确实值得一读。 第 12 章预览

回答by Kevin Day

Without going too far into it, I think your general approach is fine. I think what might be happening here is that the Graphics2D origin is different from the PDF origin, so maybe you need to change the call to drawString() so it uses 0,0 as the location??

不用太深入,我认为您的一般方法很好。我认为这里可能发生的情况是 Graphics2D 原点与 PDF 原点不同,所以也许您需要更改对 drawString() 的调用,以便它使用 0,0 作为位置?

回答by Kevin Day

I just put together the following unit test against the latest HEAD of iText:

我刚刚针对 iText 的最新 HEAD 进行了以下单元测试:

    Document document = new Document();
    PdfWriter writer = new PdfWriter();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    writer = PdfWriter.getInstance(document, baos);

    document.open();    
    PdfContentByte cb = writer.getDirectContent();
    Graphics2D graphics2D = cb.createGraphics(36, 54);
    graphics2D.setColor(Color.black);
    graphics2D.drawRect(0, 0, 18, 27);

    Font font = new Font("Serif", Font.PLAIN, 10);
    graphics2D.setFont(font);

    graphics2D.drawString("Yo Adrienne", 0, 54); 


    graphics2D.dispose();   
    document.close();

    TestResourceUtils.openBytesAsPdf(baos.toByteArray());

And it works fine - I get a small black rectangle in the lower left hand corner of the page, plus text. Note that I am specifying X=0 for my drawString method (you were specifying 36 which causes the text to render outside of the image bounds). Note also that I explicitly specified a font - if I leave that out, it still renders, but it's usually a great idea to not trust the defaults for that sort of thing. Finally, I explicitly set the foreground color - again, not truly necessary, but trusting defaults can be scary.

它工作正常 - 我在页面的左下角看到一个小的黑色矩形,加上文本。请注意,我为我的 drawString 方法指定了 X=0(您指定了 36,这会导致文本呈现在图像边界之外)。另请注意,我明确指定了一种字体 - 如果我忽略它,它仍然会呈现,但不相信此类事情的默认值通常是个好主意。最后,我明确地设置了前景色——同样,这并不是真正必要的,但相信默认值可能会很可怕。

So I'd have to say that the core issue here was the placement of the text at x=36.

所以我不得不说,这里的核心问题是文本在 x=36 的位置。

In none of my tests was I able to create an error saying that the PDF has no pages - can you post the stack trace of the exception you are getting?

在我的所有测试中,我都无法创建一个错误,指出 PDF 没有页面 - 你能发布你得到的异常的堆栈跟踪吗?

I can't imagine that adding a paragraph to the document makes any difference to this (that's the sort of bug that would have gotten taken care of long, long ago)

我无法想象在文档中添加一个段落会对此产生任何影响(这是很久以前就应该处理的那种错误)