Using Open Source iTextSharp .NET PDF library to generate PDF on the fly
Quite recently I worked on a project to generate a number of PDF’s from a single page template with data coming from an XML file. I searched for a number of options to convert an existing HTML page to PDF using .NET Open Source libraries. But I was not able to render the page correctly, my page was pure XHTML and a lot of libraries were not rendering the TAGS right. And as a result the PDF generating was all messed up with content and images everywhere.
That is when I decided to generate PDF on the fly and not converting, i.e. writing content directly to the PDF instead of converting PDF from an existing HTML page. I will be writing more about the code to fill a PDF with data using FORM elements as placeholders in the PDF in the coming days. Right now I am pasting a quick script, this is what I used initially as a test to generate and create the PDF from scratch. |
Please first ADD REFERENCE to iTextSharp DLL to your project before running the following code.
You can get the DLL by CLICKING HERE.
And here is the Home Page of ItextSharp project on SourceForge.Net - CLICK HERE.
//////////////FYI: I am using .NET 3.5///////////////////
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;
public partial class creator : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreatePDFDocument();
}
/// <summary>
/// Creates the PDF document with a given content at a given location.
/// </summary>
/// <param name=”strFilePath”>The file path to write the new PDF to.</param>
/// <param name=”strContent”>Content in HTML to write to the PDF.</param>
public static void CreatePDFDocument()
{
MemoryStream MStream = new MemoryStream();
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
try
{
PdfWriter writer = PdfWriter.GetInstance(document, MStream);
document.Open();
document.Add(new iTextSharp.text.Paragraph(”This is test and must work”));
document.Close();
}
catch (Exception e)
{
throw e;
}
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = “application/pdf”;
HttpContext.Current.Response.AddHeader(”Content-Disposition”, attachment;filename=myPDFNew.pdf”);
HttpContext.Current.Response.BinaryWrite(MStream.GetBuffer());
HttpContext.Current.Response.End();
}
}
////////////////////////////////
Related posts brought to you by Yet Another Related Posts Plugin.
















