Sivakumar

Sivakumar

  • NA
  • 551
  • 218.6k

Failed to load pdf document in c#

Apr 22 2016 1:43 AM
Hi,
 
I write code for download pdf in my project.
 
This is the 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)
{
//Maximum height is 800 pixels.
float percentage = 0.0f;
percentage = 700 / image.Height;
image.ScalePercent(percentage * 100);
}
else
{
//Maximum width is 600 pixels.
float percentage = 0.0f;
percentage = 140 / image.Width;
image.ScalePercent(percentage * 100);
}
//only happens on the first run!
if (!document.IsOpen())
{
//Open the document for writing
document.Open();
}
document.Add(image);
using (var htmlWorker = new HTMLWorker(document))
{
//HTMLWorker doesn't read a string directly but instead needs a TextReader (which StringReader subclasses)
using (var sr = new StringReader(message))
{
//Parse the HTML
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);
// paragraph.Add(text);
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 download but showing  failed to load Pdf document.
 
Please tell me the where I mistake.
 
Thanks. 

Answers (2)