Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

itextsharp document has no pages

I am trying to generate PDF from my gridview using the following code:

HtmlForm form = new HtmlForm();

form.Controls.Add(PGGridViewDetail);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string htmlContent = sw.ToString();

htmlContent = Regex.Replace(htmlContent, "</?(a|A).*?>", "");
htmlContent = Regex.Replace(htmlContent, "px", "");

Document document = new Document();

// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
string Path = Server.MapPath("~/Jaram PDF/PDFS/") + "Sample.pdf";
PdfWriter.GetInstance(document, 
                      new FileStream(Path, FileMode.Create));

// step 3: we open the document
document.Open();

// step 4: we add a paragraph to the document
document.Add(new Paragraph(htmlContent.ToString()));
System.Xml.XmlTextReader _xmlr = new 
       System.Xml.XmlTextReader(new StringReader(htmlContent));
_xmlr.WhitespaceHandling = WhitespaceHandling.None;
ITextHandler xmlHandler = new ITextHandler(document);
xmlHandler.Parse(_xmlr);
//HtmlParser.Parse(document, _xmlr);

// step 5: we close the document          
document.Close();

But it is showing the HTML markup of the grid instead of the grid in the newly generated PDF.

If I comment step 4

// step 4: we add a paragraph to the document
document.Add(new Paragraph(htmlContent.ToString()));

then I get a document that has no pages.

Any idea what I am doing wrong?

like image 957
DotnetSparrow Avatar asked Feb 23 '26 16:02

DotnetSparrow


1 Answers

Actually, you are writing you html String to the PDF. Instead, add cells in for/foreach loop into the PDF according to your Grid your want to show in the PDF.

Example:

PdfPTable DataTable0 = new PdfPTable(dtCommodities.Rows.Count);

            Chunk DataHeaderCH01 = new Chunk("Commodity", new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL, BaseColor.WHITE));
            Phrase dhph01 = new Phrase();
            dhph01.Add(DataHeaderCH01);
            PdfPCell dhcell01 = new PdfPCell();
            dhcell01.BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(80, 124, 209));
            dhcell01.AddElement(dhph01);
            DataTable0.AddCell(dhcell01);

            for (int i = 0; i < dtCommodities.Rows.Count; i++)
            {
                DataTable0.AddCell(new Phrase(dtCommodities.Rows[i]["Code"].ToString(), new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL, BaseColor.BLACK)));
            }
DataTable0.HorizontalAlignment = Element.ALIGN_LEFT;
            DataTable0.WidthPercentage = 100f;
            myDocument.Add(DataTable0);

Hope it helps. Don't forget to upvote it if it solves you problem. Thanks.. :)

like image 126
Avishek Avatar answered Feb 27 '26 02:02

Avishek