I am using docx4j for generating the Word document from html.
I want to display page border in my word document.
Is there any sample to do this?
Page borders live in the sectPr element, for example:
<w:pgBorders w:offsetFrom="page">
<w:top w:val="single" w:color="auto" w:sz="4" w:space="24"/>
<w:left w:val="single" w:color="auto" w:sz="4" w:space="24"/>
<w:bottom w:val="single" w:color="auto" w:sz="4" w:space="24"/>
<w:right w:val="single" w:color="auto" w:sz="4" w:space="24"/>
</w:pgBorders>
You can generate code to match your preferred border attributes by creating a docx in Word styled as you wish, then using either the Docx4j Helper Word AddIn, or the docx4j webapp.
For the above XML, that generates the following two forms of code.
// Create object for pgBorders
SectPr.PgBorders sectprpgborders = wmlObjectFactory.createSectPrPgBorders();
// Create object for top
CTBorder border = wmlObjectFactory.createCTBorder();
sectprpgborders.setTop(border);
border.setVal(org.docx4j.wml.STBorder.SINGLE);
border.setSz( BigInteger.valueOf( 4) );
border.setColor( "auto");
border.setSpace( BigInteger.valueOf( 24) );
// Create object for left
CTBorder border2 = wmlObjectFactory.createCTBorder();
sectprpgborders.setLeft(border2);
border2.setVal(org.docx4j.wml.STBorder.SINGLE);
border2.setSz( BigInteger.valueOf( 4) );
border2.setColor( "auto");
border2.setSpace( BigInteger.valueOf( 24) );
// Create object for bottom
CTBorder border3 = wmlObjectFactory.createCTBorder();
sectprpgborders.setBottom(border3);
border3.setVal(org.docx4j.wml.STBorder.SINGLE);
border3.setSz( BigInteger.valueOf( 4) );
border3.setColor( "auto");
border3.setSpace( BigInteger.valueOf( 24) );
// Create object for right
CTBorder border4 = wmlObjectFactory.createCTBorder();
sectprpgborders.setRight(border4);
border4.setVal(org.docx4j.wml.STBorder.SINGLE);
border4.setSz( BigInteger.valueOf( 4) );
border4.setColor( "auto");
border4.setSpace( BigInteger.valueOf( 24) );
sectprpgborders.setOffsetFrom(org.docx4j.wml.STPageBorderOffset.PAGE);
Approach 2:
String openXML
= "<w:pgBorders w:offsetFrom=\"page\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" >"
+ "<w:top w:color=\"auto\" w:space=\"24\" w:sz=\"4\" w:val=\"single\"/>"
+ "<w:left w:color=\"auto\" w:space=\"24\" w:sz=\"4\" w:val=\"single\"/>"
+ "<w:bottom w:color=\"auto\" w:space=\"24\" w:sz=\"4\" w:val=\"single\"/>"
+ "<w:right w:color=\"auto\" w:space=\"24\" w:sz=\"4\" w:val=\"single\"/>"
+ "</w:pgBorders>";
SectPr.PgBorders sectprpgborders = (SectPr.PgBorders)XmlUtils.unmarshalString(openXML);
// Hand edited; may need minor adjustment
Then its just sectpr.setPgBorders(sectprpgborders) for the relevant sectPr.