.NET Tutorials, Forums, Interview Questions And Answers
HomeTutorialArticlesForumInterview QuestionCode SnippetsTechnology NewsFun Zone Poll Certification Search
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


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 :25/06/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


Featured Articles


Best Practices No 5: - Detecting .NET application memory leaks
Memory leaks in .NET application have always being programmer's nightmare. Memory leaks are biggest problems when it comes to production servers. Productions servers normally need to run with least down time. Memory leaks grow slowly and after sometime they bring down the server by consuming huge chunks of memory. Maximum time people reboot the system, make it work temporarily and send a sorry note to the customer for the downtime. ... Read More
.NET Best Practice No: 1:- Detecting High Memory consuming functions in .NET code
One of the important factors for performance degradation in .NET code is memory consumption. Many developers just concentrate on execution time to determine performance bottle necks in a .NET application. Only measuring execution time does not clearly give idea of where the performance issue resides. Ok, said and done one of the biggest task is to understand which function, assembly or class has consumed how much memory. In this tutorial we will see how we can find which functions consume how much memory. This article discusses the best practices involved using CLR profiler for studying memory allocation.... Read More
How to improve your LINQ query performance by 5 X times ?
LINQ has been criticized by many early adopters for its performance issues. Well if you are just going to drag and drop using DBML code generator I am sure you will land up in to mess. Try doing this make a simple LINQ to SQL project using DBML and see your SQL profiler, I am sure you will never like to touch DBML code generator again. ... Read More
Responses
Author: dotnetguts         Company URL: http://www.dotnetguts.blogspot.com
Posted Date: 25/06/2009

Gr8 Tip man,

Cheers,
Dotnetguts
http://dotnetguts.blogspot.com
Author: Ali         Company URL: http://www.dotnetspark.com
Posted Date: 03/08/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: 21/08/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: 21/08/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: 21/08/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:
Posted Date: 05/09/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: 05/09/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:
Posted Date: 01/10/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: 06/01/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: 06/01/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: 06/01/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
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    Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend