我已经存在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文件,"你好吗"不是 也许我错在那里?
我还使用单独的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);
答案 0 :(得分:1)
问题是,只有"你好"被插入pdf文件,"你好吗"不是
你的观察结果不准确:"你好吗"插入,只是远离页面! (从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();
答案 1 :(得分:0)
我从Vishal Kawade链接找到答案
在每个文本之后只需使用beginText()
和endText()
,就需要插入pdf