我使用开放 XML(Microsoft Word - .docx)作为文件模板来自动生成其他文档。在模板文档中,我定义了内容控件,并编写了代码来替换这些内容控件中的内容。
内容被替换并生成文档,但我正在努力保持风格。在Word中,在检查内容控件的属性时,我选中了“使用样式将文本格式化为空控件:样式”复选框,并选中了“编辑内容时删除内容控件”。当文档由代码生成时,这似乎没有任何影响。
This is my code (which a community member here was kind enough to help with) for replacing the data in the content controls. Any ideas what I should do in order to keep the formatting? The formatting is simple text formatting, like size and font. Please advice:
private static void ReplaceTags(MainDocumentPart mainPart, string tagName, string tagValue)
{
//grab all the tag fields
var tagFields = mainPart.Document.Body.Descendants<SdtBlock>().Where
(r => r.SdtProperties.GetFirstChild<Tag>().Val == tagName);
foreach (var field in tagFields)
{
//remove all paragraphs from the content block
field.SdtContentBlock.RemoveAllChildren<DocumentFormat.OpenXml.Wordprocessing.Paragraph>();
//create a new paragraph containing a run and a text element
var newParagraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
var newRun = new DocumentFormat.OpenXml.Wordprocessing.Run();
var newText = new DocumentFormat.OpenXml.Wordprocessing.Text(tagValue);
newRun.Append(newText);
newParagraph.Append(newRun);
//add the new paragraph to the content block
field.SdtContentBlock.Append(newParagraph);
}
}
当您为内容控件分配新的样式时RunProperties
元素被添加到下面SdtProperties
。例如,如果我分配一个名为的新样式Style1
我可以看到生成了以下 XML:
<w:sdt>
<w:sdtPr>
<w:rPr>
<w:rStyle w:val="Style1" />
</w:rPr>
<w:alias w:val="LastName" />
<w:tag w:val="LastName" />
....
您需要获取该值并将其分配给新的Paragraph
您正在创建,添加Paragraph
与SdtBlock
然后删除SdtBlock
这就是当您选择“编辑内容时删除内容控件”选项时 Word 所做的操作。这RunProperties
是<w:rPr>
元素。以下内容应该可以完成您的任务。
private static void ReplaceTags(MainDocumentPart mainPart, string tagName, string tagValue)
{
//grab all the tag fields
IEnumerable<SdtBlock> tagFields = mainPart.Document.Body.Descendants<SdtBlock>().Where
(r => r.SdtProperties.GetFirstChild<Tag>().Val == tagName);
foreach (var field in tagFields)
{
//grab the RunProperties from the SdtBlcok
RunProperties runProp = field.SdtProperties.GetFirstChild<RunProperties>();
//create a new paragraph containing a run and a text element
Paragraph newParagraph = new Paragraph();
Run newRun = new Run();
if (runProp != null)
{
//assign the RunProperties to our new run
newRun.Append(runProp.CloneNode(true));
}
Text newText = new Text(tagValue);
newRun.Append(newText);
newParagraph.Append(newRun);
//insert the new paragraph before the field we're going to remove
field.Parent.InsertBefore(newParagraph, field);
//remove the SdtBlock to mimic the Remove content control when contents are edited option
field.Remove();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)