0

Using the code shown below, the PDF document seems not to be a valid PDF format. The browser displays the message, "Failed to load PDF document." If I save the download to a file and open it in Adobe Reader, it gives the message, "There was an error opening this document."

I can open and download the document manually within Google Docs. So, it is a valid PDF document.

I'm using C#, ASP.NET, and Google.Documents.

        // get the document to download
        Feed<Document> feed = request.GetEverything( );
        foreach( Document entry in feed.Entries )
        {
            if( entry.AtomEntry.AlternateUri.ToString( ) == DocumentAltUri )
            {
                document = entry;
                break;
            }
        }

        using( Stream stream = request.Download( document, Document.DownloadType.pdf ) )
        {
            StreamReader reader = new StreamReader( stream );
            string content = reader.ReadToEnd( );
            reader.Close( );

            Response.ClearContent( );
            Response.ContentType = "application/pdf";
            Response.AddHeader( "Content-Length", content.Length.ToString( ) );
            Response.AddHeader( "Content-Disposition", "inline;" );
            Response.Write( content );
            Response.Flush( );
            Response.Close( );
            Response.End( );
        }

UPDATE: Resolved. code shown below.

jim31415
  • 8,588
  • 6
  • 43
  • 64

2 Answers2

0

You might take some ideas from the following post: code to download PDF file in C#

It uses an additional header: content-disposition.

Community
  • 1
  • 1
Lindsay Morsillo
  • 530
  • 6
  • 19
  • There is a Content-Disposition header. I have used the "Response" code successfully to display a PDF file that is stored locally. – jim31415 Mar 05 '12 at 18:43
0

The problem was that the file content was being read in as text, it needs to be Byte[].

Updated code:

        using( Stream stream = request.Download( document, type ) )
        {
            long length = 0;
            Response.ClearContent( );
            Response.ContentType = contentType;

            int nBytes = 2048;
            int count = 0;
            Byte[] arr = new Byte[nBytes];
            do
            {
                length += count = stream.Read( arr, 0, nBytes );
                Response.OutputStream.Write( arr, 0, count );
            } while( count > 0 );

            Response.AddHeader( "Content-Disposition", "inline;filename=" + filename + fileext);
            Response.AddHeader( "Content-Length", length.ToString( ) );
            Response.Flush( );
            Response.Close( );
            Response.End( );
        }
jim31415
  • 8,588
  • 6
  • 43
  • 64