How can I create superscript/subscript characters in a document? - google-apps-script

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.

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

Is it possible to add a comment attributed to specific text within Google Docs using Apps Script?

Google docs comment:
My goal is to add a text-specific comment using Google Apps Script as seen in the picture above. Right now I have this working code, but it only adds a general comment for the whole document.
function myFunction() {
var fileId = '{FILE_ID}';
var resource = {'content': 'comment body text'};
Drive.Comments.insert(resource, name);
}
Not possible. In this video -- Google Drive SDK: Announcing the Comments API (5:30 - 5:39) -- it is mentioned that:
..We do have a proprietary anchoring scheme, which does make it difficult for, or actually rather impossible for you to create comments that are anchored to text in our document formats...
"in our document formats" refers to Google Docs and Sheets.
This is also mentioned in this answer. For more details regarding Comments, you can check the Manage Comments and Discussions documentation.

Retrieving HTML code used in google docs using google app scripts

Is it possible to use Google app scripts to get the html code in Google docs i.e if text in the document was say bold,i could get the html code for that.
What i have so far :
function getHtml(id) {
var doc1=DocsListExtended.getFileById("1ta7zJ6SDFgzgp-UprjehxR8Tx3-4-wtJwTYqWbol1SU").getAsHTML();
var body=HtmlService.createHtmlOutput(doc1);
var cont=body.getContent();
return cont;
Logger.log(cont);
}
I don't know a simple way for that. You can navigate the elements of the document using DocumentApp API, and converting it block by block to HTML.
I already tried
DocumentApp.getActiveDocument().getAs(MimeType.HTML).getDataAsString()
but the error says doc can't be converted to html mimetype.

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.

How to pass parameters to Google Apps Script Gadget embedded in a Sites Page?

I have a Google Apps Script gadget that is embedded in a Google Sites page. I would like to pass the gadget a page parameter, such that when the page is opened with URL like:
https://sites.google.com/a/mydomain/mysite/mypage?myparameter=1
I can access the value of the page parameter in the Apps Script gadget code like so:
function doGet(e) {
var app = UiApp.createApplication();
app.add(app.loadComponent("MyComponent"));
var myparam = e.parameter.myparameter;
return app;
}
Currently, the value of e.parameter.myparameter is coming back as null. Is there a way to setup my Apps Script to support this? Any approaches are welcome.
Maybe the link bellow will help you - I have not tried it myself yet...but I will try it out in the next days.
http://code.google.com/p/google-apps-script-issues/issues/detail?id=535
I posted this on the code.google.com page linked in the accepted answer, but the way to have parameters passed through to Apps Script is by adding "https://sites.google.com/feeds" to the Apps Script scope. (See this site for information about how to add explicit scopes.) Once this scope is added, the following works:
in Code.gs:
function doGet(e) {
var htmlTemplate = HtmlService.createTemplateFromFile("page");
htmlTemplate.urlParams = e.parameters;
return htmlTemplate.evaluate();
}
in page.html:
...
<head>
...
<script>urlParams = <?!= JSON.stringify(urlParams) ?>;</script>
</head>
...
urlParams is now available as a variable in your JS code in the following form:
urlParams = { key1: [value1, value2, ...], key2: [value1, value2] }
This example describes a parameter as "&name=value" however I have not been able to get it working in either a Google Apps Site, or in a Personal Google Site. (which seem to handle authentication in different ways)
The example seems to work fine when I hard-code the value so maybe I am just not parsing it right or something, I will try to follow up here when I understand this better but I also have not yet found adequate explanations of these features.
One Hypothesis is that Google changed something, I note the menu structure does not seem to match what I assume it use to be since I see many references to a [share] button/menu.