Google Script doc.getBody() returns plain text - google-apps-script

Just a quick question, is there anyway that I can get the body of my google doc to be as exact as it is? For example, I have a bold sentence in my google doc, but whenever i'm trying to send it using via sendEmail in google script, it's being sent as plaint text, the bold letters an other formatted texts are being converted into plain, please see my code:
var body_hw1 = doc_hw1.getBody().getText();
MailApp.sendEmail(email, subject_hw1, body_hw1);

The method getBody() returns an object that is not usable outside of Google Docs. The method getText() returns plain text.
In order for use bold fonts, etc, in an email, it has to be formatted as HTML. So you need to convert Google document to HTML. There is no built-in function for this, but a third-party solution is available: it does not support full range of Docs format but certainly supports bold and italic fonts, and similar. See this answer.

Another solution would be to extract the plain text and format it into html yourself and send that. For example:
var myText = {header:'Dear sir,',message:'We are writing to inform you...'}
var message = ("<h3>"+ myText.header +"</h3>" +
"<p>"+ myText.message +"</p>")
MailApp.sendEmail(email, 'Important Message', message);

Related

Google Apps Script Gmail getPlainBody Line Breaks

With the Google Apps Script Gmail library, when I use the function GmailMessage.getPlainBody(), the API seems to take what used to be one paragraph and break it up into multiple, potentially by using a character limit. For instance, a paragraph of my email reads:
From the link you sent me, I gleaned that Gmail refers to their secure email as confidential.
But when I call this function on the email, it becomes:
From the link you sent me, I gleaned that Gmail refers to their
secure email as confidential.
And, when I split the email text on a new line delimitor and do a bit of cleanup to create an array with my output, I end up with:
['From the link you sent me, I gleaned that Gmail refers to their', 'secure email as confidential.']
I viewed this Reddit post, which seemed to deal with the similar problem. But, I tried the resolution suggested by the person who posed the question:
body = message.getPlainBody().replace(/\r\n\r\n/gm,'aaaLINEBREAKERaaa').replace(/\r\n/gm,' ').replace(/aaaLINEBREAKERaaa/gm, '\r\r').replace(/ /gm,' ')
And it didn't quite give me what I need. Has anyone else encountered this problem, and if so, do you have a suggested workaround? Thanks!
I had the same issue. In that case, I used a workaround.
When I checked the email, I noticed that the HTML body is included in the message body and the HTML body has the original paragraph, and I used this situation. So, in this workaround, the original text is retrieved from the HTML body and the HTML is converted to a text. By this, the original paragraph is obtained. The sample script is as follows.
Sample script:
This script uses Drive API for converting HTML to text. So pelase enable Drive API at Advanced Google services.
var message = // Here, please use your "message".
var html = message.getBody();
var id = Drive.Files.insert({title: "temp", mimeType: MimeType.GOOGLE_DOCS}, Utilities.newBlob(html, MimeType.HTML)).id;
var text = DocumentApp.openById(id).getBody().getText(); // or DocumentApp.openById(id).getBody().getText().trim();
DriveApp.getFileById(id).setTrashed(true);
console.log(text)
References:
getBody()
Files: insert

Sending HTML emails using google ap script

I'm trying to send HTML emails using Google aps script. I've got the HTML on a google doc which i'm trying to send using the code below. But when I send it I receive it as unformatted text with all the HTML tags displayed. Can anyone tell me how to do this? I'd rather not include the HTML in the script, because there will eventually be an awful lot of it.
var html = UrlFetchApp.fetch('https://docs.google.com/document/d/documentID/export?format=html');
MailApp.sendEmail('emailaddress', subject, null , {htmlBody: html});
Thanks, Bryan
Here's an example of doing the same thing with a row of spreadsheet data. Link. Don't use css between <style></style> tags. Use inline style="" instead. That seems to work better.
Google Script Mail App
The format of your code seems not well-structured,
Make sure all the data passed to the:
.sendEmail() method is in Curly braces {}.
Please reference the code below to see how it works.:
MailApp.sendEmail({
to: "me#myservice.com",
subject: "Testing",
htmlBody:"<h1>Hello there</h1><p>Your HTML Here</p>"});
That's it. You can also send this HTML from external file as:
HTMLService.createTemplateFromFile("fileName")

How Can Line Breaks in Google Spreadsheets be Preserved When Posting to Google Sites?

I have a script on Google app script. This script find a data simply.
my code :
var content=this.spreadsheet.getSheetByName("sheet1").getRange("C1:C26").getValues();
this.summary = contents[4][0];
I find my data , no prob but , my data has line breaks and my webpage on Google sites shows the result without line breaks.
It's a prob of convert with GetValue () ?
my data on a Cell of Spreadsheet :
blabab---
bla
abla---
bla
the result on a Google Site
blabab---bla abla---bla
The solution is the following:
Get your string (in the cell) that you want to post to your Google Site.
Replace all line breaks (\n) in the string with the HTML version (<br />)
Something like the following:
function lineBreakTest() {
var cellWithLineBreaks = SpreadsheetApp.getActiveSheet().getRange("a1").getValue();
Logger.log(cellWithLineBreaks);
cellWithLineBreaks = cellWithLineBreaks.replace(/\n/g, '<br>');
Logger.log(cellWithLineBreaks);
// Post to your Google Site here. Logger.log is just used to demonstrate.
}
The reason you have to do this is because Spreadsheets uses normal text line breaks \n in its cells. However, Google sites uses HTML format, so you need to do the 'conversion'. This answer is also a helpful source.

