.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

simple way to create pdf document using itextsharp

Posted By:Pankaj Mishra       Posted Date: June 25, 2009    Points: 25    Category: ASP.NET    URL: http://www.dotnetspark.com  

simple way to create pdf document using itextsharp. In this article we will see how to create pdf file using itextsharp on the fly using c#,VB.net and Asp.net.
 

simple way to create pdf document using itextsharp

In this article we will see how to create pdf file using itextsharp on the fly using c#,VB.net and Asp.net.

you can also refer to my articles on ItextSharp in asp.net for adding image into pdf file here and to create table in pdf doc here

Step 1: First of all we have to download the iTextShaprp pdf library. you can download that from here

Step2 : After downloading file add the reference of iTextSharp.dll to your project by right clicking on solution explorer.

Step 3 : Now add the Namespace to your .cs or .vb file

using iTextSharp.text;
using iTextSharp.text.pdf;

Step 4 : Now one whatever click you want to generate the file you can write the below code. in this example i am generating the pdf file on button click event.

Now we will create document

//Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("c:\\Test11.pdf", FileMode.Create));
doc.Open();
//Open Document to write

Now Write some content to it

//Write some content
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse =
new Phrase("This is my second line using Pharse.");
Chunk chunk =
new Chunk(" This is my third line using Chunk.");

Add the content to document class object

// Now add the above created text using different class object to our pdf document

doc.Add(paragraph);

doc.Add(pharse);

doc.Add(chunk);

Now Close the document

doc.Close(); //Close document

And you are done.

Here is the sample pdf file

And below is the full code used inside button click event in C# example

    protected void btnGeneratePDF_Click(object sender, EventArgs e)
    {
        //Create Document class obejct and set its size to letter and give space left, right, Top, Bottom Margin
        Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
        try
        {
            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("c:\\Test11.pdf", FileMode.Create));
            //Open Document to write
            doc.Open;

            //Write some content
            Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
            Phrase pharse = new Phrase("This is my second line using Pharse.");
            Chunk chunk = new Chunk(" This is my third line using Chunk.");
            // Now add the above created text using different class object to our pdf document
            doc.Add(paragraph);
            doc.Add(pharse);
            doc.Add(chunk);
        }
        catch (DocumentException dex)
        {


            //Handle document exception
        }
        catch (IOException ioex)
        {
            //Handle IO exception
        }
        catch (Exception ex)
        {
            //Handle Other Exception
        }
        finally
        {
            doc.Close(); //Close document
        }
    }

Vb.NET Code sample

Protected Sub btnGeneratePDF_Click(ByVal sender As Object, ByVal e As EventArgs)
    'Create Document class obejct and set its size to letter and give space left, right, Top, Bottom Margin
    Dim doc As New Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35)
    Try
        Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("c:\Test11.pdf", FileMode.Create))
        'Open Document to write
        doc.Open
        
        'Write some content
        Dim paragraph As New Paragraph("This is my first line using Paragraph.")
        Dim pharse As New Phrase("This is my second line using Pharse.")
        Dim chunk As New Chunk(" This is my third line using Chunk.")
        ' Now add the above created text using different class object to our pdf document
        doc.Add(paragraph)
        doc.Add(pharse)
        doc.Add(chunk)
    Catch dex As DocumentException
        
        
        'Handle document exception
    Catch ioex As IOException
        'Handle IO exception
    Catch ex As Exception
        'Handle Other Exception
    Finally
            'Close document
        doc.Close()
    End Try
End Sub

Cheers!!!
Pankaj


 Subscribe to Articles

     

Further Readings:

Responses
Author: dotnetguts         Company URL: http://www.dotnetspark.com
Posted Date: June 25, 2009

Gr8 Tip man,

Cheers,
Dotnetguts
http://dotnetguts.blogspot.com
Author: Ali         Company URL: http://www.dotnetspark.com
Posted Date: August 03, 2009

Very Nice article. its really working. but i have a problem that how can i display Right to left language (like URDU) in pdf.

Any help will highly appreciated.


Regards,

Ali bin zubair
Author: senorita         Company URL: http://www.dotnetspark.com
Posted Date: August 21, 2009

This is a great article and its working fine on localhost.

but when i am using this

PdfWriter.GetInstance(doc, New FileStream("c:\\1.pdf", FileMode.Create))

