wordpress hit counter
Adding a header part in Java - OpenXML Developer - Blog - OpenXML Developer
Goodbye and Hello

OpenXmlDeveloper.org is Shutting Down

There is a time for all good things to come to an end, and the time has come to shut down OpenXmlDeveloper.org.

Screen-casts and blog posts: Content on OpenXmlDeveloper.org will be moving to EricWhite.com.

Forums: We are moving the forums to EricWhite.com and StackOverflow.com. Please do not post in the forums on OpenXmlDeveloper.org. Instead, please post in the forums at EricWhite.com or at StackOverflow.com.

Please see this blog post for more information about my plans moving forward.  Cheers, Eric

Adding a header part in Java

Adding a header part in Java

Rate This
  • Comments 12

Article By - Vineela Kavoori, Sonata Software Limited

This article describes how to add header to an existing word document using core java.

 

PROCEDURE TO ADD THE HEADER TO THE WORD DOCUMENT:

 

To add a header to the existing word document, the following steps are to be followed:

  1. Unzip the existing word document
  2. Add the header2.xml in the necessary directory
  3. Modify the [Content_Types].xml
  4. Modify the document.xml
  5. Modify document.xml.rels if it is present, else create a new document.xml.rels
  6. Zip back all the files

 

These steps are explained in detail as follows:

  1. Unzip the existing word document:

To unzip the existing word document

·         Get the necessary document from the location specified.

·         Using the "zip" package provided in the "util" package, unzip the word document

 

The code snippet for this is as follows:

public static void unZipFile(String zipFileName, String toExtractFile)

{

    ..……

                     ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

                    Enumeration enumeration = zipFile.entries();

                    while (enumeration.hasMoreElements())

                    {

                        ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();

                        String currName = zipEntry.getName();

                        File destFile = new File(destDirectory, currName);                       

                        File destinationParent = destFile.getParentFile();

                        destinationParent.mkdirs();                        

                        if( ! zipEntry.isDirectory())

                        {

                            BufferedInputStream is =

                                    new  BufferedInputStream(zipFile.getInputStream(zipEntry));

                           

                            int currentByte;

                           

                            FileOutputStream fos = new FileOutputStream(destFile);

                            BufferedOutputStream dest =  new BufferedOutputStream(fos);

                           

                            while((currentByte = is.read()) != -1)

                            {

                                dest.write(currentByte);

                            }

            }

        }

     ……

}

           

  1. Add "header2.xml" in the necessary directory:

To add the "header2.xml" in the necessary directory, the steps to be followed are:

·         Get the parent folder of the document.xml and then add the "header2.xml" into that directory.

·         A sample "header2.xml" is provided in the source code. To change the text of the header, change the text in the "<w:t>" element.

 

  1. To modify the [Content_Types].xml:

To modify the [Content_Types].xml, the steps to be followed are:

 

·         Get the document element of the [Content_Types].xml

·         Create an element called "Override".

·         Add the attributes - "PartName" and "ContentType" to the "Override" element.

·         Add the "Override" element to the document element of the [Content_Types].xml

 

The code snippet for this is:

            ………

            Element rootElement =  doc.getDocumentElement();

            Element override = (Element) doc.createElement("Override");

            ………

            override.setAttribute("PartName", folderForHeader + "/header2.xml");

            override.setAttribute("ContentType","application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml");

            rootElement.appendChild(override);

            ………       

 

  1. Modify document.xml

To modify the document.xml, the steps to be followed are:

 

·         Get the document element of the document.xml

·         Using the document element, navigate to the "w:sectPr" element.

·         Create a new element called "w:headerReference"

·         Add attributes - "w:type" and "r:id" to this "w:headerReference" element

·         If the "w:sectPr" element exists, then add this "w:headerReference" element to it

·         Otherwise, create a "w:sectPr" element and then add the "w:headerReference"element to it.

 

The code snippet for this is:

            Element headerRef = (Element) doc.createElement("w:headerReference");

            headerRef.setAttribute("w:type","default");

            headerRef.setAttribute ("r:id",rID);

            if(!(sectElement == null))

            {

                sectElement.appendChild(headerRef);

}

if(sectElement == null)

{

                Element sectPrElement = (Element) doc.createElement("w:sectPr");

                sectPrElement.appendChild(headerRef);

                parentElement.appendChild(sectPrElement);

            }

 

  1. Modify document.xml.rels if it exists or create a new document.xml.rels:

To modify the document.xml.rels, the steps to be followed are:

·         Navigate to the folder where document.xml.rels file exists

·         Create a element called "Relationships"

·         Create a element called "Relationship" and add attributes  - "Id", "Type", "Target" to it

·         Add this element to the "Relationships" element.

 

To create a new document.xml.rels file, the steps to be followed are:

·         Create a new document element

·         Create a element called "Relationships"

·         Create a element called "Relationship" and add attributes  - "Id", "Type", "Target" to it

·         Add this "Relationship" element to the "Relationships" element.

·         Then using FileWriter flush the output.

 

The code snippet for this is:

           

            doc = docBuilder.newDocument();

Element relationships = (Element) doc.createElement("Relationships");

relationships.setAttribute("xmlns","http://schemas.openxmlformats.org/package/2006/relationships");

Node rootNode = (Node) relationships;

Element relationship = (Element) doc.createElement("Relationship");

relationship.setAttribute("Id",rID);

relationship.setAttribute ("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/header");

           relationship.setAttribute("Target","header2.xml");

             Node childNode = (Node) relationship;

             …..     

             doc = docBuilder.parse (documentXMLRels);

             NodeList relElements = doc.getElementsByTagName("Relationships");

             Element relationships = (Element) relElements.item (0);

             Element childElement = (Element) doc.createElement ("Relationship");

             childElement.setAttribute ("Id", rID);

             childElement.setAttribute("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header");

             childElement.setAttribute ("Target", "header2.xml");

             relationships.appendChild (childElement);

             helpObj.outputXML (doc, documentXMLRels);        

 

  1. To zip back all the files:

To zip back all the files, the steps to be followed are:

·         Get the list of path of all the files that have to be zipped.

·         Get the list of relative path of all the files to be zipped.

·         Using the "zip" package provided in the "util" package, zip the files into a word document

 

The code snippet for this is:

            …….

            FileOutputStream outStream = new FileOutputStream(zipFileName);

            ZipOutputStream zipOutStream = new ZipOutputStream (outStream);

            zipOutStream.setLevel(Deflater.BEST_COMPRESSION);

            ……

             while(itr.hasNext())

             {

                             String path = (String) itr.next();

                             inStream = new FileInputStream(path);

                             String relPath = (String) relItr.next();

                             zipOutStream.putNextEntry(new ZipEntry(relPath));

                              int i=0;

                             while ((i=inStream.read()) != -1 )

                            {

                                    zipOutStream.write(i);

                            }

            }

            ….

 

This is a simple demo which demonstrates ease of use adding a Header to a word document using JAVA. The example demo is attached with the article as a zip file.

Attachment: ooxml.zip
Page 1 of 1 (12 items)