Click here to Skip to main content
15,881,757 members
Articles / Web Development / ASP.NET
Tip/Trick

How to Write Arabic Text on PDF File using iTextSharp API in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
26 Sep 2014CPOL2 min read 30K   8   3
Write an Arabic text on a specific location of PDF file using iTextSharp library.

Introduction

We can write an Arabic text on a PDF file by using iTextSharp library in ASP.NET. It is little bit tricky because of Arabic language's alignment. Arabic language starts from right side and proceeds to left.

iTextSharp is an open source library that allows to create and manipulate PDF (Portable Document Format) documents. It is easy to use with ASP.NET for dynamic PDF document generation. To know more about iTextSharp, visit this link.

The following piece of code has been used for writing Arabic text on a PDF file using iTextSharp library.

C#
using iTextSharp.text; 
using iTextSharp.text.pdf;</p>

private void CreatePDFFileWithArabicText()
{
    FileStream fs = null;
    Document document = null;
    PdfWriter writer = null;
    PdfReader reader = null;
    string str1 = "مرحبا العالم";
    //string str1 = "Hello World";
    try
    {
        string sourceFile = "E:/Data/Canon_Issues/Produktinfo.pdf";
        string newFile = "E:/Data/Canon_Issues/newFile3.pdf";
        // open the reader
        reader = new PdfReader(sourceFile);
        Rectangle size = reader.GetPageSizeWithRotation(1);
        int pageCount = reader.NumberOfPages;
        document = new Document(size);
        // open the writer
        fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
        writer = PdfWriter.GetInstance(document, fs);
        document.Open();
        
        // loop through every page of source document
        for(int i = 1; i <= pageCount; i++)
        {
            //// Read the pdf content
            PdfContentByte cb = writer.DirectContent;
            // Get new page size.
            document.SetPageSize(reader.GetPageSizeWithRotation(1));
            document.NewPage();
            float h1 = document.PageSize.Height;
            //Insert text into the third page of document.
            if(i == 3)
            {
                // select the font properties
                string fontpath = Environment.GetEnvironmentVariable("SystemRoot") + 
                "\\fonts\\tahoma.ttf";
                BaseFont basefont = BaseFont.CreateFont
                (fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font tahomaFont = new Font(basefont, 10, Font.NORMAL, BaseColor.RED);
                //set the direction of text.
                ColumnText ct = new ColumnText(writer.DirectContent);
                ct.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                //set the position of text in page.
                ct.SetSimpleColumn(100, 100, 500, 800, 24, Element.ALIGN_RIGHT);
                var chunk = new Chunk(str1, tahomaFont);
                ct.AddElement(chunk);
            }
            PdfImportedPage page = writer.GetImportedPage(reader, i);
        }        
    }
    catch(Exception ex)
    {
        throw ex;
    }
    finally
    {
        // close the streams 
        document.Close();
        fs.Close();
        writer.Close();
        reader.Close();
    }
}

First, we need to implement iTextSharp library in our code by adding this line “using iTextSharp.text.pdf;” followed by adding reference of iTextSharp.dll. You can download iTextSharp library from this link.

Second, create a temporary file “newFile3.pdf” from source PDF file “E:/Data/SourcePDFFile.pdf” by using FileStream() method, which takes 3 parameters as temporary file path, file mode type (here, we create a new file so mode isFileMode.Create) and file access type (here is FileAccess.Write).

Third, create a PdfReader object to fetch required property of source page like page size, number of pages, etc. by using PdfReader() method, which takes source file path as parameter. And a PdfWriter object, which has the instance of temporary PDF file for addressing Arabic text in a particular location.

Fourth, open the temporary PDF document and loop through every page of source file to import all the pages and page contents to temporary document by using PdfWriter's GetImportedPage() method. Here, I put Arabic text in 3rdpage of PDF document (i == 3). We need to set font family for Arabic text that supports Arabic characters, here is “tahoma.ttf”, by creating a new base font object and CreateFont() method of base font object. We can also set font size, font type and font color in base font. We can apply this font to the Arabic text using a new Chunk object and later added into the PDF page by AddElement(chunk) method of ColumnText object.

Fifth, set the direction of text from Right to Left by setting the property RunDirection of ColumnText object to PdfWriter.RUN_DIRECTION_RTL. You can also set the location of text anywhere in the page by using SetSimpleColumn() method of ColumnText object.

At last, we need to close all the open objects like file stream, PDF reader and PDF writer, etc. in finally block.

Hope it will be helpful to somebody...

Thanks!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionError: The document has no pages Pin
Member 1038394911-Apr-18 20:57
Member 1038394911-Apr-18 20:57 
QuestionExample Pin
Hisham Shaaban1-May-16 20:51
Hisham Shaaban1-May-16 20:51 
please i need a code example in vb.net
QuestionExample Pin
Hisham Shaaban1-May-16 20:51
Hisham Shaaban1-May-16 20:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.