Appending Header/Footer in MS Word

Hi,

I am facing some problems while extracting header/footer from one document and appending it in another document.

  • After running the code given below the values of the header/footer are not appearing in the appended document if it is saved in docx format. But it will work if it is saved in doc format.
  • Even with the doc format the values are again not appearing and the formatting of the header/footer gets changed(i.e. the color of the header changes) if the server is running in an linux environment.

Here is my code:-

    public static void main(String[] args) {
        try
        {
            String dir = "E:\\mergedfiles\\";
            String headerFooterWatermarkDocumentFilePath = dir + "Doc1.docx";
            Document doc = new Document(dir + "testHF1.docx");
            DocumentBuilder builder = new DocumentBuilder(doc);
            getAppendedHeaderFooterWatermark(builder, headerFooterWatermarkDocumentFilePath);
            builder.getDocument().save(dir + "document1.doc");
            builder.getDocument().save(dir + "document2.docx");
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void getAppendedHeaderFooterWatermark(DocumentBuilder builder,
                                                        String headerFooterWatermarkDocumentFilePath) throws Exception {
        Document document = builder.getDocument();
        Document headerFooterWatermarkDocument = new Document(headerFooterWatermarkDocumentFilePath);
        NodeImporter importer = new NodeImporter(headerFooterWatermarkDocument, document,
                ImportFormatMode.KEEP_SOURCE_FORMATTING);
        SectionCollection originalDocSections = headerFooterWatermarkDocument.getSections();
        Section originalDocSection = null;
        for (int sectionIndex = 0; sectionIndex < originalDocSections.getCount(); sectionIndex++)
        {
            originalDocSection = originalDocSections.get(sectionIndex);
            Section newSection = null;
            if (document.getSections().get(sectionIndex) == null)
            {
                builder.moveToDocumentEnd();
                int sectionStart = originalDocSection.getPageSetup().getSectionStart();
                switch (sectionStart) {
                    case SectionStart.CONTINUOUS:
                        builder.insertBreak(BreakType.SECTION_BREAK_CONTINUOUS);
                        break;
                    case SectionStart.EVEN_PAGE:
                        builder.insertBreak(BreakType.SECTION_BREAK_EVEN_PAGE);
                        break;
                    case SectionStart.NEW_COLUMN:
                        builder.insertBreak(BreakType.SECTION_BREAK_NEW_COLUMN);
                        break;
                    case SectionStart.NEW_PAGE:
                        builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
                        break;
                    case SectionStart.ODD_PAGE:
                        builder.insertBreak(BreakType.SECTION_BREAK_ODD_PAGE);
                        break;
                }
                newSection = builder.getCurrentSection();
            }
            else
            {
                newSection = document.getSections().get(sectionIndex);
            }
            newSection.getHeadersFooters().clear();
            HeaderFooterCollection headersFooters = originalDocSection.getHeadersFooters();
            HeaderFooter headerFooter = null;
            // //import headers and footers
            newSection.getPageSetup().setDifferentFirstPageHeaderFooter(
                    originalDocSection.getPageSetup().getDifferentFirstPageHeaderFooter());
            newSection.getPageSetup().setOddAndEvenPagesHeaderFooter(
                    originalDocSection.getPageSetup().getOddAndEvenPagesHeaderFooter());
            for (int headersFootersIndex = 0; headersFootersIndex < headersFooters.getCount(); headersFootersIndex++)
            {
                headerFooter = headersFooters.get(headersFootersIndex);
                newSection.getHeadersFooters().add(importer.importNode(headerFooter, true));
            }
        }

        //document.save(dir + "document.doc");
    }

Kindly reply as soon as possible.

Hi Nikhil,

Thanks for your inquiry. In your case, I suggest you please check either HeaderFooter of specific type exists for new section or not. If HeaderFooter for a specific type does not exists, please add it as shown in following code snippet.

HeaderFooter header = newSection.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY);

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

If you still face problem, please share following detail for investigation purposes.

  • Please attach your input Word documents.
  • Please attach the output Word file that shows the undesired behavior.
  • Please
    attach your target Word document showing the desired behavior. You can
    use Microsoft Word to create your target Word document. I will
    investigate as to how you are expecting your final document be generated
    like.

As soon as you get these pieces of information to
us we’ll start our investigation into your issue.

Hi Tahir,

The problems I am getting the described in the following scenarios:

Scenario 1:-

I
have tried using the above code but is giving me an
IllegalArgumentException(Cannot insert a node of this type at this
location).

My code:-

    public static void main(String[] args) {
        try
        {
            String dir = "E:\\mergedfiles\\";
            String headerFooterWatermarkDocumentFilePath = dir + "Doc1.docx";
            Document doc = new Document(dir + "testHF.docx");
            DocumentBuilder builder = new DocumentBuilder(doc);
            getAppendedHeaderFooterWatermark(builder, headerFooterWatermarkDocumentFilePath);
            builder.getDocument().save(dir + "document.docx");
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void getAppendedHeaderFooterWatermark(DocumentBuilder builder,
                                                        String headerFooterWatermarkDocumentFilePath) throws Exception {
        Document document = builder.getDocument();
        Document headerFooterWatermarkDocument = new Document(headerFooterWatermarkDocumentFilePath);
        NodeImporter importer = new NodeImporter(headerFooterWatermarkDocument, document,
                ImportFormatMode.KEEP_SOURCE_FORMATTING);
        SectionCollection originalDocSections = headerFooterWatermarkDocument.getSections();
        Section originalDocSection = null;
        for (int sectionIndex = 0; sectionIndex < originalDocSections.getCount(); sectionIndex++)
        {
            originalDocSection = originalDocSections.get(sectionIndex);
            Section newSection = null;
            //document.getSections().get(sectionIndex).getNodeType()
            if (document.getSections().get(sectionIndex) == null)
            {
                builder.moveToDocumentEnd();
                int sectionStart = originalDocSection.getPageSetup().getSectionStart();
                switch (sectionStart) {
                    case SectionStart.CONTINUOUS:
                        builder.insertBreak(BreakType.SECTION_BREAK_CONTINUOUS);
                        break;
                    case SectionStart.EVEN_PAGE:
                        builder.insertBreak(BreakType.SECTION_BREAK_EVEN_PAGE);
                        break;
                    case SectionStart.NEW_COLUMN:
                        builder.insertBreak(BreakType.SECTION_BREAK_NEW_COLUMN);
                        break;
                    case SectionStart.NEW_PAGE:
                        builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
                        break;
                    case SectionStart.ODD_PAGE:
                        builder.insertBreak(BreakType.SECTION_BREAK_ODD_PAGE);
                        break;
                }
                newSection = builder.getCurrentSection();
            }
            else
            {
                newSection = document.getSections().get(sectionIndex);
            }
            newSection.getHeadersFooters().clear();
            HeaderFooterCollection headersFooters = originalDocSection.getHeadersFooters();

            // //import headers and footers
            newSection.getPageSetup().setDifferentFirstPageHeaderFooter(
                    originalDocSection.getPageSetup().getDifferentFirstPageHeaderFooter());
            newSection.getPageSetup().setOddAndEvenPagesHeaderFooter(
                    originalDocSection.getPageSetup().getOddAndEvenPagesHeaderFooter());

            HeaderFooter newheaderFooter = newSection.getHeadersFooters() == null
                    || newSection.getHeadersFooters().getCount() == 0 ? null : newSection.getHeadersFooters().get(0);
            if (newheaderFooter == null)
            {
                if (headersFooters.getCount() > 0
                        && headersFooters.get(0).getHeaderFooterType() == HeaderFooterType.HEADER_PRIMARY)
                {
                    newheaderFooter = new HeaderFooter(newSection.getDocument(), HeaderFooterType.HEADER_PRIMARY);
                    newSection.getHeadersFooters().add(newheaderFooter);

                }
                else if (headersFooters.getCount() > 0
                        && headersFooters.get(0).getHeaderFooterType() == HeaderFooterType.HEADER_FIRST)
                {
                    newheaderFooter = new HeaderFooter(newSection.getDocument(), HeaderFooterType.HEADER_FIRST);
                    newSection.getHeadersFooters().add(newheaderFooter);

                }
                else if (headersFooters.getCount() > 0
                        && headersFooters.get(0).getHeaderFooterType() == HeaderFooterType.HEADER_EVEN)
                {
                    newheaderFooter = new HeaderFooter(newSection.getDocument(), HeaderFooterType.HEADER_EVEN);
                    newSection.getHeadersFooters().add(newheaderFooter);

                }
                else if (headersFooters.getCount() > 0
                        && headersFooters.get(0).getHeaderFooterType() == HeaderFooterType.FOOTER_FIRST)
                {
                    newheaderFooter = new HeaderFooter(newSection.getDocument(), HeaderFooterType.FOOTER_FIRST);
                    newSection.getHeadersFooters().add(newheaderFooter);
                }
                else if (headersFooters.getCount() > 0
                        && headersFooters.get(0).getHeaderFooterType() == HeaderFooterType.FOOTER_PRIMARY)
                {
                    newheaderFooter = new HeaderFooter(newSection.getDocument(), HeaderFooterType.FOOTER_PRIMARY);
                    newSection.getHeadersFooters().add(newheaderFooter);
                }
                else if (headersFooters.getCount() > 0
                        && headersFooters.get(0).getHeaderFooterType() == HeaderFooterType.FOOTER_EVEN)
                {
                    newheaderFooter = new HeaderFooter(newSection.getDocument(), HeaderFooterType.FOOTER_EVEN);
                    newSection.getHeadersFooters().add(newheaderFooter);
                }
                addHeaderNodesToDocumentSection(headersFooters, newSection, importer);
            }

        }

        //document.save(dir + "document.doc");
    }

    public static void addHeaderNodesToDocumentSection(HeaderFooterCollection headersFooters, Section newSection,
                                                       NodeImporter importer) {
        HeaderFooter headerFooter = null;
        for (int headersFootersIndex = 0; headersFootersIndex < headersFooters.getCount(); headersFootersIndex++)
        {
            headerFooter = headersFooters.get(headersFootersIndex);
            newSection.getHeadersFooters().add(importer.importNode(headerFooter, true));
        }
    }

Scenario 2:-

The code I specified in the previous message works is a 64 bit machine but not in a 32 bit machine.

Scenario 3:-

The code I specified in the previous message works when saved in doc format but not in docx format.
If any of the files are in doc format it works.

Scenario 4:-

The values and the format both changes if the server is running in an linux environment.

I have also attached the files you have asked. Kindly look into the issue.

Hi Tahir,

Thank you for your swift reply.

I have used the above code and it has solved one of my problems. That is the format is properly retained.

It is also working perfectly when the server is in a windows environment.

The issue I am still facing is that the value of the title and date are still not retained if the server is running in an linux environment. And this happens if the header-footer template file is a docx file,but it is working properly if the header-footer template file is a doc file. And the problem is my applcation does not support doc format, we support only docx.

Kindly see if there is a solution or a work around.

Thank You.

Hi Nikhil,

Thanks for your inquiry.

nikhil.mishra:

The issue I am still facing is that the value of the title and date are still not retained if the server is running in an linux environment. And this happens if the header-footer template file is a docx file,but it is working properly if the header-footer template file is a doc file. And the problem is my applcation does not support doc format, we support only docx.

I have tested the scenario at Ubuntu using the same code shared here. I have not found any issue while using latest version of Aspose.Words for Java 14.7.0. Please use the Aspose.Words for Java 14.7.0. I have attached the output document with this post for your kind reference.

In your case, I suggest you please remove the content control node itself but keeps the content of it inside the document tree using StructuredDocumentTag.removeSelfOnly method. In this case, you do not need to save the document to Doc file format as shared in my previous post. Please check the following highlighted code snippet.

Please let us know if you have any more queries.

    public static void getAppendedHeaderFooterWatermark(DocumentBuilder builder, String headerFooterWatermarkDocumentFilePath) throws Exception {
        Document document = builder.getDocument();
        Document headerFooterWatermarkDocument = new Document(headerFooterWatermarkDocumentFilePath);
        for (StructuredDocumentTag sdt : (Iterable)headerFooterWatermarkDocument.getChildNodes(NodeType.*STRUCTURED_DOCUMENT_TAG*, true))
        {
            sdt.removeSelfOnly();
        }
        NodeImporter importer = new NodeImporter(headerFooterWatermarkDocument, document,
                ImportFormatMode.KEEP_SOURCE_FORMATTING);
        SectionCollection originalDocSections = headerFooterWatermarkDocument.getSections();
        Section originalDocSection = null;
        for (int sectionIndex = 0; sectionIndex < originalDocSections.getCount(); sectionIndex++)
        {
            // your code…
        }
    }

    public static void addHeaderNodesToDocumentSection(HeaderFooterCollection headersFooters, Section newSection,
                                                       NodeImporter importer) throws Exception {
        HeaderFooter headerFooter = null;
        for (int headersFootersIndex = 0; headersFootersIndex < headersFooters.getCount(); headersFootersIndex++)
        {
            headerFooter = headersFooters.get(headersFootersIndex);
            HeaderFooter header
            newSection.getHeadersFooters().getByHeaderFooterType(headerFooter.getHeaderFooterType());
            if (header == null)
            {
                // There is no header of the specified type in the current section, create it.
                header = new HeaderFooter(newSection.getDocument(), headerFooter.getHeaderFooterType());
                newSection.getHeadersFooters().add(header);
            }
            for (Node srcNode : (Iterable)headerFooter.getChildNodes())
            {
                Node dstNode = newSection.getDocument().importNode(srcNode, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
                header.appendChild(dstNode);
            }
        }
    }