Itextsharp refreshing page after creating PDF - asp.net

I have a aspx page on which i have two buttons(MakePdf and View) on view button a gridview is shown on the page and with makePDF we can download PDF.
But what i need is view button code should be executing after downloading the PDF.
Please provide me a solution.
Document document = new Document(PageSize.A4, 0, 0, 15, 12);
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
PdfPCell cell;
Phrase phrase;
PdfPTable table;
table = new PdfPTable(1);
table.SetWidths(new int[] { 10 });
table.SpacingBefore = 5f;
phrase = new Phrase();
phrase.Add(new Chunk("HSE Monthly Report ", TOPTextFont));
cell = new PdfPCell(new Phrase(phrase));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Border = 0;
table.AddCell(cell);
table.CompleteRow();
document.Add(table);
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
Response.End();

Related

Adding Header Page in Itextsharp when the value is from gridview

I want to make convert gridview to pdf, the code is run well, but iam confused how to make headerpage (not header column) on it, ill try to use stringbuilder but when i tried the gridview is not view in pdf, i also tried other way but still dont know how to make it works,
maybe u can teach me how to make it works?
in this code i tried to use chunk, but the chunk isnot show :(
protected void btnConvertPDF_Click(object sender, EventArgs e)
{
gridconvertPDF.AllowPaging = false;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=ClientList.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
HtmlForm hf = new HtmlForm();
gridconvertPDF.Parent.Controls.Add(hf);
hf.Attributes["runat"] = "server";
hf.Controls.Add(gridconvertPDF);
hf.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
pdfDoc.Open();
Chunk c = new Chunk
("PEMINJAMAN INVENTARIS \n",
FontFactory.GetFont("Verdana", 25));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
Chunk chunk1 = new Chunk
("Rizki Asriningtyas \n",
FontFactory.GetFont("Verdana", 8));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_RIGHT;
p1.Add(chunk1);
pdfDoc.Add(p);
pdfDoc.Add(p1);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();}
my fault is make pdfwriter after add all the header content to pdf, here is the right code
protected void btnConvertPDF_Click(object sender, EventArgs e)
{
gridconvertPDF.AllowPaging = false;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=ClientList.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
HtmlForm hf = new HtmlForm();
gridconvertPDF.Parent.Controls.Add(hf);
hf.Attributes["runat"] = "server";
hf.Controls.Add(gridconvertPDF);
hf.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
Chunk c = new Chunk
("PEMINJAMAN INVENTARIS \n",
FontFactory.GetFont("Verdana", 25));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
Chunk chunk1 = new Chunk
("Rizki Asriningtyas \n",
FontFactory.GetFont("Verdana", 8));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_RIGHT;
p1.Add(chunk1);
pdfDoc.Add(p);
pdfDoc.Add(p1);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();}

TextBox controls are not Working with Export To PDF(iTextSharp)

I have an HTML form, which contains lables and textboxes.
After filling this form, it is exported to PDF.
All the label Texts are exported. But the textbox text is not exported to PDF.
Code
protected void btnExportPDF_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=DecForm.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
this.divToPdf.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10, 10, 2, 10);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
Why are the textbox text not exported through to PDF?
I think that when you're rendering divToPDF you are getting a fresh cut of the html and it does not have the values there were populated on the page. You may want to look at using the divToPDF is you'll want to look at accessing the InnerHtml or OuterHtml property and use that.
Try this.
List<IElement> elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(htmlString), null);
//htmlString is your form html
foreach (IElement el in elements)
{
pdfDoc.add(el);
}

aspx to pdf using itextSharp 5.3.0

