Download HEIC file in Google Photos as JPG - google-apps-script

I am using this code to upload the heic file and finding a way to convert heic as jpg or png via apps script (not right click save as)
I have my code
function uploadMediaItems() {
const albumId = "AKwCquOrmWbEihvwEqIM7Jy_H8wrkM_dof1eIGwXq8YZV-uuj9jWvkMT5oWkG6P0a-w_w9VyTOxM"; // Please set the album ID.
var arrId =
[
"1ssNYJFSEdfRI55IUi_tte3iC_JcPLG-0"
];
const items = arrId.map(id => {
const file = DriveApp.getFileById(id);
return {blob: file.getBlob(), filename: file.getName()};
});
const res = GPhotoApp.uploadMediaItems({albumId: albumId, items: items});
console.log(JSON.stringify(res))
}
Source: Google Apps Scripts: import (upload) media from Google Drive to Google Photos?

I believe your goal is as follows.
You want to upload the HEIC file to Google Photos and export it as a Jpeg or PNG file using the sample script at this thread.
From your script, the HEIC file is put on your Google Drive.
I thought that in your goal, you might have wanted to convert the HEIC file to Jpeg or PNG file. In this case, how about the following sample scripts?
Sample script 1:
In this sample script, the sample script at this thread is used. So, in this case, a Google Apps Script library of GPhotoApp is used. Ref The sample script is as follows.
In this script, it supposes that your Google Apps Script project has already been linked with Cloud Platform Project, and Photos API has already been enabled, and also, the required scopes have already been added. Please be careful this.
function myFunction() {
const arrId = ["###"]; // Please set the file ID of your HEIC file.
const albumId = "###"; // Please set your albumn ID.
const items = arrId.map(id => {
const file = DriveApp.getFileById(id);
return { blob: file.getBlob(), filename: file.getName() };
});
const res1 = GPhotoApp.uploadMediaItems({ albumId: albumId, items: items });
const mediaItemId = res1.newMediaItemResults[0].mediaItem.id;
const res2 = GPhotoApp.getMediaItems({ mediaItemIds: [mediaItemId] });
const mediaItem = res2.mediaItemResults[0].mediaItem;
const blob = UrlFetchApp.fetch(mediaItem.baseUrl).getBlob();
DriveApp.createFile(blob.setName(mediaItem.filename.replace(".heic", ".png")));
}
When this script is run, the PNG file is created to the root folder.
Sample script 2:
The HEIC file is put on your Google Drive. And, you want to convert the HEIC file to Jpeg or PNG. In this case, I thought that this can be achieved using the following simple script. In this case, Photos API is not required to be used.
When you use this script, please enable Drive API at Advanced Google services.
function myFunction2() {
const fileId = "###"; // Please set the file ID of your HEIC file.
const obj = Drive.Files.get(fileId);
const blob = UrlFetchApp.fetch(obj.thumbnailLink.replace(/=s.+/, "=s2000")).getBlob();
DriveApp.createFile(blob.setName(obj.title.replace(".heic", ".png")));
}
When this script is run, the PNG file is created to the root folder.
References:
Photos Library API
GPhotoApp
Files: get

Related

Google Apps Script to save Gmail attachments to Google Drive of only specific file types

I am trying to use Google Apps Script to automate downloading attachments from a Gmail inbox to a specific folder on the account's Google Drive using label. I found the code below that does that part well, but I need to modify it to save only specific file type. So please help me how to save only specific file type i.e .xlsx.
// copying-gmail-attachments-to-google-drive-using-apps-script
function saveAttachmentInFolder(){
var folder = DriveApp.getFolderById('1cqkjQWj2QkT7TyvllHI7YJFfWNcEupW0');// your Google Drive Folder ID to save the files
var userId = "acoounts.mfc66#gmail.com";// your email.I mean your own Gmail to
var query = "label:Thrive_from april 2022 till 20th jan 2023";// the label you created to fetch attachments from
var res = Gmail.Users.Messages.list(userId, {q: query});//The searching and using the results; never mind
res.messages.forEach(function(m){
var attA=GmailApp.getMessageById(m.id).getAttachments();
attA.forEach(function(a){
folder.createFile(a.copyBlob()).setName(a.getName()); // gets name of file
});
});
}
// end of script
Thanks in advance for your help.
In your situation, how about checking the mimeType of the data as follows?
From:
var attA=GmailApp.getMessageById(m.id).getAttachments();
To:
var attA = GmailApp.getMessageById(m.id).getAttachments().filter(a => a.getContentType() == MimeType.MICROSOFT_EXCEL);
or, if you want to check both mimeType and the extension of the filename, how about the following modification?
var attA = GmailApp.getMessageById(m.id).getAttachments().filter(a => a.getContentType() == MimeType.MICROSOFT_EXCEL || (/\.pdf$/i).test(a.getName());
When this modified script is used, the attachment files are filtered by the mimeType of XLSX format.
References:
filter()
Enum MimeType
getContentType()

Save gmail attachment as google sheets in gdrive [duplicate]

I know it is possible to convert excel files to Google Sheets using script and drive API, but I'm looking for script to convert the excel sheet and move the converted file to a different folder.
So the required steps are as follows:
Convert excel (.xls/.xlsx) to Google Sheet from FolderA.
Move converted file from FoldarA to FolderB.
Delete original excel file from FolderA
Hopefully step 3 avoids this, but avoid duplicating already converted file.
The excel files are being pasted into a local folder that is being synced to google drive, and the files are no larger than 3mb. The current script is as follows. This is converting the files but placing them in the root folder, and will duplicate the conversion when the script runs again.
function importXLS(){
var files = DriveApp.getFolderById('1hjvNIPgKhp2ZKIC7K2kxvJjfIeEYw4BP').searchFiles('title != "nothing"');
while(files.hasNext()){
var xFile = files.next();
var name = xFile.getName();
if (name.indexOf('.xlsx')>-1){
var ID = xFile.getId();
var xBlob = xFile.getBlob();
var newFile = { title : name+'_converted',
key : ID
}
file = Drive.Files.insert(newFile, xBlob, {
convert: true
});
}
}
}
You want to create the converted Google Spreadsheet files to "FolderB".
You want to delete the XLSX files in "FolderA" after the files were converted.
You want to achieve above using Google Apps Script.
If my understanding correct, how about this modification? In this modification, I modified your script.
Modification points:
You can directly create the file to the specific folder using the property of parents in the request body.
You can delete the file using Drive.Files.remove(fileId).
Modified script:
Before you use this script, please enable Drive API at Advanced Google services.
function importXLS(){
var folderBId = "###"; // Added // Please set the folder ID of "FolderB".
var files = DriveApp.getFolderById('1hjvNIPgKhp2ZKIC7K2kxvJjfIeEYw4BP').searchFiles('title != "nothing"');
while(files.hasNext()){
var xFile = files.next();
var name = xFile.getName();
if (name.indexOf('.xlsx')>-1){
var ID = xFile.getId();
var xBlob = xFile.getBlob();
var newFile = {
title : name+'_converted',
parents: [{id: folderBId}] // Added
};
file = Drive.Files.insert(newFile, xBlob, {
convert: true
});
// Drive.Files.remove(ID); // Added // If this line is run, the original XLSX file is removed. So please be careful this.
}
}
}
Note:
If the number of XLSX files is large, the execution time might be over 6 minutes.
About // Drive.Files.remove(ID);, when you run this script, please be careful. Because the original XLSX files are completely deleted when the script is run. So I commented this. At first, please test the script using sample files.
References:
Files: insert
Files: delete

How to convert PDF to image using Google Apps Script? [duplicate]

is there a way to create an image (e.g. a png) from a google document?
I really mean an image, not just a pdf. GetAS only creates pdf, but returns an error if contentType is set to image/png or other equivalent formats.
My (actually trivial) code is
function convertFile() {
var SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
var TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";
var source = DriveApp.getFileById(SOURCE_TEMPLATE);
var targetFolder = DriveApp.getFolderById(TARGET_FOLDER);
var target = source.makeCopy(source,targetFolder);
var newFile = DriveApp.createFile(target.getAs('image/png'));
}
When I run this code, I get the following error (my translation):
The conversion from application/vnd.google-apps.document to image/png is not supported.
Ty
How about this answer?
Reason of error:
makeCopy() returns File object. getAs() cannot be used for this. By this, the error occurs.
Workaround:
Unfortunately, in the current stage, Google Document cannot be directly exported as PNG images. So it is required to think of workarounds. Google Document can be converted to PDF. This answer uses this. As a workaround, I would like to propose to use an external API which is ConvertAPI. I thought that using the external API, the script becomes simple. This a method (PDF to PNG API) of API can be converted from PDF data to PNG data.
When you try this, for example, you can also test this using "Free Package". When you try using "Free Package", please Sign Up at "Free Package" and retrieve your Secret key.
Sample script:
Before you run this script, please retrieve your Secret key and set it.
var secretkey = "###"; // Please set your secret key.
var SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
var TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";
var url = "https://v2.convertapi.com/convert/pdf/to/png?Secret=" + secretkey;
var options = {
method: "post",
payload: {File: DriveApp.getFileById(SOURCE_TEMPLATE).getBlob()},
}
var res = UrlFetchApp.fetch(url, options);
res = JSON.parse(res.getContentText());
res.Files.forEach(function(e) {
var blob = Utilities.newBlob(Utilities.base64Decode(e.FileData), "image/png", e.FileName);
DriveApp.getFolderById(TARGET_FOLDER).createFile(blob);
});
References:
makeCopy()
getAs()
ConvertAPI
PDF to PNG API of ConvertAPI
Updated on January 11, 2023:
In the current stage, Google Apps Script can use V8 runtime. By this, there are some Javascript libraries that can be used with Google Apps Script. Ref1, Ref2 In this question, in the current stage, by using pdf-lib, all pages in a PDF file can be converted to PNG images using Google Apps Script. The sample script is as follows.
Sample script:
This method uses Drive API. Please enable Drive API at Advanced Google services.
Please set SOURCE_TEMPLATE and TARGET_FOLDER, and run main().
/**
* This is a method for converting all pages in a PDF file to PNG images.
* PNG images are returned as BlobSource[].
* IMPORTANT: This method uses Drive API. Please enable Drive API at Advanced Google services.
*
* #param {Blob} blob Blob of PDF file.
* #return {BlobSource[]} PNG blobs.
*/
async function convertPDFToPNG_(blob) {
// Convert PDF to PNG images.
const cdnjs = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js";
eval(UrlFetchApp.fetch(cdnjs).getContentText()); // Load pdf-lib
const setTimeout = function (f, t) { // Overwrite setTimeout with Google Apps Script.
Utilities.sleep(t);
return f();
}
const data = new Uint8Array(blob.getBytes());
const pdfData = await PDFLib.PDFDocument.load(data);
const pageLength = pdfData.getPageCount();
console.log(`Total pages: ${pageLength}`);
const obj = { imageBlobs: [], fileIds: [] };
for (let i = 0; i < pageLength; i++) {
console.log(`Processing page: ${i + 1}`);
const pdfDoc = await PDFLib.PDFDocument.create();
const [page] = await pdfDoc.copyPages(pdfData, [i]);
pdfDoc.addPage(page);
const bytes = await pdfDoc.save();
const blob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `sample${i + 1}.pdf`);
const id = DriveApp.createFile(blob).getId();
Utilities.sleep(3000); // This is used for preparing the thumbnail of the created file.
const link = Drive.Files.get(id, { fields: "thumbnailLink" }).thumbnailLink;
if (!link) {
throw new Error("In this case, please increase the value of 3000 in Utilities.sleep(3000), and test it again.");
}
const imageBlob = UrlFetchApp.fetch(link.replace(/\=s\d*/, "=s1000")).getBlob().setName(`page${i + 1}.png`);
obj.imageBlobs.push(imageBlob);
obj.fileIds.push(id);
}
obj.fileIds.forEach(id => DriveApp.getFileById(id).setTrashed(true));
return obj.imageBlobs;
}
// Please run this function.
async function myFunction() {
const SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
const TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";
// Use a method for converting all pages in a PDF file to PNG images.
const blob = DriveApp.getFileById(SOURCE_TEMPLATE).getBlob();
const imageBlobs = await convertPDFToPNG_(blob);
// As a sample, create PNG images as PNG files.
const folder = DriveApp.getFolderById(TARGET_FOLDER);
imageBlobs.forEach(b => folder.createFile(b));
}
When this script is run, all pages of the inputted PDF file are converted to PNG images, and those images are created in the destination folder.
Note:
I think that the above script works. But, in this case, when you directly copy and paste the Javascript retrieved from https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js to your Google Apps Script project, the process cost for loading it can be reduced.
References:
pdf-lib
copyPages of pdf-lib
addPage of pdf-lib
I know this is an older question, but I thought I'd answer, since I believe I've found a solution that doesn't involve paying for a third-party subscription.
This can be accomplished by accessing the thumbnail of the Doc and creating a new PNG file from that thumbnail. Try this:
function convertFile() {
var SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
var TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";
var source = DriveApp.getFileById(SOURCE_TEMPLATE).getThumbnail().getAs('image/png');
var targetFolder = DriveApp.getFolderById(TARGET_FOLDER);
TARGET_FOLDER.createFile(source);
}
However, I've found that getting the thumbnail of the Doc is not as high quality as getting the thumbnail of a PDF created from the Doc. You can try the code below to compare which version of the new PNG you prefer.
To do this, you will also need to enable Advanced Services on your project, specifically the Drive API service. To do this, follow these instructions to add a new Service to your Google Apps Script project:
Open the Apps Script project.
At the left, click Editor < >.
At the left, next to Services, click Add a service +.
Select Drive API and click Add.
Once you do that, you'll be able to use the Drive command in your script, which is different than DriveApp. Note also the update to source.makeCopy() to only include the TARGET_FOLDER:
function convertFile() {
var SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
var TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";
var source = DriveApp.getFileById(SOURCE_TEMPLATE);
var targetFolder = DriveApp.getFolderById(TARGET_FOLDER);
var target = source.makeCopy(targetFolder);
var pdfBlob = target.getAs(MimeType.PDF);
var newPDF = TARGET_FOLDER.createFile(pdfBlob).setName('Some Name.pdf');
var newId = newPDF.getId();
Drive.Files.update({
title: newPDF.getName(), mimeType: MimeType.PDF
}, newId, pdfBlob);
var newFile = DriveApp.getFileById(newId).getThumbnail().getAs('image/png');
TARGET_FOLDER.createFile(newFile);
target.setTrashed(true);
newPDF.setTrashed(true);
}
This code will create a copy of your Google Doc file, convert it to a PDF, then grab the thumbnail of the PDF as a PNG, and then delete the copy of the Doc file and the PDF that were created.
The Drive.Files.update() function is the critical part of this code, as it finalizes the creation of the PDF file in your Drive. Trying to run the code without that portion will just return the new PDF file as null since the new PDF hasn't completely finished being created at that point.
Hope this helps!