on live web server. I mean where i am hosting my website. its giving me the error

Access to the path 'c:\1.pdf' is denied.

be'se that server wouldnt give me permission to create file on c drive.
and if i am using this

PdfWriter.GetInstance(doc, New FileStream("http://www.domainname.com/1.pdf", FileMode.Create))
its giving me the error : URI format not supported

What should i do to solve this problem.

Please help.
Author: Pankaj Mishra         Company URL: http://www.dotnetspark.com
Posted Date: August 21, 2009

HI Sanorita,

you cna use Server.MapPath() method to save or get file from web shoting server like this

PdfWriter.GetInstance(doc, New FileStream(Server.MapPath("/PDFFile/1.pdf"), FileMode.Create))

Hope this will help you.

Cheers
Pankaj
Author: Pankaj Mishra         Company URL: http://www.dotnetspark.com
Posted Date: August 21, 2009

Hi Ali,

you can use ColumnText.setRundirection() method to write right to left like Urdu or Arabic language.

You can also use ColumnText.showTextAligned() for each line you want to change the direction of the statement.

Just check out this property and let me know.

Sorry for late reply.

Cheers,
Pankaj
Author: shakila         Company URL: http://www.dotnetspark.com
Posted Date: September 05, 2009

Hi,

This is very good article. you really impressed all. Pls let me know samples how to create arabic pdf with this dll.

Pls help me Urgent.......

Thanks to all
Shakila
Author: senorita         Company URL: http://www.dotnetspark.com
Posted Date: September 05, 2009

If i want to use this for generating reports on online web portal. each user cant create file on server. and "filestream" wont work on clients local machine.

what is the solution?

this will be solve all my problems.

Thanks
Author: Deepak         Company URL: http://www.dotnetspark.com
Posted Date: October 01, 2009

This is awesome....but Is there any solution to add images in pdf ...using same ddl.or any other method..


deepak.dynamite@gmail.com
Author: newbi         Company URL: http://www.dotnetspark.com
Posted Date: January 06, 2010

Thanks for d article..

can u pl tell me how to create tables with itextsharp..Actually i want to export my datagridview data into pdf without using crystal reports..M working on desktop application.

Thanks in advance.
Author: Pankaj Mishra         Company URL: http://www.dotnetspark.com
Posted Date: January 06, 2010

Hi Newbi,

I wrote an article to create table in pdf file using ItextSharp...

take a look at it

http://www.dotnetspark.com/kb/1365-create-custom-table-pdf-document-using-itextsharp.aspx

Cheers
Pankaj
Author: Pankaj Mishra         Company URL: http://www.dotnetspark.com
Posted Date: January 06, 2010

Hi Deepak,

Sorry to reply late

I wrote an article to add an image in pdf document using ItextSharp...and as you know this library is free

take a look at it

http://www.dotnetspark.com/kb/1364-add-image-to-pdf-document-using-itextsharp.aspx

Cheers
Pankaj
Author: vijay patel         Company URL: http://www.dotnetspark.com
Posted Date: May 28, 2010

Hi Pankaj,

I have a Question,
I want to parse HTML to PDF using ItextSharp in c# Asp.
Suppose I have text "<p>Vijay <br /> Patel</p>"
then there are 2 lines should be created.
if I uses new Paragraph() or other functions then the HTML tags will be written in PDF file, I want to Run HTML tags and after display proper format in PDF File.

In short I want write Data to PDF Direct From FCKEditor.
So It will display in proper format.
I hope you will give me proper guidance.
Thanks in Advance.
Author: Pankaj Mishra         Company URL: http://www.dotnetspark.com
Posted Date: June 04, 2010

Hi Vijay,

If I understood your question correctly that you want to replace <br/> with \n\t and for new line you can use \n or Environment.NewLine.

Thanks
Pankaj
Author: vijay patel         Company URL: http://www.dotnetspark.com
Posted Date: June 11, 2010

Hello Pankaj,

Thanks For Reply,
Bt actually I have content as full html, that means I have all html tags like <font><p><table><div> and many tags. I want to parse these tags direct to pdf, not only <br/>.

Thanks & Regards.
Author: Sunil MSDOTNET         Company URL: http://www.dotnetspark.com
Posted Date: August 13, 2010

Hi Pankaj Mishra,


It's very use full in my project. It's very simple to get results.

Thanks lot

