【问题标题】:How to download a PDF document from Google Docs and display it in the browser?如何从 Google Docs 下载 PDF 文档并在浏览器中显示?
【发布时间】:2012-03-05 18:30:17
【问题描述】:

使用下面显示的代码,PDF 文档似乎不是有效的 PDF 格式。浏览器显示消息“加载 PDF 文档失败。”如果我将下载保存到文件并在 Adob​​e Reader 中打开,它会显示消息“打开时出错这份文件。

我可以在 Google 文档中手动打开和下载文档。因此,它是一个有效的 PDF 文档。

我正在使用 C#、ASP.NET 和 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( );
        }

更新:已解决。代码如下。

【问题讨论】:

    标签: asp.net google-docs


    【解决方案1】:

    您可能会从以下帖子中获得一些想法: code to download PDF file in C#

    它使用了一个额外的标头:content-disposition。

    【讨论】:

    • 有一个 Content-Disposition 标头。我已成功使用“响应”代码显示本地存储的 PDF 文件。
    【解决方案2】:

    问题是文件内容是作为文本读入的,它需要是字节[]。

    更新代码:

            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( );
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-07
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 2022-06-28
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多