Trying to export to pdf using google app scripts - google-apps-script

I am currently trying to export a sheet as a pdf. This works fine using the getBlob() parameter, but I wish to export with a custom name of the file. When trying to use the following, the MimeType throws up an error message, and if removed the file is exported as plain text which I don't want. Any help would be great, either with exporting the file as a pdf or renaming it later
var sqc = ss.getSheetByName('SQC')
var folder = DriveApp.getFolderById('FOLDER ID')
//var pdf = folder.createFile(ss.getBlob());
var pdf = folder.createFile('New Text File', ss.getBlob, MimeType.exportPDF)

Based on my understanding you are trying to export your Google Sheet to a PDF file.
Here are some of my observations:
You are using an invalid MimeType, it should be MimeType.PDF
When you use createFile(name, content, mimeType), It expects a string input (Not a blob object). If you use a blob object as its content, the output pdf file will have the text Blob in it.
The most easiest way to export your sheet to pdf is to set your blob's name with file extension.
Sample Replication:
var blob = ss.getBlob();
// Test 1, set the file name and mimetype using createFile()
folder.createFile("Test1",blob,MimeType.PDF);
// Test 2, set the file name with extension in the blob object
blob.setName("Test2.pdf");
folder.createFile(blob);
Output:
Test1
Test2

I was able to sort it out. Just chuck in
pdf.setName = "Name"

Related

Exception: Blob object must have non-null data for this operation. (line 19)

Hi I'm trying to attach multiple Google Doc files from a folder to send to an Email. However, the above exception arises.
The code is as follows
function email() {
// Get attachments folder
var attachementFolderId = "xyz";
Logger.log("Attachement Folder ID: " + attachementFolderId)
var getAttachementFolder = DriveApp.getFolderById(attachementFolderId);
// Get all files from the folder
var files = DriveApp.getFolderById(attachementFolderId).getFiles();
//Get All attachments
var attachements = [];
while (files.hasNext()) {
var file = files.next();
attachements.push(file.getAs(MimeType.GOOGLE_DOCS));
}
MailApp.sendEmail({
to: email,
subject: subject,
attachments: attachements
})
}
This code works fine if the file is either a pdf or a Microsoft Word doc but causes an issue for a Google Doc.
Modification points:
When the official document of getAs(contentType)
) is seen, it says as follows.
The MIME type to convert to. For most blobs, 'application/pdf' is the only valid option. For images in BMP, GIF, JPEG, or PNG format, any of 'image/bmp', 'image/gif', 'image/jpeg', or 'image/png' are also valid.
In this case, unfortunately, MimeType.GOOGLE_DOCS cannot be used for this.
When you want to retrieve the blob from Google Document. It is required to convert it to other mimeType.
When you want to convert it to PDF format, please modify file.getAs(MimeType.GOOGLE_DOCS) to file.getBlob().
When you want to convert it to DOCX format, I think that this thread might be useful.
References:
getAs(contentType)
Related question
Convert Google Doc to Docx using Google Script

Load or Read a JSON from local in Google AppScript

I am looking to read a json file, namely config.json from a AppScript to generate a Google Form from the meta data in the config.json. I am not sure how to read the JSON file - could someone help me with it please? Some example code would be greatly appreciated.. Thanks
Assuming that your file is in Google Drive, you can use the DriveApp service to read the file and parse it.
function getFileContent() {
var fileName = "config.json.txt";
var files = DriveApp.getFilesByName(fileName);
if (files.hasNext()) {
var file = files.next();
var content = file.getBlob().getDataAsString();
var json = JSON.parse(content);
Logger.log(json);
}
}
Make sure that Google Drive has not converted the text file into a native format else the script won't be able to parse it.
If you're like me, you may have looked here to see how to store the JSON file inside the actual Apps Script project (e.g. alongside Code.gs) and then retrieve it in Code.gs.
I did this:
Add an HTML file to your project.
Remove all the content of the HTML file and put in your JSON
In your Code.gs file, use something like the following:
//Assume the file you added to your project is called 'my-json.html'
const jsonString = HtmlService.createHtmlOutputFromFile("my-json.html").getContent();
const jsonObject = JSON.parse(jsonString);

How can I specify an extension when using the Picker (specifically .json)

My goal is to have the user open a file picker, select a .json file and then have the script read the file.
At the moment I have a picker working, but I cannot figure out how to limit it to just show me files with the .json extension.
I figured it out:
To open just a JSON file in picker, you need the below view:
new google.picker.View(google.picker.ViewId.DOCS).setMimeTypes("application/json");
to read the file you picked, you need to grab the ID of the file you picked, and then run it through the below function:
function readJson(id) {
var file =DriveApp.getFileById(id);
var blob = file.getBlob();
var asString = blob.getDataAsString();
var asJson = JSON.parse(asString);
}

How to replace text within a pdf file?

Is it possible to replace text within a pdf file using Google Apps Script?
I am trying the following code without success on the replace, it seems like the string is encoded in a way I cannot understand.
var pdfFile = DocsList.getFileById("pdf-doc-id");
var asBlob = pdfFile.getBlob();
var asString = asBlob.getDataAsString();
var s2s = "old string";
var s2r = "new string";
var repString = asString.replace(s2s, s2r);
var repBlob = Utilities.newBlob(repString).setContentType("application/pdf").setName("Testing");
DocsList.createFile(repBlob);
EDIT1: I got an empty pdf back
Any ideas?
Thanks
The function getDataAsString() doesn't return the textual content of a PDF file, but instead a textual representation of the binary content of the file. That function works on any file, even those that don't have text (like images).
Unfortunately I don't think you can fully accomplish your goal with Apps Script. If you are able to import your PDF as a Google Document using the Drive UI, then you can use Apps Script's DocumentApp to modify the document and export it as a PDF.

Is it possible to search with in an uploaded pdf or google doc for keywords?

Here is the situation:
I have a pdf and google doc in my drive list of documents. I would like to build an interface that could search through these documents for keywords and return the document name and possible preview of the text that matched the search parameters. Is this or some variation of this possible?
Regards,
Shawn
Getting text from a Google Doc is simple:
// Get text from GDOC
var gdocDoc = DocumentApp.openById(gdocFile.id);
var text = gdocDoc.getBody().getText();
The pdfToText() utility from Get pdf-attachments from Gmail as text uses the advanced Drive service and DocumentApp to convert PDF to Google-Doc to text. You can get the OCR'd text this way, or save it directly to a txt file in any folder on your Drive.
// Start with a Blob object
var blob = DriveApp.getFilesByName("my.pdf")[0];
// filetext will contain text from pdf file, no residual files are saved:
var filetext = pdfToText( blob, {keepTextfile: false} );
Once you have the text, a search for keywords becomes dead easy!
if (filetext.indexOf( keyword ) !== -1) {
// Found keyword...
}