I am using wkHTMLtoPDF and I want to change orientation on the PDF based on the length of the headers in the HTML, but I'm not sure if it's the right way to do this.
private const double A4Width = 2480; // A4 pixel width
Landscape detection method
private bool IsLandscape(string html)
{
int start = html.IndexOf("<th>");
int end = html.LastIndexOf("</th>") - start;
string tableHeadings = html.Substring(start, end).Replace("<th>", string.Empty).Replace("</th>", string.Empty);
FontFamily fontFamily = new FontFamily("Arial");
Font font = new Font(fontFamily, 13);
var size = MeasureString(tableHeadings, font);
if(size.Width > A4Width)
{
return true;
}
return false;
}
Method for font calculus
private SizeF MeasureString(string content, Font font)
{
SizeF result = SizeF.Empty;
using (var image = new Bitmap(1,1))
{
using (var g = Graphics.FromImage(image))
{
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
result = g.MeasureString(content, font, int.MaxValue, StringFormat.GenericTypographic);
}
}
return result;
}
Note: This code is in a library so that is the reason I have used this question to measure string.
Update
To be short:
I am looking for a best practice of implementing the problem.
The problem summary:
I am building from HTML a PDF that has a table inside. I get the table columns (eg: Col1, Col2) and remove the tags (eg: Col1Col2). Next I want to calculate the size (in px) of that string result (using a Font with a specified text size), and if that size excedes the A4 portrait size than rotate the PDF to the landscape orientation.