Tcl 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



load ./chilkat.dll

set rest [new_CkRest]

#   Provide a previously obtained OAuth2 access token.
set oauth2 [new_CkOAuth2]

CkOAuth2_put_AccessToken $oauth2 "OAUTH2_ACCESS_TOKEN"
CkRest_SetAuthOAuth2 $rest $oauth2

set success [CkRest_Connect $rest "www.googleapis.com" 443 1 1]
if {[expr $success != 1]} then {
    puts [CkRest_lastErrorText $rest]
    delete_CkRest $rest
    delete_CkOAuth2 $oauth2
    exit
}

CkRest_AddQueryParam $rest "mimeType" "application/pdf"

#  First send the HTTP request.
set success [CkRest_SendReqNoBody $rest "GET" "/drive/v3/files/1zvzpTHO1dM9vNKYxpmr4YrX7x_R6qiNGFb8WB8h9wuI/export"]
if {[expr $success != 1]} then {
    puts [CkRest_lastErrorText $rest]
    delete_CkRest $rest
    delete_CkOAuth2 $oauth2
    exit
}

#  Read the response header.  If the response status code is success, stream to the file.
#  Otherwise receive the error response text.
set statusCode [CkRest_ReadResponseHeader $rest]
if {[expr $statusCode < 0]} then {
    puts [CkRest_lastErrorText $rest]
    delete_CkRest $rest
    delete_CkOAuth2 $oauth2
    exit
}

if {[expr $statusCode != 200]} then {
    puts "Received error response code: $statusCode"
    #  Read the error response body.
    set sbErrResponse [new_CkStringBuilder]

    set success [CkRest_ReadRespSb $rest $sbErrResponse]
    if {[expr $success != 1]} then {
        puts [CkRest_lastErrorText $rest]
        delete_CkRest $rest
        delete_CkOAuth2 $oauth2
        delete_CkStringBuilder $sbErrResponse
        exit
    }

    puts "Error response:[CkStringBuilder_getAsString $sbErrResponse]"
    delete_CkRest $rest
    delete_CkOAuth2 $oauth2
    delete_CkStringBuilder $sbErrResponse
    exit
}

#  Stream the response body to the output file.
set respBodyStream [new_CkStream]

CkStream_put_SinkFile $respBodyStream "/someDirectoryPath/test.pdf"
set success [CkRest_ReadRespBodyStream $rest $respBodyStream 1]
if {[expr $success != 1]} then {
    puts [CkRest_lastErrorText $rest]
    delete_CkRest $rest
    delete_CkOAuth2 $oauth2
    delete_CkStringBuilder $sbErrResponse
    delete_CkStream $respBodyStream
    exit
}

puts "Example Completed."

delete_CkRest $rest
delete_CkOAuth2 $oauth2
delete_CkStringBuilder $sbErrResponse
delete_CkStream $respBodyStream