Set word document page margins through java - java

I have created a file by using Java where I want to change page margins but I can't
Here is my code:
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
paragraph.setAlignment(ParagraphAlignment.LEFT);
paragraph.setNumID(BigInteger.ONE);
run.setFontSize(18);
run.setText("Test");
try{
FileOutputStream output = new FileOutputStream("C://WordDocument.docx");
document.write(output);
output.close();
} catch (Exception e){
e.printStackTrace();
}
What I want to do is something like document.setMarginLeft( Left_Margin ); and document.setMarginRight( Right_Margin );
Thanks in advance

I think he/she meant for ooxml-schemas library and rest dependencies.

you need to get the body of the document and adding a Section, then adding a CTPageMar, this object proovide methods for setting margins for the section you just created.
this is actually working for me,
values are large i suppose 10000 is the total width of a page but i'm not sure about it, so find your own desidered values :)
XWPFDocument doc = new XWPFDocument();
CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
CTPageMar pageMar = sectPr.addNewPgMar();
pageMar.setLeft(BigInteger.valueOf(1500L));
pageMar.setRight(BigInteger.valueOf(1500L));
pageMar.setTop(BigInteger.valueOf(2000L));
pageMar.setBottom(BigInteger.valueOf(1000L));
enjoy

Related

apache poi disable default footer for the first page

I am trying to create a word document in which I will have no footer only in the first page and a footer for the rest of the pages. I wrote the following code (I also tried to change -reverse- the order of creation of footer and footerFirst objects) but that did not help. I still have the default footer on all pages.
How should I disable the footer from the first page? Thanks in advance.
private XWPFDocument initDocument(String FILE) throws Exception{
XWPFDocument document = new XWPFDocument();
XWPFHeaderFooterPolicy headerFooterPolicy = document.getHeaderFooterPolicy();
if (headerFooterPolicy == null) headerFooterPolicy = document.createHeaderFooterPolicy();
// create header start
XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
//XWPFParagraph paragraph = footer.createParagraph();
XWPFParagraph paragraph = footer.getParagraphArray(0);
if (paragraph == null)
paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun run = paragraph.createRun();
run.setFontSize(11);
run.setFontFamily("Times New Roman");
run.setText("Some company info in the footer");
XWPFFooter footerFirst = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.FIRST);
paragraph = footerFirst.getParagraphArray(0);
if (paragraph == null)
paragraph = footerFirst.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();
run.setText(" ");
return document;
}
That there is a different header set for first page only, means not that this header will also be shown. In Word GUI there is a checkbox [x] Different First Page in Header & Footer Tools to achieve that.
And according Office Open XML Part 4 - Markup Language Reference there must a boolean XML element titlePg be set to determine that there is a title page present.
In old apache poi versions using XWPFHeaderFooterPolicy this XML element titlePg can only be set using underlying low level objects using document.getDocument().getBody().getSectPr().addNewTitlePg();.
But using current apache poi versions (since 3.16) there is no need using XWPFHeaderFooterPolicy directly. Now there is XWPFDocument.createHeader and XWPFDocument.createFooter using a HeaderFooterType. This sets titlePg flag in XML when HeaderFooterType.FIRST is used.
Complete example which sets and uses HeaderFooterType.FIRST and HeaderFooterType.DEFAULT:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;
public class CreateWordFooters {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
// the body content
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The Body... first page");
paragraph = document.createParagraph();
run=paragraph.createRun();
run.addBreak(BreakType.PAGE);
run.setText("The Body... second page");
// create first page footer
XWPFFooter footer = document.createFooter(HeaderFooterType.FIRST);
paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();
run.setText("First page footer...");
// create default footer
footer = document.createFooter(HeaderFooterType.DEFAULT);
paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setText("Default footer...");
FileOutputStream out = new FileOutputStream("CreateWordFooters.docx");
document.write(out);
out.close();
document.close();
}
}

Problem adding image in the header of word document

I'm adding a picture in the header of a word document. It shows a frame for the image and says "the image cannot currently be display". If I add text to the header it show the text, and if I add the image in the document body, it also shows the image. So is getting the image and it show text on the header, but no the image.
I'm running out of checkings, can anyone advise with this please?
Thank you!
public static void createHeaderAndFotter(XWPFDocument document) throws IOException, BadElementException, InvalidFormatException {
XWPFHeaderFooterPolicy headerFooterPolicy = document.getHeaderFooterPolicy();
if (headerFooterPolicy == null) headerFooterPolicy = document.createHeaderFooterPolicy();
File image = new ClassPathResource("/static/images/NIAB_Header.bmp").getFile();
BufferedImage bimg1 = ImageIO.read(image);
int width = bimg1.getWidth();
int height = bimg1.getHeight();
String imageName= image.getName();
XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
XWPFParagraph paragraph = header.createParagraph();
// XWPFParagraph paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun run = paragraph.createRun();
run.addPicture(new FileInputStream(image), XWPFDocument.PICTURE_TYPE_PNG, imageName, Units.toEMU(width), Units.toEMU(height));
run.setText("HEADER");
}
If I remove the commment on this line and comment the one before, then it adds the image
XWPFParagraph paragraph = document.createParagraph();
I believe whether this works or not highly depends on apache poiversion used. There was multiple issues with pictures in header/footer in former apache poi versions.
The following is the most minimal working code using apache poi 4.0.1. It is recommend always using the latest stable version.:
Code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.util.Units;
public class CreateWordHeaderWithImage {
public static void main(String[] args) throws Exception {
XWPFDocument doc = new XWPFDocument();
// the body content
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The Body...");
// create header
XWPFHeader header = doc.createHeader(HeaderFooterType.DEFAULT);
// header's first paragraph
paragraph = header.getParagraphArray(0);
if (paragraph == null) paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();
FileInputStream in = new FileInputStream("samplePict.jpeg");
run.addPicture(in, Document.PICTURE_TYPE_JPEG, "samplePict.jpeg", Units.toEMU(100), Units.toEMU(50));
in.close();
run.setText("HEADER");
FileOutputStream out = new FileOutputStream("CreateWordHeaderWithImage.docx");
doc.write(out);
doc.close();
out.close();
}
}
Result:

How to define narrow margin in word document using Apache POI?

I am using Apache POI to create a docx document and I want the margin to be set to narrow as if using the Layout > Margins > Narrow in MS Word.
I have seen some other answers suggesting RecordInputStream but I do not know how to integrate it in my code because it uses FileInputStream as a parameter.
I use a ByteArrayOutputStream because I am exporting it with omnifaces and I would like a way to make it work.
Here is my code:
ByteArrayOutputStream output = new ByteArrayOutputStream();
XWPFDocument document = new XWPFDocument();
XWPFParagraph titleParagraph = document.createParagraph();
//some code here...
document.write(output);
document.close();
Faces.sendFile(output.toByteArray(), wordFilename, true);
Please help. Thanks in advance!
There is nothing for setting page margins in XWPFDocument until now. So we needs using the low level beans org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr and org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar.
What wordcalls narrow margins is 0.5 inches margins all around.
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar;
import java.math.BigInteger;
public class CreateWordPageMargins {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Text");
CTSectPr sectPr = document.getDocument().getBody().getSectPr();
if (sectPr == null) sectPr = document.getDocument().getBody().addNewSectPr();
CTPageMar pageMar = sectPr.getPgMar();
if (pageMar == null) pageMar = sectPr.addNewPgMar();
pageMar.setLeft(BigInteger.valueOf(720)); //720 TWentieths of an Inch Point (Twips) = 720/20 = 36 pt = 36/72 = 0.5"
pageMar.setRight(BigInteger.valueOf(720));
pageMar.setTop(BigInteger.valueOf(720));
pageMar.setBottom(BigInteger.valueOf(720));
pageMar.setFooter(BigInteger.valueOf(720));
pageMar.setHeader(BigInteger.valueOf(720));
pageMar.setGutter(BigInteger.valueOf(0));
FileOutputStream out = new FileOutputStream("CreateWordPageMargins.docx");
document.write(out);
out.close();
document.close();
}
}

Add image as a header in XWPF document

How do I add a image as a header to every page in XWPF document ?
I have tried every possible thing I could think of , below is my code :
XWPFDocument docx = new XWPFDocument();
CTSectPr sectPr = docx.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx, sectPr);
XWPFHeader header = policy.createHeader(XWPFHeaderFooterPolicy.FIRST);
String imgFile="sample.png";
header.addPictureData(new FileInputStream(imgFile), XWPFDocument.PICTURE_TYPE_PNG);
String nameoffile ="customer"+".docx";
FileOutputStream out = new FileOutputStream(nameoffile);
docx.write(out);
out.close();
However this is giving me a java.lang.IndexOutOfBoundsException at line java.lang.IndexOutOfBoundsException
You should add a correct directory for image. Probably "new FileInputStream(imgFile)" is null.
Put your image in directory then set path as:
String imgFile="C:\Users\{user}\Desktop\Project\sample.png";

Adding footer to ms word using POI api

I searched a lot and getting some results in which some sample code is there but no one is working. All are either getting null pointer exception or if document is generated then at the time of opening file (.docx) giving error and displaying message
A text/xml declaration may occur only at the very beginning of innput.
I thought may be I am adding some content and then adding footer is giving some problem so I pasted my footer code at very beginning now this time I am getting
index out of bound exception
Here is my complete code
String fileName ="Book.docx";
String folderPath=SystemProperties.get(SystemProperties.TMP_DIR)+File.separator+"liferay" + File.separator + "document_preview";
String filePath=folderPath+File.separator+fileName;
File file=new File(filePath);
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraphOne = document.createParagraph();
paragraphOne.setAlignment(ParagraphAlignment.CENTER);
XWPFRun paragraphOneRunOne = paragraphOne.createRun();
paragraphOneRunOne.setText("Training Report");
paragraphOneRunOne.addBreak();
XWPFTable table = document.createTable();
XWPFTableRow tableRowOne = table.getRow(0);
tableRowOne.getCell(0).setText("No");
tableRowOne.createCell().setText("Name");
XWPFHeaderFooterPolicy headerFooterPolicy = document.getHeaderFooterPolicy();
if (headerFooterPolicy == null) {
CTBody body = document.getDocument().getBody();
CTSectPr sectPr = body.getSectPr();
if (sectPr == null) {
sectPr = body.addNewSectPr();
}
headerFooterPolicy = new XWPFHeaderFooterPolicy(document, sectPr);
}
CTP ctP1 = CTP.Factory.newInstance();
CTR ctR1 = ctP1.addNewR();
CTText t = ctR1.addNewT();
t.setStringValue("first footer");
XWPFParagraph codePara = new XWPFParagraph(ctP1);
XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
newparagraphs[0] = codePara;
XWPFFooter xwpfFooter = null;
xwpfFooter = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
FileOutputStream fileoutOfTraining = new FileOutputStream(file);
document.write(fileoutOfTraining);
fileoutOfTraining.flush();
fileoutOfTraining.close();
downloadOperation(file, fileName, resourceResponse);
code in downloadOperation method
HttpServletResponse httpServletResponse =PortalUtil.getHttpServletResponse(resourceResponse);
BufferedInputStream input = null;
BufferedOutputStream output = null;
httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"; filename*=UTF-8''"+fileName);
int DEFAULT_BUFFER_SIZE=1024;
try {
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
resourceResponse.flushBuffer();
output = new BufferedOutputStream(httpServletResponse.getOutputStream(), DEFAULT_BUFFER_SIZE);
} catch (IOException e) {
e.printStackTrace();
}
byte[] buffer = new byte[2*DEFAULT_BUFFER_SIZE];
int length;
try {
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Please help me to generate footer, this is my code, if I add footer code after my paragraph and table then no run time error but error in opening generated file, if I placed footer at before the contents that I want to add in documents then I am getting error "index out of bound exception".
Please help me if any one having any code snippet or at least some pointers towards the solution.
Thanks
I faced this issue and the solution is
We have to use 3.10 final poi jar.
3.9 having this problem.
Please remove jars of previous version and add jars of 3.10 final version in which this bug is fixed.
Jars requires are:
poi-3.10-FINAL.jar
poi-ooxml-3.10-FINAL.jar
poi-ooxml-schemas-3.10-FINAL.jar
Easily available in net:
http://mvnrepository.com/artifact/org.apache.poi/poi/3.10-FINAL
XWPFDocument document = new XWPFDocument();
CTP ctp = CTP.Factory.newInstance();
CTR ctr = ctp.addNewR();
CTRPr rpr = ctr.addNewRPr();
CTText textt = ctr.addNewT();
textt.setStringValue( " Page 1" );
XWPFParagraph codePara = new XWPFParagraph( ctp, document );
XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
newparagraphs[0] = codePara;
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy( document, sectPr );
headerFooterPolicy.createFooter( STHdrFtr.DEFAULT, newparagraphs );
The above code is working perfectly, please use 3.10 wars those I mentioned above.
I don't know if adding image to header from scratch works in new version, but I know for a fact that "templating" works just perfectly. I created the template document in word, adapted the header the way I needed it to be (in my case, logo-image was on the right, paragraph with dummy text on the left, and another image that separates the upper two objects from the content, on the header bottom, and all was repeating on all the pages) and left the rest of the document empty. On the very beginning, I didn't create the XWPFDocument by calling the ...new XWPFDocument() anymore, I created it this way:
XWPFDocument doc = new XWPFDocument(new FileInputStream("pathTo/template.docx"));
Than just fill your document with your content, and if you need to update the header text for different exports like I did, call the update header function, that in my case looks something like this:
public void updateHeader() throws InvalidFormatException, IOException {
// load the header policy from template and update the paragraph text
XWPFHeaderFooterPolicy headerFooterPolicy = document
.getHeaderFooterPolicy();
XWPFHeader defaultHeader = headerFooterPolicy.getDefaultHeader();
defaultHeader.getParagraphs().get(0).getRuns().get(0)
.setText(profileName, 0);
// this is only to put some space between the content in the header and the real content
defaultHeader.getParagraphs()
.get(defaultHeader.getParagraphs().size() - 1)
.setSpacingAfter(300);
}
As far as I know, this works since 3.10, and if you stumble upon some java security issues, try the current nightly version where many of these security issues were resolved. For me it even worked on Google App Engine.

Categories

Resources