I am using C# and iText 7.2.1.
I want to draw texts right inside rectangles. I see in document that the positioning anchor of rectangles and paragraphs are both 'left-bottom corner'. But when I use the following code, they are not at the same location. Seems they have different understanding of the Y coordinate.
My code:
using iText.IO.Font;
using iText.IO.Font.Constants;
using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Layout;
using iText.Layout.Element;
namespace iTextTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var str = "ABCD1234";
var fontSize = 32;
var x = 100;
var y = 700;
var writer = new PdfWriter("test.pdf");
var pdfdoc = new PdfDocument(writer);
var doc = new Document(pdfdoc);
var font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
var width = font.GetWidth(str, fontSize);
var height = fontSize;
// Draw rectangle
var pdfPage = pdfdoc.AddNewPage();
var pdfCanvas = new PdfCanvas(pdfPage);
pdfCanvas.SetFillColor(ColorConstants.YELLOW);
pdfCanvas.Rectangle(x, y, width, height);
pdfCanvas.Fill();
// Draw text
var p = new Paragraph().Add(str).SetFont(font);
p.SetFontSize(fontSize).SetFontColor(ColorConstants.BLACK);
p.SetFixedPosition(x, y, width);
doc.Add(p);
doc.Close();
pdfdoc.Close();
writer.Close();
}
}
}
A line of a paragraph does not require the height of the font size but instead of the leading. For tightly set text the leading may equal the font size (or sometimes even be smaller than it) but for easy-to-read text the leading usually is larger than the font size.
When drawing a paragraph with iText, the extra space is located at the bottom of the line. This causes the empty space under the line you see in your output.
For your code to work, therefore, you have to set the leading to match your font size, i.e.
// Draw text
var p = new Paragraph().Add(str).SetFont(font);
p.SetFontSize(fontSize).SetFontColor(ColorConstants.BLACK);
p.SetFixedPosition(x, y, width);
p.SetFixedLeading(fontSize); // <-- added
doc.Add(p);
(TextPosition test TextAndPositionLikeLandings
)
The result: