I'm a Google Apps Script Developer and a beginner with API integrations. I'm attempting to convert a PDF file stored in Google Drive to PNG format and save it back to the same folder. For this purpose, I'm using CloudConvert API. Unfortunately, my code is not functioning correctly. I would greatly appreciate it if someone could review my code and provide me with the correct solution.
function convertPDFtoPNG(fileName) {
var apiKey = "xyz";
var file = folder.getFilesByName(fileName + ".pdf").next();
var folderId = folder.getId();
var fileUrl = file.getDownloadUrl();
var requestBody = {
"tasks": {
"import-pdf-file": {
"operation": "import/url",
"url": fileUrl,
"filename": file.getName()
},
"convert-pdf-file": {
"operation": "convert",
"input": "import-pdf-file",
"input_format": "pdf",
"output_format": "png"
},
"export-png-file": {
"operation": "export/url",
"input": "convert-pdf-file",
"folder_id": folderId
}
},
"tag": "convert-pdf-to-png"
};
var options = {
method: 'post',
headers: {
'Authorization': 'Bearer ' + apiKey,
'Content-Type': 'application/json'
},
payload: JSON.stringify(requestBody)
};
var response = UrlFetchApp.fetch('https://api.cloudconvert.com/v2/jobs', options);
var job = JSON.parse(response.getContentText());
var downloadUrl = job.url;
var pngBlob = UrlFetchApp.fetch(downloadUrl).getBlob();
var newFile = folder.createFile(pngBlob).setName(fileName + ".png");
}
Check if the file is shared correctly with "Anyone with the link can view" option. If it's not, the server won't be able to download it.
If the file is a single-page PDF, this workaround could help without requiring an external API: the same code can be applied to any image format including HEIC and TIFF files. However, this is just a workaround that works for my use case and may not fit yours.
Please also check out this question. The accepted answer includes similar code to mine, but with support for PDFs with multiple pages... Convert a gdoc into image