I want to Export Sql Data to PDF file.
I used the following code.
I am Getting Error as HtmlParser.Parse(Doc, xmlReader);
The name 'HtmlParser' does not exist in the current context
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;
using System.Data.SqlClient;
using System.Windows.Forms;
protected void btnPdf_Click(object sender, EventArgs e)
{
HtmlForm form = new HtmlForm();
form.Controls.Add(StdA_grid);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string html = sw.ToString();
Document Doc = new Document();
//PdfWriter.GetInstance
//(Doc, new FileStream(Request.PhysicalApplicationPath
//+ "\\AmitJain.pdf", FileMode.Create));
PdfWriter.GetInstance
(Doc, new FileStream(Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf", FileMode.Create));
Doc.Open();
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);
Chunk chunk1 = new Chunk
("By Amit Jain, amit_jain_online#yahoo.com \n",
FontFactory.GetFont("Verdana", 8));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_RIGHT;
p1.Add(chunk1);
Doc.Add(p);
Doc.Add(p1);
System.Xml.XmlTextReader xmlReader =
new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(Doc, xmlReader); // error shown on this line
Doc.Close();
string Path = Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf";
ShowPdf(Path);
}
private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader
("Content-Disposition", "attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
//Response.WriteFile(strS);
Response.Flush();
Response.Clear();
}
Please Give some solution for the same or you can suggest me any other better procedure.
Try searching for the HtmlParser class in your set-up. According to a quick Google search, HtmlParser doesn't exist in newer versions of iTextSharp. See this, this and search for any help on using iTextSharp. From the second link, here is some code that may help:
//make an arraylist ....with STRINGREADER since its no IO reading file...
List<IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(htmlText), null);
//add the collection to the document
for (int k = 0; k < htmlarraylist.Count; k++)
{
document.Add((IElement)htmlarraylist[k]);
}
Related
This question already has answers here:
Convert TXT file to PDF using iText (keep formatting)
(3 answers)
Closed 6 years ago.
This is my code:
using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
{
//step 1
using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 140f, 10f))
{
try
{
// step 2.
StreamReader sr = new StreamReader("TextFile.txt");
string line;
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
pdfWriter.PageEvent = new ITextEvents();
//open the stream
pdfDoc.Open();
for (int i = 0; i < 100; i++)
{
if ((line = sr.ReadLine()) != null)
{
Paragraph para = new Paragraph(line, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 6));
para.Alignment = Element.ALIGN_LEFT;
pdfDoc.Add(para);
//pdfDoc.NewPage();
}
}
sr.Close();
pdfDoc.Close();
and it's working...It reads the text file that is in my computer and adds it to PDF... The problem is - it doesn't keep the formatting from the text file. It just adds text. And I need to keep it the way it is. Is there any way to keep the formatting of the text? Can I somehow add it to a table and format the table, or something like that?
Try this one
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace TxtToPdf
{
class Program
{
static void Main(string[] args)
{
//Read the Data from Input File
StreamReader rdr = new StreamReader("Path/Test.txt");
//Create a New instance on Document Class
Document doc = new Document();
//Create a New instance of PDFWriter Class for Output File
PdfWriter.GetInstance(doc, new FileStream("Path/Test.pdf", FileMode.Create));
//Open the Document
doc.Open();
//Add the content of Text File to PDF File
doc.Add(new Paragraph(rdr.ReadToEnd()));
//Close the Document
doc.Close();
//Open the Converted PDF File
System.Diagnostics.Process.Start("Path/Test.pdf");
}
}
}
You can do it by reading escape sequence too like when line changes you should Read it as \n and then write it in PDF with your text.
This question already has answers here:
Convert HTML to PDF in .NET [closed]
(26 answers)
Closed 9 years ago.
Can anybody help me how to export Repeater data to PDF file without using iTextSharp.
I am generating PDF files from Repeater control using iTextSharp, it works properly but are there any other suggestions on how to export repeater data to a PDF document?
use the below code.Hope it will resolve your issue.
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Text;
protected void BtnExportToPdf_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=FileName.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
Repeater1.DataBind();
Repeater1.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();
}
I am using c#.net and need for some data to be displayed in a .pdf file. I am able to do so by using a PdfTable but then it is displayed in a tabular format.
I want a simple format like:
I dont want the exact tabular format.I am using iTextSharp dll.
Is it possible to display data in the above metioned format?
Any suggestions are welcome..
You can use PdfParagraph class to render genreal text in PDF
So when you say that you don't want exact tabular format are you talking about the borders? If so, I'd recommend using a PdfPTable and turning the borders off then. Cells in a PdfPTable are all based on the table's DefaultCell, so to turn the borders off for a table called t you'd do this:
t.DefaultCell.Border = 0;
Below is a full working WinForms app targetting iTextSharp 5.1.1.0 that does exactly that:
//PdfPTable Example
using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//PDF file to output
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
//Create a basic stream to write to
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
//Create a new PDF document
using (Document doc = new Document())
{
//Bind a the document to the stream
using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
{
//Open our PDF for writing
doc.Open();
//Insert a new page into our output PDF
doc.NewPage();
//Create a three column table
PdfPTable t = new PdfPTable(3);
//Remove the border from the table
t.DefaultCell.Border = 0;
//For the first row we some extra padding
t.DefaultCell.PaddingBottom = 10;
t.AddCell("ColumnA");
t.AddCell("ColumnB");
t.AddCell("ColumnC");
//Reset the padding for the remaining cells
t.DefaultCell.PaddingBottom = 0;
t.AddCell("Value1");
t.AddCell("Value1");
t.AddCell("Value1");
t.AddCell("Value2");
t.AddCell("Value2");
t.AddCell("Value2");
//Add the table to the document
doc.Add(t);
//Close our output PDF
doc.Close();
}
}
}
this.Close();
}
}
}
If for some reason you don't want to do this with a PdfPTable you can try hacking it together with a Paragraph but unless alignment isn't important you are going to give yourself a headache. The sample below uses paragraphs and formats each "column" within the paragraph to be 20 characters each, padding spaces as necessary. NOTE: This is 20 characters of a variable-width font so things don't actually align. If you want that, either use the PdfPTable above or you are going to have to measure strings which is not fun.
//Paragraph Example
using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//PDF file to output
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
//Create a basic stream to write to
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
//Create a new PDF document
using (Document doc = new Document())
{
//Bind a the document to the stream
using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
{
//Open our PDF for writing
doc.Open();
//Insert a new page into our output PDF
doc.NewPage();
//Right-pad each "column" for a total of 20 characters
string FormatString = "{0,-20}{1,-20}{2,-20}";
//Add the first row
doc.Add(new Paragraph(String.Format(FormatString, "ColumnA", "ColumnB", "ColumnC")));
//Add a blank line
doc.Add(new Paragraph(""));
//Add the two data rows
doc.Add(new Paragraph(String.Format(FormatString, "Value1", "Value1", "Value1")));
doc.Add(new Paragraph(String.Format(FormatString, "Value2", "Value2", "Value2")));
//Close our output PDF
doc.Close();
}
}
}
this.Close();
}
}
}
In iTextSharp dll, you just pass your data by creating table/tr/td structure in string like this :
string strData = string.Emrty;
strData = "<table border='0' cellpadding='0' cellspacing='0' width='100%'>";
strData += "<tr>";
strData += "<td>";
strData += "</td>";
strData += "</tr>";
strData += "</table>";
by creating table/tr/td structure of your data, just pass this variable data to pdf, then you will get your resulted output in pdf.
I have use ItextSharp to generate pdf file from an aspx page.
But it gives me an error in an obj.Parse(se), where se is the string reader and it takes the path of:-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
I am stuck with this problem.
Please help and give suggesstion.
Thank You
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using System.Xml;
using iTextSharp.text.html.simpleparser;
public partial class Pdf : System.Web.UI.Page
{
protected override void Render(HtmlTextWriter writer)
{
MemoryStream mem = new MemoryStream();
StreamWriter twr = new StreamWriter(mem);
HtmlTextWriter myWriter = new HtmlTextWriter(twr);
base.Render(myWriter);
myWriter.Flush();
myWriter.Dispose();
StreamReader strmRdr = new StreamReader(mem);
strmRdr.BaseStream.Position = 0;
string pageContent = strmRdr.ReadToEnd();
strmRdr.Dispose();
mem.Dispose();
writer.Write(pageContent);
CreatePDFDocument(pageContent);
}
public void CreatePDFDocument(string strHtml)
{
string strFileName = HttpContext.Current.Server.MapPath("test.pdf");
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
StringReader se = new StringReader(strHtml);
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
document.Close();
ShowPdf(strFileName);
}
public void ShowPdf(string strFileName)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
Response.ContentType = "application/pdf";
Response.WriteFile(strFileName);
Response.Flush();
Response.Clear();
}
}
Here is an example that worked for me. There is a bit of code but it shows ways you can take advantage of things like css. Hope it helps.
private void ExportToPDF()
{
string s = "<table><td><tr>First<b>row</b></tr></td></table>";
Document document = new Document(PageSize.LETTER, 30, 30, 60, 35);
MemoryStream msReport = new MemoryStream();
string strHTMLpath = Server.MapPath("../myHTML.html");
string strPDFpath = Server.MapPath("../myPDF.pdf");
try
{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
StreamWriter strWriter = new StreamWriter(strHTMLpath, false, Encoding.UTF8);
strWriter.Write(s.ToString());
strWriter.Close();
strWriter.Dispose();
iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
styles.LoadTagStyle("ol", "leading", "16,0");
PdfWriter.GetInstance(document, new FileStream(strPDFpath, FileMode.Create));
document.Add(new Header(iTextSharp.text.html.Markup.HTML_ATTR_STYLESHEET, "Style.css"));
document.Open();
ArrayList objects;
styles.LoadTagStyle("li", "face", "garamond");
styles.LoadTagStyle("span", "size", "8px");
styles.LoadTagStyle("body", "font-family", "times new roman");
styles.LoadTagStyle("body", "font-size", "10px");
document.NewPage();
objects = iTextSharp.text.html.simpleparser.
HTMLWorker.ParseToList(new StreamReader(strHTMLpath, Encoding.Default), styles);
for (int k = 0; k < objects.Count; k++)
{
document.Add((IElement)objects[k]);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
document.Close();
Response.Write(strPDFpath);
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=myFileName.pdf");
Response.ContentType = "application/octet-stream";
Response.WriteFile(strPDFpath);
Response.Flush();
Response.Close();
File.Delete(strPDFpath);
}
}
I have to get an ordered list into pdf.The data stored is in html format.When exporting to pdf using itextsharp,the ol-li tags should be replaced by an ordered list.
You'll want to use iTextSharp's iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList() method. Below is a full working sample WinForms app targeting iTextSharp 5.1.1.0 that does what you're looking for. See the inline comments for what's going on.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//File to export to
string exportFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "HTML.pdf");
//Create our PDF document
using (Document doc = new Document(PageSize.LETTER)){
using (FileStream fs = new FileStream(exportFile, FileMode.Create, FileAccess.Write, FileShare.Read)){
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)){
//Open the doc for writing
doc.Open();
//Insert a page
doc.NewPage();
//This is our sample HTML
String HTML = "<ol><li>Row 1</li><li>Row 2</li></ol>";
//Create a StringReader to parse our text
using (StringReader sr = new StringReader(HTML))
{
//Pass our StringReader into iTextSharp's HTML parser, get back a list of iTextSharp elements
List<IElement> ies = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, null);
//Loop through each element and add to the document
foreach (IElement ie in ies)
{
doc.Add(ie);
}
}
//Close our document
doc.Close();
}
}
}
}
}
}