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);
}
}
Related
I am trying to export a div to pdf with style using code:
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + Fullname.Text + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
var cssText = System.IO.File.ReadAllText(Server.MapPath("/css/bootstrap.css"));
var memoryStream = new MemoryStream();
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
pfd.RenderControl(htmlTextWriter);
StringReader stringReader = new StringReader(stringWriter.ToString().Replace("<br>", "<br/>").Replace("<td>", "<td/>").Replace("<tr>", "<tr/>").Replace("<td>", "<td/>"));
Document Doc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
PdfWriter writer = PdfWriter.GetInstance(Doc, Response.OutputStream);
Doc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, Doc, stringReader);
Doc.Close();
Response.Write(Doc);
Response.End();
How i can attach css file to pdf to keep same appearance in HTML?
Try below code,
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
byte[] pdf; // result will be here
var cssText = File.ReadAllText(MapPath("~/css/style.css"));
var html = File.ReadAllText(MapPath("~/css/index.html"));
using (var memoryStream = new MemoryStream())
{
var document = new Document(PageSize.A4, 20, 20, 30, 30);
var writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
{
using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, cssMemoryStream);
}
}
document.Close();
pdf = memoryStream.ToArray();
}
I'm trying to generate a pdf file using itextsharp.
Here is the method that's supposed to generate the PDF:
private void Page_onPreRenderComplete(object sender, EventArgs e)
{
// createPdf.GeneratePDF(htmlMarkup);
MemoryStream memoryStream = new MemoryStream();
StringBuilder sBuilder = new StringBuilder();
StringWriter sw = new StringWriter(sBuilder);
HtmlTextWriter htmlText = new HtmlTextWriter(sw);
Page.RenderControl(htmlText);
string pdfBody = sBuilder.ToString();
Document document = new Document();
PdfWriter.GetInstance(document, memoryStream);
document.Open();
StyleSheet styles = new StyleSheet();
HTMLWorker hw = new HTMLWorker(document);
try
{
hw.Parse(new StringReader(pdfBody));
}
catch (Exception ex)
{
string msg = ex.Message;
}
finally
{
document.Close();
}
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.Write(memoryStream);
HttpContext.Current.Response.End();
}
an error is generated on the line within the try block. How can I fix this?
may be the image tags etc are in relative paths instead of absolute paths in the rendered HTML
We are unable to change font size of pdf generated from below code anybody can help us?
We would like to convert that html file into pdf after changing the font size.
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
protected void ConvertToPDFNow()
{
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
print.RenderControl(w);
string htmWrite = sw.GetStringBuilder().ToString();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=FileName.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
htmWrite = Regex.Replace(htmWrite, "</?(a|A).*?>", "");
htmWrite = htmWrite.Replace("\r\n", "");
StringReader reader = new StringReader(htmWrite);
Document doc = new Document(PageSize.A4);
//Creating Document of A4 Size
HTMLWorker parser = new HTMLWorker(doc);
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
try
{
//rendering Html File
parser.Parse(reader);
}
catch (Exception ex)
{
}
finally
{
doc.Close();
}
}
try to apply stylesheet:
...
var style = new StyleSheet();
style.LoadTagStyle("body", "size", "12px");
parser.SetStyleSheet(style);
...
The C# code below works fantastically to change itextpdf font size:
var style = new StyleSheet();
style.LoadTagStyle("body", "size", "8px");
HTMLWorker htmlworker = new HTMLWorker(document);
htmlworker.SetStyleSheet(style);
export data grid view to excel code is run and all data export into excel sheet but i want to only selected column in excel sheet how to solve this problem
protected void btnexcel_Click1(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=ActualsAndBudgets.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
fillgrid();
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
gvdetails.AllowPaging = true;
fillgrid();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
using System;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Whatever
{
///
/// This class provides a method to write a dataset to the HttpResponse as
/// an excel file.
///
public class ExcelExport
{
public static void ExportDataSetToExcel(DataSet ds, string filename)
{
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;
filename=\"" + filename + "\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
}
}
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]);
}