Google Cloud Print from Web

940 views Asked by At

I wrote a script that prints some test pages from url on Web-site, and every time I press a print button, a dialog frame for choosing printer appears . But I want to avoid this because my account synchronized with printer.

window.onload = function() {
var gadget = new cloudprint.Gadget();
gadget.setPrintButton(
    cloudprint.Gadget.createDefaultPrintButton("print_button_container")); // div id to contain the button
    gadget.setPrintDocument("url", "Test Page", "https://www.google.com/landing/cloudprint/testpage.pdf");
}
1

There are 1 answers

0
user2970721 On

You could use oath and an html button rather than a gadget to accomplish this. This requires using the google developer console to get oauth permissions.

Then you need to authorize the cloud print service.

The following set of functions are specifically good for use in Google Apps Scripts, but can be adapted. The first thing to do is Log a url link that you can go to in order to Authorize the cloud print service.

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

In the following component of this set of functions, make sure to replace the client Id and Secret.

function getCloudPrintService() {
  return OAuth2.createService('print')
  .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
  .setTokenUrl('https://accounts.google.com/o/oauth2/token')
  .setClientId('**YOUR CLIENT ID FROM GOOGLE DEVELOPER CONSOLE**')
  .setClientSecret('**YOUR 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');
  }
}

Next, get the ID of the Cloud Print Printer that you want to use. This can be obtained in the settings menu of Chrome. Settings --> Show Advanced Settings --> Under Cloud Print " Manage" --> Select the Printer that you want to use "Manage" -->Advanced Details

To initiate cloud print, you need to add the details to a ticket:

var ticket = {
  version: "1.0",
  print: {
    color: {
      type: "STANDARD_COLOR",
      vendor_id: "Color"
    },
    duplex: {
      type: "LONG_EDGE"
    },
    copies: {copies: 1},
    media_size: {
       width_microns: 215900,
       height_microns:279400
    },
    page_orientation: {
      type: "PORTRAIT"  
    },
    margins: {
      top_microns:0,
      bottom_microns:0,
      left_microns:0,
      right_microns:0
    },
    page_range: {
      interval: 
        [{start:1,
        end:????}]
    }
  }
};

There are many options that you can add to the ticket. See documentation

Finally, you need to initiate the Cloud Print Service. Here is where you get to define the specific printer that you want.

var payload = {
"printerid" : '**COPY YOUR PRINTER ID HERE**',
"title"     : "Prep Print",
"content"   : PUT YOUR CONTENT HERE...(e.g. If you do all of this using Google Apps Script...HtmlService.createHtmlOutput(VARIABLE).getAs('application/pdf')),
"contentType": 'text/html',
"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);}

  var outcome = response.message;
 }