How do I embed an image uploaded by form to google doc/auto generating PDF? - image

I have a google form (Medical report). Whenever someone answers the form, the answers go to a sheet and creates copy of a doc template, replaces keywords and then generates a pdf. I've create separate folders to organize the PDFs for the responses. This is working well thus far.
However, the report (Google Form) requires the user to upload an image as part of some of the answers (Sample Form Layout). I would like to have two separate images automatically appear on the doc for Before Treatment and After Treatment (To replace the sample text from google doc with pictures).
The image uploads to drive fine, but I don't know how to have the uploaded image appear on the Google docs and pdf. So far I'm only able to obtain a drive link instead of an actual image (How the PDF generated file looks like)
Here's a sample of my script:
Function afterFormSubmit(e) {
const info = e.namedValues;
//Running the createPDF fuction into the form submission
createPDF(info);
}
//Function to create PDF
function createPDF(info){
const pdfFolder = DriveApp.getFolderById("pdfFolderId");
const tempFolder = DriveApp.getFolderById("tempFolderId");
const templateDoc = DriveApp.getFileById("docTemplateId");
//Get ID of file and open as a document
const OpenDoc = DocumentApp.openById(newTempFile.getId());
const body = OpenDoc.getBody();
//Get body from the PDF text and replace the keywords based on the response submission
body.replaceText("{name}", info['Patient Name'][0] );
body.replaceText("{report no}", info['Report No'][0]);
body.replaceText("{before}", info['Before Treatment Image'][0]);
body.replaceText("{after}", info['After Treatment Image'][0]);
OpenDoc.saveAndClose();
//Creating a file name based on the report no
const blobPDF = newTempFile.getAs(MimeType.PDF);
const PdfFile = pdfFolder.createFile(blobPDF).setName(info['Report No'][0]])
tempFolder.removeFile(newTempFile);
}

Related

How do I move all Google Sheets rows of data into Google Docs template fields

I'm currently have a Google Sheet (Pushed to a website via PHP) with all my clients beer data. I'd like to take that data and copy it into a Google Doc Template for easy printing. In my example I can move the first row of data from the Sheet into the Doc but all the other rows from the sheet do not copy over.
I could use some help with the forEach statement, I'm thinking I need to parse the array and iterate through it in a different way than I'm currently attempting. (First time using Apps Script)
Here is what I've currently coded up.
function onOpen() {
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu('Print Menu');
menu.addItem('Create New Print Menu', 'createNewMenu')
menu.addToUi();
}
function createNewMenu() {
//Google Doc Template ID and Where to Save the New File
const googleDocTemplate = DriveApp.getFileById('1xzlvVOSW_LsgOrm2N2o1-FKYzfqp_2EAbhqrLTn53yk');
const destinationFolder = DriveApp.getFolderById('11HU0TvSPMMXUZaK5gTgg8jvofxTTt02j');
//Get all spreadsheet sheets and add values as 2D arrays.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Draft List');
const rows = sheet.getDataRange().getValues();
//Create date for new filename.
const dateData = new Date();
const curr_date = dateData.getDate();
const curr_month = dateData.getMonth() + 1; //Months are zero based
const curr_year = dateData.getFullYear();
const theDate = curr_year + "-" + curr_month + "-" + curr_date;
const newFileName = theDate + ' - Bar Print Menu';
//Using the row data in a template literal, we make a copy of our template document in our destinationFolder
const copy = googleDocTemplate.makeCopy(newFileName, destinationFolder)
//Once we have the copy, we then open it using the DocumentApp
const doc = DocumentApp.openById(copy.getId())
//All of the content lives in the body, so we get that for editing
const body = doc.getBody();
rows.forEach(function(rowData) {
//In these lines, we replace our template replacement tokens with values from our spreadsheet rows.
body.replaceText('{{onTapName}}', rowData[0]);
body.replaceText('{{onTapDescription}}', rowData[1]);
body.replaceText('{{onTapPrice}}', rowData[2]);
//Logger.log(rowData);
});
//We make our changes permanent by saving and closing the document
doc.saveAndClose();
}
This code will create a copy of the template file, copy the first row of data from Google Sheets and paste it into the template in the {{onTapName}}, {{onTapDescription}} & {{onTapPrice}} areas but the other rows from the Google Sheet do not copy over.
- Screenshot of Google Sheet, Google Doc Template and Result after running above code
If I uncomment out the "Logger.log(rowData);" line, I can see the code is going through each line of the data from the Google Sheet.
- Screenshot of Execution Log
How do I modify this forEach area to copy through each line of code into the template? I feel like I'm missing something very obvious here.
Thanks in advance for the help.

How do I obtain a File ID, Blob, or URL of a screenshot that has been inserted in a Google Sheet cell?

