简体   繁体   English

无法在C#中加载pdf文档

[英]Failed to load pdf document in c#

Hi This is my C# code : 嗨,这是我的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 is downloaded but it shows failed to load pdf document. Pdf已下载,但显示无法加载pdf文档。

Failed to load pdf document in c# 无法在C#中加载pdf文档

I didn't find where I mistake in code. 我没有发现我在代码中出错的地方。

Please give me correct code 请给我正确的密码

Thanks. 谢谢。

You are not creating a complete PDF file. 您没有创建完整的PDF文件。 Please take a look at my answer to the question Trying to get a memory stream from a pdfstamper into a pdfreader but getting: "PDF startxref not found" 请看一下我对以下问题的回答: 试图将内存流从pdfstamper放入pdfreader,但得到:“未找到PDF startxref”

A PDF document is finalized when you close it: 当您关闭PDF文档时,它会完成:

document.Close();

The PDF is not complete before you do this. 执行此操作之前 ,PDF不完整。

However, you ask the MemoryStream before you close the document: 但是, 关闭文档之前 ,请询问MemoryStream

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

This means that bytes doesn't contain the complete PDF. 这意味着bytes不包含完整的PDF。

Moreover, you are using HTMLWorker . 此外,您正在使用HTMLWorker That class has been abandoned many years ago, please read the intro of the documentation about XML Worker . 该类已经被放弃很多年了,请阅读有关XML Worker文档的介绍。

It's possible that HTMLWorker implicitly closes the document object (I don't remember, as I said: HTMLWorker is no longer used). HTMLWorker可能会隐式关闭document对象(我不记得了,正如我所说的:不再使用HTMLWorker )。 In that case, the code that adds the paragraph object to the document will throw an exception saying that the document is closed and that you can no longer add any extra content. 在这种情况下,将paragraph对象添加到文档的代码将引发异常,表明文档已关闭,并且您无法再添加任何其他内容。

@shivakumar, Please try like this sample and change it for your data. @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();

If you have a valid stream containing a PDF, and you're getting "Failed to Load PDF Document" from Chrome, this will definitely cause a problem: 如果您有包含PDF的有效流,并且从Chrome浏览器获取“无法加载PDF文档”,则肯定会导致问题:

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

'attachment' specifically tells the browser not display this document in-browser, but rather to send the file directly. “附件”明确告诉浏览器不要在浏览器中显示此文档,而是直接发送文件。 And I just spent a few hours learning that Chrome's PDF viewer chokes in that situation, probably by design! 而且我花了几个小时来了解Chrome的PDF查看器在这种情况下可能会被设计阻塞!

Try this: 尝试这个:

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

More: Content-Disposition:What are the differences between "inline" and "attachment"? 更多: 内容配置:“内联”和“附件”有什么区别?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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