Delphi DLL 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


var
rest: HCkRest;
success: Boolean;
oauth2: HCkOAuth2;
statusCode: Integer;
sbErrResponse: HCkStringBuilder;
respBodyStream: HCkStream;

begin
rest := CkRest_Create();

//   Provide a previously obtained OAuth2 access token.
oauth2 := CkOAuth2_Create();
CkOAuth2_putAccessToken(oauth2,'OAUTH2_ACCESS_TOKEN');
CkRest_SetAuthOAuth2(rest,oauth2);

success := CkRest_Connect(rest,'www.googleapis.com',443,True,True);
if (success <> True) then
  begin
    Memo1.Lines.Add(CkRest__lastErrorText(rest));
    Exit;
  end;

CkRest_AddQueryParam(rest,'mimeType','application/pdf');

//  First send the HTTP request.
success := CkRest_SendReqNoBody(rest,'GET','/drive/v3/files/1zvzpTHO1dM9vNKYxpmr4YrX7x_R6qiNGFb8WB8h9wuI/export');
if (success <> True) then
  begin
    Memo1.Lines.Add(CkRest__lastErrorText(rest));
    Exit;
  end;

//  Read the response header.  If the response status code is success, stream to the file.
//  Otherwise receive the error response text.
statusCode := CkRest_ReadResponseHeader(rest);
if (statusCode < 0) then
  begin
    Memo1.Lines.Add(CkRest__lastErrorText(rest));
    Exit;
  end;
if (statusCode <> 200) then
  begin
    Memo1.Lines.Add('Received error response code: ' + IntToStr(statusCode));
    //  Read the error response body.
    sbErrResponse := CkStringBuilder_Create();
    success := CkRest_ReadRespSb(rest,sbErrResponse);
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkRest__lastErrorText(rest));
        Exit;
      end;
    Memo1.Lines.Add('Error response:' + CkStringBuilder__getAsString(sbErrResponse));
    Exit;
  end;
//  Stream the response body to the output file.
respBodyStream := CkStream_Create();
CkStream_putSinkFile(respBodyStream,'/someDirectoryPath/test.pdf');
success := CkRest_ReadRespBodyStream(rest,respBodyStream,True);
if (success <> True) then
  begin
    Memo1.Lines.Add(CkRest__lastErrorText(rest));
    Exit;
  end;

Memo1.Lines.Add('Example Completed.');

CkRest_Dispose(rest);
CkOAuth2_Dispose(oauth2);
    CkStringBuilder_Dispose(sbErrResponse);
CkStream_Dispose(respBodyStream);