Missing header when watermark is applied from 2nd page onwards

We are using ASPOSE for Word(Java) and applying the Watermark on a document which already has a header & footer. The issue we are getting is the header info is lost from 2nd page onwards but the watermark is applied on all pages. We currently have aspose-words-17.4.0-jdk16.jar. Also tried with 18.1 version but the result is same.
Please find attached sample document & code.aspose-upload.zip (22.7 KB)

@mpinnamaneni,

Thanks for your inquiry. Please ZIP and attach your input and expected output Word documents here for testing. We will investigate the issue on our side and provide you more information.

Hi Tahir,
I already have the input document in the attachment. The expected output is to have watermarks applied to all pages and still keep the data in the headers. The issue is we have the watermarks on all pages but it deletes the headers from 2nd page.
Thanks,
Mahesh

@mpinnamaneni,

Thanks for your inquiry. The ZIP file shared in your first post contains source code (.java file) and Test.docx that is output document generated by Aspose.Words.

In your case, we suggest you please insert watermark in the header of first section only and link the header of second section of document to first section using HeaderFooterCollection.LinkToPrevious method. We suggest you please read following article about linking header/footers.
Continuing Headers and Footers from the Destination Document

Please check the following code example. This code example removes the header and footer of second section of document. The watermark and header will appear on all pages of document.

Document doc = new Document(MyDir + "test.docx");
doc.getSections().get(1).getHeadersFooters().clear();

doc.save(MyDir + "output.docx");

sorry here is the source document.Source.zip (17.7 KB)

This was working for other templates.
Do you still suggest use the link to previous option?

@mpinnamaneni,

Thanks for sharing the document. Please use the following modified method to get the desired output.

private static void insertWatermarkText(Document doc, String watermarkText) throws Exception {
    // Create a watermark shape.
    Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);

    // Set up the text of the watermark.
    watermark.setName("NIAIDDOCXWaterMark_" + System.currentTimeMillis());
    watermark.getTextPath().setText(watermarkText);
    watermark.getTextPath().setFontFamily("Times New Roman");
    watermark.setWidth(500);
    watermark.setHeight(100);
    // Text will be directed from the bottom-left to the top-right corner.
    watermark.setRotation(-40);
    // Remove the following two lines if you need a solid black text.
    watermark.getFill().setColor(Color.GRAY); // Try LightGray to get more
    // Word-style watermark
    watermark.setStrokeColor(Color.GRAY); // Try LightGray to get more
    // Word-style watermark

    // Place the watermark in the page center.
    watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
    watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
    watermark.setWrapType(WrapType.NONE);
    watermark.setVerticalAlignment(VerticalAlignment.CENTER);
    watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
 
    insertWatermarkIntoHeader(watermark, doc.getFirstSection(), HeaderFooterType.HEADER_PRIMARY);
    insertWatermarkIntoHeader(watermark, doc.getFirstSection(), HeaderFooterType.HEADER_FIRST);
    insertWatermarkIntoHeader(watermark, doc.getFirstSection(), HeaderFooterType.HEADER_EVEN);
}

Thanks Tahir. It worked.

Just curious: I see that the difference is there is no for loop to get the sections. How is it different than the old one? We have couple of apps that use the old method. Will all those work if we replace it with this?

@mpinnamaneni,

Thanks for your inquiry. Your input document has two sections. The second section has not header/footers. In this case, same header/footer is appeared on all pages of document.

In your old code, you are adding new header/footer into section of document when section has no header/footer and adding watermark to new header. The new header is different from the header of first section. This is the reason you are not getting the header/footer from second page of document.

In your case, we suggest you please do not create new header for the section that have no header.

Hi Tahir,
so in insertWatermarkIntoHeader method, if we dont create a new header when its null, where do we append the watermark? can you share an example?

@mpinnamaneni,

Thanks for your inquiry. It depends how you want your final output. Please read following article about header and footers.
Continuing Headers and Footers from the Destination Document

Please check insertWatermarkIntoHeader method shard in following article.
How to Add a Watermark to a Document

If you still face problem, please ZIP and attach your input and expected output Word documents here for our reference. We will then provide you more information about your query along with code example.

