I have a custom Google Script with a simple logic: it looks up parts from the spreadsheet and builds an in-memory HTML string, then I call the following code to produce the PDF.
var blob = Utilities.newBlob(html_body, 'text/html').getAs('application/pdf').setName(pdf_name);
var newDoc = DriveApp.createFile(blob);
var pdf_url = newDoc.getUrl();
Surprisingly for the same content, it sometimes works and randomly returns the error:
Conversion from text/html to application/pdf failed.
I see this happening most for larger files, so I am probably hitting some quota limitations.
But as per https://developers.google.com/apps-script/guides/services/quotas#current_limitations hitting any limitations should raise a relevant message.
Also documentation around https://developers.google.com/apps-script/reference/base/blob#getAs(String) does not state anything.
Any ideas?
Thank you!
I had the same problem, and did the following:
var html = HtmlService.createHtmlOutput(html_body);//This is now an object
html = html.getContent();//Get data as string - So its not an object or file
var blob = Utilities.newBlob(html,'application/pdf');//Create pdf from string
blob.setName(pdf_name);
In my case, the getAs('application/pdf') method was failing to convert a blob from a text file to a pdf file.
I had the same problem (that everybody else started getting Aug 9 2021) commencing Friday Aug 13th (because I run weekly processes/triggers).
Here is the WORKING solution by muhdtam...#gmail.com that I got from the Google Apps Script Community:
You have to add the following authorization to your "headers" section that is pointed to in your "options" statement that is part of...
var blob = UrlFetchApp.fetch(fileUrl, options).getBlob();
"authorization": "Bearer " + ScriptApp.getOAuthToken()
After I did that and re-tested, the error "Exception: Conversion from text/html to application/pdf failed" went away.
Google must have changed something but never told anybody.
I`m facing more or less the same trouble "text/html to application/pdf failed" error message.
As far as I understood, the issue is coming from the migration of the new version
"This project is running on our new Apps Script runtime powered by Chrome V8.", on existing script which was converting snapshot of only one tab from google sheet to PDF.
https://pastebin.pl/view/8ebb6742
Related
I want to create a Google Sheet in a specific folder on Google Drive using Google Apps Script. According to the documentation of the File class:
createFile(name, content, mimeType)
Creates a file in the current folder with the given name, contents, and MIME type. Throws an exception if content is larger than 10MB.
// Create an HTML file with the content "Hello, world!"
DriveApp.getRootFolder().createFile('New HTML File', '<b>Hello, world!</b>', MimeType.HTML);
And according to the MimeType documentation:
Enum MimeType
An enumeration that provides access to MIME-type declarations without typing the strings explicitly. Methods that expect a MIME type rendered as a string (for example, 'image/png') also accept any of the values below, so long as the method supports the underlying MIME type.
There is no mention of createFile supporting only a subset of available MIME types. The page includes a table, which includes this MIME type:
GOOGLE_SHEETS Enum Representation of MIME type for a Google Sheets file.
My issue lies in implementing this method of creating a file as described in the File documentation.
var folder = DriveApp.createFolder('new folder');
var ss = folder.createFile('new sheet', '', MimeType.GOOGLE_SHEETS);
This will throw an error, stating
Invalid argument: file.contentType (line 2, file "Code")
Replacing MimeType.GOOGLE_SHEETS with the string application/vnd.google-apps.spreadsheet obviously did not help. I am aware of this question, but the accepted answer simply admits defeat and uses a common messy workaround by creating the file in SpreadsheetApp, copying it, and deleting the original. This question has a similarly disappointing accepted answer to the same problem, except for Google Docs. The SpreadsheetApp workaround is fine, but I'm hoping 3 years on that someone holds the answer as to how to use createFile properly.
The Google issue tracker has a long, long history of this question being asked. Way back in 2014, a Google staff member declared that it was a resolved issue, and they had decided that MimeType.GOOGLE_-type files could not be created by the createFile method.
Marked as fixed.
After extensive consideration, we have determined that DriveApp.createFile() should not be used to create MimeType.GOOGLE_* files.
Shortly, attempting to do so will fail and result in a more descriptive error message.
Unfortunately, despite promising otherwise, the error message was never changed and the documentation was never updated to reflect this "extensive consideration".
The correct solution to add a MimeType.GOOGLE_-type file to a specific folder with 1 server call (no copying, removing, or updating) is
var folder = DriveApp.createFolder('folder');
var file = {
title: 'New Sheet',
mimeType: MimeType.GOOGLE_SHEETS,
parents: [{id: folder.getId()}]
}
ssId = Drive.Files.insert(file).id;
Drive.Files.insert does require the Advanced Drive Service, which you can enable on your script with this guide.
Try this:
function createFolderAndFile() {
var folder = DriveApp.createFolder('RootSub');
var file = SpreadsheetApp.create('RootSubSheet');
Drive.Files.update({"parents": [{"id": folder.getId()}]}, file.getId());
}
In general I want to print the URL of the google document I am actually working with in a text field.
If I copy the google sheet the function should also work for the new document.
I scripted a solution which was working for 20 month and now I have a problem.
Now I would like to know what could happen? Why do I have a server problem? Is is it possible to have to many google documents, (i have ~9000 - it works as a small ERP system) that the server got problems?
Formula in Google sheet:
=hyperlink(getSheetUrl()
Code in Script editor:
function getSheetUrl() {
var SS = SpreadsheetApp.getActiveSpreadsheet();
var ss = SS.getActiveSheet();
var url = '';
url += SS.getUrl();
url += '#gid=';
url += ss.getSheetId();
return url;
}
This is the error message in my document:
Error: Server error occurred. Please try saving the project again. (Row 0).
If I try to save the project in my script editor I get no failure.
If I try to run the project in my script editor I get:
A server error has occurred. Please try to save the project again.
Thanks for your answers.
Today I started the system and everything works fine.
Yesterday i was also able to run my code in a new enviroment, but i was not able to copy a existing document. there i got the failure.
Maybe it was really because the lan connection was to weak.
My company is a very rural area ;)
I will take an eye on that,
By the way.
Does anyone has another idea how to get the link from a document and print it in a textfield in the same document (hopefully you know what i mean)
I've had a Google Sheets script running for some time (a year) that needs to read an HTML file from it's Google Drive directory. The code to open the file looks like this:
var myHtmlFile = UrlFetchApp.fetch("https://googledrive.com/host/0B1m........JtZzQ/myfile.htm");
... and I could use the HTM file for further parsing.
Suddenly, the code above is throwing an error 404.
Has anything changed recently, stopping me from opening the file?
After a discussion with 'azawaza' (thanks for all the tips), I have finally solved this, so I'm posting the resolution in case others fall into this.
It looks like the construct
https://googledrive.com/host/{public_folder_id}/myfile.htm
in UrlFetchApp.fetch(url, true) can no longer be used. It gives error 404.
I was getting it from the following construct (for simplicity, assuming there is only one parent folder of my spreadsheet):
...
var myId = DocsList.getFileById(SpreadsheetApp.getActive().getId());
var folderId = myId.getParents()[0].getId();
var url = "https://googledrive.com/host/" + folderId + "/myfile.htm";
// url looks like: https://googledrive.com/host/0B1m....JtZzQ/myfile.htm"
var httpResp = UrlFetchApp.fetch(url,true); //throws 404 !!!
// now, parse 'httpResp'
The solution that worked for me, is to find the file directly using this construct (again, assuming there is only one file of given name) :
var htmlCont = DocsList.find("myfile.htm")[0].getContentAsString();
// now, parse htmlCont
I don't know why the 'old' solution no longer works. As I mentioned it worked for a year.
UPDATE (May 2015)
The 'DocsList' has been deprecated, a new construct:
var files = DriveApp.getFilesByName(myURL);
if (files.hasNext()) {
var htmlCont = files.next().getBlob().getDataAsString()
}
has to be used instead
I find it strange that it ever worked before! If it did, it was probably a bug - pretty sure it was never intended to work like that with "local" files... I have never seen it mentioned anywhere that UrlFetchApp.fetch() can fetch "local" files like that.
A simple fix would be to just use proper full url of the file:
var myHtmlFile = UrlFetchApp.fetch("https://googledrive.com/host/{public_folder_id}/myfile.htm");
That will ensure your code complies with the API and does not break next time Google changes something.
I get an "Unexpected Error" from the following function:
function getBomgarFeedbackXML(){
var url = "https://help.tradingtechnologies.com/api/reporting.ns?" +
"username=xxxxxx&password=xxxxxx&generate_report=SupportCustExitSurvey&" +
"start_date=2000-01-01&duration=0&report_type=rep&id=all";
var response = UrlFetchApp.fetch(url).getContentText();
Logger.log(response);
return(Xml.parse(response, true));
}
The line that causes the error is:
var response = UrlFetchApp.fetch(url).getContentText();
I am able to fetch the URL programatically using other scripting languages, such as python
I have tried fetching the URL in my browser which I was able to do successfully
I can fetch "http://www.google.com" from Google apps script successfully
I get the following warning when navigating to the URL in chrome, could this be related to the issue ?
Any help is appreciated
Thanks
The last bit with the untrusted certs is the big clue here. Seems like the SSL cert associated with 'help.tradingtechnologies.com'is not valid or signed by a trusted CA per the Google Data Centers (from where the UrlFetch calls originate).
To work around this try this line of code instead of your UrlFetch call. Note the additional option for validateHttpsCertificates documented here.
var response = UrlFetchApp.fetch(url, {'validateHttpsCertificates':false}).getContentText();
I have a simple script that pulls about 30,000 characters of JSON.
I get SyntaxError: Unexpected token: F (line 12) when I try to parse it with JSON.parse() or Utilities.jsonParse();
function refresh() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
sheet.clear();
var text = UrlFetchApp.fetch("http://blablah/json");
Logger.log(text.getContentText());
//error SyntaxError: Unexpected token: F (line 12)
json = JSON.parse(text);
)
The logger only shows about 59 lines of the JSON, but I was told that the logger has a space limit - but I'm not so sure that's it.
Running on my own server, JSON.parse parses the data just fine and so does jQuery get().
So I'm thinking UrlFetchApp.fetch() just can't get long files?
Hard to accept and I've found no documentation about it :(
You can check the UrlFetch and other services limitations on the new Apps Script dashboard. From my experience, Logger.log has a much more tighter limitation for a single log than UrlFetch, it's possible that UrlFetch is getting it fine, Logger.log is not showing it and you're running into other problem.
Try placing the getContentText result somewhere else, e.g. a spreadsheet cell. Or split it and call logger log in a for-loop.
A possible error that you might be facing (besides the quota limitation) is character encoding, getContentText has an optional parameter where you might inform the encoding of the page, have you checked that?