如何计算iText中的字符串宽度?
我正在使用 iText 编写 PDF。在某些情况下,我需要使用 SetVisibleSignature
函数对 PDF 进行签名。使用此函数,我们需要指定要写入内容的矩形。
但我很难计算字符串的宽度,因此我可以在 PDF 上设置签名之前设置矩形。
如何计算 iText 中的字符串宽度?
I am using iText to write a PDF. In some cases, I need to sign the PDF with the SetVisibleSignature
function. With this function, we need to designate the rectangle that we will write the content into.
But it's hard for me to calculate how wide the string will be, so that I can set the rectangle before setting a signature on the PDF.
How can I calculate the string width in iText?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
接受的答案
BaseFont.getWidthPoint
在 itext 5.5.4 中不起作用,因为该方法不再是静态的。即使它仍然存在,它也不会考虑正在使用的真实字体(其系列或其粗体/斜体),因为它是静态的并且接收的参数有限。正如后面所述,chunk.getWidthPoint() 确实可以使用真实字体,但对于某些用途来说,不断地仅为宽度创建块是一种浪费,特别是如果该块不打算被使用的话。稍后使用。
这是
chunk.getWidthPoint()
用作独立替代品的底层代码,假设您没有进行任何水平缩放:The accepted answer
BaseFont.getWidthPoint
, won't work in itext 5.5.4 since the method isn't static anymore. Even if it did still exist, it doesn't take into account the true font being used (its family or its bold/italics) since it's static and is receiving limited parameters.chunk.getWidthPoint()
does work with the true font as later stated, but for certain uses it is a waste to constantly create a chunk just for the width, especially if the chunk isn't planned on being used later.This is the underlying code for
chunk.getWidthPoint()
to use as a standalone substitute, assuming you are not doing any horizontal scaling:我最终用
ColumnText.getWidth( Phrase phrase )
来调整 < 的宽度code>Phrase 将在用ColumnText.showTextAligned
。在此代码片段中,我使用 ColumnText.getWidth 来调整字符串的长度,以将其放置在页面的右上角。它适用于纵向 A4,尚未进一步测试。
I ended up doing this with
ColumnText.getWidth( Phrase phrase )
to size what the width of aPhrase
would be before showing it withColumnText.showTextAligned
.In this snippet, I used the
ColumnText.getWidth
to size the length of a string to place it top right of a page. It works in portrait A4, haven't tested it further.您可以使用 BaseFont.getWidthPoint(String text, float fontSize) 获取字符串的宽度(以 pt 为单位)。
或者将字符串放入 Chunk 中并执行
chunk.getWidthPoint()
You can use
BaseFont.getWidthPoint(String text, float fontSize)
to get the width of the string in pt.Or put the string in a Chunk and do
chunk.getWidthPoint()