-1

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.

Community
  • 1
  • 1
Botea Bogdan
  • 182
  • 2
  • 15
  • Hi, sorry can you please extend your question, I did not understand Your Problem. Are you looking a best practice exactly for what? – Payedimaunt Oct 22 '15 at 09:01
  • I have updated the question. Feel free to ask if you don't understand something. Thank you! – Botea Bogdan Oct 22 '15 at 11:02
  • I haven't found an exact exact solution but below I have found some informations about how to find the actual printable area. I hope it could help you dude – Payedimaunt Oct 23 '15 at 08:52

1 Answers1

1

I have found that the best implementation of this problem is to add to wkHTMLtoPDF an attribute to force the PDF to be A4 size.

Attribute used : --page-size A4

Also I have changed the code that checks if the measured width size is grater than the A4 size.

if(size.Width > (A4Width / 4))
{
    return true;
}
Botea Bogdan
  • 182
  • 2
  • 15