编辑Word书签更改字体

编辑Word书签更改字体

本文介绍了编辑Word书签更改字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用OpenXml生成文档的C#程序.它使用以下方法用值替换书签:

I have a C# program that generates documents using OpenXml. It replaces bookmarks with values using the following method :

private void FillBookmark(BookmarkStart bookmark, string value)
{
    var text = new Text(value);
    bookmark.RemoveAllChildren();

    IEnumerable<OpenXmlElement> elementsAfter = bookmark.ElementsAfter();
    IEnumerable<OpenXmlElement> insideBookmark = elementsAfter.TakeWhile(element => !(element is BookmarkEnd));
    foreach (OpenXmlElement element in insideBookmark)
    {
        element.RemoveAllChildren();
    }
    OpenXmlElement previousSibling = bookmark.PreviousSibling();
    while (previousSibling is BookmarkStart || previousSibling is BookmarkEnd)
    {
        previousSibling = previousSibling.PreviousSibling();
    }
    var container = new Run(text);
    previousSibling.AppendChild(container);
}

在此特定的word文档中,使用的字体是Raleway.有几个书签,执行此方法后,两个书签使用Calibri字体.我试图重写这些书签,以确保它们在Raleway中,但它们仍会更改为Calibri.

In this particular word document, the font used is Raleway. There are several bookmarks and after the execution of this method, two bookmarks are using the Calibri font. I tried to rewrite theses bookmarks to be sure they are in Raleway but they continue to change to Calibri.

这怎么可能?

推荐答案

首先,您的代码创建了没有先前RunProperty的新元素.因此,您将获得类似下一个片段的内容:

First of all your code creates new element without previous RunProperties.So, you get something like next snippet:

<w:r>
    <w:t>valuexX</w:t>
</w:r>

代替它:

<w:r w:rsidRPr="00DE66A4">
    <w:rPr>
        <w:rFonts w:ascii="Algerian" w:hAnsi="Algerian" />
            <w:lang w:val="en-US" />
    </w:rPr>
    <w:t>6</w:t>
</w:r>

您可以复制以下任何属性:

You can copy any properties like this:

private void FillBookmark(BookmarkStart bookmark, string value)
{
  var text = new Text(value);
  bookmark.RemoveAllChildren();

  IEnumerable<OpenXmlElement> elementsAfter = bookmark.ElementsAfter();
  IEnumerable<OpenXmlElement> insideBookmark = elementsAfter.TakeWhile(element => !(element is BookmarkEnd));
  foreach (OpenXmlElement element in insideBookmark)
  {
    element.RemoveAllChildren();
  }
  OpenXmlElement previousSibling = bookmark.PreviousSibling();
  while (previousSibling is BookmarkStart || previousSibling is BookmarkEnd)
  {
    previousSibling = previousSibling.PreviousSibling();
  }

  //Get previous font.
  var runProperties = previousSibling.GetFirstChild<ParagraphMarkRunProperties>().GetFirstChild<RunFonts>();
  //var runProperties = previousSibling.GetFirstChild<RunProperties>(); - if its simple element.

  // Clone.
  var newProperty = (RunFonts)runProperties.Clone();

  // Create container with properties.
  var container = new Run(text)
  {
    RunProperties = new RunProperties() { RunFonts = newProperty }
  };

  previousSibling.AppendChild(container);
}

这篇关于编辑Word书签更改字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 07:08