【问题标题】:Failed to load pdf document in c#无法在 C# 中加载 pdf 文档
【发布时间】:2016-08-15 16:04:12
【问题描述】:

嗨,这是我的 C# 代码:

Byte[] bytes;

int orderID = Convert.ToInt32(e.CommandArgument);

var templateData = ordersBL.GetTemplateDetails(orderID);

using (MemoryStream ms = new MemoryStream())
{

using (Document document = new Document(PageSize.A4, 10, 10, 10, 10))
{
PdfWriter writer = PdfWriter.GetInstance(document, ms);
foreach (var temp in templateData.ToList())
{

string message = temp.Message;
string tempimage = Convert.ToBase64String(temp.logo);
string base64 = tempimage;
byte[] imageBytes = Convert.FromBase64String(base64);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageBytes);
if (image.Height > image.Width)
{
float percentage = 0.0f;
percentage = 700 / image.Height;
image.ScalePercent(percentage * 100);
}
else

{

float percentage = 0.0f;
percentage = 140 / image.Width;
image.ScalePercent(percentage * 100);
}

if (!document.IsOpen())
{

document.Open();
}
document.Add(image);
using (var htmlWorker = new HTMLWorker(document))
{

using (var sr = new StringReader(message))
{


htmlWorker.Parse(sr);
}
}
Paragraph paragraph = new Paragraph();
paragraph.SpacingBefore = 10;
paragraph.SpacingAfter = 10;
paragraph.Alignment = Element.ALIGN_LEFT;
// paragraph.Font = FontFactory.GetFont(FontFactory.HELVETICA, 12f, BaseColor.GREEN);

document.Add(paragraph);
document.NewPage();
}
bytes = ms.ToArray();
document.Close();

}
}
Response.ContentType = "application/pdf";
string pdfName = "User";
Response.AddHeader("Content-Disposition", "attachment; filename=" + pdfName + ".pdf");
Response.Buffer = true;
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
Response.Close();
Response.Flush();
}

PDF已下载,但显示加载pdf文档失败。

在c#中加载pdf文档失败

我没有找到我在代码中出错的地方。

请给我正确的代码

谢谢。

【问题讨论】:

标签: c# asp.net pdf itextsharp


【解决方案1】:

您没有创建完整的 PDF 文件。请看我对问题的回答Trying to get a memory stream from a pdfstamper into a pdfreader but getting: "PDF startxref not found"

当您关闭 PDF 文档时,它就完成了:

document.Close();

在您执行此操作之前PDF 不完整。

但是,您在关闭文档之前询问MemoryStream

bytes = ms.ToArray();
document.Close();

这意味着bytes 不包含完整的 PDF。

此外,您使用的是HTMLWorker。那个班多年前就被废弃了,请看documentation about XML Worker的介绍。

HTMLWorker 可能会隐式关闭 document 对象(我不记得了,正如我所说:HTMLWorker 不再使用)。在这种情况下,将paragraph 对象添加到文档的代码将引发异常,说明文档已关闭并且您不能再添加任何额外内容。

【讨论】:

    【解决方案2】:

    @shivakumar,请尝试喜欢这个示例并根据您的数据进行更改。

    Byte[] bytes = ImageToByteArray(System.Drawing.Image.FromFile(@"D:\Test\Sample1.png"));
             //Converted Image to byte[] 
    
            using (MemoryStream ms = new MemoryStream())
            {
                Document document = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                PdfWriter.GetInstance(document, Response.OutputStream);
                document.Open();     
                byte[] imageBytes = bytes;
                ms.Write(bytes, 0, bytes.Length);
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageBytes);
                if (image.Height > image.Width)
                {
                    float percentage = 0.0f;
                    percentage = 700 / image.Height;
                    image.ScalePercent(percentage * 100);
                }
                else
                {
    
                    float percentage = 0.0f;
                    percentage = 140 / image.Width;
                    image.ScalePercent(percentage * 100);
                }
    
                if (!document.IsOpen())
                {
    
                    document.Open();
                }
                document.Add(image);
                var htmlWorker = new HTMLWorker(document);
                string message="hi";
                using (var sr = new StringReader(message))
                {
    
    
                    htmlWorker.Parse(sr);
                }
    
                bytes = ms.ToArray();
                document.Close();
            }
            Response.ContentType = "application/pdf";
            string pdfName = "User";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + pdfName + ".pdf");
            Response.Buffer = true;
            Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
            Response.BinaryWrite(bytes);
            Response.End();
            Response.Close();
            Response.Flush();
    

    【讨论】:

      【解决方案3】:

      如果您有一个包含 PDF 的有效流,并且您从 Chrome 收到“加载 PDF 文档失败”,这肯定会导致问题:

      Response.AddHeader("Content-Disposition", "attachment; filename=" + pdfName + ".pdf");
      

      'attachment' 专门告诉浏览器在浏览器中显示这个文件,而是直接发送文件。我花了几个小时才了解到 Chrome 的 PDF 查看器在这种情况下会卡住,这可能是设计使然!

      试试这个:

      Response.AddHeader("Content-Disposition", "inline; filename=" + pdfName + ".pdf");
      

      更多:Content-Disposition:What are the differences between "inline" and "attachment"?

      【讨论】:

        猜你喜欢
        • 2018-05-24
        • 2018-01-10
        • 1970-01-01
        • 2016-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-14
        相关资源
        最近更新 更多