I have a user control which has a panel used to display the information which I print when needed. I have a grid view in which I get search result It has a link button clicking on which I want to open a pdf of that panel in the above one.
2 Answers
I have implemented this, and I hope someone else can do it as well. I have listed my code below.
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
Import the above DLL
string attachment = "attachment; filename=" + "File Name" + ".pdf";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/pdf";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
htextw.AddStyleAttribute("font-size", "7pt");
htextw.AddStyleAttribute("color", "Black");
Page pg = new Page();
HtmlForm frm = new HtmlForm();
pg.EnableEventValidation = false;
pg.RenderControl(htextw);
Document document = new Document();
document = new Document(PageSize.A4, 5, 5, 15, 5);
FontFactory.GetFont("Arial", 50, iTextSharp.text.BaseColor.BLUE);
PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
//This is how you can add text in div in a pdf
Chunk c = new Chunk(TextHere + "\n", FontFactory.GetFont("Verdana", 15));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_LEFT;
p.Add(c); p.Add(c1);
// This is how you can generate table and can set proprties
PdfPTable table = new PdfPTable(2);
table.WidthPercentage = 100;
//Bill No and Bill Date
PdfPCell pdfcell1 = new PdfPCell(new Phrase("Text in TAble" + "TExt From Database"));
pdfcell1.Border = iTextSharp.text.Rectangle.BOTTOM_BORDER | iTextSharp.text.Rectangle.TOP_BORDER;
table.AddCell(pdfcell1);
PdfPCell pdfcell = new PdfPCell(new Phrase("Text in TAble" + "TExt From Database"));
pdfcell.Border = iTextSharp.text.Rectangle.BOTTOM_BORDER | iTextSharp.text.Rectangle.TOP_BORDER;
pdfcell.HorizontalAlignment = Element.ALIGN_RIGHT;
table.AddCell(pdfcell);
document.Add(p);
document.Add(table);
document.Add(tablegrid);
StringReader str = new StringReader(stw.ToString());
HTMLWorker htmlworker = new HTMLWorker(document);
htmlworker.Parse(str);
document.Close();
Response.Write(document);
Comments
I think you might run into some trouble on this one. You can't do this all client-side, since JavaScript can not manipulate files (by design). So your options are:
- Full postback
- Ajax call
You could try an Ajax call to a custom handler (.ashx) file whick returns a response with the PDF file. I havn't tried this before, but it might work. How about opening another page with target="_blank" and it will run the server-side code and generate the PDF, while the original page remains where it was?