我刚刚从PdfBox 1.8传递到2.0.0,并且存在相当大的差异。在现有的pdf页面上写文本之前,我使用了drawString。在2.0.0中,不推荐使用绘制字符串,但showText在块文本中不起作用。
我在1.8中的代码:
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()
我的代码在2.0
'T option
但它不起作用......
任何人都知道如何在1.8中编写文本
答案 0 :(得分:3)
LineTo
是画一条线。你想要的是newLineAtOffset
(moveTextPositionByAmount的弃用通知是这样说的),所以你的代码是这样的:
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!
答案 1 :(得分:0)
如果您要查找在PDF中的所需位置添加多行语句的代码
像这样
这是第一行
这是第二行
这是第三行
那么您需要使用
//to load PDF where you
PDDocument pdDocument = PDDocument.load(new File(resourceBundle.getString("F:\PDF\loki.pdf")));
//get the page where you want to write code,for first page you need to use 0
PDPage firstPage = pdDocument.getPage(0);
//you can load new font if required, by using `ttf` file for that font
PDFont pdfFont = PDType0Font.load(pdDocument,
new File(resourceBundle.getString("F:\PDF\data\verdana.ttf")));
int fontSize = 9;
//PDPageContentStream.AppendMode.APPEND this part is must if you want just add new data in exsitnig one
PDPageContentStream contentStream = new PDPageContentStream(pdDocument, pdDocument.getPage(0),
PDPageContentStream.AppendMode.APPEND, true, true);
contentStream.setFont(PDType0Font.load(pdDocument, new File(resourceBundle.getString("pdfFont"))), 9);
//for first Line
contentStream.beginText();
//For adjusting location of text on page you need to adjust this two values
contentStream.newLineAtOffset(200,685);
contentStream.showText("this is line first");
contentStream.endText();
//for second line
contentStream.beginText();
contentStream.newLineAtOffset(200,685);
contentStream.showText("this is line second");
contentStream.endText();
//for third line
contentStream.beginText();
contentStream.newLineAtOffset(200,685);
contentStream.showText("this is line third");
contentStream.endText();
//and so on.
//at last you need to close the document to save data
contentStream.close();
//this is for saving your PDF you can save with new name
//or you can replace existing one by giving same name
pdDocument.save(resourceBundle.getString("F:\PDF\lokiTheKing.pdf"));