Google script API - How to create a google doc in a particular folder

Basically this question is giving an answer for what I'd like to do:
Google script to create a folder and then create a Google Doc in that folder
But it's 5 years old, and I was wondering if there was an easier way now. In my case I have lots of existing folders and I want to create a particular file in each of them via a script that runs at intervals.
Thx.
EDIT:
Ok, the code below works fine (using a modified sample script 1 in the answer) when the folder 'test folder' is in a shared drive.
function testFunction() {
const notesFileName = 'test doc';
const folderName = 'test folder';
const query = "title = '" + folderName + "'";
// Find all folders that match the query.
var folders = DriveApp.searchFolders(query);
while (folders.hasNext()) {
// In all the sub-folders, of each found folder, create a file with the same name.
var folder = folders.next();
Logger.log("Found a folder: " + folder);
var subFolders = folder.getFolders();
while( subFolders.hasNext() ) {
var subFolder = subFolders.next();
Logger.log('Folder id: ' + subFolder.getId());
const doc = Drive.Files.insert({title: notesFileName, mimeType: MimeType.GOOGLE_DOCS, parents: [{id: subFolder.getId()}]}, null, {supportsAllDrives: true});
}
}
}
I believe your goal as follows.
You want to create new Google Document to the specific folders.
You have a lot of folders you want to create new Google Document. So you want to reduce the process cost of the script.
In this case, I would like to propose to create the new Google Document using Drive API. When Drive API is used, the creation of Google Document to each folder can run with the asynchronous process. The sample script is as follows.
Sample script 1:
Before you use this script, please enable Drive API at Advanced Google services. In this sample script, the new Google Documents are created to the specific folders in a loop.
function sample1() {
const titleOfDocument = "sample document";
const folderIds = ["### folder ID1 ###", "### folder ID 2 ###",,,];
const documentIds = folderIds.map(id => Drive.Files.insert({title: titleOfDocument, mimeType: MimeType.GOOGLE_DOCS, parents: [{id: id}]}).id);
console.log(documentIds)
}
In this script, the created Document IDs are returned.
If the process time of this script was long in your actual situation, please test the following sample script 2.
Sample script 2:
Before you use this script, please enable Drive API at Advanced Google services. In this sample script, the new Google Documents are created to the specific folders using the batch request of Drive API using a Google Apps Script library. By this, the tasks are run with the asynchronous process.
Please install the Google Apps Script library for using the batch request. Ref
function sample2() {
const titleOfDocument = "sample document";
const folderIds = ["### folder ID1 ###", "### folder ID 2 ###",,,];
const requests = {
batchPath: "batch/drive/v3",
requests: folderIds.map(id => ({
method: "POST",
endpoint: `https://www.googleapis.com/drive/v3/files`,
requestBody: {name: titleOfDocument, mimeType: MimeType.GOOGLE_DOCS, parents: [id]},
})),
accessToken: ScriptApp.getOAuthToken(),
};
const result = BatchRequest.EDo(requests); // Using GAS library
const documentIds = result.map(({id}) => id);
console.log(documentIds)
}
Note:
For above sample scripts, if you want to retrieve the folder IDs under the specific folder, you can also use for folderIds as follows.
const topFolderId = "### top folder ID ###";
const folders = DriveApp.getFolderById(topFolderId).getFolders();
const folderIds = [];
while (folders.hasNext()) {
folderIds.push(folders.next().getId());
}
By the way, in the current stage, in order to move the file, you can use moveTo(destination). Using this, the script of this can be modified as follows.
function createDoc(folderID, name) {
var folder = DriveApp.getFolderById(folderID);
var doc = DocumentApp.create(name);
DriveApp.getFileById(doc.getId()).moveTo(folder);
return doc;
}
References:
Files: insert of Drive API v2
Files: create of Drive API v3
BatchRequest

