Consider the following code:
var path = AppDomain.CurrentDomain.BaseDirectory;
var filePath = Path.Combine(path, "test1.pdf");
using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
using (var document = new Document(new Rectangle(PageSize.A4.Width, PageSize.A4.Height)))
using (var writer = PdfWriter.GetInstance(document, stream))
{
try
{
document.Open();
const string value = "The quick brown fox";
for (int i = 0; i < 4; i++)
{
var chunk = new Chunk(value);
chunk.SetCharacterSpacing(i);
var origin = new Phrase(chunk);
var paragraph1 = new Paragraph(origin);
document.Add(paragraph1);
var widthPoint = chunk.GetWidthPoint();
Debug.WriteLine(widthPoint);
}
writer.CloseStream = false;
}
finally
{
document.Close();
stream.Close();
}
}
I am attempting to add a paragraph/chunk to a single PdfPCell in a new PdfPTable. We have no control over the actual text going into the cells, and it is possible the text will be a little longer that the available space. Either the text would break onto multiple lines or flow out of the cell and be hidden.
The idea is to automatically reduce the letter-spacing of the text (up to a minimum amount) in order to try and mitigate the text being cropped. Basically apply a small negative letter spacing until the text fits. The issue is the value of widthPoint is always the same, no matter the letter-spacing applied. The PDF generated clearly has the text rendered with different widths.
Is there a way to calculate the actual width of the text with letter-spacing, or it's container? The chunk / paragraph are (what I would describe as) box-model type elements. That is to say they fill the cell and always have the same width.
No idea how to proceed.
This is for iTextSharp version 5.5.9.0