Best regards
Sunil
Author: narama87         Company URL: http://www.dotnetspark.com
Posted Date: February 09, 2011

hello Pankaj ,
please i didn't understand how to put this code .
i work with asp , can i use itextsharp to generate pdf ?
please i need your help
Author: narama87         Company URL: http://www.dotnetspark.com
Posted Date: February 09, 2011

i didn't understand since step2 please help
Author: Pankaj Mishra         Company URL: http://www.dotnetspark.com
Posted Date: February 09, 2011

Hi Narama87,

Step 2 is just adding the iTextSharp dll reference in your project. You can download the sample project and check out the sample. This may help you.

Thanks
Pankaj
Author: narama87         Company URL: http://www.dotnetspark.com
Posted Date: February 10, 2011

thanks a lot Pankaj for answering me
i installed framework .Net 2.0 , and i copied
i copied Vb.NET Code sample to itextsharp.aspx and i copied itextsharp.dll to
the same directory and look what i got :
Message d'erreur du compilateur: BC30002: Type 'Document' is not defined.
please pankaj i do need your help , i need to create a pdf document and write arabic in it , i was looking for a solution for a month , and yesterday i found this website and i wish to end finally this nightmare :( ...
Author: narama87         Company URL: http://www.dotnetspark.com
Posted Date: February 11, 2011

hello ,
where to place using
iTextSharp.text;
using iTextSharp.text.pdf; ?
Author: narama87         Company URL: http://www.dotnetspark.com
Posted Date: February 23, 2011

hello ,
i think i've been better in understanding this code : here what i wrote in page.aspx :

<%@ Import Namespace="itexsharp" %>
<%@ Import Namespace="itextsharp.text" %>
<%@ Import Namespace="itextsharp.text.pdf" %>

<script runat="server">

Sub Page_Load
if Not Page.IsPostBack then
lbl1.Text="The date and time is " & now()
end if
End Sub

Sub submit(s As Object, e As EventArgs)
lbl2.Text="Hello World!"
End Sub
Sub submit2(ByVal Source As Object, ByVal e As EventArgs)
button3.Text = "You clicked me!"
End Sub
Protected Sub btnGeneratePDF_Click(ByVal sender As Object, ByVal e As EventArgs)



'Create Document class obejct and set its size to letter and give space left, right, Top, Bottom Margin

Dim doc As New Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35)

Try

Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("c:\Test11.pdf", FileMode.Create))

'Open Document to write

doc.Open()



'Write some content

Dim paragraph As New Paragraph("This is my first line using Paragraph.")

Dim pharse As New Phrase("This is my second line using Pharse.")

Dim chunk As New Chunk(" This is my third line using Chunk.")

' Now add the above created text using different class object to our pdf document

doc.Add(paragraph)

doc.Add(pharse)

doc.Add(chunk)

Catch dex As DocumentException

and i added the reference itextsharp.dll too , but i still have a problem :
Message d'erreur du compilateur: BC30002: Type 'FileStream' is not defined.

Erreur source:


Ligne 27 : Try
Ligne 28 :
Ligne 29 : Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("c:\Test11.pdf", FileMode.Create))
Ligne 30 :
Ligne 31 : 'Open Document to write

Fichier source: c:\inetpub\wwwroot\Rahma\Default.aspx Ligne: 29

if any one could help me out , i would be so grateful ...
Author: narama87         Company URL: http://www.dotnetspark.com
Posted Date: February 23, 2011

it's working :)))
i've just added <%@ Import Namespace="System.io" %> :) ,
i hope that help another people that start with asp.net ,
thanks Pankaj Mishra for this amazing code :))
Author: narama87         Company URL: http://www.dotnetspark.com
Posted Date: February 23, 2011

hi Pankaj Mishra ,
thanks again for this amazing code ,
one more thing please , did you test ColumnText.setRundirection() or ColumnText.showTextAligned() , could you please tell me how to use them
what namespace to add because i need to display arabic langage
i will appreciate that
Author: DOTNETWORLD         Company URL: http://www.dotnetspark.com
Posted Date: March 04, 2011

Hi Pankaj

I have created a PDF using this iTextSharp dll.
My question is can we authinticate this PDF. If yes can you provide me the details like code and dll and classes to used.

My purpose is other users dont want to open my PDF. I want to restrict the pdf from the other users.


Thanks
Sudheer



Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend