iTextSharp – An Open Source .NET PDF library

I Love Crystal Reports, but difficulty in handling Dynamic Fields pushed Me to work with iTextSharp Library.

one day I ran into a problem, I needed to make a report in pdf but from an existing one with dynamic fields that had to be completed according to the information sent from the software (data comming from and EndPoint).

So i built logic and displayed content as required and exported content in to Pdf using iTextSharp Library.

The .NET framework does not contain any native way to work with PDF files.
So, if you want to generate or work with PDF files as part of your .NET application, you will have to rely on one of the many third party components that are available. One of the free components is iTextSharp.

Below is an example to convert Web Content into Pdf :

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

protected void BtnExportHtmlToPdf_Click(object sender, EventArgs e)

{

try
{
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
PnlData.RenderControl(hw);   // Exporting Panel Data
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 15f, 15f, 15f, 15f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
MemoryStream memoryStream = new MemoryStream();
PdfWriter.GetInstance(pdfDoc, memoryStream);

pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();

byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
MemoryStream input = new MemoryStream(bytes);
MemoryStream output = new MemoryStream();
string password = ViewState[“PasswordPay”].ToString();
PdfReader reader = new PdfReader(input);
PdfEncryptor.Encrypt(reader, output, true, password, password, PdfWriter.ALLOW_SCREENREADERS);
bytes = output.ToArray();

Response.ContentType = “application/pdf”;
Response.AddHeader(“content-disposition”, “attachment;filename=FileName_” + ViewState[“UserName”].ToString().Trim() + “.pdf”);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
catch (Exception ex)
{
LblErrorMessage.Text = “Error :: ” + ex.Message;
}
}

For more Info – http://itextpdf.com
Free Book – https://leanpub.com/itext_pdfabc/
Get Latest Download – http://sourceforge.net/projects/itextsharp/

Advertisements