Swift 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



func chilkatTest() {
    let rest = CkoRest()
    var success: Bool

    //   Provide a previously obtained OAuth2 access token.
    let oauth2 = CkoOAuth2()
    oauth2.AccessToken = "OAUTH2_ACCESS_TOKEN"
    rest.SetAuthOAuth2(oauth2)

    success = rest.Connect("www.googleapis.com", port: 443, tls: true, autoReconnect: true)
    if success != true {
        print("\(rest.LastErrorText)")
        return
    }

    rest.AddQueryParam("mimeType", value: "application/pdf")

    //  First send the HTTP request.
    success = rest.SendReqNoBody("GET", uriPath: "/drive/v3/files/1zvzpTHO1dM9vNKYxpmr4YrX7x_R6qiNGFb8WB8h9wuI/export")
    if success != true {
        print("\(rest.LastErrorText)")
        return
    }

    //  Read the response header.  If the response status code is success, stream to the file.
    //  Otherwise receive the error response text.
    var statusCode: Int = rest.ReadResponseHeader().integerValue
    if statusCode < 0 {
        print("\(rest.LastErrorText)")
        return
    }

    if statusCode != 200 {
        print("Received error response code: \(statusCode)")
        //  Read the error response body.
        let sbErrResponse = CkoStringBuilder()
        success = rest.ReadRespSb(sbErrResponse)
        if success != true {
            print("\(rest.LastErrorText)")
            return
        }

        print("Error response:\(sbErrResponse.GetAsString())")
        return
    }

    //  Stream the response body to the output file.
    let respBodyStream = CkoStream()
    respBodyStream.SinkFile = "/someDirectoryPath/test.pdf"
    success = rest.ReadRespBodyStream(respBodyStream, autoSetStreamCharset: true)
    if success != true {
        print("\(rest.LastErrorText)")
        return
    }

    print("Example Completed.")

}