I am using DotNetCore.NPOI V1.0.2 in my .NET Core 2 MVC web app. I have been researching for instructions or examples to create .docx document with header and footer without any success. Does anyone know how to create two lines header and footer with page numbers like Page 1/x format?
Asked
Active
Viewed 893 times
1 Answers
0
This unit test creates headers given an existing document. I tried it and it works.
However, I couldn't find a way to create a header from new without reading in a source docx first. Creating headers from a new XWPFDocument()
yields a null reference exception.
The solution for my use case is to seed the thing with an empty template.docx
, populate it as I want, and save it out to something else. Based on the unit test:
class Program
{
static void Main(string[] args)
{
var here = AppContext.BaseDirectory;
using (var input = new FileStream(Path.Combine(here, "template.docx"), FileMode.Open))
{
var doc = new XWPFDocument(input);
var rawParagraph = new CT_P();
var rawRun = rawParagraph.AddNewR();
var rawText = rawRun.AddNewT();
rawText.Value = "Paragraph in header";
var headerParagraph = new XWPFParagraph(rawParagraph, doc);
var paragraphs = new XWPFParagraph[] { headerParagraph };
var header = doc.GetHeaderFooterPolicy().CreateHeader(XWPFHeaderFooterPolicy.DEFAULT, paragraphs);
// etc for footer
using (var fs = new FileStream(Path.Combine(here, "output.docx"), FileMode.Create, FileAccess.Write))
{
doc.Write(fs);
}
}
}
}