export to pdf not working in asp.net - c#

can any one help me export the pdftable in pdf . my file is not getting exported to pdf and it also not showing any error i have written a code below code for export to pdf but it is not working properly i have use itextsharp dll for writing the code
her is my code
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
Paragraph p, p1, p2;
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
string imagepath = GetImageUrl("images");
iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(imagepath + "/Logo.png");
p2 = new Paragraph();
p2.Add(gif);
p2.Alignment = Element.ALIGN_LEFT;
pdfDoc.Add(p2);
p1 = new Paragraph(new Phrase(new Chunk(" INVOICE ", FontFactory.GetFont("verdana", 15, BaseColor.GRAY))));
p1.Alignment = Element.ALIGN_CENTER;
pdfDoc.Add(p1);
p = new Paragraph(new Chunk("\n"));
pdfDoc.Add(p);
pdfDoc.Add(table1);
pdfDoc.Add(table);
string str = "This is a computer generated invoice. Please contact MSWindowsCare billing for more information at billing#mswindowscare.com";
p = new Paragraph(str, FontFactory.GetFont("verdana", 7, BaseColor.GRAY));
p.Alignment = Element.ALIGN_CENTER;
pdfDoc.Add(p);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + "filename=SalesInvoice.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
HttpContext.Current.ApplicationInstance.CompleteRequest();

Do some debugging. First thing I would do is write out the pdfDoc to a file and check whether this actually is correct pdf or empty or something.
Basically replace:
Response.Write(pdfDoc);
with something putting it to the dile system then try to open it.
And then take it from there. THis helps you nail down the issue.
Never used PdfWriter but I think the line up may not write the bytes of the pdf as you think it does. The result would be an obvious error on the client, not on the server.

Related

c# save pdf file to specific path

I am using Visual Studio 2012. I am converting an aspx page into a PDF file.
It works fine...
the code is like this
string attachment = "attachment; filename=" + FileName + ".pdf";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/pdf";
StringWriter s_tw = new StringWriter();
HtmlTextWriter h_textw = new HtmlTextWriter(s_tw);
h_textw.AddStyleAttribute("font-size", "7pt");
h_textw.AddStyleAttribute("color", "Black");
pnlPrincipal.RenderControl(h_textw);//Name of the Panel
Document doc = new Document();
doc = new Document(PageSize.A4, 5, 5, 15, 5);
FontFactory.GetFont("Verdana", 80, iTextSharp.text.BaseColor.RED);
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
StringReader s_tr = new StringReader(s_tw.ToString());
HTMLWorker html_worker = new HTMLWorker(doc);
html_worker.Parse(s_tr);
doc.Close();
Response.Write( doc);
The problem I am facing is that it is saved in c:/Users/Download folder.
I want to save the file in an specific folder.
Where can I specified that?
Thanks
You can write a document with
string folder = #"C:\Temp\";
string fileName = "mydocument.txt";
string fullPath = folder + fileName;
string data = "My string to write in a document";
File.WriteAllLines(fullPath, data);
// Read & print in console
string readText = File.ReadAllText(fullPath);
Console.WriteLine(readText);
Finally I found the way...
Instead of using Response I have to use FileStream
System.IO.FileStream fs = new FileStream(Server.MapPath("PDFDIR") + "\\" + otd.NumeroOTD.ToString() + ".pdf", FileMode.Create);
StringWriter s_tw = new StringWriter();
HtmlTextWriter h_textw = new HtmlTextWriter(s_tw);
h_textw.AddStyleAttribute("font-size", "7pt");
h_textw.AddStyleAttribute("color", "Black");
pnlPrincipal.RenderControl(h_textw);//Name of the Panel
// Create an instance of the document class which represents the PDF document itself.
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
// Create an instance to the PDF file by creating an instance of the PDF
// Writer class using the document and the filestrem in the constructor.
FontFactory.GetFont("Verdana", 80, iTextSharp.text.BaseColor.RED);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.AddCreator("Sample application using iTextSharp");
document.AddSubject("Document subject - Describing the steps creating a PDF document");
document.AddTitle("The document title - PDF creation using iTextSharp");
// Open the document to enable you to write to the document
document.Open();
// Add a simple and wellknown phrase to the document in a flow layout manner
// document.Add(new Paragraph("Hello World!"));
StringReader s_tr = new StringReader(s_tw.ToString());
HTMLWorker html_worker = new HTMLWorker(document);
html_worker.Parse(s_tr);
// Close the document
document.Close();
// Close the writer instance
writer.Close();
// Always close open filehandles explicity
fs.Close();

MVC - Convert PdfPTable to Html

I am working on downloading a PDF document. I have used PdfPTable to create a table. Below is my shortened code.
var document = new Document(PageSize.A4, 50, 50, 25, 25);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
document.Open();
PdfPTable table = new PdfPTable(2);
table.WidthPercentage = 80;
PdfPCell cell = new PdfPCell(new Phrase("Description", fntTableFontBold));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
table.AddCell(cell);
......
document.Add(table);
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.pdf", "Journal"));
Response.BinaryWrite(output.ToArray());
All is working fine. Above code straight away downloads the PDF in browser.
Now i want to add Preview functionality, If the User clicks on Preview, He should see the HTML output.
How to convert this above code to show as HTML? There is lots of code & queries which are used for creating PdfPTable.
Creating a pdf using iTextSharp involves a lot of coding. You cannot render a pdf as HTML code (that I know of), but you can create an HTML first, convert it into a pdf and then render the pdf as stream to a browser. If you are creating the HTML first then you can use the html for preview.
Here is a block of code that I once wrote to convert html to pdf.
protected void ConvertHTMLToPDF(String HTMLCode, String fileName)
{
//Create PDF document
iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4);
PdfWriter.GetInstance(doc, new FileStream(HttpContext.Current.Server.MapPath("~") + "/Resources/Temp/" + fileName, FileMode.Create));
doc.Open();
foreach (IElement element in HTMLWorker.ParseToList(new StringReader(HTMLCode), null))
{
doc.Add(element);
}
doc.Close();
//Response.End();
}

