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?
Once downloaded, simply open your pdf file in Adobe Acrobat Reader, press Ctrl+D or File > Properties (Document Properties). And voilà! In the Advanced Information section, you will find 'Page size'.
iText vs iTextSharp As you can tell from the historical overview, iTextSharp has always been kept in sync with iText, but before version 5, there was a difference in version numbers. Starting with version 7, the name iTextSharp is no longer used in favor of using the name iText.
iText is a Java library originally created by Bruno Lowagie which allows to create PDF, read PDF and manipulate them. The following tutorial will show how to create PDF files with iText. This tutorial assumes that you have basis Java and Eclipse knowledge.
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()
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:
font.getCalculatedBaseFont(true).getWidthPoint(text, font.getCalculatedSize());
I ended up doing this with ColumnText.getWidth( Phrase phrase )
to size what the width of a Phrase
would be before showing it with ColumnText.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.
Phrase phrase = new Phrase( "Bla bla bla!", new Font( FontFamily.HELVETICA, 9 ) );
float width = ColumnText.getWidth( phrase );
ColumnText.showTextAligned (
canvas,
Element.ALIGN_LEFT,
phrase,
canvas.getPdfDocument( ).right( ) - width,
canvas.getPdfDocument( ).top( ) + 9,
0
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With