Arabic in pdf using iTextSharp in c#

12,520

Solution 1

@csharpcoder has the right idea, but his execution is off. He doesn't add the cell to a table, and the table doesn't end up in the document.

void Go()
{
    Document doc = new Document(PageSize.LETTER);
    string yourPath = "foo/bar/baz.pdf";
    using (FileStream os = new FileStream(yourPath, FileMode.Create))
    {
        PdfWriter.GetInstance(doc, os); // you don't need the return value

        doc.Open();

        string fontLoc = @"c:\windows\fonts\arialuni.ttf"; // make sure to have the correct path to the font file
        BaseFont bf = BaseFont.CreateFont(fontLoc, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        Font f = new Font(bf, 12);

        PdfPTable table = new PdfPTable(1); // a table with 1 cell
        Phrase text = new Phrase("العقد", f);
        PdfPCell cell = new PdfPCell(text);
        table.RunDirection = PdfWriter.RUN_DIRECTION_RTL; // can also be set on the cell
        table.AddCell(cell);
        doc.Add(table);
        doc.Close();
    }
}

You will probably want to get rid of the cell borders etc, but that information can be found elsewhere on SO or the iText website. iText should be able to handle text that contains both RTL and LTR characters.

EDIT

I think the source problem is actually with how the Arabic text is rendered in Visual Studio and in Firefox (my browser), or alternatively with how the Strings are concatenated. I'm not very familiar with Arabic text editors, but the text seems to come out correctly if we do this:

Arabic text in Visual Studio

FYI I had to take a screenshot, because copy-pasting into the browser from VS (and vice versa) messes up the order of the parts of the text.

Solution 2

Right-to-left writing and Arabic ligatures are only supported in ColumnText and PdfPTable!

Try out the below code :

    Document Doc = new Document(PageSize.LETTER);

//Create our file stream
using (FileStream fs = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf"), FileMode.Create, FileAccess.Write, FileShare.Read))
{
    //Bind PDF writer to document and stream
    PdfWriter writer = PdfWriter.GetInstance(Doc, fs);

    //Open document for writing
    Doc.Open();

    //Add a page
    Doc.NewPage();

    //Full path to the Unicode Arial file
    string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arabtype.TTF");

    //Create a base font object making sure to specify IDENTITY-H
    BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    Font f = new Font(bf, 12);
    //Write some text, the last character is 0x0278 - LATIN SMALL LETTER PHI
    Doc.Add(new Phrase("This is a ميسو ɸ", f));

    //add Arabic text, for instance in a table
    PdfPCell cell = new PdfPCell();
    cell.AddElement(new Phrase("Hello\u0682", f));
    cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
    //Close the PDF
    Doc.Close();
}

Solution 3

I hope these notes can help you from other answers:

  1. Use a safe code to achieve your font:

    var tahomaFontFile =  Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Fonts), 
        "Tahoma.ttf");
    
  2. Use BaseFont.IDENTITY_H and BaseFont.EMBEDDED properties.

    var tahomaBaseFont = BaseFont.CreateFont(tahomaFontFile, 
         BaseFont.IDENTITY_H, 
         BaseFont.EMBEDDED);
    var tahomaFont = new Font(tahomaBaseFont, 8, Font.NORMAL);
    
  3. Use PdfWriter.RUN_DIRECTION_RTL, for both your cell and your table:

    var table = new PdfPTable(1) 
        { 
            RunDirection = PdfWriter.RUN_DIRECTION_RTL 
        };
    
    var phrase = new Phrase("تم إبرام هذا العقد في هذا اليوم [●] م الموافق [●] من قبل وبين .", 
         tahomaFont);
    var cell = new PdfPCell(phrase)
        {
            RunDirection = PdfWriter.RUN_DIRECTION_RTL,
            Border = 0,
        };
    

Solution 4

