I have a document that i use as a template, url: https://docs.google.com/document/d/1Ng00Sw0V-3_htLF2-SyPj895g_V9bi1mKQc1LOaHPNY/edit?usp=sharing
I'm using a script when a form is submited and export it to pdf
function testExport() {
var pdf = DocumentApp.openById(docTemplate).getAs("application/pdf");
DriveApp.createFile(pdf);
};
But the exported link looks like https://drive.google.com/file/d/0B_YrT5Ue-LAvUllyQ0ZpbkRodVU/view?usp=sharing
Size of rows between the table seems to increased and the overall quality looks bad, is there a way to fix it? When I download the doc file as pdf the then it looks really good.
Document.getAs() uses a slightly different converter then the Google Docs UI does. You can get closer by using the conversion functionality built into the Drive API, exposed in File.exportLinks. The sample below uses the Drive Advanced Service to do the conversion and save the result.
function exportAsPdf(documentId) {
var file = Drive.Files.get(documentId);
var url = file.exportLinks['application/pdf'];
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = response.getBlob();
contents.setName(file.title + '.pdf');
DriveApp.createFile(contents);
}
Related
Good Morning All. I have written a short script which batch-creates [single page] Google Slides based on rows from a spreadsheet. While in the loop for each creation, I would like to create a PNG of the Slide in Google Drive (or download on the user's desktop). These pictures should be the same specs as if a user clicked File>Download>PNG - the heavy small text requires full projector HD - so I don't believe I can use the "Thumbnail" function which appears limited to 1600 pixels.
My code below generates the error "Converting from text/html to image/png is not supported" - so I'm not sure if this is a limitation of the API or a problem with my coding. Thank you in advance.
var options =
{
"contentType" : "image/PNG"
};
var url = 'https://docs.google.com/presentation/d/' + presentationCopyId + '/export/PNG';
var response = UrlFetchApp.fetch(url, options);
var image = response.getAs(MimeType.PNG);
image.setName(SlideName);
DriveApp.createFile(image);
Yes, It is possible.
You can use Google slide API and make a PNG file of every page of Google slide.
Here is the code,
BUT first you have to enable API as following
open script editor
click on resources-> Advanced Google Services
Enable Google slide API and Drive API .
click on ok
now copy and paste this code,
and write your slide ID in presentationID.
function generateScreenshots() {
var presentationId = "***ADD YOUR Google Slide ID Only***";
var presentation = SlidesApp.openById(presentationId);
var baseUrl =
"https://slides.googleapis.com/v1/presentations/{presentationId}/pages/{pageObjectId}/thumbnail";
var parameters = {
method: "GET",
headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
contentType: "application/json",
muteHttpExceptions: true
};
// Log URL of the main thumbnail of the deck
Logger.log(Drive.Files.get(presentationId).thumbnailLink);
// For storing the screenshot image URLs
var screenshots = [];
var slides = presentation.getSlides().forEach(function(slide, index) {
var url = baseUrl
.replace("{presentationId}", presentationId)
.replace("{pageObjectId}", slide.getObjectId());
var response = JSON.parse(UrlFetchApp.fetch(url, parameters));
// Upload Googel Slide image to Google Drive
var blob = UrlFetchApp.fetch(response.contentUrl).getBlob();
DriveApp.createFile(blob).setName("Image " + (index + 1) + ".png");
screenshots.push(response.contentUrl);
});
return screenshots;
}
This answer is outdated, leaving up for documentation purposes but please see other answer.
Answer:
Unfortunately it is not possible to export a Slides as a PNG file using the the Slides nor Drive APIs.
More Information:
According to the documentation, there are only four available MimeTypes for exporting Presentations files:
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/vnd.oasis.opendocument.presentation
application/pdf
text/plain
Attempting to export to the image/png MIME Type results in the following error:
Converting from text/html to image/png is not supported
For testing purposes, I tried using the /export/pdf endpoint and making a second conversion to PNG from there like so:
function slidesAsPngAttempt() {
var presentationCopyId = "1Loa...pQs";
var options =
{
"contentType" : "application/pdf"
};
// for exporting to pdf the /export/pdf needs to be all lower case to avoid 404
var url = 'https://docs.google.com/presentation/d/' + presentationCopyId + '/export/pdf';
var response = UrlFetchApp.fetch(url, options);
var pdfAsblob = response.getBlob();
var image = pdfAsblob.getAs('image/png');
image.setName(DriveApp.getFileById(presentationCopyId).getName());
DriveApp.createFile(image);
}
Unfortunately, a similar error occurs when running var image = pdfAsblob.getAs('image/png'):
Converting from application/pdf to image/png is not supported.
From the same export MIME types reference documentation, the only export types available for PDF files are:
text/csv
text/tab-separated-values
application/zip
References:
G Suite documents and corresponding export MIME types
Google Apps Script - method Blob.getAs(contentType)
I have a Google sheet that is exported as PDF and emailed using App Script but there are a few cases where the PDF shows #NAME? in cells where I used a custom function. But in most cases it is fully displayed.
Is there a way around this? It looks like before the sheet has fully refreshed, it is already exported into PDF.
If I manually open the spreadsheet, it shows the figures but sometimes it refreshes and takes about 2 to 3 seconds to redisplay the values.
Here is how it looks like:
My code to email as PDF is here:
//Now, get the file and email as PDF attachment
var file = DriveApp.getFileById(GsheetFileID);
GmailApp.sendEmail(approverEmail, emailIdentifier + " OT Claim for your approval", "", {
cc: ccOthers,
htmlBody: html4Approver,
//attachments : [blob]
attachments : [file.getAs(MimeType.PDF)]
});
I have also tried exporting it this way but the result is still the same.
var url = "https://www.googleapis.com/drive/v3/files/" + fileID + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var pdfFile = UrlFetchApp.fetch(url, options).getBlob();
Thanks in advance for any ideas.
This is a common issue that arise then there's a lot of data and latency problems arise. You can workaround it using getDisplayValues() to create another sheet which will contain pure data.
This is sample code, which will load data correctly but w/o formatting
function copyTab(sheet) {
var data = SpreadsheetApp.getActive().getSheetByName(sheet).getDataRange().getDisplayValues();
if(data.length > 0) {
var bufferSheet = SpreadsheetApp.getActive().getSheetByName('Buffer');
if(!bufferSheet)
bufferSheet = SpreadsheetApp.getActive().insertSheet('Buffer');
else
bufferSheet.clear({contentsOnly: true});
bufferSheet.getRange(1,1,data.length,data[0].length).setValues(data);
/* Here you can add your code to create PDF from Buffer sheet */
}
}
Good Morning All. I have written a short script which batch-creates [single page] Google Slides based on rows from a spreadsheet. While in the loop for each creation, I would like to create a PNG of the Slide in Google Drive (or download on the user's desktop). These pictures should be the same specs as if a user clicked File>Download>PNG - the heavy small text requires full projector HD - so I don't believe I can use the "Thumbnail" function which appears limited to 1600 pixels.
My code below generates the error "Converting from text/html to image/png is not supported" - so I'm not sure if this is a limitation of the API or a problem with my coding. Thank you in advance.
var options =
{
"contentType" : "image/PNG"
};
var url = 'https://docs.google.com/presentation/d/' + presentationCopyId + '/export/PNG';
var response = UrlFetchApp.fetch(url, options);
var image = response.getAs(MimeType.PNG);
image.setName(SlideName);
DriveApp.createFile(image);
Yes, It is possible.
You can use Google slide API and make a PNG file of every page of Google slide.
Here is the code,
BUT first you have to enable API as following
open script editor
click on resources-> Advanced Google Services
Enable Google slide API and Drive API .
click on ok
now copy and paste this code,
and write your slide ID in presentationID.
function generateScreenshots() {
var presentationId = "***ADD YOUR Google Slide ID Only***";
var presentation = SlidesApp.openById(presentationId);
var baseUrl =
"https://slides.googleapis.com/v1/presentations/{presentationId}/pages/{pageObjectId}/thumbnail";
var parameters = {
method: "GET",
headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
contentType: "application/json",
muteHttpExceptions: true
};
// Log URL of the main thumbnail of the deck
Logger.log(Drive.Files.get(presentationId).thumbnailLink);
// For storing the screenshot image URLs
var screenshots = [];
var slides = presentation.getSlides().forEach(function(slide, index) {
var url = baseUrl
.replace("{presentationId}", presentationId)
.replace("{pageObjectId}", slide.getObjectId());
var response = JSON.parse(UrlFetchApp.fetch(url, parameters));
// Upload Googel Slide image to Google Drive
var blob = UrlFetchApp.fetch(response.contentUrl).getBlob();
DriveApp.createFile(blob).setName("Image " + (index + 1) + ".png");
screenshots.push(response.contentUrl);
});
return screenshots;
}
This answer is outdated, leaving up for documentation purposes but please see other answer.
Answer:
Unfortunately it is not possible to export a Slides as a PNG file using the the Slides nor Drive APIs.
More Information:
According to the documentation, there are only four available MimeTypes for exporting Presentations files:
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/vnd.oasis.opendocument.presentation
application/pdf
text/plain
Attempting to export to the image/png MIME Type results in the following error:
Converting from text/html to image/png is not supported
For testing purposes, I tried using the /export/pdf endpoint and making a second conversion to PNG from there like so:
function slidesAsPngAttempt() {
var presentationCopyId = "1Loa...pQs";
var options =
{
"contentType" : "application/pdf"
};
// for exporting to pdf the /export/pdf needs to be all lower case to avoid 404
var url = 'https://docs.google.com/presentation/d/' + presentationCopyId + '/export/pdf';
var response = UrlFetchApp.fetch(url, options);
var pdfAsblob = response.getBlob();
var image = pdfAsblob.getAs('image/png');
image.setName(DriveApp.getFileById(presentationCopyId).getName());
DriveApp.createFile(image);
}
Unfortunately, a similar error occurs when running var image = pdfAsblob.getAs('image/png'):
Converting from application/pdf to image/png is not supported.
From the same export MIME types reference documentation, the only export types available for PDF files are:
text/csv
text/tab-separated-values
application/zip
References:
G Suite documents and corresponding export MIME types
Google Apps Script - method Blob.getAs(contentType)
I know that it is possible to convert a Google Doc file to pdf using Google Apps Script.
Is there a similar syntax like the one below that works for epub?
docblob = DocumentApp.getActiveDocument().getAs('application/pdf');
This code will convert your document and save it in your Drive root folder.
function convert(fileId) {
var link = Drive.Files.get(fileId).exportLinks["application/epub+zip"];
var response = UrlFetchApp.fetch(exportLink, {
headers: {
Authorization: "Bearer " + ScriptApp.getOAuthToken()
}
});
DriveApp.createFile(response.getBlob()).setName("file.epub");
}
I create and send a periodic email as an update from a Google Sheet. For various client reasons this is done 3 ways, as a link to the Sheet, and as attachments (PDF and XLSX).
This was working 'til recently. The XSLX attachment still works, but the PDF is no longer sent as a response to a UrlFetch to the file.exportLinks('application/pdf') url. No matter what the request headers it always returns as Content-Type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Did something else undocumented change that I am missing here?
function exportAsPDF(spreadsheetId) {
spreadsheetId = spreadsheetId || 'SECRET_ID';
var file = Drive.Files.get(spreadsheetId),
url = file.exportLinks['application/pdf'];
url += '&format=pdf&size=7&fzr=true&portrait=true&fitw=true&gid=0&gridlines=false&printtitle=false&sheetnames=false&pagenum=UNDEFINED&attachment=true'
var token = ScriptApp.getOAuthToken(),
response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var headers = response.getAllHeaders(); // revealing content-type returned isn't pdf
var pdfBlob = response.getBlob().getAs('application/pdf');
var pdfString = pdfBlob.getDataAsString(); // this naturally throws an error
return response.getBlob(); // this returns to the send mail script
}
I'm able to get PDFs using the utility from Convert all sheets to PDF with Google Apps Script.
That working script modifies the spreadsheet's edit URL into an export URL, which looks like:
https://docs.google.com/spreadsheets/d/<%SS-ID%>/export?exportFormat=pdf...
The advanced Drive service gives an export URL formatted like:
https://docs.google.com/spreadsheets/export?id=<%SS-ID%>&exportFormat=pdf...
I'd expect the URL provided by exportLinks to be more reliable than the hack in the working script. Apparently, it's not.
This has been raised as Issue 5114. Star it to receive updates.