Convert a gdoc into image

is there a way to create an image (e.g. a png) from a google document?
I really mean an image, not just a pdf. GetAS only creates pdf, but returns an error if contentType is set to image/png or other equivalent formats.
My (actually trivial) code is
function convertFile() {
var SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
var TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";
var source = DriveApp.getFileById(SOURCE_TEMPLATE);
var targetFolder = DriveApp.getFolderById(TARGET_FOLDER);
var target = source.makeCopy(source,targetFolder);
var newFile = DriveApp.createFile(target.getAs('image/png'));
}
When I run this code, I get the following error (my translation):
The conversion from application/vnd.google-apps.document to image/png is not supported.
Ty
How about this answer?
Reason of error:
makeCopy() returns File object. getAs() cannot be used for this. By this, the error occurs.
Workaround:
Unfortunately, in the current stage, Google Document cannot be directly exported as PNG images. So it is required to think of workarounds. Google Document can be converted to PDF. This answer uses this. As a workaround, I would like to propose to use an external API which is ConvertAPI. I thought that using the external API, the script becomes simple. This a method (PDF to PNG API) of API can be converted from PDF data to PNG data.
When you try this, for example, you can also test this using "Free Package". When you try using "Free Package", please Sign Up at "Free Package" and retrieve your Secret key.
Sample script:
Before you run this script, please retrieve your Secret key and set it.
var secretkey = "###"; // Please set your secret key.
var SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
var TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";
var url = "https://v2.convertapi.com/convert/pdf/to/png?Secret=" + secretkey;
var options = {
method: "post",
payload: {File: DriveApp.getFileById(SOURCE_TEMPLATE).getBlob()},
}
var res = UrlFetchApp.fetch(url, options);
res = JSON.parse(res.getContentText());
res.Files.forEach(function(e) {
var blob = Utilities.newBlob(Utilities.base64Decode(e.FileData), "image/png", e.FileName);
DriveApp.getFolderById(TARGET_FOLDER).createFile(blob);
});
References:
makeCopy()
getAs()
ConvertAPI
PDF to PNG API of ConvertAPI
Updated on January 11, 2023:
In the current stage, Google Apps Script can use V8 runtime. By this, there are some Javascript libraries that can be used with Google Apps Script. Ref1, Ref2 In this question, in the current stage, by using pdf-lib, all pages in a PDF file can be converted to PNG images using Google Apps Script. The sample script is as follows.
Sample script:
This method uses Drive API. Please enable Drive API at Advanced Google services.
Please set SOURCE_TEMPLATE and TARGET_FOLDER, and run main().
/**
* This is a method for converting all pages in a PDF file to PNG images.
* PNG images are returned as BlobSource[].
* IMPORTANT: This method uses Drive API. Please enable Drive API at Advanced Google services.
*
* #param {Blob} blob Blob of PDF file.
* #return {BlobSource[]} PNG blobs.
*/
async function convertPDFToPNG_(blob) {
// Convert PDF to PNG images.
const cdnjs = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js";
eval(UrlFetchApp.fetch(cdnjs).getContentText()); // Load pdf-lib
const setTimeout = function (f, t) { // Overwrite setTimeout with Google Apps Script.
Utilities.sleep(t);
return f();
}
const data = new Uint8Array(blob.getBytes());
const pdfData = await PDFLib.PDFDocument.load(data);
const pageLength = pdfData.getPageCount();
console.log(`Total pages: ${pageLength}`);
const obj = { imageBlobs: [], fileIds: [] };
for (let i = 0; i < pageLength; i++) {
console.log(`Processing page: ${i + 1}`);
const pdfDoc = await PDFLib.PDFDocument.create();
const [page] = await pdfDoc.copyPages(pdfData, [i]);
pdfDoc.addPage(page);
const bytes = await pdfDoc.save();
const blob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `sample${i + 1}.pdf`);
const id = DriveApp.createFile(blob).getId();
Utilities.sleep(3000); // This is used for preparing the thumbnail of the created file.
const link = Drive.Files.get(id, { fields: "thumbnailLink" }).thumbnailLink;
if (!link) {
throw new Error("In this case, please increase the value of 3000 in Utilities.sleep(3000), and test it again.");
}
const imageBlob = UrlFetchApp.fetch(link.replace(/\=s\d*/, "=s1000")).getBlob().setName(`page${i + 1}.png`);
obj.imageBlobs.push(imageBlob);
obj.fileIds.push(id);
}
obj.fileIds.forEach(id => DriveApp.getFileById(id).setTrashed(true));
return obj.imageBlobs;
}
// Please run this function.
async function myFunction() {
const SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
const TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";
// Use a method for converting all pages in a PDF file to PNG images.
const blob = DriveApp.getFileById(SOURCE_TEMPLATE).getBlob();
const imageBlobs = await convertPDFToPNG_(blob);
// As a sample, create PNG images as PNG files.
const folder = DriveApp.getFolderById(TARGET_FOLDER);
imageBlobs.forEach(b => folder.createFile(b));
}
When this script is run, all pages of the inputted PDF file are converted to PNG images, and those images are created in the destination folder.
Note:
I think that the above script works. But, in this case, when you directly copy and paste the Javascript retrieved from https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js to your Google Apps Script project, the process cost for loading it can be reduced.
References:
pdf-lib
copyPages of pdf-lib
addPage of pdf-lib
I know this is an older question, but I thought I'd answer, since I believe I've found a solution that doesn't involve paying for a third-party subscription.
This can be accomplished by accessing the thumbnail of the Doc and creating a new PNG file from that thumbnail. Try this:
function convertFile() {
var SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
var TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";
var source = DriveApp.getFileById(SOURCE_TEMPLATE).getThumbnail().getAs('image/png');
var targetFolder = DriveApp.getFolderById(TARGET_FOLDER);
TARGET_FOLDER.createFile(source);
}
However, I've found that getting the thumbnail of the Doc is not as high quality as getting the thumbnail of a PDF created from the Doc. You can try the code below to compare which version of the new PNG you prefer.
To do this, you will also need to enable Advanced Services on your project, specifically the Drive API service. To do this, follow these instructions to add a new Service to your Google Apps Script project:
Open the Apps Script project.
At the left, click Editor < >.
At the left, next to Services, click Add a service +.
Select Drive API and click Add.
Once you do that, you'll be able to use the Drive command in your script, which is different than DriveApp. Note also the update to source.makeCopy() to only include the TARGET_FOLDER:
function convertFile() {
var SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
var TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";
var source = DriveApp.getFileById(SOURCE_TEMPLATE);
var targetFolder = DriveApp.getFolderById(TARGET_FOLDER);
var target = source.makeCopy(targetFolder);
var pdfBlob = target.getAs(MimeType.PDF);
var newPDF = TARGET_FOLDER.createFile(pdfBlob).setName('Some Name.pdf');
var newId = newPDF.getId();
Drive.Files.update({
title: newPDF.getName(), mimeType: MimeType.PDF
}, newId, pdfBlob);
var newFile = DriveApp.getFileById(newId).getThumbnail().getAs('image/png');
TARGET_FOLDER.createFile(newFile);
target.setTrashed(true);
newPDF.setTrashed(true);
}
This code will create a copy of your Google Doc file, convert it to a PDF, then grab the thumbnail of the PDF as a PNG, and then delete the copy of the Doc file and the PDF that were created.
The Drive.Files.update() function is the critical part of this code, as it finalizes the creation of the PDF file in your Drive. Trying to run the code without that portion will just return the new PDF file as null since the new PDF hasn't completely finished being created at that point.
Hope this helps!