3

So I've got a HTML file, that I am using to send emails, but in some instances I want it simply to use that file to create a PDF of the same template.

I've got it functioning for the most part - it creates the file, runs the evaluations and gets the content, but it doesn't actually render the html. It simply leaves all the html notation in place.

For example, it outputs a pdf but it reads:

Dear Martin, <br />

instead of:

Dear Martin

How do I make sure it renders the HTML so that the PDF is laid out correctly, and doesn't have the html code noted in the text?

Here's the code:

var docName = "test";
var htmlBody = HtmlService.createHtmlOutput(template.evaluate().getContent()).getContent()
var doc = DocumentApp.create(docName);
  doc.appendParagraph(htmlBody);
doc.saveAndClose();
DocsList.createFile(doc.getAs('application/pdf')).rename(docName);

2 Answers 2

7

You can use your existing HTML as a blob, and convert it to PDF like this:

var htmlBody = HtmlService.createHtmlOutputFromFile('my_file_within_script_project.html').getContent();
var blob = Utilities.newBlob(htmlBody, 'text/html').getAs('application/pdf').setName('my_output_in_drive.pdf');
DriveApp.createFile(blob);
Sign up to request clarification or add additional context in comments.

Comments

2

The best option when you want to create a PDF from a template is to use Google Docs directly so that no formatting is lost and also avoid the problem you are facing.

Why don't you just create your template directly in Google Docs. Have some placeholders such as {name} instead of the actual name. Instead of using template.evaluate(), you can do a find and replace in the doc.

3 Comments

The template is also used to generate html emails. This is actually it's main purpose for which the method works fine. Would using the Google Doc method work for creating the body of my email? Thanks!
So, you send an email and a PDF with the same content as the email ? THe HTML file is good for emails and the Google Doc is better for creating PDFs. So, if the answer to my question is yes, then you're better off having the same content in two places. Not ideal but it is perhaps the best option
Sorry, not going to accept this answer. I am not sending both to the same client. The function I run looks to see if there is an email address, if not it uses the template to make a pdf, so I can print and mail a hard copy. I will not update two templates in two places.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.