如何通过Google Apps脚本将简单的Google纯文本文档转换为HTML? [英] How to Convert a simple Google text-only Document to HTML via Google Apps Script?

查看:215
本文介绍了如何通过Google Apps脚本将简单的Google纯文本文档转换为HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Google文档的内容,并通过Google Apps脚本将其转换为HTML代码(用于发送为HTML电子邮件)。

I need to take the contents of a Google Doc and turn it into the HTML code equivalent (for sending as an HTML email), via Google Apps Script.

我可以阅读文件,并通过身体中的元素循环获取文本,但是如何将格式(粗体,斜体)转换为HTML?通过isBold(偏移)和isItalic(偏移),并循环通过每个角色?

I can read the file and get the text by cycling thru the elements in the body, but how would one get the formatting (bold, italic) into HTML? Via isBold(offset) and isItalic(offset) and cycling thru each character?

感谢任何帮助。 〜

推荐答案

使用文档编写您的消息,将其转换为html格式并将其用作html正文,这是完美可行的在消息中。

This is perfectly doable using a document to compose your message, converting it to html format and using that as an html body in the message.

代码如下:

function sendAsHtmlBody(){
  var id = DocumentApp.getActiveDocument().getId();
  var url = 'https://docs.google.com/feeds/';
  var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=html&format=html&id='+id,
                                  googleOAuth_('docs',url)).getContentText(); 
  MailApp.sendEmail(Session.getEffectiveUser().getEmail(),'testHTML Body','html content',{'htmlBody':doc});
}


function googleOAuth_(name,scope) {
  var oAuthConfig = UrlFetchApp.addOAuthService(name);
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setConsumerKey('anonymous');
  oAuthConfig.setConsumerSecret('anonymous');
  return {oAuthServiceName:name, oAuthUseToken:"always"};
}

此代码将以两个步骤要求授权,一个用于正常服务(mail,documentApp,..),另一个用于Oauth功能,后者必须通过从脚本编辑器调用函数触发(如果您进行菜单并让新用户调用该菜单它不会工作...,您必须使用脚本编辑器,请参阅 issue 677 here )。

This code will ask for authorization in 2 steps, one for "normal" services (mail, documentApp, ..) and a second for the Oauth function, this latter must be triggered by calling the function from the script editor (if you make a menu and let a new user call that menu it won't work..., you have to use the script editor, see issue 677 here).

And 这里是一个共享文档(只读,复制使用)来测试不同字体,图像和一些文本的代码。 (Google文档中几乎所有的功能都是以html格式翻译的...只有少数几个对齐方式有时候会丢失,我经常使用,没有明显的问题)

And here is a shared document( read only, make a copy to use) to test the code with different fonts, an image and some text.(almost every feature available in Google docs are translated in html... only a few alignment are missing sometimes. I use that very often without noticeable issue)

这篇关于如何通过Google Apps脚本将简单的Google纯文本文档转换为HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