Delphi ActiveX 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: TChilkatRest;
success: Integer;
oauth2: TChilkatOAuth2;
statusCode: Integer;
sbErrResponse: TChilkatStringBuilder;
respBodyStream: TChilkatStream;

begin
rest := TChilkatRest.Create(Self);

//   Provide a previously obtained OAuth2 access token.
oauth2 := TChilkatOAuth2.Create(Self);
oauth2.AccessToken := 'OAUTH2_ACCESS_TOKEN';
rest.SetAuthOAuth2(oauth2.ControlInterface);

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

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

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

//  Read the response header.  If the response status code is success, stream to the file.
//  Otherwise receive the error response text.
statusCode := rest.ReadResponseHeader();
if (statusCode < 0) then
  begin
    Memo1.Lines.Add(rest.LastErrorText);
    Exit;
  end;
if (statusCode <> 200) then
  begin
    Memo1.Lines.Add('Received error response code: ' + IntToStr(statusCode));
    //  Read the error response body.
    sbErrResponse := TChilkatStringBuilder.Create(Self);
    success := rest.ReadRespSb(sbErrResponse.ControlInterface);
    if (success <> 1) then
      begin
        Memo1.Lines.Add(rest.LastErrorText);
        Exit;
      end;
    Memo1.Lines.Add('Error response:' + sbErrResponse.GetAsString());
    Exit;
  end;
//  Stream the response body to the output file.
respBodyStream := TChilkatStream.Create(Self);
respBodyStream.SinkFile := '/someDirectoryPath/test.pdf';
success := rest.ReadRespBodyStream(respBodyStream.ControlInterface,1);
if (success <> 1) then
  begin
    Memo1.Lines.Add(rest.LastErrorText);
    Exit;
  end;

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