I am using this dll iTextSharp 5.3.0 to make a pdf file .
Is there a way to convert full .aspx page in pdf ? My page has grids and server side code .
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
createPDF(Server.MapPath("Default.aspx"));
}
private void createPDF(string html)
{
TextReader reader = new StringReader(html);
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c://test.pdf", FileMode.Create));
HTMLWorker worker = new HTMLWorker(document);
document.Open();
worker.StartDocument();
List<IElement> p = HTMLWorker.ParseToList(new StreamReader(html), new StyleSheet());
for (int k = 0; k < p.Count; k++)
{
document.Add((IElement)p[k]);
}
worker.EndDocument();
worker.Close();
document.Close();
}
It's working but the file test.pdf is just plain text. The html isn't well interpreted, my grids are missing and my server side values (the values from the grids) are also missing .
I also tried the codes from here:
http://forums.asp.net/t/1199774.aspx
and here:
Problem with HTMLParser in Itextsharp
Thanks in advance!
This is my honest advice! Don't waste your time on the HTMLWorker.ParseToList. It has a very elementary HTML parser.
Try this packge and you will never look back!
https://github.com/pruiz/WkHtmlToXSharp
ITextSharp only renders inline css, it is giving problem while adding CSS files.
System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=BookingDetails.pdf");
System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
this.CreateBookingMainDiv.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(new Rectangle(922,1296),7f,7f,7f,0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
//HtmlPipeline
CssAppliers ca = new CssAppliersImpl();
//ICssFile cfile = new CssFileProcessor();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(ca);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
//CSS stuff
//var cssResolver = new StyleAttrCSSResolver();
//var DamcoCss = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath("~/css/damco.css"), FileMode.Open));
ICssFile cfile = new CssFileImpl();
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
//String DamcoCss = HttpContext.Current.Server.MapPath("~/css/damco.css");
//String BootStrapCss = HttpContext.Current.Server.MapPath("~/css/bootstrap.css");
//String BootStrapCssTheme = HttpContext.Current.Server.MapPath("~/css/bootstrap-theme.css");
//Add the external CSS file
//cssResolver.AddCssFile(DamcoCss, true);
//cssResolver.AddCssFile(BootStrapCss, true);
//cssResolver.AddCssFile(BootStrapCssTheme, true);
//Pipeline
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, writer)));
//XMLWorker
XMLWorker worker = new XMLWorker(pipeline, true);
//and...we parse
XMLParser parser = new XMLParser(true, worker);
//parser.AddListener(worker);
parser.Parse(sr);
parser.Flush();
pdfDoc.Close();
System.Web.HttpContext.Current.Response.Write(pdfDoc);
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
//System.Web.HttpContext.Current.Response.End();
Use XMLWorker instead of HTMLWorker. works like charm.

Merging 2 gridviews into one generated PDF file using iTextSharp

I'm using 2 gridviews. The first one has paging enabled, and the number of rows allowed per page is one. The second gridview takes values from the first row as time range, and everytime I change the page on gridview1 the second GV changes it's content automatically based on GV1's values.
Previously, I was able to generate a PDF file using iTextSharp with only one gridview and no paging enabled. But now I'm struggling first of all with the paging enabled, and second with merging both gridviews into one pdf file.
Anybody know how can I do that?
Thanks in advance.
EDIT: This is the code I use to generate a PDF file from a gridview using iTextSharp.
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
gvReportes.AllowPaging = false;
gvReportes.HeaderRow.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
gvReportes.HeaderRow.Style.Add("font-size", "7.20px");
gvReportes.HeaderRow.Style.Add("color", "#284775");
gvReportes.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
gvReportes.Style.Add("font-size", "6px");
gvReportes.RenderControl(htextw);
Document document = new Document();
string path = "path.pdf";
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
document.Open();
StringReader str = new StringReader(stw.ToString());
HTMLWorker htmlworker = new HTMLWorker(document);
htmlworker.Parse(str);
Response.Write(document);
document.Close();
And this is how the gridviews are displayed, as you can see the values "Salida" and "Llegada" on GV1 work as a time range to display data on GV2.
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear(); //this clears the Response of any headers or previous output
Response.Buffer = true; //ma
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=injoin.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}

iTextSharp appending table to document in memory stream after PDFStamper has been used

