JBruce
JBruce

Reputation: 449

Create PDF from HTML and set page size and margin

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...

Upvotes: 7

Views: 38400

Answers (2)

Anamika
Anamika

Reputation: 1

  let options: any = {
    format: "A4",
    path: `${PDFS_PATH}\\${pdfName}.pdf`,
    margin: {
      top: "80px",
      right: "80px",
      bottom: "100px",
      left: "80px",
    }
  };

Upvotes: -1

TheMaster
TheMaster

Reputation: 50382

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>

Upvotes: 17

Related Questions