basel adel
basel adel

Reputation: 45

Creating a properly encoded/decoded pdf files from google app script

I'm setting up a spreadsheet which creates a pdf file and share it with someone to print it and sign it.

 var content = getMessage(X,Y,Z, etc);
 var FolderFile = DriveApp.getFoldersByName('CreatingFolderTest').next();
 var FileCreation = FolderFile.createFile(EmployeeID, content, MimeType.PDF).addViewer(Email);

the issue is that when I'm trying to download the file it gives me an error that pdf file is not properly decoded.

Tried to search for solutions and found that it might the metadata tags I'm using

 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width"/>

I expect that I can create a file in PDF format from the HTML file already in the code and send it to the employee to print it out! will be extra if I can add a password to the pdf file, but that's a kind of extra mile

Upvotes: 0

Views: 425

Answers (1)

Tanaike
Tanaike

Reputation: 201378

  • You want to create the file of text/html as a PDF file.
  • MimeType of content of var content = getMessage(X,Y,Z, etc) is text/html.

If my understanding is correct, how about this modification?

Modification points:

  • Unfortunately, the file of text/html cannot be directly converted to PDF format using createFile(EmployeeID, content, MimeType.PDF). When your script is run, a file that the content and mimeType are HTML and application/pdf is created. By this, when the file is opened, an error occurs. Because the content is not PDF format.
  • In order to avoid this issue, I used HtmlService.createHtmlOutput().

Please think of this as just one of several answers.

Modified script:

From:
var content = getMessage(X,Y,Z, etc);
var FolderFile = DriveApp.getFoldersByName('CreatingFolderTest').next();
var FileCreation = FolderFile.createFile(EmployeeID, content, MimeType.PDF).addViewer(Email);
To:
var content = getMessage(X,Y,Z, etc);
var FolderFile = DriveApp.getFoldersByName('CreatingFolderTest').next();

var html = HtmlService.createHtmlOutput(content); // Added
var FileCreation = FolderFile.createFile(html.getAs(MimeType.PDF)).setName(EmployeeID); // Modified

Note:

  • If the HTML includes the images retrieving from URLs, please put the images to HTML as base64 data. You can see the sample script at here.

References:

Upvotes: 1

Related Questions