我正在使用pdfbox向pdf文件添加一行 . 但我补充的文字是相反的 .
File file = new File(filePath);
PDDocument document = PDDocument.load(file);
PDPage page = document.getPage(0);
PDPageContentStream contentStream = new PDPageContentStream(document, page,PDPageContentStream.AppendMode.APPEND,true);
int stampFontSize = grailsApplication.config.pdfStamp.stampFontSize ? grailsApplication.config.pdfStamp.stampFontSize : 20
contentStream.beginText();
contentStream.setFont(PDType1Font.TIMES_ROMAN, stampFontSize);
int leftOffset = grailsApplication.config.pdfStamp.leftOffset ? grailsApplication.config.pdfStamp.leftOffset : 10
int bottomOffset = grailsApplication.config.pdfStamp.bottomOffset ? grailsApplication.config.pdfStamp.bottomOffset : 20
contentStream.moveTextPositionByAmount(grailsApplication.config.xMove,grailsApplication.config.yMove)
contentStream.newLineAtOffset(leftOffset, bottomOffset)
String text = "i have added this line...!!!!";
contentStream.showText(text);
contentStream.endText();
contentStream.close();
document.save(new File(filePath));
document.close();
byte[] pdfData;
pdfData = Files.readAllBytes(file.toPath());
return pdfData;
我尝试使用moveTextPositionByAmount方法,但这似乎对文本没有任何影响 . 为什么我的文字被颠倒了,我怎样才能将它设置为正确的方向 .
1 回答
您的代码本身不会导致镜像输出,因此原因必须在您要标记的PDF内部 . 很遗憾,您没有提供有问题的PDF,因此我们必须在此猜测 .
最有可能的问题是由预先存在的页面内容将当前转换矩阵设置为镜像仿射变换而不在最后重置它 .
如果确实如此,PDFBox提供了一个简单的解决方法:
你像这样构建你的
PDPageContentStream
:还有另一个构造函数接受另一个
boolean
参数 . 如果您使用该构造函数将其他参数设置为true
,则PDFBox会尝试重置内容的图形状态:Beware: 如果这确实解决了问题,那么您当前使用的坐标和偏移依赖于变换矩阵按原样更改 . 在这种情况下,您必须相应地更新它们 .
或者,引入反镜像可以帮助,例如,通过在每个文本对象的开头设置这样的文本矩阵:
此后,所有 y 坐标更改都需要被否定,特别是
contentStream.moveTextPositionByAmount
和contentStream.newLineAtOffset
的第二个参数 .(顺便说一句,
moveTextPositionByAmount
和newLineAtOffset
做同样的事情,前者只是不推荐使用的变体,所以你可能想在两种情况下使用后者 . )