打开PDF时出错

时间:2016-05-09 11:44:03

标签: c#

我收到" 无法加载PDF文档"在Chrome和" 文件已损坏且无法修复"在IE中只有少量文件。

代码如下:

PDFSteramer:

if (pdf != null)
{
    Response.ContentType = "application/PDF";
    Response.AddHeader("Content-Type", "application/pdf");
    Response.AddHeader("Content-Disposition", "inline");

    pdf.Renderer.Render(pdf, Response.OutputStream);

    Response.Flush();
}

在Render课程中:

using (FileStream fs = new FileStream(this._ParentDocument.Document.FullName, FileMode.Open, FileAccess.Read))
{                                                 
    byte[] buffer = new byte[bufferSize];

    fs.Read(buffer, 0, bufferSize);

    using (StringReader reader = new StringReader(System.Text.ASCIIEncoding.ASCII.GetString(buffer)))
    {                        
        Decoder decoder = new UuDecoder(stream, "");

        string data;

        while ((data = reader.ReadLine()) != null)
        {
            decoder.DecodeLine(data);
        }
    }
}

并在DecodeLine中如下:

public override bool DecodeLine(string line)
{
    try
    {                                                             
        byte[] data = Encoding.UTF8.GetBytes(line);
        //byte[] data = uuDecode(line);

        outStream.Write(data, 0, data.Length);                  
    }
    catch (Exception ex)
    {
    }
    return false;
}    

以下是Firefox中的内容:

enter image description here

在Adobe阅读器上:

enter image description here

3 个答案:

答案 0 :(得分:2)

如果您的PDF存储在物理文件中,您根本不需要使用中间流,只需使用TransmitFile method,它也有不使用.NET内存的好处(在大多数情况下) ):

   Response.AddHeader("Content-Type", "application/pdf");
   Response.AddHeader("Content-Disposition", "inline");
   Response.TransmitFile(your pdf path);

答案 1 :(得分:0)

不是使用SGML中的META数据,是否可以直接将其呈现为PDF?将HTML直接转换为PDF非常容易,而不是试图提取随机数据并希望它仍能正常工作。你能告诉我们SGML文件中的什么内容吗?可能会帮助每个人进入你想要实现的目标。

答案 2 :(得分:0)

我对图像有同样的问题,过了一段时间我通过将编码(在您的情况下为Encoding.UTF8)更改为ASCII(Encoding.ASCII)来使其工作。试试看。我不保证成功,但绝对值得一试。

它可能有帮助的另一个原因是你显然使用了两种不同的编码,在你写的System.Text.ASCIIEncoding.ASCII.GetString(buffer)的Render类中,后来使用UTF-8编码。