java - 使用 itext 将多文本添加到现有 pdf

标签 java pdf itext

我已经存在pdf模板

现在我想向此文件添加一些文本,所以我这样做了:

 PdfReader reader = new PdfReader(path + PdfCreator.TEMPORARY);
 PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(path + PdfCreator.DEST));
 PdfContentByte canvasBookingDate = stamper.getOverContent(1);
 //add text "Hellow"
 canvasBookingDate.setFontAndSize(base, 9.5f);   
 canvasBookingDate.moveText(72f, 788f);
 canvasBookingDate.showText("Hello");
 canvasBookingDate.moveText(72f, 762f);
 //add text "How are you"
 canvasBookingDate.setFontAndSize(base, 9.5f);   
 canvasBookingDate.showText("How are you");
 canvasBookingDate.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);

问题是,pdf 文件中只插入了“Hello”,而没有插入“How are you” 也许我错了什么?

我还使用单独的 PdfContentByte 对象来编写每个文本,但没有运气

PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(path + PdfCreator.DEST));
 PdfContentByte canvasBookingDate = stamper.getOverContent(1);
 //add text "Hellow"
 canvasBookingDate.setFontAndSize(base, 9.5f);   
 canvasBookingDate.moveText(72f, 788f);
 canvasBookingDate.showText("Hello");
 canvasBookingDate.moveText(72f, 762f);

 //add text "How are you"
 PdfContentByte canvasPlanName2 = stamper.getOverContent(1);
 canvasPlanName2.setFontAndSize(base, 9.5f);   
 canvasPlanName2.moveText(72f, 762f);
 canvasPlanName2.showText(entity.getPlanName());
 canvasPlanName2.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);

最佳答案

The problem is that, only "Hello" was inserted to pdf file, "How are you" was not

您的观察不准确:插入了“你好吗”,只是远离页面! (从 adobe reader 中执行 CtrlA CtrlC 并将其粘贴到某个编辑器中,您会发现它就在那里。)

原因是您误解了 moveText 的工作原理。看一下它的 JavaDoc 文档:

/**
 * Moves to the start of the next line, offset from the start of the current line.
 *
 * @param       x           x-coordinate of the new current point
 * @param       y           y-coordinate of the new current point
 */
public void moveText(final float x, final float y)

因此,坐标是相对的,而不是绝对的!

所以你应该这样做

canvasBookingDate.beginText();
canvasBookingDate.setFontAndSize(base, 9.5f);   
canvasBookingDate.moveText(72f, 788f);
canvasBookingDate.showText("Hello");
canvasBookingDate.moveText(0f, -16f);
//add text "How are you"
canvasBookingDate.showText("How are you");
canvasBookingDate.endText();

关于java - 使用 itext 将多文本添加到现有 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48698512/

相关文章:

itextsharp - 如何将书签添加到 pdfpcell

java - 获取使用 iText 和 Xchart 创建的圆环图之间的线

c# - 使用 iTextSharp 将 PDF 文件中使用的字体保存到文件

java - 我们可以在 java 中使用多线程概念和 WatchService API 吗?

java - 如何使用ibatis注释进行批量插入

pdf - Solr 4.0 用户界面问题

iphone - 是否可以在 iphone 中以编程方式将多个 pdf 文件组合成一个 pdf 文件?

java - 使用 RestHighLevelClient 使用 Basic-Auth-Proxy 后面的 ElasticSearch 端点

java - 在 jar 文件中配置 SLF4J

javascript - 获取嵌入式pdf的当前页码