我正在使用iText 7为.NET实现PDF创建,从iTextSharp 5.5.12升级,一切都运行得很好,而且它比以前的版本简单得多,速度也快得多,但是,我想我发现了一个bug。
具体地说,在使用具有表单域的预先存在的PDF并填充它时,如果域标记为多行,则忽略任何预设或覆盖的文本对齐方式,文本始终左对齐。如果我将该字段取消标记为多行,则将遵循预设对齐方式。
有没有人知道解决这个问题的方法?谢谢!
发布于 2018-01-13 17:23:41
这确实是iText 7中的一个错误。我认为仅仅用你自己的代码来解决这个问题是很难的。在iText 7中没有修复错误的情况下,能够对多行字段使用对齐的最简单方法可能是自己修复问题并从源代码构建二进制文件。
看一看PdfFormField的实现。在这里,我采用了最新的开发版本,但是如果您愿意,您可以将您的修复基于master
或任何其他版本。
感兴趣的方法是drawMultiLineTextAppearance
。您可以看到Canvas
实例已创建,并且Paragraph
实例已添加到Canvas
中。而且任何地方都没有提到正当性!这是我们应该修复的地方。首先,我们应该将PdfFormField
的justification
属性转换为layout
模块的TextAlignment
属性,稍后可以在Paragraph
上使用该属性
Integer justification = getJustification();
if (justification == null) {
justification = 0;
}
TextAlignment textAlignment = TextAlignment.LEFT;
if (justification == ALIGN_RIGHT) {
textAlignment = TextAlignment.RIGHT;
} else if (justification == ALIGN_CENTER) {
textAlignment = TextAlignment.CENTER;
}
我们就快完成了!剩下的就是将TextAlignment
设置为段落。请确保在将Paragraph
添加到Canvas
之前执行此操作
// This line was already there
Paragraph paragraph = new Paragraph(strings.get(index)).setFont(font).setFontSize(fontSize).setMargins(0, 0, 0, 0).setMultipliedLeading(1);
// This is the new line we are adding to fix the alignment problem
paragraph.setTextAlignment(textAlignment);
完整的代码片段:
// The block below was already there:
Paragraph paragraph = new Paragraph(strings.get(index)).setFont(font).setFontSize(fontSize).setMargins(0, 0, 0, 0).setMultipliedLeading(1);
paragraph.setProperty(Property.FORCED_PLACEMENT, true);
// These are the new lines
Integer justification = getJustification();
if (justification == null) {
justification = 0;
}
TextAlignment textAlignment = TextAlignment.LEFT;
if (justification == ALIGN_RIGHT) {
textAlignment = TextAlignment.RIGHT;
} else if (justification == ALIGN_CENTER) {
textAlignment = TextAlignment.CENTER;
}
paragraph.setTextAlignment(textAlignment);
就这样!剩下要做的就是使用mvn package
/ mvn install
构建模块。有关构建的更多信息,请参阅BUILDING.md
。
这些说明是针对Java语言的,但是如果您使用的是.NET
版本,那么它基本上是相同的,只是构建步骤有所不同。
iText是一个开源产品,所以请不要害怕探索代码和玩弄。
https://stackoverflow.com/questions/48236264
复制相似问题