2

I am trying to set a custom page size with OpenHTMLtoPDF. I am trying to convert an HTML source to a 58mm x 110mm thermal paper print job, however, I got stuck on this.

I have tried setting the page size directly like so:

var pdf = Pdf.From(html).OfSize(58,110);//Invalid arguments 

and

var pdf = Pdf.From(html).OfSize(new PaperSize(58,110));//Invalid arguments
Marcello B.
  • 4,177
  • 11
  • 45
  • 65
  • I posted this as a Q&A style question as I got stuck on this for an hour, and was unable to find anything on how to do this. After playing around for an hour I figured it out and thought it was worth sharing. – Marcello B. Jan 11 '19 at 21:16

1 Answers1

1

You are defining the size incorrectly.

What you need to do is create a new paper size like so:

OpenHtmlToPdf.PaperSize size = new OpenHtmlToPdf.PaperSize(Length.Millimeters(58), Length.Millimeters(110));

Then to set your PDF document to have the right paper size you would call this like so

var pdf = Pdf.From(html).OfSize(size);

Side Note

If you are using a different unit of measurement you can define what unit of measurement you are using like so:

Length.Inches(MeasurementInInches);
Length.Centimeters(MeasurementInCentimeters);
Marcello B.
  • 4,177
  • 11
  • 45
  • 65
  • Is there any possibility for fixed width and dynamic height?(set the height to the final html element height) for like thermal printer paper. – qakmak Jul 24 '20 at 18:27
  • @qakmak not that I know of. One solution would be to roughly calculate the size based off the number of lines to be printed. – Marcello B. Jul 24 '20 at 18:34
  • I think that's not a good solution, because the words in html, it might be auto-break to new line, in that cause I wouldn't know the number of lines.... – qakmak Jul 24 '20 at 19:44
  • There’s one more solution I can think of. Do a test with a set paper size (100mm) then see how many pages (lets say 4 pages in the test) it is and then rerun it with the set size and the number of pages so then you would have 400mm page height. – Marcello B. Jul 24 '20 at 19:57
  • Sounds like a really good idea, but I think I need to find an external library for check PDF page size too, OpenHTMLtoPDF can't check it... – qakmak Jul 24 '20 at 21:01
  • You should just be able to calculate it cause you are setting the page size yourself. But if you still need a library for pdf info you should checkout pdflib it worked well for me in a past project – Marcello B. Jul 24 '20 at 21:05
  • 1
    Um..., I can set the height of page, but I still need to check the final generated pdf file page count. at the end I use PdfReader of pdfium, because it's free. Thanks for give me good advice. – qakmak Jul 24 '20 at 21:44
  • What version of OpenHtmlToPdf are you using? I tried the above and my pdf is 280mm x 360mm - no idea why – AriesConnolly Oct 25 '22 at 11:13