简体   繁体   中英

Error while opening PDF

I am getting " Failed to load PDF document " in Chrome and " The file is damaged and could not be repaired " in IE for few files.

The code is as below:

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

And in Render class:

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

and in DecodeLine is as below:

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

Below is what it throws in Firefox:

在此处输入图片说明

And on Adobe reader:

在此处输入图片说明

If your PDF is stored in a physical file, you don't need to use intermediary streams at all, just use the TransmitFile method which also has the benefit of not using .NET memory (in most cases):

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

Instead of working with the META data in the SGML, is it possible to render it directly as a PDF? It is so easy to convert HTML directly to PDF instead of trying to pull random data and hoping that it still works. Can you show us whats in the SGML file? Might help everyone get into your mindset of what you are trying to achieve.

I had the same problem with images, and after a while I got it working by changing the encoding (in your case Encoding.UTF8 ) to ASCII ( Encoding.ASCII ). Try it out. I do not guarantee success, but it is definitely worth a try.

Another reason it could help is that you apparently use two different encodings anyway, in the Render class you wrote System.Text.ASCIIEncoding.ASCII.GetString(buffer) while later using the UTF-8 encoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM