Defining paragraph with RTL direction in word file by OpenXML in C#

流过昼夜 提交于 2019-12-06 07:16:50

问题


How to set the right-to-left direction for a paragraph in word with OpenXML in C#? I use codes below to define it but they won't make any change:

 RunProperties rPr = new RunProperties();

 Style style = new Style();
 style.StyleId = "my_style";
 style.Append(new Justification() { Val = JustificationValues.Right });
 style.Append(new TextDirection() { Val = TextDirectionValues.TopToBottomRightToLeft });
 style.Append(rPr);

and at the end I will set this style for my paragraph:

...
heading_pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "my_style" };

But is see no changes in the output file.

I have found some post but they didn't help me at all,like:

Changing text direction in word file

How can solve this problem?

Thanks in advance.


回答1:


Use the BiDi class to set the text direction to RTL for a paragraph. The following code sample searches for the first paragraph in a word document and sets the text direction to RTL using the BiDi class:

using (WordprocessingDocument doc =
   WordprocessingDocument.Open(@"test.docx", true))
{
  Paragraph p = doc.MainDocumentPart.Document.Body.ChildElements.First<Paragraph>();

  if(p == null)
  {
    Console.Out.WriteLine("Paragraph not found.");
    return;
  }

  ParagraphProperties pp = p.ChildElements.First<ParagraphProperties>();

  if (pp == null)
  {
    pp = new ParagraphProperties();
    p.InsertBefore(pp, p.First());
  }

  BiDi bidi = new BiDi();
  pp.Append(bidi);

}

There are a few more aspects to bi-directional text in Microsoft Word. SanjayKumarM wrote an article about how right-to-left text content is handled in Microsoft Word. See this link for more information.




回答2:


This code worked for me to set the direction Right to Left

var run = new Run(new Text("Some text"));
var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(run);
paragraph.ParagraphProperties = new ParagraphProperties()
{
    BiDi = new BiDi(),
    TextDirection = new TextDirection()
    {
        Val = TextDirectionValues.TopToBottomRightToLeft
    }
};


来源:https://stackoverflow.com/questions/15461035/defining-paragraph-with-rtl-direction-in-word-file-by-openxml-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!