简体   繁体   English

使用插件或Google扩展程序在Google脚本中打印

[英]Print in google script using add-ons or Google extensions

I started working on Google Script. 我开始研究Google脚本。

I wonder if there is some way to print in google script( be it text or google sheet data ) when a cell event is generated on the Google sheet. 我想知道在Google工作表上生成单元格事件时,是否有某种方法可以在Google脚本中打印(无论是文本还是Google工作表数据)。

Any suggestion would be helpful. 任何建议都会有所帮助。 Thanks. 谢谢。

Google脚本不能使用系统功能,例如打印对话框。

Before proceeding further make sure you have added google cloud supporting printer to google account for printing because of security reasons services like print is not supported by google script 在继续进行之前,请确保您出于安全原因已将支持Google Cloud的打印机添加到Google帐户进行打印,但出于安全原因,Google脚本不支持诸如Print之类的服务

  • Open Google Drive. 打开Goog​​le云端硬盘。

    1. Right-click to make open Google Sheet. 右键单击以打开Goog​​le表格。
    2. Add some rows. 添加一些行。
    3. Click on Tools menu and select Script editor option. 单击工具菜单,然后选择脚本编辑器选项。
    4. Select File menu from script editor and then select project properties option. 从脚本编辑器中选择“ 文件”菜单,然后选择“ 项目属性”选项。
    5. Note down the Project key (Deprecated) and Script_id from info tab. 信息选项卡中记下Project项 (不推荐使用)和Script_id
    6. Select Resources > Libraries. 选择资源>库。
    7. Add key MswhXl8fVhTFUH_Q3UOJbXvxhMjh3Sh48 to add library box . 添加密钥MswhXl8fVhTFUH_Q3UOJbXvxhMjh3Sh48添加库框 Select latest version from list and set identifier OAuth2 . 从列表中选择最新版本,并设置标识符 OAuth2
  • Open Google Cloud Console. 打开Goog​​le Cloud Console。

    1. To open Google Cloud Console follow this link Google Cloud Console link, there in left navigation section you will find a credentials link. 要打开Goog​​le Cloud Console,请点击此链接Google Cloud Console链接,在左侧导航部分中,您会找到凭据链接。
    2. Click on Credentials link > Create Credentials . 单击凭证链接 > 创建凭证 A popup will appear. 将会出现一个弹出窗口。 From there select OAuth Client Id option. 从那里选择OAuth Client Id选项。
    3. Under Application Type select Web Application. 在“应用程序类型”下,选择“ Web应用程序”。 Set some name to Application. 为“应用程序”设置一些名称。 In authorised script origins url box paste below link. 在授权的脚本来源网址框中,粘贴以下链接。 https://apis.google.com

      In authorized redirected url box paste below link. 在授权的重定向网址框中,粘贴以下链接。 https://script.google.com/macros/d/{SCRIPT_ID}/usercallback

    4. SCRIPT_ID is from project properties. SCRIPT_ID来自项目属性。

    5. Save the details. 保存详细信息。
    6. Note down Client_id and Client_secret for future use. 记下Client_id和Client_secret,以备将来使用。
  • Script. 脚本。

Paste Below code in script window. 在脚本窗口中粘贴以下代码。

function showURL() {
  var cpService = getCloudPrintService();
  if (!cpService.hasAccess()) {
    console.log(cpService.getAuthorizationUrl());
  }
}

function getCloudPrintService() {
  return OAuth2.createService('print')
    .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
    .setTokenUrl('https://accounts.google.com/o/oauth2/token')
    .setClientId('CLIENT_ID’)
    .setClientSecret('CLIENT_SECRET')
    .setCallbackFunction('authCallback')
    .setPropertyStore(PropertiesService.getUserProperties())
    .setScope('https://www.googleapis.com/auth/cloudprint')
    .setParam('login_hint', Session.getActiveUser().getEmail())
    .setParam('access_type', 'offline')
    .setParam('approval_prompt', 'force');
}

function authCallback(request) {
  var isAuthorized = getCloudPrintService().handleCallback(request);
  if (isAuthorized) {
    return HtmlService.createHtmlOutput('You can now use Google Cloud Print from Apps Script.');
  } else {
    return HtmlService.createHtmlOutput('Cloud Print Error: Access Denied');
  }
}

getPrinterList this method will check list of linked printer to account and return printer ID, NAME and DESCRIPTION getPrinterList此方法将检查到帐户的链接打印机列表,并返回打印机ID,名称和说明

function getPrinterList() {
  var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/search', {
    headers: {
      Authorization: 'Bearer ' + getCloudPrintService().getAccessToken()
    },
    muteHttpExceptions: true
  }).getContentText();
  var printers = JSON.parse(response).printers;
  for (var p in printers) {
    Logger.log("%s %s %s", printers[p].id, printers[p].name, printers[p].description);
  }
}
  • Last step. 最后一步。

    1. In script window select Select Function from toolbar and select showURL function and run code. 在脚本窗口中,从工具栏中选择“选择函数”,然后选择showURL函数并运行代码。
    2. Hit CMD + ENTER to open logs. 点击CMD + ENTER打开日志。 Copy the url from logs and paste in browser. 复制日志中的网址,然后粘贴到浏览器中。
    3. Follow the direction and allow permissions for printer. 按照说明进行操作并允许打印机权限。

Run below method with required parameters to add print job to cloud printer. 使用所需参数运行以下方法以将打印作业添加到云打印机。

function printGoogleDocument(docID, printerID, docName) {
  var ticket = {
    version: "1.0",
    print: {
      color: {
        type: "STANDARD_COLOR",
        vendor_id: "Color"
      },
      duplex: {
        type: "NO_DUPLEX"
      }
    }
  };

  var payload = {
    "printerid" : printerID,
    "title"     : docName,
    "content"   : DriveApp.getFileById(docID).getBlob(),
    "contentType": "application/pdf",
    "ticket"    : JSON.stringify(ticket)
  };

  var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
    method: "POST",
    payload: payload,
    headers: {
      Authorization: 'Bearer ' + getCloudPrintService().getAccessToken()
    },
    "muteHttpExceptions": true
  });

  response = JSON.parse(response);

  if (response.success) {
    Logger.log("%s", response.message);
  } else {
    Logger.log("Error Code: %s %s", response.errorCode, response.message);
  }
}

Thanks. 谢谢。

If you face any error , kindly leave a reply. 如果您遇到任何错误,请留下答复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM