我使用Open XML
(DocumentFormat.OpenXml
nuget包)生成docx文件。这是我的方法:
我有一个名为template.docx
的文件。在此文件中,我有一个Cover Page
和一个空白页面,其中包含header
,footer
和背景图片。无论如何,我首先打开文档,然后在文档中附加一些文本,然后关闭它。
另一方面,我有一个名为template-back.docx
的文件,我想在上面修改过的文档(template.docx
)的末尾追加它。
我可以使用此代码段来完成此操作:
public static void MergeDocumentWithPagebreak(string sourceFile, string destinationFile, string altChunkID) {
using (var myDoc = WordprocessingDocument.Open(sourceFile, true)) {
var mainPart = myDoc.MainDocumentPart;
//Append page break
var para = new Paragraph(new Run((new Break() { Type = BreakValues.Page })));
mainPart.Document.Body.InsertAfter(para, mainPart.Document.Body.LastChild);
//Append file
var chunk = mainPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.WordprocessingML, altChunkID);
using (var fileStream = File.Open(destinationFile, FileMode.Open))
chunk.FeedData(fileStream);
var altChunk = new AltChunk{
Id = altChunkID
};
mainPart.Document
.Body
.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
mainPart.Document.Save();
}
}
但是,当我这样做时,header
,footer
和背景图片会应用到最后一页。我希望能够排除最后一页获得这些设计。我想要它干净,简单和白色。但谷歌搜索问题,没有任何帮助。你有什么想法吗?提前致谢。
P.S。
关于合并文档的原始文章here:
答案 0 :(得分:0)
这有点棘手,但并不那么复杂。
首先,您必须了解单词是如何运作的:
关于&#34;如何在单词&#34;中创建不同标题的一些文档。 http://www.techrepublic.com/blog/microsoft-office/accommodate-different-headers-and-footers-in-a-word-document/
如果我们转换为您的代码,在将文档插入另一端之前,您必须:
要创建新标头,请使用其他一些文档:https://msdn.microsoft.com/en-us/library/office/cc546917.aspx
技巧:如果您插入的文档不包含页眉/页脚,请创建空文章并重新复制它们
信息:我尝试删除bundle exec rspec
或将r:id设置为0,但它不起作用。创建一个空头是最快的方法
答案 1 :(得分:0)
使用以下代码替换您的分页符
Paragraph PageBreakParagraph = new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Break() { Type = BreakValues.Page }));
我也看到你在最后一个孩子之后插入,这个孩子与追加不一样,但是效果很好!请改用它。
wordprocessingDocument.MainDocumentPart.Document.Body.Append(PageBreakParagraph)
您需要将分节符添加到节属性中。然后,您需要将section属性附加到段落属性。然后将段落属性附加到段落。
Paragraph paragraph232 = new Paragraph();
ParagraphProperties paragraphProperties220 = new ParagraphProperties();
SectionProperties sectionProperties1 = new SectionProperties();
SectionType sectionType1 = new SectionType(){ Val = SectionMarkValues.NextPage };
sectionProperties1.Append(sectionType1);
paragraphProperties220.Append(sectionProperties1);
paragraph232.Append(paragraphProperties220);
//Replace your last but one line with this one.
mainPart.Document
.Body
.Append(altChunk);
生成的Open XML是:
<w:p>
<w:pPr>
<w:sectPr>
<w:type w:val="nextPage" />
</w:sectPr>
</w:pPr>
</w:p>
最简单的方法是实际创建文档,然后在Open XML Productivity Tool中打开它,您可以反映代码并查看C#代码将生成您正在尝试的各种Open XML元素实现。希望这有帮助!