pdf - 生成的pdf中的文本是反向的

我正在使用 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 方法,但这似乎对文本没有任何影响。为什么我的文字颠倒了,我如何将其设置为正确的方向。

最佳答案

您的代码本身不会导致镜像输出,因此原因必须在您正在加盖的 PDF 内。不幸的是,您没有提供相关的 PDF,因此我们必须在这里猜测。

最有可能的问题是由于预先存在的页面内容将当前变换矩阵设置为镜像仿射变换而没有在最后重置它。

如果确实如此,PDFBox 提供了一个简单的解决方法:

您可以像这样构建 PDPageContentStream:

PDPageContentStream contentStream = new PDPageContentStream(document, page,PDPageContentStream.AppendMode.APPEND,true);

还有另一个构造函数接受额外的 boolean 参数。如果您使用该构造函数将附加参数设置为 true ,PDFBox 会尝试重置内容的图形状态:
PDPageContentStream contentStream = new PDPageContentStream(document, page,PDPageContentStream.AppendMode.APPEND,true,true);

当心: 如果这确实解决了问题,则您当前使用的坐标和偏移量依赖于按原样更改的变换矩阵。在这种情况下,您必须相应地更新它们。

或者,引入反镜像可能会有所帮助,例如通过在每个文本对象的开头设置这样的文本矩阵:
contentStream.beginText();
contentStream.setTextMatrix(new Matrix(1f, 0f, 0f, -1f, 0f, 0f));

此后所有 y 坐标变化都需要否定,特别是 contentStream.moveTextPositionByAmountcontentStream.newLineAtOffset 的第二个参数。

(顺便说一句,moveTextPositionByAmountnewLineAtOffset 的作用相同,前者只是不推荐使用的变体,因此您可能希望在两种情况下都使用后者。)

https://stackoverflow.com/questions/46924286/

相关文章:

grails - 查找第一个匹配项-DomainClass.findAll()[0]的替代方法

colors - 在 ssh 之前导出 TERM

grails - 如何在Grails(2.5.5)中自动在前面带有多个大写字母的服务接线

svn - 通过SSH的svn diff-结果与Trac不同吗?

grails - repo.grails.org - 证书过期

unit-testing - 基于 Spock 交互的测试 : too few invocation

grails - 访问 Grails 全局变量时是否需要使用互斥锁?

grails - 使用Compass/Lucene搜索对象的子集

grails - 将视频文件转换为.flv格式

grails - 为Grails安装Nimble