Java Google Drive: Export File to Requested MIME Type (Export to PDF)

Back to Index

Exports a Google Doc to the requested MIME type and returns the exported content. Please note that the exported content is limited to 10MB.
(Export only supports Google Docs) See https://developers.google.com/drive/v3/web/manage-downloads for a list of MIME types.

Documentation: https://developers.google.com/drive/v3/reference/files/export


import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    CkRest rest = new CkRest();
    boolean success;

    //   Provide a previously obtained OAuth2 access token.
    CkOAuth2 oauth2 = new CkOAuth2();
    oauth2.put_AccessToken("OAUTH2_ACCESS_TOKEN");
    rest.SetAuthOAuth2(oauth2);

    success = rest.Connect("www.googleapis.com",443,true,true);
    if (success != true) {
        System.out.println(rest.lastErrorText());
        return;
        }

    rest.AddQueryParam("mimeType","application/pdf");

    //  First send the HTTP request.
    success = rest.SendReqNoBody("GET","/drive/v3/files/1zvzpTHO1dM9vNKYxpmr4YrX7x_R6qiNGFb8WB8h9wuI/export");
    if (success != true) {
        System.out.println(rest.lastErrorText());
        return;
        }

    //  Read the response header.  If the response status code is success, stream to the file.
    //  Otherwise receive the error response text.
    int statusCode = rest.ReadResponseHeader();
    if (statusCode < 0) {
        System.out.println(rest.lastErrorText());
        return;
        }

    if (statusCode != 200) {
        System.out.println("Received error response code: " + statusCode);
        //  Read the error response body.
        CkStringBuilder sbErrResponse = new CkStringBuilder();
        success = rest.ReadRespSb(sbErrResponse);
        if (success != true) {
            System.out.println(rest.lastErrorText());
            return;
            }

        System.out.println("Error response:" + sbErrResponse.getAsString());
        return;
        }

    //  Stream the response body to the output file.
    CkStream respBodyStream = new CkStream();
    respBodyStream.put_SinkFile("/someDirectoryPath/test.pdf");
    success = rest.ReadRespBodyStream(respBodyStream,true);
    if (success != true) {
        System.out.println(rest.lastErrorText());
        return;
        }

    System.out.println("Example Completed.");
  }
}