Console: Draw text in rectangle on PDF page and maintain aspect ratio of text.
Posted: Wed Jun 07, 2023 10:08 am
Here is C# code that demonstrates how to draw text in rectangle on PDF page and maintain aspect ratio of text:
Code: Select all
class Program
{
static void Main(string[] args)
{
// create new PDF document
using (Vintasoft.Imaging.Pdf.PdfDocument document = new Vintasoft.Imaging.Pdf.PdfDocument())
{
// add empty page to the PDF document
document.Pages.Add(new Vintasoft.Imaging.Pdf.Tree.PdfPage(document, Vintasoft.Imaging.PaperSizeKind.A4));
// create PDF font
Vintasoft.Imaging.Pdf.Tree.Fonts.PdfFont font =
document.FontManager.GetStandardFont(Vintasoft.Imaging.Pdf.Tree.Fonts.PdfStandardFontType.TimesRoman);
// get graphics object for PDF page
using (Vintasoft.Imaging.Pdf.Drawing.PdfGraphics graphics = document.Pages[0].GetGraphics())
{
// use green brush
graphics.SetBrush(new Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Green));
// draw text in rectangle and do not maintain aspect ratio of text
DrawTextInRect(graphics, "Test string (no aspect ratio)", font, new System.Drawing.RectangleF(50, 200, 500, 200), false);
// use red brush
graphics.SetBrush(new Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Red));
// draw text in rectangle and maintain aspect ratio of text
DrawTextInRect(graphics, "Test string (maintain aspect ratio)", font, new System.Drawing.RectangleF(50, 200, 500, 200), true);
}
// save PDF document to a file
document.Save("out.pdf");
}
}
public static void DrawTextInRect(
Vintasoft.Imaging.Pdf.Drawing.PdfGraphics graphics,
string text,
Vintasoft.Imaging.Pdf.Tree.Fonts.PdfFont font,
System.Drawing.RectangleF rect,
bool maintainAspectRatio)
{
const float FontSize = 1;
// measure text
graphics.MeasureString(text, font, FontSize, out float textWidth, out float textHeight);
// calulate scales
float scaleX = rect.Width / textWidth;
float scaleY = rect.Height / textHeight;
if (maintainAspectRatio)
{
if (scaleX > scaleY)
{
scaleX = scaleY;
rect.X += (rect.Width - textWidth * scaleX) / 2;
}
else
{
scaleY = scaleX;
rect.Y += (rect.Height - textHeight * scaleY) / 2;
}
}
// save graphics state
graphics.SaveGraphicsState();
// set transform
Vintasoft.Imaging.AffineMatrix transform = Vintasoft.Imaging.AffineMatrix.CreateTranslation(rect.X, rect.Y);
transform.MultiplyPrepend(Vintasoft.Imaging.AffineMatrix.CreateScaling(scaleX, scaleY));
graphics.MultiplyTransform(transform);
// draw text
graphics.DrawString(text, font, FontSize, 0, 0);
// restore graphics state
graphics.RestoreGraphicsState();
}
}