gskumar
gskumar

Reputation: 21

Failed to load pdf document in c#

Hi This is my C# code :

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.

Failed to load pdf document in c#

I didn't find where I mistake in code.

Please give me correct code

Thanks.

Upvotes: 1

Views: 16703

Answers (3)

Brian MacKay
Brian MacKay

Reputation: 32037

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:

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!

Try this:

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

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

Upvotes: 0

Bruno Lowagie
Bruno Lowagie

Reputation: 77606

You are not creating a complete PDF file. 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"

A PDF document is finalized when you close it:

document.Close();

The PDF is not complete before you do this.

However, you ask the MemoryStream before you close the document:

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

This means that bytes doesn't contain the complete PDF.

Moreover, you are using HTMLWorker. That class has been abandoned many years ago, please read the intro of the documentation about XML Worker.

It's possible that HTMLWorker implicitly closes the document object (I don't remember, as I said: HTMLWorker is no longer used). 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.

Upvotes: 4

Ponmani Chinnaswamy
Ponmani Chinnaswamy

Reputation: 855

@shivakumar, Please try like this sample and change it for your data.

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

Upvotes: 1

Related Questions