You show two param’s but there are never used????
/// The file path to write the new PDF to.
/// Content in HTML to write to the PDF.
Is there a version that does use these params?
Those parametres were intended to use with following example. I guess I didnt delete them while posting the above code.
strContent was to hold the HTML code and strFilePath was for (holding the PATH of final PDF created.
Here is another example with those params used -
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Xml;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
public partial class creator : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreatePDFDocument();
}
/// <summary>
/// Creates the PDF document with a given content at a given location.
/// </summary>
public static void CreatePDFDocument()
{
// step 1: creation of a document-object
Document document = new Document();
string strContent = getHTML();
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter.GetInstance(document, new FileStream(strFilePath, FileMode.Create));
//System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(@”<html><body><div>This is first line test</div><div style=’Color:red;’>This is my <bold>test</bold> string</div></body></html>”));
System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(strContent));
_xmlr.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
HtmlParser.Parse(document, _xmlr);
}
public static string getHTML()
{
return “<html><body><img src=\”http://localhost/images/community.jpg\” width=\”446\” height=\”174\”/></body></html>”;
}
}
Hello i want to save data of pdf generated through Itextsharp in the database. my pdf shall have save button which saves data of the pdf to database.How can i do that…need help :(
Hello Daisy,
You create a button using the convenience class PushbuttonField. You want this button to be visible on the screen, but not if somebody prints the form (for instance, to fill it in manually).
The key method is PdfAction.createSubmitForm(). By
adding this action to the pushbutton form field, you create a button that submits the form to the URL passed as the first parameter. The second parameter is null because you want to submit all the fields (except those flagged with the FF_NO_EXPORT flag).
If you want to specify by name the fields that must be exported, you should pass an array with these names instead.
The third parameter defines the submit method; extra options can be defined. Basically, you can submit an AcroForm four ways: as an HTML query string, as a Forms Data Format (FDF) form, as an XFDF form, and as PDF if you’re using the full Acrobat.
Here is an example of submitting as HTML (convert to .NET but you can use the same classes and methods) -
PushbuttonField button1 = new PushbuttonField(writer,
new Rectangle(150, 560, 200, 590), “submitPOST”);
button1.setBackgroundColor(Color.BLUE);
button1.setText(”POST”);
button1.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
PdfFormField submit1 = button1.getField();
submit1.setAction(
PdfAction.createSubmitForm(”http://your.domain.com/”, null,
PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_COORDINATES));
writer.addAnnotation(submit1);
Hi MK,
I’ve a requirement to convert any type of file(.txt, .doc, .html etc) to pdf file.
Can iTextSharp fulfill my requirement ?
Here is my actual requirement :
I have a web page ConvertToPDF.aspx. It contains a text box and a button control on it.
I’ll type the full path of the file name(let it be C:\krushna.txt) in the text box and hit the button. Then it should convert to krushna.pdf and store in My Document folder automatically.
I’m using visual studio 2005. I’ve also Adobe PDF Printer installed in my system and set it as default printer. Also, in the PDF printer the default port is set to My Document\*.pdf
Can it be possible with iTextSharp or I need to go for some other method ?
Please guide me in this.
Thank you.
You can accomplish this by converting DOC to text or HTML and then use iTextSharp to convert that to PDF. You will have to put in some coding effort though.
Or you can read this post and use word object library 12.0 for conversion.
http://forums.asp.net/p/1225661/2446174.aspx
first code doesn’t work with memory stream. after we save the file it will gives the error saying file has been damaged when we try to open it out. plz let me know whatz the reason for that and how cani slove it?
I need to embed a pdf file into a windows form and have it so that the user can select text from the pdf and save it. I have created a user control that has a web browser control in it and then I navigate to the pdf. That’s enough to render it inside the form, I just do not know how to get access to it now. If you know how to or if you can suggest a better way please let me know. I have been trying to use iTextSharp to do this but with no luck.
thanks in advance
Iam using itextSharp,
Dim imagepath As String = Server.MapPath(”InventoryImages/”)
Dim jpg As Image = Image.GetInstance(imagepath & objInventorydetail.MainImage)
table.AddCell(cell.Add(jpg))
Iam trying to fit image with in table cell, But this is not done, May any body help me.
I want to display image with in table cell, may any body help me, thanks
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports itextsharp.text.pdf.pdfwriter
Imports iTextSharp.text.html
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim link As Font = FontFactory.GetFont(”Arial”, 12, Font.UNDERLINE, New Color(0, 0, 255))
Dim anchor As New Anchor(”www.xyz.com”, link)
anchor.Reference = “http://www.xyz.com”
Dim InventoryId As Integer = Request.QueryString(”InventoryId”)
Dim objInventorydetail As New InventoryInfo
objInventorydetail = InventoryBLL.GetInventoryDetail3(InventoryId)
Dim doc As Document = New Document
‘ PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + “\flyer.pdf”, FileMode.Create))
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + “\flyer.pdf”, FileMode.Create))
doc.Open()
Dim table As Table = New Table(3)
table.BorderWidth = 3
table.BorderColor = New Color(0, 0, 255)
table.Padding = 2
table.Spacing = 1
‘ Title row of Table….
Dim bfTimes As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, False)
Dim times As New Font(bfTimes, 14, Font.BOLD, Color.RED)
Dim bfTimes1 As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, False)
Dim times1 As New Font(bfTimes, 12, Font.BOLD, Color.RED)
‘ doc.Add(New Paragraph(”This is a Red Font Test using Times Roman”, times))
Dim cell As Cell = New Cell(New Paragraph(objInventorydetail.Title, times))
cell.Header = True
cell.HorizontalAlignment = Element.ALIGN_CENTER
cell.VerticalAlignment = Element.ALIGN_MIDDLE
cell.Colspan = 3
table.AddCell(cell)
table.AddCell(”Make: ” & objInventorydetail.ManufacturerName)
cell.BorderColor = New Color(0, 0, 255)
table.AddCell(”Model: ” & objInventorydetail.ModelName & “”)
cell.BorderColor = New Color(0, 0, 255)
table.BorderWidth = 3
table.AddCell(”Year: ” & objInventorydetail.YearName & “”)
cell.BorderColor = New Color(0, 0, 255)
table.BorderWidth = 3
table.AddCell(”Internet Price: ” & objInventorydetail.Cost & “”)
cell.BorderColor = New Color(0, 0, 255)
table.BorderWidth = 3
cell = New Cell(”Color: ” & objInventorydetail.ColorName & “”)
‘cell.Rowspan = 2
cell.BorderColor = New Color(0, 0, 255)
table.BorderWidth = 3
table.AddCell(cell)
table.AddCell(”Stock Code: ” & objInventorydetail.StockCode & “”)
cell.BorderColor = New Color(0, 0, 255)
table.BorderWidth = 3
table.AddCell(”VIN Code: ” & objInventorydetail.VINCode & “”)
cell.BorderColor = New Color(0, 0, 255)
table.BorderWidth = 3
table.AddCell(”Engine: ” & objInventorydetail.Engine & “”)
cell.BorderColor = New Color(0, 0, 255)
table.BorderWidth = 3
table.AddCell(”Milage: ” & objInventorydetail.Milage & “”)
cell.BorderColor = New Color(0, 0, 255)
table.BorderWidth = 3
cell = New Cell(”Description: ” & objInventorydetail.Description & “”)
cell.BorderColor = New Color(0, 0, 255)
table.BorderWidth = 3
‘cell.Rowspan = 2
cell.Colspan = 3
cell.HorizontalAlignment = Element.ALIGN_LEFT
cell.VerticalAlignment = Element.ALIGN_TOP
‘ cell.BackgroundColor = New Color(192, 192, 192)
‘ add image
Dim imagepath As String = Server.MapPath(”InventoryImages/idi_”)
Dim jpg As Image = Image.GetInstance(imagepath & objInventorydetail.MainImage)
‘ set position of image
‘ jpg.ScaleToFit(600.0F, 600.0F)
‘jpg.SpacingAfter = 5.0F
‘jpg.SpacingBefore = 12.0F
’set size of image -
jpg.ScalePercent(25.0F)
’set position
‘ jpg.SetAbsolutePosition(doc.PageSize.Width - 100.0F - 100.0F, doc.PageSize.Height - 100.0F - 100.6F)
‘ columns.AddElement(jpg)
table.AddCell(cell)
table.AddCell(doc.Add(anchor))
cell.BorderColor = New Color(0, 0, 255)
table.BorderWidth = 3
jpg.Alignment = Image.BOTTOM_BORDER
table.AddCell(cell.Add(jpg))
cell.BorderColor = New Color(0, 0, 255)
table.BorderWidth = 3
‘ add link….
‘Shapes
‘Dim cb As PdfContentByte = writer.DirectContent
‘cb.RoundRectangle(100.0F, 500.0F, 200.0F, 200.0F, 20.0F)
‘cb.Stroke()
‘ table.AddCell(doc.Add(anchor))
doc.Add(table)
‘ doc.Add(jpg)
‘ doc.Add(anchor)
doc.Close()
Response.Redirect(”~/flyer.pdf”)
End Sub