Definition
Itextsharp is an advanced tool library which is used for creating complex pdf repors. itext is used by different techonologies -- Android , .NET, Java and GAE developer use it to enhance their applications with PDF functionality.It creates documents and reports based on data from databases or xml files and Merge or split pages from existing PDF files.
How to use-
Step 1 N
Download itextsharp.dll
Here is the link for download.
- usingiTextSharp.text;
- usingiTextSharp.text.pdf;
First We use
- Documentdoc=newDocument(PageSize.A4,7f,5f,5f,0f);
For set font style
- iTextSharp.text.FontmainFont=FontFactory.GetFont("SegoeUI",22,newiTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#999")));
- iTextSharp.text.FontmainFont=FontFactory.GetFont("SegoeUI",22,newiTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#999")));
For Paragraph
- PhrasemainPharse=newPhrase();
- PhrasemainPharse=newPhrase();
For image
- iTextSharp.text.ImagemobileImage=iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/goodmorning.jpg"));
- mobileImage.ScaleToFit(10,10);
- ChunkcmobImg=newChunk(mobileImage,0,-2);
Add References
- iTextSharp.text.dll
- iTextSharp.text.pdf.dll
Add a aspx page with name profile name,
Add table in sql server,
Bind grid view from database.---Source code for ProfileResume.aspx,
- <%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="ProfileResume.aspx.cs"
- Inherits="architecture.ProfileResume"%>
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Web;
- usingSystem.Web.UI;
- usingSystem.Web.UI.WebControls;
- usingSystem.Data;
- usingSystem.Configuration;
- usingSystem.Data.SqlClient;
- usingSystem.IO;
- usingSystem.Collections;
- usingSystem.Linq.Expressions;
- namespacearchitecture
- {
- publicpartialclassProfileResume:System.Web.UI.Page
- {
- publicstaticstringconstr=ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
- protectedvoidPage_Load(objectsender,EventArgse)
- {
- if(!IsPostBack)
- {
- ShowData();
- }
- }
- //methodforDisplayingDatainGridview
- protectedvoidShowData()
- {
- SqlConnectioncon=newSqlConnection(constr);
- stringstr="Select*fromTbDemo;select*fromTbDemo";
- con.Open();
- SqlCommandcmd=newSqlCommand(str,con);
- DataTabledt=newDataTable();
- SqlDataReaderreader=cmd.ExecuteReader();
- dt.Load(reader);
- DataViewdv=dt.DefaultView;
- gvlist.DataSource=dv;
- gvlist.DataBind();
- inti=0;
- con.Close();
- }
- protectedvoidSubmit(objectsender,EventArgse)
- {
- using(SqlConnectionconnection=newSqlConnection(constr))
- {
- connection.Open();
- SqlCommandcommand=newSqlCommand("SELECTFirstName,LastName,EmailFROMTbDemo",connection);
- SqlDataAdapteradapter=newSqlDataAdapter(command);
- SqlCommandBuilderbuilder=newSqlCommandBuilder(adapter);
- DataSetdataset=newDataSet();
- adapter.Fill(dataset);
- stringline=newstring('-',40)+Environment.NewLine;
- Console.WriteLine(builder.GetUpdateCommand().CommandText);
- Console.WriteLine(line);
- Console.WriteLine(builder.GetDeleteCommand().CommandText);
- Console.WriteLine(line);
- Console.WriteLine(builder.GetInsertCommand().CommandText);
- Console.WriteLine(line);
- Console.ReadLine();
- //insertarow
- SqlCommandinsert=builder.GetInsertCommand();
- insert.Parameters["@P1"].Value="Ak";
- insert.Parameters["@P2"].Value="KK";
- insert.Parameters["@P3"].Value="PaulKimmel";
- insert.ExecuteNonQuery();
- adapter.Fill(dataset);
- DataRow[]rows=dataset.Tables[0].Select("ID='4'");
- if(rows.Length==1)Console.WriteLine(rows[0]["FirstName"]);
- Console.ReadLine();
- }
- }
- protectedvoidOnCommandPdf_click(objectsender,GridViewCommandEventArgse)
- {
- GridViewRowgvr=(GridViewRow)(((Button)e.CommandSource).NamingContainer);
- stringid=e.CommandArgument.ToString();
- Response.Redirect("PdfProfile.aspx?Id="+id);
- }
- }
- }
Code behind for ProfileResume.aspx.cs
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Web;
- usingSystem.Web.UI;
- usingSystem.Web.UI.WebControls;
- usingSystem.Data;
- usingSystem.Configuration;
- usingSystem.Data.SqlClient;
- usingSystem.IO;
- usingSystem.Collections;
- usingSystem.Linq.Expressions;
- namespacearchitecture
- {
- publicpartialclassProfileResume:System.Web.UI.Page
- {
- publicstaticstringconstr=ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
- protectedvoidPage_Load(objectsender,EventArgse)
- {
- if(!IsPostBack)
- {
- ShowData();
- }
- }
- //methodforDisplayingDatainGridview
- protectedvoidShowData()
- {
- SqlConnectioncon=newSqlConnection(constr);
- stringstr="Select*fromTbDemo;select*fromTbDemo";
- con.Open();
- SqlCommandcmd=newSqlCommand(str,con);
- DataTabledt=newDataTable();
- SqlDataReaderreader=cmd.ExecuteReader();
- dt.Load(reader);
- DataViewdv=dt.DefaultView;
- gvlist.DataSource=dv;
- gvlist.DataBind();
- inti=0;
- con.Close();
- }
- protectedvoidSubmit(objectsender,EventArgse)
- {
- using(SqlConnectionconnection=newSqlConnection(constr))
- {
- connection.Open();
- SqlCommandcommand=newSqlCommand("SELECTFirstName,LastName,EmailFROMTbDemo",connection);
- SqlDataAdapteradapter=newSqlDataAdapter(command);
- SqlCommandBuilderbuilder=newSqlCommandBuilder(adapter);
- DataSetdataset=newDataSet();
- adapter.Fill(dataset);
- stringline=newstring('-',40)+Environment.NewLine;
- Console.WriteLine(builder.GetUpdateCommand().CommandText);
- Console.WriteLine(line);
- Console.WriteLine(builder.GetDeleteCommand().CommandText);
- Console.WriteLine(line);
- Console.WriteLine(builder.GetInsertCommand().CommandText);
- Console.WriteLine(line);
- Console.ReadLine();
- //insertarow
- SqlCommandinsert=builder.GetInsertCommand();
- insert.Parameters["@P1"].Value="Ak";
- insert.Parameters["@P2"].Value="KK";
- insert.Parameters["@P3"].Value="PaulKimmel";
- insert.ExecuteNonQuery();
- adapter.Fill(dataset);
- DataRow[]rows=dataset.Tables[0].Select("ID='4'");
- if(rows.Length==1)Console.WriteLine(rows[0]["FirstName"]);
- Console.ReadLine();
- }
- }
- protectedvoidOnCommandPdf_click(objectsender,GridViewCommandEventArgse)
- {
- GridViewRowgvr=(GridViewRow)(((Button)e.CommandSource).NamingContainer);
- stringid=e.CommandArgument.ToString();
- Response.Redirect("PdfProfile.aspx?Id="+id);
- }
- }
- }
Click On make resume button for pdf
- <%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="PdfProfile.aspx.cs"Inherits="architecture.PdfProfile"%>
- <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <htmlxmlns="http://www.w3.org/1999/xhtml">
- <headrunat="server">
- <title></title>
- </head>
- <body>
- <formid="form1"runat="server">
- <div></div>
- </form>
- </body>
- </html>
And code behind
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Web;
- usingSystem.Web.UI;
- usingSystem.Web.UI.WebControls;
- usingSystem.Data;
- usingSystem.Configuration;
- usingSystem.Data.SqlClient;
- usingSystem.IO;
- usingSystem.Collections;
- usingiTextSharp.text;
- usingiTextSharp.text.pdf;
- usingSystem.Text;
- usingSystem.Drawing;
- namespacearchitecture
- {
- publicpartialclassPdfProfile:System.Web.UI.Page
- {
- publicstaticstringconstr=ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
- protectedvoidPage_Load(objectsender,EventArgse)
- {
- if(Request.QueryString["Id"]!=null)
- {
- SqlConnectioncon=newSqlConnection(constr);
- Documentdoc=newDocument(PageSize.A4,7f,5f,5f,0f);
- stringstr1="Select*fromTbDemowhereid='"+Request.QueryString["Id"]+"'";
- con.Open();
- SqlCommandcmd=newSqlCommand(str1,con);
- DataTabledt=newDataTable();
- SqlDataReaderreader=cmd.ExecuteReader();
- dt.Load(reader);
- con.Close();
- //DataViewdv=dt.DefaultView;
- stringfilePath=HttpContext.Current.Server.MapPath("~/Resume/"+Request.QueryString["Id"]);
- if(File.Exists(filePath+"/"+"UserProfile.pdf"))
- {
- Response.Redirect("~/ProfileReport.aspx?ID="+Request.QueryString["Id"]);
- }else
- {
- try
- {
- //Create[Portfolio]directoryIfdoesnotexist
- if(!Directory.Exists(filePath))
- {
- Directory.CreateDirectory(filePath);
- }
- stringnewFilePath=filePath+"\\"+"UserProfile.pdf";//GetFileName(filePath,"UserProfile");//
- PdfWriterwriter=PdfWriter.GetInstance(doc,newFileStream(newFilePath,FileMode.Create));
- doc.Open();
- //Gettheuserphotostobeshowinpdf
- Int64_userProfileID=Int64.Parse(Request.QueryString["Id"]);
- DataTabledtPhotos=dt;
- iTextSharp.text.FontmainFont=FontFactory.GetFont("SegoeUI",22,newiTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#999")));
- iTextSharp.text.FontinfoFont1=FontFactory.GetFont("Kalinga",10,newiTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#666")));
- iTextSharp.text.FontexpHeadFond=FontFactory.GetFont("Calibri(Body)",12,newiTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#666")));
- PdfContentBytecontentByte=writer.DirectContent;
- DataTableobjDataTable=dt;
- ColumnTextct=newColumnText(contentByte);
- //Createthefontforshowthenameofuser
- doc.Open();
- PdfPTablemodelInfoTable=newPdfPTable(1);
- modelInfoTable.TotalWidth=100f;
- modelInfoTable.HorizontalAlignment=Element.ALIGN_LEFT;
- PdfPCellmodelInfoCell1=newPdfPCell()
- {
- BorderWidthBottom=0f,BorderWidthTop=0f,BorderWidthLeft=0f,BorderWidthRight=0f
- };
- //Setrighthandthefirstheading
- PhrasemainPharse=newPhrase();
- ChunkmChunk=newChunk(dt.Rows[0]["FirstName"].ToString()+""+dt.Rows[0]["LastName"].ToString(),mainFont);
- mainPharse.Add(mChunk);
- mainPharse.Add(newChunk(Environment.NewLine));
- //Settheuserrole
- ChunkinfoChunk1=newChunk("Profile-"+dt.Rows[0]["RoleName"].ToString(),infoFont1);
- mainPharse.Add(infoChunk1);
- mainPharse.Add(newChunk(Environment.NewLine));
- //SettheuserGender
- ChunkinfoChunk21=newChunk("Gender-"+dt.Rows[0]["Gender"].ToString(),infoFont1);
- mainPharse.Add(infoChunk21);
- mainPharse.Add(newChunk(Environment.NewLine));
- //Settheuserage
- ChunkinfoChunk22=newChunk("Age-"+dt.Rows[0]["Age"].ToString(),infoFont1);
- mainPharse.Add(infoChunk22);
- mainPharse.Add(newChunk(Environment.NewLine));
- iTextSharp.text.FontinfoFont2=FontFactory.GetFont("Kalinga",10,newiTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#848282")));
- stringLocation=dt.Rows[0]["Location"].ToString()==string.Empty?string.Empty:dt.Rows[0]["Location"].ToString();
- ChunkinfoChunk2=newChunk("Address-"+Location,infoFont2);
- mainPharse.Add(infoChunk2);
- modelInfoCell1.AddElement(mainPharse);
- //Setthemobileimageandnumber
- PhrasemobPhrase=newPhrase();
- //iTextSharp.text.ImagemobileImage=iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/goodmorning.jpg"));
- //mobileImage.ScaleToFit(10,10);
- //ChunkcmobImg=newChunk(mobileImage,0,-2);
- Chunkcmob=newChunk("Contact"+dt.Rows[0]["Phone"].ToString(),infoFont2);
- //mobPhrase.Add(cmobImg);
- mobPhrase.Add(cmob);
- modelInfoCell1.AddElement(mobPhrase);
- //Setthemessageimageandemailid
- PhrasemsgPhrase=newPhrase();
- //iTextSharp.text.ImagemsgImage=iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/goodmorning.jpg"));
- //msgImage.ScaleToFit(10,10);
- //ChunkmsgImg=newChunk(msgImage,0,-2);
- iTextSharp.text.FontmsgFont=FontFactory.GetFont("Kalinga",10,newiTextSharp.text.BaseColor(System.Drawing.Color.Pink));
- Chunkcmsg=newChunk("EMail-"+dt.Rows[0]["Email"].ToString(),msgFont);
- //msgPhrase.Add(msgImg);
- msgPhrase.Add(cmsg);
- //Setthelineaftertheusersmallinformation
- iTextSharp.text.FontlineFont=FontFactory.GetFont("Kalinga",10,newiTextSharp.text.BaseColor(System.Drawing.ColorTranslator.FromHtml("#e8e8e8")));
- ChunklineChunk=newChunk("____________________________________________________________________",lineFont);
- msgPhrase.Add(newChunk(Environment.NewLine));
- msgPhrase.Add(lineChunk);
- modelInfoCell1.AddElement(msgPhrase);
- modelInfoTable.AddCell(modelInfoCell1);
- //Setthebiography
- PdfPCellcell1=newPdfPCell(){
- BorderWidthBottom=0f,BorderWidthTop=0f,BorderWidthLeft=0f,BorderWidthRight=0f
- };
- cell1.PaddingTop=5f;
- PhrasebioPhrase=newPhrase();
- ChunkbioChunk=newChunk("Biography",mainFont);
- bioPhrase.Add(bioChunk);
- bioPhrase.Add(newChunk(Environment.NewLine));
- ChunkbioInfoChunk=newChunk(dt.Rows[0]["BriefBio"].ToString(),infoFont1);
- bioPhrase.Add(bioInfoChunk);
- bioPhrase.Add(newChunk(Environment.NewLine));
- bioPhrase.Add(lineChunk);
- cell1.AddElement(bioPhrase);
- modelInfoTable.AddCell(cell1);
- PdfPCellcellExp=newPdfPCell()
- {
- BorderWidthBottom=0f,BorderWidthTop=0f,BorderWidthLeft=0f,BorderWidthRight=0f
- };
- cellExp.PaddingTop=5f;
- PhraseExperiencePhrase=newPhrase();
- ChunkExperienceChunk=newChunk("Experience",mainFont);
- ExperiencePhrase.Add(ExperienceChunk);
- cellExp.AddElement(ExperiencePhrase);
- modelInfoTable.AddCell(cellExp);
- if(dt.Rows.Count>0)
- {
- for(inti=0;i<dt.Rows.Count;i++)
- {
- //Settheexperience
- PdfPCellexpcell=newPdfPCell()
- {
- BorderWidthBottom=0f,BorderWidthTop=0f,BorderWidthLeft=0f,BorderWidthRight=0f
- };
- expcell.PaddingTop=5f;
- PhraseexpPhrase=newPhrase();
- StringBuilderexpStringBuilder=newStringBuilder();
- StringBuilderexpStringBuilder1=newStringBuilder();
- //Settheexperiencedetails
- expStringBuilder.Append(dt.Rows[i]["Title"].ToString()+Environment.NewLine);
- expStringBuilder.Append(dt.Rows[i]["CompanyName"].ToString()+Environment.NewLine);
- expStringBuilder.Append(dt.Rows[i]["ComanyAddress"].ToString()+Environment.NewLine);
- expStringBuilder1.Append("From"+dt.Rows[i]["From"].ToString()+"To"+dt.Rows[i]["to"].ToString()+Environment.NewLine);
- //expPhrase.Add(newChunk(Environment.NewLine));
- ChunkexpDetailChunk=newChunk(expStringBuilder.ToString(),expHeadFond);
- expPhrase.Add(expDetailChunk);
- expPhrase.Add(newChunk(expStringBuilder1.ToString(),infoFont2));
- expcell.AddElement(expPhrase);
- modelInfoTable.AddCell(expcell);
- if(dt.Rows[i]["Description"].ToString().Length>600){
- PdfPCellpCell1=newPdfPCell()
- {
- BorderWidth=0f
- };
- PdfPCellpCell2=newPdfPCell()
- {
- BorderWidth=0f
- };
- Phraseph1=newPhrase();
- Phraseph2=newPhrase();
- stringexperience1=dt.Rows[i]["Description"].ToString().Substring(0,599);
- stringexperience2=dt.Rows[i]["Description"].ToString().Substring(599,dt.Rows[i]["Description"].ToString().Length-600);
- ph1.Add(newChunk(experience1,infoFont1));
- ph2.Add(newChunk(experience2,infoFont1));
- pCell1.AddElement(ph1);
- pCell2.AddElement(ph2);
- modelInfoTable.AddCell(pCell1);
- modelInfoTable.AddCell(pCell2);
- }else{
- PdfPCellpCell1=newPdfPCell()
- {
- BorderWidth=0f
- };
- Phraseph1=newPhrase();
- stringexperience1=dt.Rows[i]["Description"].ToString();
- ph1.Add(newChunk(experience1,infoFont1));
- pCell1.AddElement(ph1);
- modelInfoTable.AddCell(pCell1);
- }
- }
- }
- doc.Add(modelInfoTable);
- //Setthefooter
- PdfPTablefooterTable=newPdfPTable(1);
- footerTable.TotalWidth=644f;
- footerTable.LockedWidth=true;
- PdfPCellfooterCell=newPdfPCell(newPhrase("Resume"));
- footerCell.BackgroundColor=newiTextSharp.text.BaseColor(Color.Black);
- iTextSharp.text.ImagefooterImage=iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/goodmorning.jpg"));
- footerImage.SpacingBefore=5f;
- footerImage.SpacingAfter=5f;
- footerImage.ScaleToFit(100f,22f);
- footerCell.AddElement(footerImage);
- footerCell.MinimumHeight=30f;
- iTextSharp.text.FontnewFont=FontFactory.GetFont("SegoeUI,LucidaGrande,LucidaGrande",8,newiTextSharp.text.BaseColor(Color.White));
- ParagraphrightReservedLabel=newParagraph("©"+DateTime.Now.Year+"Resume.Allrightsreserved.",newFont);
- footerCell.AddElement(rightReservedLabel);
- footerCell.PaddingLeft=430f;
- footerTable.AddCell(footerCell);
- footerTable.WriteSelectedRows(0,-1,0,doc.PageSize.Height-795,writer.DirectContent);
- }catch(Exception)
- {
- throw;
- }finally
- {
- doc.Close();
- }
- Response.Redirect("~/ProfileReport.aspx?ID="+Request.QueryString["Id"]);
- }
- }
- }
- }
- }
Add One more aspx page for make pdf pagea. Source code ProfileReport.aspx,
- <%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="ProfileReport.aspx.cs"Inherits="architecture.ProfileReport"%>
- <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <htmlxmlns="http://www.w3.org/1999/xhtml">
- <headrunat="server">
- <title></title>
- </head>
- <body>
- <formid="form1"runat="server">
- <div></div>
- </form>
- </body>
- </html>
Code behind page
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Web;
- usingSystem.Web.UI;
- usingSystem.Web.UI.WebControls;
- usingSystem.IO;
- usingSystem.Net;
- namespacearchitecture
- {
- publicpartialclassProfileReport:System.Web.UI.Page
- {
- protectedvoidPage_Load(objectsender,EventArgse)
- {
- stringfilePath=Server.MapPath(string.Concat("~/Resume/",Request.QueryString["Id"]));
- try
- {
- //Openpdfinwebbrowser
- WebClientclient=newWebClient();
- if(!string.IsNullOrEmpty(Request.QueryString["Id"]))
- {
- Byte[]buffer=client.DownloadData(filePath+"/"+"UserProfile.pdf");
- if(buffer!=null){
- HttpContext.Current.Response.ContentType="application/pdf";
- HttpContext.Current.Response.AddHeader("content-length",buffer.Length.ToString());
- HttpContext.Current.Response.BinaryWrite(buffer);
- //HttpContext.Current.Response.End();
- HttpContext.Current.ApplicationInstance.CompleteRequest();
- }
- }
- }catch(Exceptionex){
- throwex;
- }
- }
- }
- }