Export div content to pdf format

I used the following code to export div content to pdf format using itextsharp
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
Panel1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
// Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
Document pdfDoc = new Document(new Rectangle(1000f, 1000f));
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
it shows the following error
Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\Images\logo.png'.`
if i hide the logo in desin then it exported to pdf but the alignment are missing. how to correct it.The page i need to export is follows
In order to export the content to any pdf file, you need to follow the basic conventions of pdf file, those are given in the appendix G of the following pdf reference,
http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
Firstly install class in Nuget console: Install-Package itextsharp.xmlworker
Then add namespace: using iTextSharp.tool.xml;
Response.ContentType = "application/pdf";
//string pdf;
// pdf = Convert.ToInt32(hidTablEmpCode.ToString()).ToString() + ".Pdf";
Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
//Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
// var example_html = #"<p>This is <span class="" headline="" style="">some</span> sample text<span style="">!!!</span></p>";
StringReader sr = new StringReader(lblMessageDetail.Text);
Document pdfDoc = new Document(PageSize.A4, 50f, 50f, 50f, 50f);
var writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
for (int i = 0; i < 5; i++)
{
string imageFilePath2 = Server.MapPath(".") + "/images/GraphicNew.jpg";
iTextSharp.text.Image jpg3 = iTextSharp.text.Image.GetInstance(imageFilePath2);
jpg3.Alignment = iTextSharp.text.Image.UNDERLYING;
jpg3.ScaleToFit(3530, 835);
jpg3.SetAbsolutePosition(0, 0);
pdfDoc.Add(jpg3);
}
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
string imageFilePath = Server.MapPath(".") + "/Bimages/ns5.png";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
GetEmp();
string imageURLS = Server.MapPath("~/Emp/Document/") + hidTablEmpCode.Value + "/" + hidSign.Value.ToString();
iTextSharp.text.Image jpg2 = iTextSharp.text.Image.GetInstance(imageURLS);
jpg2.ScaleToFit(100, 50);
jpg2.SetAbsolutePosition(370, 530);
jpg2.Alignment = Element.ALIGN_LEFT;
pdfDoc.Add(jpg2);
jpg.Alignment = iTextSharp.text.Image.ALIGN_LEFT;
jpg.ScaleToFit(100, 50);
jpg.SetAbsolutePosition(50, 735);
pdfDoc.Add(jpg);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();

Itextsharp pdf GridView Positioning

I am working with asp.net application and in which i am using itexsharp to generate pdf file. I need to export my gridview to pdf and the problem is after generating pdf the gridview is always postioning at the top of the page. My requriement is i need the gridview at the centre of the page and at the top i will have some text entered throught the textbox from the front end..
Please help me to find solution for this and Thanks in Advance
here is the code for my button click:
Here is my code for the button click to generate PDF:
{
string name = TextBox1.Text;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Chunk c = new Chunk("Export GridView to PDF Using iTextSharp \n",FontFactory.GetFont("Verdana", 15));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
string s = sw.ToString();
GridView1.AllowPaging = false;
BindDDL();
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
var wri = PdfWriter.GetInstance(pdfDoc, new FileStream("D:/xyz" + ".pdf", FileMode.Create));
pdfDoc.Open();
htmlparser.Parse(sr);
string contents = File.ReadAllText(Server.MapPath("~/bill.htm"));
contents = contents.Replace("[CNAME]", name);
var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);
foreach (var htmlElement in parsedHtmlElements)
pdfDoc.Add(htmlElement as IElement);
pdfDoc.Add(p);
System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(new StringReader(s));
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
set gridview property as follows to position it in center
<asp:GridView ID="GridView1" RowStyle HorizontalAlign="Center" ...>
m not gettin wat you exactly need...
but place your txtbox and gridview inside the table

Showing Nothing in created PDF using iTextSharp?

i am trying to export my HTML page to PDF using iTextSharp lib. firstly i am trying to print table which is in my Aspx page.PDF is created successfully but there nothing in PDF.
i am using this code below :
protected void btnExportToPdf_Click(object sender, EventArgs e)
{
btnExportToPdf.Visible = false;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
exportTable.RenderControl(hw);
//this.Page.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End(); }
Now I'm not too seasoned, but the problem to me looks like you are never actually writing the strings to the file. I see a few different string objects you initialize, and I see you adding the HTML to it, but I never see you actually write them to the PDF. This is my usual process for parsing HTML to PDF, maybe you can look at it, and see what you are missing.
System.Text.StringBuilder store = new System.Text.StringBuilder();
string line;
while ((line = htmlReader.ReadLine()) != null)
{
store.Append(line + Environment.NewLine);
}
string html = store.ToString();
FileStream stream = new FileStream(newFileName, FileMode.Create, FileAccess.Write);
Document document = new Document(PageSize.LETTER, 15, 15, 35, 25);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
document.Open();
System.Collections.Generic.List<IElement> htmlarraylist = new List<IElement>(HTMLWorker.ParseToList(new StringReader(html), new StyleSheet()));
foreach (IElement element in htmlarraylist)
{
document.Add(element);
}
document.Close();
That was what jumped out to me at least, was the fact that it doesn't look like you actually write the generated text to the PDF. I hope this helps.

Categories

Resources