i believe your problem in string structure part, try to use the below code it works fine with me, Good Luck.` public static void GeneratePDF() {

        //Declare a itextSharp document 
        Document document = new Document(PageSize.A4);
        Random ran = new Random();
        string PDFFileName = string.Format(@"C:\Test{0}.Pdf", ran);
        //Create our file stream and bind the writer to the document and the stream 
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(PDFFileName, FileMode.Create));
        //Open the document for writing 
        document.Open();
        //Add a new page 
        document.NewPage();


        var ArialFontFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.ttf");
        //Reference a Unicode font to be sure that the symbols are present. 
        BaseFont bfArialUniCode = BaseFont.CreateFont(ArialFontFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        //Create a font from the base font 
        Font font = new Font(bfArialUniCode, 12);


        //Use a table so that we can set the text direction 
        var table = new PdfPTable(1)
        {
            RunDirection = PdfWriter.RUN_DIRECTION_RTL,
        };
        //Ensure that wrapping is on, otherwise Right to Left text will not display 
        table.DefaultCell.NoWrap = false;

        ContentObject CO = new ContentObject();
        CO.Name = "Ahmed Gomaa";
        CO.StartDate = DateTime.Now.AddMonths(-5);
        CO.EndDate = DateTime.Now.AddMonths(43);

        string content = string.Format(" تم إبرام هذا العقد في هذا اليوم من قبل {0} في تاريخ بين {1} و {2}", CO.Name, CO.StartDate, CO.EndDate);
        var phrase = new Phrase(content, font);
        //var phrase = new Phrase("الحمد لله رب العالمين", font);
        //Create a cell and add text to it 
        PdfPCell text = new PdfPCell(phrase)
        {
            RunDirection = PdfWriter.RUN_DIRECTION_RTL,
            Border = 0
        };
        //Ensure that wrapping is on, otherwise Right to Left text will not display 
        text.NoWrap = false;

        //Add the cell to the table 
        table.AddCell(text);

        //Add the table to the document 
        document.Add(table);

        //Close the document 
        document.Close();

        //Launch the document if you have a file association set for PDF's 
        Process AcrobatReader = new Process();
        AcrobatReader.StartInfo.FileName = PDFFileName;
        AcrobatReader.Start();
    }
}

public class ContentObject
{
    public string Name { set; get; }
    public DateTime StartDate { set; get; }
    public DateTime EndDate { set; get; }
}

`

Share:
12,520
NOBLE M.O.
Author by

NOBLE M.O.

I'm basically a .Net developer and I have experience in c#, Ado.Net, Sql Server, ASP.Net, MVC and entity framework. I have also worked in android and iOS development. I have experience in Web API and WCF. I also worked in Angular JS.

Updated on June 17, 2022

Comments

  • NOBLE M.O.
    NOBLE M.O. about 2 years

    I want to create a PDF file with Arabic text content in C#. I'm using iTextSharp to create this. I followed the instruction in http://geekswithblogs.net/JaydPage/archive/2011/11/02/using-itextsharp-to-correctly-display-hebrew--arabic-text-right.aspx. I want to insert the following Arabic sentence in pdf.

    تم إبرام هذا العقد في هذا اليوم [●] م الموافق [●] من قبل وبين .

    The [●] need to be replaced by dynamic English words. I tried to implement this by using ARIALUNI.TTF [This tutorial link suggested it]. The code is given below.

    public void WriteDocument()
    {
        //Declare a itextSharp document 
        Document document = new Document(PageSize.A4);
    
        //Create our file stream and bind the writer to the document and the stream 
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"D:\Test.Pdf", FileMode.Create));
    
        //Open the document for writing 
        document.Open();
    
        //Add a new page 
        document.NewPage();
    
        //Reference a Unicode font to be sure that the symbols are present. 
        BaseFont bfArialUniCode = BaseFont.CreateFont(@"D:\ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        //Create a font from the base font 
        Font font = new Font(bfArialUniCode, 12);
    
        //Use a table so that we can set the text direction 
        PdfPTable table = new PdfPTable(1);
        //Ensure that wrapping is on, otherwise Right to Left text will not display 
        table.DefaultCell.NoWrap = false;
    
        //Create a regex expression to detect hebrew or arabic code points 
        const string regex_match_arabic_hebrew = @"[\u0600-\u06FF,\u0590-\u05FF]+";
        if (Regex.IsMatch("م الموافق", regex_match_arabic_hebrew, RegexOptions.IgnoreCase))
        {
            table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
        }
    
        //Create a cell and add text to it 
        PdfPCell text = new PdfPCell(new Phrase(" : "+"من قبل وبين" + " 2007 " + "م الموافق" + " dsdsdsdsds " + "تم إبرام هذا العقد في هذا اليوم ", font));
        //Ensure that wrapping is on, otherwise Right to Left text will not display 
        text.NoWrap = false;
    
        //Add the cell to the table 
        table.AddCell(text);
    
        //Add the table to the document 
        document.Add(table);
    
        //Close the document 
        document.Close();
    
        //Launch the document if you have a file association set for PDF's 
        Process AcrobatReader = new Process();
        AcrobatReader.StartInfo.FileName = @"D:\Test.Pdf";
        AcrobatReader.Start();
    }
    

    While calling this function, I got a PDF with some Unicode as given below.

    اذه يف دقعلا اذه ماربإ مت dsdsdsdsds قفاوملا م 2007 نيبو لبق نم مويلا

    It is not matching with our hard coded Arabic sentence. Is this a issue of font? Please help me or suggest me any other method to implement the same.

  • NOBLE M.O.
    NOBLE M.O. over 8 years
    I tried this. But Doc.Add(new Phrase("This is a ميسو ɸ", f)); is printing as This is a وسيم ɸ. Both are different. How to fix this?
  • coder3521
    coder3521 over 8 years
    make sure that you have the Arabic font which is being refereed their . This is a working code. . Give your self a break and try again . You will figure out .
  • mahdi moghimi
    mahdi moghimi almost 6 years
    I hope this comment use by all users. this is ItextSharp arabic text only work with Table and phrase keyword