[英]How to keep style on open xml documents
我使用開放XML(Microsoft Word - .docx)作為文件模板來自動生成其他文檔。 在模板文檔中,我定義了內容控件,並且我編寫了代碼來替換這些內容控件中的內容。
內容被替換並生成文檔,但我正在努力保持風格。 在Word中,當檢查內容控件的屬性時,我檢查了checbox“使用樣式將文本格式化為空控件:樣式”,並檢查“在編輯內容時刪除內容控件”。 當代碼生成文檔時,這似乎沒有任何影響。
這是我的代碼(這里的社區成員非常友好地幫助)來替換內容控件中的數據。 任何想法,我應該做什么,以保持格式? 格式化是簡單的文本格式,如大小和字體。 請指教:
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.