Context: I want to be able to extract text via OCR from a screenshot that I insert into a Google Sheet cell. I have tried for hours, searching the Internet, trying different tactics, but I cannot find a way to get a file ID, URL, or Blob for the screenshot that has been inserted into the cell (the sheet has only 1 cell). BTW I have already worked out the code I need once I get a fileID, URL, or Blob to do the OCR.
Questions:
First, is it possible to get a reference (file ID, etc.) to an image in a cell?
Second, when I select a function in a dropdown (e.g. .getContentURL) and it produces a “not a function” error, what does that indicate (e.g. there is no content, or something else)?
function getImageHandle()
{
// get the sheet object
var inputSheet = ss.getSheetByName("InPutSheet");
// get the file ID of the cell content
var fileID = inputSheet.getRange("A1").getValue().fileID();
// get the Blob of the cell content
var blob = inputSheet.getRange("A1").getValue().getBlob();
// get the URL of the cell content
var url = inputSheet.getRange("A1").getContentUrl();
// return the reference to the image in the cell
return one of the above (fileID, blob, or URL) ;
}

How can I list and merge inline-images in a PDF file using IText7-dotnet?

I have several PDF documents that supposedly contain scanned images, but upon inspection in Acrobat Pro, each page contains a huge number of tiny "inline images". From what I understand these are not regular images inside XObjects, but rather images embedded directly inside content streams.
How could I go about extracting and merging these images?
The only code I could find online starts out like this:
var reader = new PdfReader(#"path\to\file.pdf");
PdfDocument document = new PdfDocument(reader);
for (var i = 1; i <= document.GetNumberOfPages(); i++)
{
PdfDictionary obj = (PdfDictionary)document.GetPdfObject(i);
// ... more code goes here
}
...but the rest of the code doesn't work because the PdfDictionary returned from GetPdfObject is not a stream, only a dictionary. I don't know how to access the images inside it.

Auto Import Image in sheet?

I run my own fantasy baseball yearly projections and I'm looking to automatically add player images to a sheet I created.
Test Page
I use a formula to create a link to the player's image page on ESPN.
https://a.espncdn.com/combiner/i?img=/i/headshots/mlb/players/full/33859.png
Is there a way to automatically add the player image to the page?
=image("Link") is the formula, but i cant use the cell location as the link.
Any advise or guidance will be helpful and appreciated
I created an Apps Script method to achieve your target as it is not possible to do it using formula.
Here's the script I did with comments:
function SpecialOnEdit(e) {
//Get the edited cell
var range = e.range;
//Get the active sheet
var sheet = SpreadsheetApp.getActiveSheet();
//Download the image. (e.value is the URL in Google sheet)
var response = UrlFetchApp.fetch(e.value);
//Get the binary data of the image and create a blob object
var binaryData = response.getContent();
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
//Insert the image into the same row that the user place the image URL link
var image = sheet.insertImage(blob, range.getHeight(), range.getRow());
//Set the height of the row, show that the image can fit the row
sheet.setRowHeight(range.getRow(), image.getHeight() + 10);
}
You should add triggers next after pasting the script. Go to your Script Editor and click Edit->Current project's triggers->Add Trigger->under Select event type, select On edit->click Save
Next, to test the trigger and script, paste a URL of a PNG image format in the spreadsheet to validate the result.
Here's a sample output of the script and trigger:

Google Advanced Drive API fails on insert of some PDFs but not others

function extractTextFromPDF() {
// PDF File URL
// You can also pull PDFs from Google Drive
// this Fall2019_LLFullCatalog.pdf will not insert - internal error on insert is all the feedback that gets logged"
// doesn't matter if I retrieve it from the university website or if I first copy it to my google drive and then retrieve it from there
//var url = "https://uwf.edu/media/university-of-west-florida/offices/continuing-ed/leisure-learning/docs/Fall2019_LLFullCatalog.pdf";
//var url = "https://drive.google.com/drive/u/0/my-drive/Fall2019_LLFullCatalog.pdf";
// both of these pdfs will insert just fine. Size is not the issue because this one is much larger than the one I need to insert
var url = "https://eloquentjavascript.net/Eloquent_JavaScript_small.pdf";
//var url = "https://img.labnol.org/files/Most-Useful-Websites.pdf";
var blob = UrlFetchApp.fetch(url).getBlob();
var size = blob.getBytes().length;
var resource = {
title: blob.getName(),
mimeType: blob.getContentType()
};
// Enable the Advanced Drive API Service
var file = Drive.Files.insert(resource, blob, {ocr: true, ocrLanguage: "en"});
// Extract Text from PDF file
var doc = DocumentApp.openById(file.id);
var text = doc.getBody().getText();
return text;
}
See comments in code above that describe the problem.
The PDF that I need to insert with OCR is not working - regardless of whether I retrieve it from the original site or retrieve a copy that I put on google drive. However, two other PDF urls will insert just fine and one of them is considerably larger than the one that fails.
What else could be the issue, if not size limitation?
Thanks,
Steve
It could very well be a bug in the Chrome API. Not all PDF software is created equal, check if the PDF can be read in Adobe Acrobat as a simple test.

Resources