However, it is straightforward to insert a page break between imported chunks of content. The following example sets up a document with two imported chunks, with a page break inserted between them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
class Program
{
static void AppendAltChunk(WordprocessingDocument doc,
string altChunkId, string html)
{
MainDocumentPart mainPart = doc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
“application/xhtml+xml”, altChunkId);
using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
using (StreamWriter stringStream = new StreamWriter(chunkStream))
stringStream.Write(html);
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
OpenXmlElement last = doc.MainDocumentPart.Document
.Body
.Elements()
.LastOrDefault(e => e is Paragraph || e is AltChunk);
if (last == null)
doc.MainDocumentPart.Document.Body.InsertAt(altChunk, 0);
else
last.InsertAfterSelf(altChunk);
}
static void AppendPageBreak(WordprocessingDocument myDoc)
{
MainDocumentPart mainPart = myDoc.MainDocumentPart;
OpenXmlElement last = myDoc.MainDocumentPart.Document
.Body
.Elements()
.LastOrDefault(e => e is Paragraph || e is AltChunk);
last.InsertAfterSelf(new Paragraph(
new Run(
new Break() { Type = BreakValues.Page })));
}
static void Main(string[] args)
{
using (WordprocessingDocument doc =
WordprocessingDocument.Open(“Test.docx”, true))
{
// First, delete all paragraphs in the document, creating a blank document.
var paras = doc.MainDocumentPart
.Document
.Body
.Elements<Paragraph>()
.ToList();
foreach (var p in paras)
p.Remove();
string html1 =
@”<html>
<head/>
<body>
<h1>Html Heading</h1>
<p>On the Insert tab, the galleries include items that are designed to coordinate.</p>
<p>Most controls offer a choice of using the look from the current theme.</p>
</body>
</html>”;
string html2 =
@”<html>
<head/>
<body>
<h1>New Heading</h1>
<p>This content is on its own page.</p>
<p>This is the second paragraph.</p>
</body>
</html>”;
AppendAltChunk(doc,
“AltChunkId1”,
html1);
AppendPageBreak(doc);
AppendAltChunk(doc,
“AltChunkId2”,
html2);
}
}
}