Convert HTML to PDF with Apps Script

With Google Script, you can convert any HTML content into a PDF file with a few lines of code. The PDF file can be saved to Google Drive or you can email the file as an attachment using the GmailApp service.

function htmlToPDF() {
  
  var html = "<h1>Hello world</h1>"
           + "<p>The quick brown fox jumped over the lazy dog";
  
  var blob = Utilities.newBlob(html, "text/html", "text.html");
  var pdf = blob.getAs("application/pdf");
  
  DriveApp.createFile(pdf).setName("text.pdf");
  
  MailApp.sendEmail("email@labnol.org", "PDF File", "", 
     {htmlBody: html, attachments: pdf});
  
}