Using Google Script to Convert HTML to PDF

August 29, 2021 Twinkle Kapoor How To

Google apps script is a scripting platform that was developed by Google with an aim to offer lightweight application development in the Google workspace platform.

Apps script was developed to make it easy and feasible to build and publish add-ons for Google Docs, Sheets, Slides, and Forms. Till now we have followed the guides to make use of Apps Script to automate scheduling Google Meet, connecting Google sheets with notion workspace, and a lot more. In this guide, we will learn to convert HTML files to PDF documents in Google Drive with the help of Google Scripts and Cloud functions.

Convert HTML to PDF using Google Script

It is quite easy and feasible to convert HTML content into a PDF file using Google scripts. Once converted, you can either save the converted PDF file to a folder in Google drive, email the file as an attachment or use the URLFetchApp service offered by Apps Script to post the PDF file to an external service like Amazon S3 or Dropbox.

/* This function will convert HTML content to a PDF file,
and also send it as an email attachment */

const convertHTMLtoPDF = () => {
const htmlContent = `

<p>All standard HTML5 tags are supported during conversion including <b>bold</b>, <i>italic</i>, <u>underline</u>, tables, and <a href=’https://www.techstreettimes.com/’>inline URLs</a></p>`;

const blob = Utilities.newBlob(htmlContent, MimeType.HTML);
blob.setName(“file.pdf”);

const recipientEmail = “amit@labnol.org”;
const emailSubject = “The PDF file is attached”;

MailApp.sendEmail({
to: recipientEmail,
subject: emailSubject,
htmlBody: htmlContent,
attachments: [blob.getAs(MimeType.PDF)],
});
};

This approach is recommended since it doesn’t require access to any sensitive OAuth scopes and uses the Utility services of Apps Script to create a Blob object from an HTML string.

Related Post: Create Telegram Bot using Google Script

Creating PDF Files with Google Drive

There’s also an option available for you to use the advanced drive service of Apps Script to convert HTML into a PDF file utilizing a Google Document at an intermediate step.

The process is that you start with creating a Google document in Drive with HTML content and then export the document in a PDF format and move the temporary document to trash. You can also override the content of the HTML document with the PDF blob.

Start with sliding into your Apps script editor, then open the appsscript.json manifest file and update scope as shown:

{

“dependencies”: {

“enabledAdvancedServices”: [
{

“userSymbol”: “Drive”,
“serviceId”: “drive”,
“version”: “v2”
}
]
},
“oauthScopes”: [“https://www.googleapis.com/auth/drive.file”],
“runtimeVersion”: “V8”,
“timeZone”: “Asia/Kolkata”,
“exceptionLogging”: “STACKDRIVER”

}

Now, inside the main code editor, paste the below-mentioned snippet. It is a three-step process:

  1. Convert the HTML string to a blob
  2. Convert the Blob into Google Document
  3. Export the Google Doc as PDF file and move the file created in step 2 to trash.
const convertHTMLtoPDF = () => {
const htmlContent = `

<p>All standard HTML5 tags are supported during conversion including <b>bold</b>, <i>italic</i>, <u>underline</u>, tables, and <a href=’https://www.techstreettimes.com/’>inline URLs</a></p>`;

const { id, exportLinks } = Drive.Files.insert(
{ mimeType: MimeType.GOOGLE_DOCS },
htmlBlob: Utilities.newBlob(htmlContent, MimeType.HTML)
);

const pdfExportLink = exportLinks[MimeType.PDF];

const blob = UrlFetchApp.fetch(pdfExportLink, {
headers: { Authorization: Bearer ${ScriptApp.getOAuthToken()} },
}).getBlob();

Drive.Files.trash(id);

const { alternateLink } = Drive.Files.insert({ title: “file.pdf” }, blob);

Logger.log(“View file %s”, alternateLink);
};

Note:  We are using the drive.file reduced scope in the manifest file but if you want to save files in Google Drive folders, or Shared Team Drives, use the broader googleapis.com/auth/drive scope.

Guide to convert HTML to PDF with Chrome Puppeteer

Chrome Puppeteer with Node JS is so your option if you want to build a standalone HTML to PDF conversion engine, which doesn’t use any of the Google Drive services.

Additionally, you can host the service on AWS Lambda or Google Cloud functions and invoke the service with an HTTP call.

const express = require(“express”);
const chromium = require(“chrome-aws-lambda”);

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

const html2pdf = async (html) => {
const browser = await chromium.puppeteer.launch({
args: chromium.args,
executablePath: await chromium.executablePath,
headless: true,
ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
await page.setContent(html, {
waitUntil: [“networkidle0”, “load”, “domcontentloaded”],
timeout: 30000,
});

const pdf = await page.pdf({
format: “A4”,
printBackground: true,
});

await browser.close();

return pdf;

};
app.post(“/pdf”, async (request, response) => {
try {
const { content } = request.body;
const pdf = await html2pdf(content);
response.contentType(“application/pdf”);
response.status(200).send(pdf);
} catch (f) {
response.status(500).send(f.message);
}
});

const PORT = process.env.PORT || 8080;

app.listen(PORT, async () => {
console.log(App listening on port ${PORT});
});

Voila! We are done with this guide to convert HTML to PDF using Google Apps script. Hope this could help you enough. Stay tuned to this corner for such amazing guide on utilizing Google Apps script for your use.

Author

Leave a Reply

Your email address will not be published. Required fields are marked *