PdfBox 2.0.0 在页面中的给定位置写入文本
我刚刚从 PdfBox 1.8 过渡到 2.0.0,并且有相当显着的差异.在现有的 pdf 页面上写文本之前,我使用了 drawString.在 2.0.0 中不推荐使用绘制字符串,但 showText 在块文本中不起作用.
I have just passed from PdfBox 1.8 to 2.0.0 and there are quite significant differences. Before to write a text on an existing pdf page I used drawString. In 2.0.0 draw string is deprecated but showText does not work in a block text.
我在 1.8 中的代码:
My code in 1.8:
contentStream.beginText()
contentStream.moveTextPositionByAmount(250, 665)
contentStream.drawString("1 2 3 4 5 6 7 8 9 1 0")
contentStream.endText()
我在 2.0 中的代码
My code in 2.0
PDDocument newPdf=null
newPdf=PDDocument.load(sourcePdfFile)
PDPage firstPage=newPdf.getPage(0)
PDPageContentStream contentStream = new PDPageContentStream(newPdf, firstPage, PDPageContentStream.AppendMode.APPEND,true,true)
contentStream.setFont(pdfFont, fontSize)
contentStream.beginText()
contentStream.lineTo(200,685)
contentStream.showText("John")
contentStream.endText()
但它不起作用...
任何人都知道我如何像 1.8 一样编写文本
Anyone has any idea about how can I write text as in 1.8
LineTo
是画一条线.你想要的是newLineAtOffset
(moveTextPositionByAmount的弃用通知是这么说的),所以你的代码是这样的:
LineTo
is to draw a line. What you want is newLineAtOffset
(the deprecation notice of moveTextPositionByAmount says so), so your code is like this:
PDDocument newPdf = PDDocument.load(sourcePdfFile);
PDPage firstPage=newPdf.getPage(0);
PDFont pdfFont= PDType1Font.HELVETICA_BOLD;
int fontSize = 14;
PDPageContentStream contentStream = new PDPageContentStream(newPdf, firstPage, PDPageContentStream.AppendMode.APPEND,true,true);
contentStream.setFont(pdfFont, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(200,685);
contentStream.showText("John");
contentStream.endText();
contentStream.close(); // don't forget that one!