Tuesday, May 12, 2009

Working with the Google Documents API to download PDF in C#

I got caught up for a bit trying to use Google.GData.Documents.DocumentsFeed and Google.GData.Documents.DocumentEntry to download a Google Document as a PDF. Then I found the Google.Documents namespace and the problem became trivially easy.

using System;
using System.IO;
using System.Net;
using Google.Documents;
using Google.GData.Client;

namespace Google
{
    class Program
    {
        private static string applicationName = "Testing";

        static void Main(string[] args)
        {
            GDataCredentials credentials = new GDataCredentials("username@gmail.com", "password");
            RequestSettings settings = new RequestSettings(applicationName, credentials);
            settings.AutoPaging = true;
            settings.PageSize = 100;
            DocumentsRequest documentsRequest = new DocumentsRequest(settings);
            Feed documentFeed = documentsRequest.GetDocuments();
            foreach (Document document in documentFeed.Entries)
            {
                Document.DownloadType type = Document.DownloadType.pdf;

                Stream downloadStream = documentsRequest.Download(document, type);

                Stream fileSaveStream = new FileStream(string.Format(@"C:\Temp\{0}.pdf", document.Title), FileMode.CreateNew);

                if (fileSaveStream != null)
                {
                    int nBytes = 2048;
                    int count = 0;
                    Byte[] arr = new Byte[nBytes];

                    do
                    {
                        count = downloadStream.Read(arr, 0, nBytes);
                        fileSaveStream.Write(arr, 0, count);

                    } while (count > 0);
                    fileSaveStream.Flush();
                    fileSaveStream.Close();
                }
                downloadStream.Close();
            }

        }
    }
}