Populating a Word Document with Arabic/English text from Database with DocumentFormat.OpenXml

431 Views Asked by At

I'm populating a Word document using DocumentFormat.OpenXml in .Net Core 5.0, the text is coming from a database, sometime the text includes Arabic text with few English words, the words do not appear in the right order, for example if this is a an Arabic text and the 2nd work is English "one TWO three" it will appear in Word document like this "three TWO one", if I copy the same text from database and paste it in Word it will appear in the correct order.

I think Word is dividing the text I'm pasting to different runs and put them in the right order but in my code I'm placing the complete text in one run, is there a way to process this automatically by OpenXML or I have to do it manually?

here is my code:

int rowNo = 2;
  foreach (DataLine line in data.Lines)
  {
    TableRow row = table.Elements<TableRow>().ElementAt(rowNo++);
    Paragraph p1 = row.Elements<TableCell>().ElementAt(0).Elements<Paragraph>().First();
    Run r1 = new();
    Text t1 = new(line.AmountString);
    r1.AddChild(t1);
    p1.AddChild(r1);
    
    Paragraph p2 = row.Elements<TableCell>().ElementAt(1).Elements<Paragraph>().First();
    Run r2 = new();
    Text t2 = new(line.Description);
    r2.AddChild(t2);
    p2.AddChild(r2);
    
    ParagraphProperties pp = p2.ChildElements.First<ParagraphProperties>();
    BiDi bidi = new BiDi();
    pp.TextDirection = new TextDirection() { Val = TextDirectionValues.TopToBottomRightToLeft };
    pp.Append(bidi);
}

The last 4 lines make no difference.

Note that the Work document is well formatted with correct text direction and fonts.

Regards

Ameen

1

There are 1 best solutions below

0
Ameen Nihad On

It turned out that it's possible to put RTL and LTR text in single Run, the following RunPropoetries worked for me:

run.RunProperties = new RunProperties
  {
    RunFonts = new RunFonts { ComplexScript = "Calibri" },
    RightToLeftText = new RightToLeftText(),
    Languages = new Languages() { 
      Bidi = new StringValue("ar-IQ"), 
      Val = new StringValue("en-US") 
    }
  };

I extracted the values from a Word document created in MS Word, but there the paragraph was separated to 3 Runs.

Credit goes to (amiry jd) who had the same issue 5 years ago check this post