Hi Tahir,
We are now using the modified code to apply watermarks but this time on the templates we have images. When we apply watermarks the image in the header section is lost.
Can you please let us know what is the best approach for applying watermarks? This appears to be a constant issue for us and really appreciate for a permanent solution which works for all templates.
Thank you very much in advance.

MaheshSOP_Template.zip (49.6 KB)

@mpinnamaneni,

Thanks for your inquiry. The code example shared in the following article works fine and we suggest you please use this code example.
How to Add a Watermark to a Document

The issue you reported in this thread is that the header is missing after using this code. This is because the insertWatermarkIntoHeader method inserts new HeaderFooter for section that has no HeaderFooter.

If you want the same HeaderFooter on the second page of document, you need to copy the HeaderFooter of first section into second section.

Please manually create your expected Word document using Microsoft Word and attach it here for our reference. We will investigate how you want your final Word output be generated like. We will then provide you more information on this along with code.

Hi Tahir,
The sample document is already attached in my previous post. Anyway I have uploaded here too…

Thanks,
MaheshSOP_Template.zip (49.6 KB)

@mpinnamaneni,

Please use the following code example to get the expected output. We have attached the output documents for both input documents that you shared in this thread. watermark output.zip (54.1 KB)

Document doc = new Document(MyDir + "SOP_Template.docx");
insertWatermarkText(doc, "Watermark");
doc.save(MyDir + "SOP_Template output.docx");

    private static void insertWatermarkText(Document doc, String watermarkText) throws Exception {
        // Create a watermark shape. This will be a WordArt shape.
        // You are free to try other shape types as watermarks.
        Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);

        // Set up the text of the watermark.
        watermark.getTextPath().setText(watermarkText);
        watermark.getTextPath().setFontFamily("Arial");
        watermark.setWidth(500);
        watermark.setHeight(100);
        // Text will be directed from the bottom-left to the top-right corner.
        watermark.setRotation(-40);
        // Remove the following two lines if you need a solid black text.
        watermark.getFill().setColor(Color.GRAY); // Try LightGray to get more Word-style watermark
        watermark.setStrokeColor(Color.GRAY); // Try LightGray to get more Word-style watermark

        // Place the watermark in the page center.
        watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
        watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
        watermark.setWrapType(WrapType.NONE);
        watermark.setVerticalAlignment(VerticalAlignment.CENTER);
        watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);

        // Create a new paragraph and append the watermark to this paragraph.
        Paragraph watermarkPara = new Paragraph(doc);
        watermarkPara.appendChild(watermark);

        // Insert the watermark into all headers of each document section.
        for (Section sect : doc.getSections()) {
            // 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, HeaderFooterType.HEADER_PRIMARY);
            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST);
            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN);
        }
    }

    private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType) throws Exception {
        HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);

        if (header == null) {
            // There is no header of the specified type in the current section, create it.
            header = new HeaderFooter(sect.getDocument(), headerType);
            sect.getHeadersFooters().add(header);

            if(sect.getPreviousSibling() != null && !sect.equals(((Document)sect.getDocument()).getFirstSection()))
            {
                CopyHeaderFooter((Section)sect.getPreviousSibling(), sect, headerType);
            }

        }
        // Insert a clone of the watermark into the header.
        header.appendChild(watermarkPara.deepClone(true));
    }

    public static void CopyHeaderFooter(Section srcSection, Section dstSection, int type) throws Exception
    {
        //Remove existing header/footer
        dstSection.getHeadersFooters().getByHeaderFooterType(type).remove();

            // There is no header of the specified type in the current section, create it.
            HeaderFooter header = new HeaderFooter(dstSection.getDocument(), type);
            dstSection.getHeadersFooters().add(header);

            HeaderFooter srcheader = srcSection.getHeadersFooters().getByHeaderFooterType(type);

            //Copy nodes from source document to destination
            for (Node srcNode : (Iterable<Node>)srcheader.getChildNodes())
            {
                Node dstNode = dstSection.getDocument().importNode(srcNode, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
                header.appendChild(dstNode);
            }

    }