Create PDF from HTML and set page size and margin
Asked Answered
C

2

7

I am trying to create PDF from an HTML page through google-apps-script and set page size to "Letter" not "A4" (8.26 X 11.69). I have checked many related posts and have actually figured out background colors, images, etc... Related Creating PDF from HTML background color in the PDF but I am unable to make any changes to the page size.

function htmlToPDF() {

  var html = "<h1>Hello world</h1>"
       + "<p>This is just a paragraph"
       + "<p style='color:red;'>I am red</p>"
       + "<p style='color:blue;'>I am blue</p>"
       + "<p style='font-size:50px;'>I am big</p>"
       + "<table style='border-collapse: collapse; width: 698px; height: 115px; background-color: #C5D9F1;' border='0' cellpadding='10'>"
       + "<tbody>"
       + "<tr>"
       + "<td style='padding: 5px;background-color:powderblue;' nowrap='nowrap'><strong>Bold with background-color:</strong></td>"
       + "</tr>"
       + "</tbody>"
       + "</table>";

  var blob = Utilities.newBlob(html, "text/html", "text.html");
  var pdf = blob.getAs("application/pdf");

  DriveApp.createFile(pdf).setName("text.pdf");

  MailApp.sendEmail("[your email here ]", "PDF File", "", 
     {htmlBody: html, attachments: pdf});
}

I have tried several approaches to setting the size

1) Adding the following adjusts the margin to zero

<style> @page { margin: 0; }

But adding Width & Height as follows, does nothing.

@page { margin: 0; width: 216mm; height: 279mm }

and/or

@media print { margin: 0; width: 600px; height: 800px }

2) I have even tried to adjust the Width & Height when creating the HTML Output as follows

  var h = HtmlService.createHtmlOutput(myHTML);
  h.setWidth(2550);
  h.setHeight(3300);

Thank you...

Conchology answered 9/4, 2019 at 20:35 Comment(0)
O
17

As written in the documentation,

You can't change all CSS properties with @page. You can only change the margins, orphans, widows, and page breaks of the document. Attempts to change any other CSS properties will be ignored.

You can however use the highly experimental size property:

<style>
@page  {
  margin: 0;
  size: letter; /*or width then height 150mm 50mm*/
}
</style>
Orola answered 9/4, 2019 at 21:19 Comment(2)
Thank you, both "size: letter;" and "size: 215.9mm 279.4mm;" worked.Conchology
Using <style>@page { margin: 1cm;size: landscape;}</style> worked better for meMeiosis
S
-1
  let options: any = {
    format: "A4",
    path: `${PDFS_PATH}\\${pdfName}.pdf`,
    margin: {
      top: "80px",
      right: "80px",
      bottom: "100px",
      left: "80px",
    }
  };
Sibert answered 14/10, 2022 at 9:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.