hi,
After the Word document to add a watermark, all headers are lost behind the first section, test document “多语种文档测试用.docx”,Version:aspose-words-14.9.0-jdk16.jar, code following:
private void insertTextWatermark(DecorateContext context, byte[] qrCodeBytes, byte[] wmBytes) throws Exception {
Document doc = context.getContent(Document.class);
Map wmGraphMap = new HashMap<>();
Map qrCodeGraphMap = new HashMap<>();
HeaderFooter headerFooter = null;
// Insert the watermark into all headers of each document section.
for (Section sect : doc.getSections()) {
PageSetup ps = sect.getPageSetup();
String key = ps.getPageWidth() + "_" + ps.getPageHeight();
if (wmBytes != null) {
Paragraph watermarkPara = wmGraphMap.get(key);
if (watermarkPara == null) {
watermarkPara = new Paragraph(doc);
watermarkPara.appendChild(generateShape(context, doc, ps, wmBytes, ImageType.WATERMARK));
wmGraphMap.put(key, watermarkPara);
}
// There could be up to three different headers in each section,
// since we want
// the watermark to appear on all pages, insert into all headers.
insertWatermarkIntoHeader(watermarkPara, sect, headerFooter, HeaderFooterType.HEADER_PRIMARY);
insertWatermarkIntoHeader(watermarkPara, sect, headerFooter, HeaderFooterType.HEADER_FIRST);
insertWatermarkIntoHeader(watermarkPara, sect, headerFooter, HeaderFooterType.HEADER_EVEN);
}
if (qrCodeBytes != null) {
Paragraph watermarkPara = qrCodeGraphMap.get(key);
if (watermarkPara == null) {
watermarkPara = new Paragraph(doc);
watermarkPara.appendChild(generateShape(context, doc, ps, qrCodeBytes, ImageType.QRCODE));
qrCodeGraphMap.put(key, watermarkPara);
}
// There could be up to three different headers in each section,
// since we want
// the watermark to appear on all pages, insert into all headers.
insertWatermarkIntoHeader(watermarkPara, sect, headerFooter, HeaderFooterType.HEADER_PRIMARY);
insertWatermarkIntoHeader(watermarkPara, sect, headerFooter, HeaderFooterType.HEADER_FIRST);
insertWatermarkIntoHeader(watermarkPara, sect, headerFooter, HeaderFooterType.HEADER_EVEN);
}
}
doc.updatePageLayout();
}
private void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, HeaderFooter headerFooter, int headerType) throws Exception {
HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);
if (header == null) {
if (headerFooter == null) {
header = new HeaderFooter(sect.getDocument(), headerType);
sect.getHeadersFooters().add(header);
} else {
header = (HeaderFooter) headerFooter.deepClone(true);
}
} else {
headerFooter = (HeaderFooter) header.deepClone(true);
}
Paragraph gg = header.getLastParagraph();
if (gg != null) {
Paragraph newnode = (Paragraph) watermarkPara.deepClone(true);
int count = newnode.getCount();
if (count >= 1) {
gg.appendChild(newnode.getFirstChild());
}
if (count >= 2) {
gg.appendChild(newnode.getLastChild());
}
} else {
header.appendChild(watermarkPara.deepClone(true));
}
}