如何使用 iText 获取连字的宽度
How to get the width of the ligature using iText
如何获取连字的宽度?假设我有一个连字,我能得到它的确切宽度吗?
当我这样做时:
doc.setProperty(Property.TYPOGRAPHY_CONFIG, new TypographyConfigurator()
.addFeatureConfig(
new StandardScriptConfig(new HashSet<Character.UnicodeScript>(Arrays.asList(Character.UnicodeScript.LATIN, Character.UnicodeScript.CYRILLIC)))
.setLigaturesApplying(true)
));
PdfFont font = PdfFontFactory.createFont(FONT, PdfEncodings.IDENTITY_H, true);
font.getWidth("ff", 13);
这给出了通常的宽度 ff
具体获取“”连字的宽度
有问题的连字有其自己指定的 Unicode 字符 U+FB00
,因此要获取它,您可以使用。
font.getWidth("\uFB00", 12);
获取pdfCalligraph处理的任意文本字符串的宽度
通过指定 Property.TYPOGRAPHY_CONFIG
,您隐含地使用了 pdfCalligraph
模块,该模块负责应用书法特征,如连字。这是一个闭源插件,没有 public API 交互,旨在无缝集成到现有代码中。
要使任何布局元素有效(因为它会显示在生成的 PDF 中),您可以手动布局此类元素,然后获取布局结果的一些属性,例如计算的宽度.
您可以使用如下方法计算文本的宽度:
float calculateTextWidth(Document document, String text) throws IOException {
PdfFont font = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, true);
Paragraph p = new Paragraph(text).setFont(font);
IRenderer paragraphRenderer = p.createRendererSubTree();
paragraphRenderer.setParent(document.getRenderer()).layout(new LayoutContext(new LayoutArea(1, new Rectangle(100, 100))));
return paragraphRenderer.getChildRenderers().get(0).getOccupiedArea().getBBox().getWidth();
}
确保传递给 LayoutArea
构造函数的矩形足够大以容纳所有文本(在我们的例子中 100x100 就足够了)。
然后,如果您尝试比较设置 Property.TYPOGRAPHY_CONFIG
之前和之后的方法输出,您很可能会看到不同的值,前提是字体包含连字。在我的例子中,这些值分别是 9.984
和 9.768
。由于您对连字的宽度感兴趣,请务必在将排版配置应用到文档后调用此方法。
如何获取连字的宽度?假设我有一个连字,我能得到它的确切宽度吗? 当我这样做时:
doc.setProperty(Property.TYPOGRAPHY_CONFIG, new TypographyConfigurator()
.addFeatureConfig(
new StandardScriptConfig(new HashSet<Character.UnicodeScript>(Arrays.asList(Character.UnicodeScript.LATIN, Character.UnicodeScript.CYRILLIC)))
.setLigaturesApplying(true)
));
PdfFont font = PdfFontFactory.createFont(FONT, PdfEncodings.IDENTITY_H, true);
font.getWidth("ff", 13);
这给出了通常的宽度 ff
具体获取“”连字的宽度
有问题的连字有其自己指定的 Unicode 字符 U+FB00
,因此要获取它,您可以使用。
font.getWidth("\uFB00", 12);
获取pdfCalligraph处理的任意文本字符串的宽度
通过指定 Property.TYPOGRAPHY_CONFIG
,您隐含地使用了 pdfCalligraph
模块,该模块负责应用书法特征,如连字。这是一个闭源插件,没有 public API 交互,旨在无缝集成到现有代码中。
要使任何布局元素有效(因为它会显示在生成的 PDF 中),您可以手动布局此类元素,然后获取布局结果的一些属性,例如计算的宽度.
您可以使用如下方法计算文本的宽度:
float calculateTextWidth(Document document, String text) throws IOException {
PdfFont font = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, true);
Paragraph p = new Paragraph(text).setFont(font);
IRenderer paragraphRenderer = p.createRendererSubTree();
paragraphRenderer.setParent(document.getRenderer()).layout(new LayoutContext(new LayoutArea(1, new Rectangle(100, 100))));
return paragraphRenderer.getChildRenderers().get(0).getOccupiedArea().getBBox().getWidth();
}
确保传递给 LayoutArea
构造函数的矩形足够大以容纳所有文本(在我们的例子中 100x100 就足够了)。
然后,如果您尝试比较设置 Property.TYPOGRAPHY_CONFIG
之前和之后的方法输出,您很可能会看到不同的值,前提是字体包含连字。在我的例子中,这些值分别是 9.984
和 9.768
。由于您对连字的宽度感兴趣,请务必在将排版配置应用到文档后调用此方法。