Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Google Cloud Print API with Android

I am working on an android application that needs to print to a printer. I decided on using the Google Cloud Print, as it seemed easy to set up. Initially, I followed the steps found here for integrating into Android. This works, as in it will print to my desired printer. However, this process is a bit involved for the user. In my case, the process is as follows:

  1. The user selects the print button that I have displayed next to some information.
  2. A Dialog is shown with a preview of what will be printed. There is a button in the ActionBar that says "Print". This begins the process.
  3. A new Activity is displayed showing a list of printers that are connected to that users Google Account. The user must select one.
  4. A new page is shown giving a description of the print job.
  5. The user has to select "Print" in the upper right hand corner.
  6. The print job is started and the printer prints out the picture.

Unfortunately, my client does not want this process. They want the user to click "Print" in step two, and then have the picture printed (steps 1, 2 and 6). Thus, I cannot use Intent provided by Google, I must use the actual API. This requires me to get a Google Auth token, get the desired printer, and submit a print job that way. I do the following:

  1. Use the Google Play Services to retrieve an OAuth token for the users Gmail account.
  2. Get a list of printers using the /search API call.
  3. Submit a print job using the /submit API call.

I have the first two finished. I am just having trouble with the actual printing of the picture. Instead of printing the picture, the byte data of the picture is being printed (Base64 encoded). Here is some code as to how I am sending up the request:

ContentResolver contentResolver = context.getContentResolver();
try {
    InputStream is = contentResolver.openInputStream(uri);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buffer = new byte[4096];
    int n = is.read(buffer);
    while (n >= 0) {
            baos.write(buffer, 0, n);
            n = is.read(buffer);
    }
    is.close();
    baos.flush();

    content = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
} catch (FileNotFoundException e) {
    Log.d(TAG, "File not found: " + uri.toString(), e);
} catch (IOException e) {
    e.printStackTrace();
}

This code retrieves the picture (the variable "uri" is the URI of that file), and turns it into a Base64 encoded string. This is the same method used in the PrintDialogActivity that is provided on the Google Cloud Print page (linked to above). The following is how I send that up:

  • URL: http://www.google.com/cloudprint/submit?access_token=[AUTH_TOKEN_GOES_HERE]&cookies=false&printerid=[PRINTER_ID_HERE]
  • HTTP Method: POST
  • POST Parameters: [printerId=PRINTER_ID_HERE, title=TestPrint, contentType=image/jpeg, capabilities={"capabilities":[{}]}, content=[Base64 Encoded data string is placed here]]

As far as I can tell, this is how it is supposed to be. I am getting a response of {"success":true} when printing. But, as I said above, it prints out the actual Base64 data string. Any help would be appreciated.

EDIT: Using what powerje said below, I managed to fix this. Rather than using the code above, I used the following:

public void submitPrintJobWithFile(String printerId, String title, String token, String filePath, String contentType){
    File file = new File(filePath);
    // Method that gets the correct headers
    List<Header> headers = getHeaders(contentType, token);
    // Method that gets the correct post parameters
    String url = CLOUDPRINT_URL + PATH_SUBMIT;
    List<NameValuePair> postParams = getParams(title, contentType);
    String params = "access_token=" + token + "&cookies=false" + "&printerid=" + printerId;
    url += params;
    response = sendMultipartData(url, file, postParams, headers);
}

private String sendMultipartData(String url, File file, List<NameValuePair> fields, List<Header> headers){
    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity();
    for(NameValuePair pair : fields){
        String name = pair.getName();
        String value = pair.getValue();
        try{
            entity.addPart(name, new StringBody(value));
        }catch (UnsupportedEncodingException e){
            Log.d(TAG, "Error turning pair (name=" + name + ", value=" + value + ") into StringBody.");
    }
    entity.addPart("content", new FileBody(file));
    post.setEntity(entity);
    // Finish HttpClient request here...
}
like image 299
ariets Avatar asked Jan 22 '13 21:01

ariets


People also ask

How do I use Google Cloud Print on Android?

On your Android device Cloud Print is the official Android app for printing to Google Cloud Print from your Android devices. Once it's installed, you can share your documents, photos, or PDFs to the app, choose your printer and preferred print options, and hit Print -- that's all there is to it.

How can I remotely print from my Android phone?

Open the Settings app on your Android phone and type “Printing” in the search box. Tap on the Printing option that shows up. Alternatively, you can find this setting in Settings > Connected devices > Connection preferences > Printing. Tap on Cloud Print.


2 Answers

It looks like you need to use multipart encoding, example here:

http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/

FTA:

The files needed are apache-mime4j, httpclient, httpcore and httpmime. All are opensource projects built by the Apache foundation.

Download the 4 files and add them to your project then you should be able to use the following code to post strings and files to pages.

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.tumblr.com/api/write");

try {
    MultipartEntity entity = new MultipartEntity();

    entity.addPart("type", new StringBody("photo"));
    entity.addPart("data", new FileBody(image));
    httppost.setEntity(entity);
    HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
} 

The image variable in this case is a File that contains an image captured by the camera on the phone.

like image 101
powerj1984 Avatar answered Oct 18 '22 00:10

powerj1984


Looking at the Python Sample Code SubmitJob method it seems that only the PDF typs needs to be encoded in Base64.

like image 39
Benjamin Cassidy Avatar answered Oct 17 '22 22:10

Benjamin Cassidy