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

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();
}
}

Related

How to add title page image in apache poi with header image in it. Currently, whenever I add image in header, title page image disappears

Here I am trying to insert image in the title page in apache poi but with the header image, it is not displaying the image on the title page. If I remove the addPicture from the header part, then, title page correctly displays the proper image. I am not sure what's the issue. I have added the code here.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.apache.poi.util.Units;
import org.apache.poi.wp.usermodel.HeaderFooterType;
public class Check {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
sectPr.addNewTitlePg();
File image = new File("D:\\Img.png");
FileInputStream imageData = new FileInputStream(image);
run = paragraph.createRun();
int imageType = XWPFDocument.PICTURE_TYPE_PNG;
String imageFileName = image.getName();
int width = 612;
int height = 550;
run.addPicture(imageData, imageType, imageFileName, Units.toEMU(width), Units.toEMU(height));
paragraph = document.createParagraph();
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");
XWPFHeader header = document.createHeader(HeaderFooterType.FIRST);
paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();
run.setText("First page footer...");
// adding header here
header = document.createHeader(HeaderFooterType.DEFAULT);
paragraph = header.getParagraphArray(0);
if (paragraph == null)
paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.RIGHT);
image = new File("D:\\Picture.png");
imageData = new FileInputStream(image);
run = paragraph.createRun();
imageType = XWPFDocument.PICTURE_TYPE_PNG;
imageFileName = image.getName();
width = 100;
height = 50;
// adding image here.
run.addPicture(imageData, imageType, imageFileName, Units.toEMU(width), Units.toEMU(height));
// header image part completed
FileOutputStream out = new FileOutputStream("D:\\CreateWordFooters.docx");
document.write(out);
out.close();
document.close();
}
}

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();
}
}

Apache-poi : cannot add image in docx header

I want to create a header in an existing docx document with Apache POI (I have tried versions 3.14 and 4.0.1).
But when I open the docx, in the header I am getting this ("we cannot display this image"):
I am doing this :
document = new XWPFDocument(OPCPackage.open("C:\\users\\thomas\\withoutHeader.docx"));
CTSectPr sectPr1 = document.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr1);
//Header content
CTP ctpHeader = CTP.Factory.newInstance();
CTR ctrHeader = ctpHeader.addNewR();
CTText ctHeader = ctrHeader.addNewT();
String headerText = "This is header";
ctHeader.setStringValue(headerText);
XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, document);
XWPFParagraph[] parsHeader = new XWPFParagraph[1];
parsHeader[0] = headerParagraph;
policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);
//Header image
policy = new XWPFHeaderFooterPolicy(document);
XWPFHeader header = policy.getDefaultHeader();
System.out.println(header.getText());
XWPFParagraph paragraph = header.getParagraphArray(0);
if (paragraph == null) paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun r = paragraph.createRun();
FileInputStream in = new FileInputStream("C:\\Users\\thomas\\dev\\logo.png");
r.addPicture(in, Document.PICTURE_TYPE_JPEG, "C:\\Users\\thomas\\dev\\logo.png", Units.toEMU(100), Units.toEMU(50));
in.close();
FileOutputStream out = new FileOutputStream("C:\\users\\thomas\\withHeader.docx");
document.write(out);
document.close();
out.close();
What am I missing?
Following complete example works for me using current apache poi 4.1.1.
The example opens a *.docx template which should not have headers already. Then it adds a default header having text and a logo.png.
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(new FileInputStream("./Template.docx"));
XWPFParagraph paragraph;
XWPFRun run;
// 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();
run.setText("This is header ");
FileInputStream in = new FileInputStream("./logo.png");
run.addPicture(in, Document.PICTURE_TYPE_PNG, "logo.png", Units.toEMU(100), Units.toEMU(50));
in.close();
FileOutputStream out = new FileOutputStream("./CreateWordHeaderWithImage.docx");
doc.write(out);
doc.close();
out.close();
}
}
Same code works using apache poi 3.17 too.

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:

Set word document page margins through 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

Categories

Resources