Hi I am trying to add a table to a pdf after I have used the stamper.
// CREATE MEMORY STRING
MemoryStream ms = new MemoryStream();
string formFile = Server.MapPath("testImg.pdf");
PdfReader reader = new PdfReader(formFile);
PdfStamper outStamper = new PdfStamper(reader, ms);
AcroFields fields = outStamper.AcroFields;
// UPDATE THE FORM FIELDS
fields.SetField("Text1", "John Smith");
fields.SetField("Text2", "1234567890");
fields.SetField("Text3", "1234567890");
//ADD LOGO
iTextSharp.text.Image headerlogo = iTextSharp.text.Image.GetInstance(Server.MapPath("logo.jpg"));
headerlogo.ScaleToFit(140, 399);
headerlogo.Alignment = iTextSharp.text.Image.UNDERLYING;
headerlogo.SetAbsolutePosition(200, 500);
int pageCount = reader.NumberOfPages;
PdfContentByte body = outStamper.GetOverContent(pageCount);
body.AddImage(headerlogo);
outStamper.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=test");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
I want to be able to append the document with a table.
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));
cell.Colspan = 3;
cell.BorderWidth = 5;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
table.AddCell("Col 1 Row 1");
table.AddCell("Col 2 Row 1");
table.AddCell("Col 3 Row 1");
table.AddCell("Col 1 Row 2");
table.AddCell("Col 2 Row 2");
table.AddCell("Col 3 Row 2");
document.Add(table);
I am having trouble with defining the document to add the table to. Please can someone advise how I would add the table to the PDF in the Memory Stream.
Any help would be greatly appreciated.
Alex
Not sure how you have the two pieces working together but here is how I've done it for my application.
Basically i keep the stamping separate from adding structured content and then merging the results into one big pdf. You could try and do all of it together in one big step using table.WriteSelectedRows (which takes a PdfContentByte as one of its arguments) but the time that i have to spend with manual layouts, tends to outweigh the benefit of having it all done in one step (besides the fact that it becomes one huge method which is hard to maintain / reuse)
For clarification & testing purpose, I've used FileStream but of course, the same works fine with MemoryStream and reuse streams should you end up creating one monolithic function in your development code.
Here is my test application that I used to confirm the code and run your scenario:
Steps:
Create Test2.pdf (stamped contents
of original source) from Test.pdf
(our original source)
Create Test3.pdf (containing all our content to be appended at the end)
Open Test2.pdf & Test3.pdf and merge them into Test4.pdf final stream
Note: I haven't used image stamping code and you may have to adjust using on Document in first section if PdfStamper closes the underlying Document as well (can't recall if it does from top of my head but it will throw a helpful exception in case you need to adjust the using statement)
private static void Main(string[] args)
{
using (FileStream ms = new FileStream("C:\\Test2.pdf", FileMode.Create))
using (FileStream formFile = new FileStream("C:\\Test.pdf", FileMode.Open))
{
PdfReader reader = new PdfReader(formFile);
using (Document document = new Document(reader.GetPageSizeWithRotation(1)))
{
//PdfStamper outStamper = new PdfStamper(reader, ms);
//PdfContentByte body = outStamper.GetOverContent(reader.NumberOfPages);
//document.Open(); //Open document to work with
//AcroFields fields = outStamper.AcroFields;
//// UPDATE THE FORM FIELDS
//fields.SetField("Text1", "John Smith");
//fields.SetField("Text2", "1234567890");
//fields.SetField("Text3", "1234567890");
////ADD LOGO
//iTextSharp.text.Image headerlogo = iTextSharp.text.Image.GetInstance(Server.MapPath("logo.jpg"));
//headerlogo.ScaleToFit(140, 399);
//headerlogo.Alignment = iTextSharp.text.Image.UNDERLYING;
//headerlogo.SetAbsolutePosition(200, 500);
//body.AddImage(headerlogo);
//outStamper.Close();
}
}
using (FileStream ms = new FileStream("C:\\Test3.pdf", FileMode.Create))
using (FileStream formFile = new FileStream("C:\\Test2.pdf", FileMode.Open))
{
PdfReader reader = new PdfReader(formFile);
using (Document document = new Document(reader.GetPageSizeWithRotation(1)))
{
PdfWriter pdfWriter = PdfWriter.GetInstance(document, ms);
document.Open();
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns")) { Colspan = 3, BorderWidth = 5, HorizontalAlignment = 1 };
table.AddCell(cell);
table.AddCell("Col 1 Row 1");
table.AddCell("Col 2 Row 1");
table.AddCell("Col 3 Row 1");
table.AddCell("Col 1 Row 2");
table.AddCell("Col 2 Row 2");
table.AddCell("Col 3 Row 2");
table.CompleteRow(); //Added - table won't add the final row if its cells are incomplete - safe to have it ending a table
document.Add(table);
}
}
using (FileStream ms = new FileStream("C:\\Test4.pdf", FileMode.Create))
using (FileStream stampedfile = new FileStream("C:\\Test2.pdf", FileMode.Open))
using (FileStream appendfile = new FileStream("C:\\Test3.pdf", FileMode.Open))
{
PdfReader stampedContentReader = new PdfReader(stampedfile);
PdfReader appendContentReader = new PdfReader(appendfile);
using (Document document = new Document(stampedContentReader.GetPageSizeWithRotation(1)))
{
PdfCopy pdfCopy = new PdfCopy(document, ms);
document.Open();
for (int i = 1; i <= stampedContentReader.NumberOfPages; i++)
pdfCopy.AddPage(pdfCopy.GetImportedPage(stampedContentReader, i));
for (int i = 1; i <= appendContentReader.NumberOfPages; i++)
pdfCopy.AddPage(pdfCopy.GetImportedPage(appendContentReader, i));
}
}
}
Hope this helps.

Resources