Using HTML file to output a PDF

So I've got a HTML file, that I am using to send emails, but in some instances I want it simply to use that file to create a PDF of the same template.
I've got it functioning for the most part - it creates the file, runs the evaluations and gets the content, but it doesn't actually render the html. It simply leaves all the html notation in place.
For example, it outputs a pdf but it reads:
Dear Martin, <br />
instead of:
Dear Martin
How do I make sure it renders the HTML so that the PDF is laid out correctly, and doesn't have the html code noted in the text?
Here's the code:
var docName = "test";
var htmlBody = HtmlService.createHtmlOutput(template.evaluate().getContent()).getContent()
var doc = DocumentApp.create(docName);
doc.appendParagraph(htmlBody);
doc.saveAndClose();
DocsList.createFile(doc.getAs('application/pdf')).rename(docName);
You can use your existing HTML as a blob, and convert it to PDF like this:
var htmlBody = HtmlService.createHtmlOutputFromFile('my_file_within_script_project.html').getContent();
var blob = Utilities.newBlob(htmlBody, 'text/html').getAs('application/pdf').setName('my_output_in_drive.pdf');
DriveApp.createFile(blob);
The best option when you want to create a PDF from a template is to use Google Docs directly so that no formatting is lost and also avoid the problem you are facing.
Why don't you just create your template directly in Google Docs. Have some placeholders such as {name} instead of the actual name. Instead of using template.evaluate(), you can do a find and replace in the doc.

How can I create superscript/subscript characters in a document?

I'm working on a script to convert some documents in a proprietary format over to google docs. I've been able to handle most of the various formatting options (fonts, point sizes, bold, etc.) but I'm stuck on subscript and superscript.
I've tried creating a new google doc with a paragraph in subscript. I then wrote a script to look at the paragraphs and children and in both cases didn't see an attribute that was set as I could for underline.
I've tried wrapping the text in st but that only added that exact text to the document. Here is a bit of the code I'm currently using:
if (superscript == true ) {
paragraph.appendText(txt.sup()).setAttributes(style);
} else if (subscript == true) {
paragraph.appendText(txt.sub()).setAttributes(style);
} else {
paragraph.appendText(txt).setAttributes(style);
}
Anything else to try?
There's currently no way to do this — it would exist somewhere in the Text class API (https://developers.google.com/apps-script/reference/document/text) if it were possible.
I filed a feature request for superscript / subscript here https://code.google.com/p/google-apps-script-issues/issues/detail?id=2885 . Feel free to star the issue to register your support.
For the benefit of anyone looking for this, it's been implemented since this question was asked as a TextAlignment class - it's not explicit in the documentation*, but thankfully these create indices on text elements observed with the getTextAttributeIndices method.
* as in, it's not an attribute listed by getAttributes but is indexed with getTextAttributeIndices()
I've just modified a Docs-to-markdown processing script I'm working on to incorporate sub- and superscript alignment handling which may be useful as an example (see commit diff).
Note that if applied across paragraphs the getTextAlignment method returns null.
You want to put the superscript and subscript characters to Google Document using Google Apps Script.
If my understanding is correct, how about this sample script? Unfortunately, even in the current stage, there are still no methods for putting the superscript and subscript characters using Document Service.
But when Google Docs API which was added at early 2019 is used, those can be achieved. Such function might be added to Document Service in the future. So as a current workaround, I would like to propose the method using Docs API. The sample script is as follows.
Before you use this script, please enable Google Docs API at Advanced Google services.
Sample script:
function myFunction() {
var documentId = "###"; // Please set document ID here.
var resource = {requests: [
{insertText: {text: "SampleSuperscriptSubscript", location: {index: 1}}},
{updateTextStyle: {range: {startIndex: 7, endIndex: 18}, textStyle: {baselineOffset: "SUPERSCRIPT"}, fields: "baselineOffset"}},
{updateTextStyle: {range: {startIndex: 18, endIndex: 27}, textStyle: {baselineOffset: "SUBSCRIPT"}, fields: "baselineOffset"}}
]};
Docs.Documents.batchUpdate(resource, documentId);
}
Result:
When above script is run for new Google Document, the following result is obtained. At first, a text of SampleSuperscriptSubscript is put. Then, the text style is modified. These are run using the batchUpdate method. If you want to put those values for the existing Document, please modify above object of resource.
References:
Document Service
Google Docs API
Advanced Google services
Method: documents.batchUpdate
TextStyle
BaselineOffset
If this was not the direction you want, I apologize.