InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(TEMPLATE);
XWPFDocument document = new XWPFDocument(is);
List<IBodyElement> elements = document.getBodyElements();
for (int i = 0; i < elements.size(); i++) {
document.removeBodyElement(i);
}
CTBody body = document.getDocument().getBody();
CTSectPr docSp = body.getSectPr();
CTPageSz pageSize = docSp.getPgSz();
CTPageMar margin = docSp.getPgMar();
BigInteger pageWidth = pageSize.getW();
pageWidth = pageWidth.add(BigInteger.ONE);
BigInteger totalMargins = margin.getLeft().add(margin.getRight());
BigInteger contentWidth = pageWidth.subtract(totalMargins);
...
XWPFTable table = document.createTable(totalRows, totalColumns);
Starting from a template I create a XWPFDocument and add a table to. How would could I add multiple tables each on a page? That is, perhaps, how do I insert a page break ?
I am just a beginner using POI to generate .docx files, but I have so far figured out how to insert a page break. When you have created an XWPFParagraph, you can insert a page break like this:
XWPFDocument document = new XWPFDocument(is);
...
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.addBreak(BreakType.PAGE);
Hope this helps.
Another way is you can set the page break using XWPFParagraph:
XWPFDocument document = new XWPFDocument(is);
...
XWPFParagraph paragraph = document.createParagraph();
paragraph.setPageBreak(true);
Related
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();
}
}
I am trying to generate a word document with a table. There is only one page page and it has 5 rows and 2 columns. I am using the letter page and the size is 8.5" x 11". And I gave the margins to the program.
Here is my code,
XWPFDocument xWPFDocument = new XWPFDocument();
CTSectPr cTSectPr = xWPFDocument.getDocument().getBody().addNewSectPr();
CTPageMar cTPageMar = cTSectPr.addNewPgMar();
cTPageMar.setLeft(BigInteger.valueOf(475));
cTPageMar.setTop(BigInteger.valueOf(720));
cTPageMar.setRight(BigInteger.valueOf(446));
cTPageMar.setBottom(BigInteger.valueOf(605));
XWPFTable xWPFTable = xWPFDocument.createTable(5, 2);
xWPFTable.getCTTbl().getTblPr().unsetTblBorders();
xWPFTable.setTableAlignment(TableRowAlign.CENTER);
xWPFTable.setWidth("100%");
And I am setting cell width and row height using the following code. But I am not noticing any change.
XWPFTableRow xWPFTableRow;
for (int i = 0; i < 5; i++) {
xWPFTableRow = xWPFTable.getRow(i);
xWPFTableRow.setHeight(2880);
xWPFTableRow.getCell(i).getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(6033));
}
What I am looking for is how to set Horizontal and Vertical Spacing also is there a way to set Horizontal and Vertical Pitch using Apache POI?
The current apache poi 4.1.2 provides a method setWidth(java.lang.String widthValue) where widthValue can be a String giving a percentage width in XWPFTable as well as in XWPFTableCell.
Setting the cell spacing is not supported directly until now. So underlying ooxml-schemas classes must be used for this.
Complete example:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
public class CreateWordTableCellSpacing {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The table");
int cols = 3;
int rows = 3;
XWPFTable table = document.createTable(rows, cols);
table.setWidth("100%");
table.getRow(0).getCell(0).setWidth("20%");
table.getRow(0).getCell(1).setWidth("30%");
table.getRow(0).getCell(2).setWidth("50%");
//set spacing between cells
table.getCTTbl()
.getTblPr()
.addNewTblCellSpacing()
.setType(
org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth.DXA
);
table.getCTTbl()
.getTblPr()
.getTblCellSpacing()
.setW(java.math.BigInteger.valueOf(
180 // 180 TWentieths of an Inch Point (Twips) = 180/20 = 9 pt = 9/72 = 0.125"
));
paragraph = document.createParagraph();
FileOutputStream out = new FileOutputStream("CreateWordTableCellSpacing.docx");
document.write(out);
out.close();
document.close();
}
}
I am trying to convert a PDF document to a Word file using Java. On Internet, I found a code snippet which converts PDF document to Word. but the alignments in the resulting Word document is clumsy. Images tables and graphs are not in sync. Everything is displaying as string paragraph/words.
The code, I have written is given below.
XWPFDocument doc = new XWPFDocument();
String pdf = "D:\\xyz.pdf";
PdfReader reader = new PdfReader(pdf);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
TextExtractionStrategy strategy = (TextExtractionStrategy)
parser.processContent(i,new SimpleTextExtractionStrategy());
String text = strategy.getResultantText();
XWPFParagraph p = doc.createParagraph();
XWPFRun run = p.createRun();
run.setText(text);
run.addBreak(BreakType.PAGE);
Please anyone help.....
I have tried to set page orientation on single pages with help from here with no luck. This code snippet generates a document, but it only sets the last page to landscape. I can't figure out what is wrong... Any help or guidance would be appreciated!
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("FIRST PAGE");
changeOrientation(document, "landscape");
paragraph = document.createParagraph();
run = paragraph.createRun();
run.setText("SECOND PAGE");
changeOrientation(document, "portrait");
paragraph = document.createParagraph();
run = paragraph.createRun();
run.setText("THIRD PAGE");
changeOrientation(document, "landscape");
paragraph = document.createParagraph();
run = paragraph.createRun();
run.setText("FOURTH PAGE");
FileOutputStream fos = new FileOutputStream(new File("C:/test.docx"));
document.write(fos);
fos.close();
}
private static void changeOrientation(XWPFDocument document, String orientation){
CTDocument1 doc = document.getDocument();
CTBody body = doc.getBody();
CTSectPr section = body.addNewSectPr();
XWPFParagraph para = document.createParagraph();
CTP ctp = para.getCTP();
CTPPr br = ctp.addNewPPr();
br.setSectPr(section);
CTPageSz pageSize = section.isSetPgSz() ? section.getPgSz() : section.addNewPgSz();
if(orientation.equals("landscape")){
pageSize.setOrient(STPageOrientation.LANDSCAPE);
pageSize.setW(BigInteger.valueOf(842 * 20));
pageSize.setH(BigInteger.valueOf(595 * 20));
}
else{
pageSize.setOrient(STPageOrientation.PORTRAIT);
pageSize.setH(BigInteger.valueOf(842 * 20));
pageSize.setW(BigInteger.valueOf(595 * 20));
}
}
EDIT:
This give me the document.xml (which don't look right):
<?xml version="1.0" encoding="UTF-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>
<w:p><w:r><w:t>FIRST PAGE</w:t></w:r></w:p>
<w:p><w:pPr><w:sectPr/></w:pPr></w:p>
<w:p><w:r><w:t>SECOND PAGE</w:t></w:r></w:p>
<w:p><w:pPr><w:sectPr/></w:pPr></w:p>
<w:p><w:r><w:t>THIRD PAGE</w:t></w:r></w:p>
<w:p><w:pPr><w:sectPr/></w:pPr></w:p>
<w:p><w:r><w:t>FOURTH PAGE</w:t></w:r></w:p>
<w:sectPr><w:pgSz w:orient="landscape" w:w="16840" w:h="11900"/></w:sectPr>
<w:sectPr><w:pgSz w:orient="portrait" w:h="16840" w:w="11900"/></w:sectPr>
<w:sectPr><w:pgSz w:orient="landscape" w:w="16840" w:h="11900"/></w:sectPr>
</w:body></w:document>
EDIT 2: This is how the document.xml looks like when created with Word (with some irrelevant stuff removed...). I'm afraid that I'm noot good enough at POI to figure out what to do to make it generate the xml like this instead:
<w:p w:rsidR="004E2FF4" w:rsidRDefault="004E2FF4"><w:pPr><w:sectPr w:rsidR="004E2FF4"><w:pgSz w:w="11906" w:h="16838"/></w:sectPr></w:pPr><w:r><w:t>FIRST PAGE</w:t></w:r></w:p>
<w:p w:rsidR="004E2FF4" w:rsidRDefault="004E2FF4"><w:pPr><w:sectPr w:rsidR="004E2FF4" w:rsidSect="004E2FF4"><w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/></w:sectPr></w:pPr>
<w:r><w:lastRenderedPageBreak/><w:t>SECOND PAGE</w:t></w:r></w:p><w:p w:rsidR="004E2FF4" w:rsidRDefault="004E2FF4"><w:pPr><w:sectPr w:rsidR="004E2FF4"><w:pgSz w:w="11906" w:h="16838"/></w:sectPr></w:pPr>
<w:r><w:lastRenderedPageBreak/><w:t>THIRD PAGE</w:t></w:r></w:p><w:p w:rsidR="00D70BD0" w:rsidRDefault="004E2FF4">
<w:r><w:lastRenderedPageBreak/><w:t>FOURTH PAGE</w:t></w:r></w:p><w:sectPr w:rsidR="00D70BD0" w:rsidSect="004E2FF4"><w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/></w:sectPr>
Edit 3:
Thanks for the nice guiding, but I can still not get it to work 100%. I have now changed the code to the following. But this resulting in setting the previous page orientation instead of the desired one. And the rest is not getting correct.
Image that shows the resulting pages
private static void changeOrientation(XWPFDocument document, String orientation, boolean pFinalSection){
CTSectPr section;
if (pFinalSection) {
CTDocument1 doc = document.getDocument();
CTBody body = doc.getBody();
section = body.getSectPr() != null ? body.getSectPr() : body.addNewSectPr();
XWPFParagraph para = document.createParagraph();
CTP ctp = para.getCTP();
CTPPr br = ctp.addNewPPr();
br.setSectPr(section);
} else {
XWPFParagraph para = document.createParagraph();
CTP ctp = para.getCTP();
CTPPr br = ctp.addNewPPr();
section = br.addNewSectPr();
br.setSectPr(section);
}
CTPageSz pageSize = section.isSetPgSz() ? section.getPgSz() : section.addNewPgSz();
if(orientation.equals("landscape")){
pageSize.setOrient(STPageOrientation.LANDSCAPE);
pageSize.setW(BigInteger.valueOf(842 * 20));
pageSize.setH(BigInteger.valueOf(595 * 20));
}
else{
pageSize.setOrient(STPageOrientation.PORTRAIT);
pageSize.setH(BigInteger.valueOf(842 * 20));
pageSize.setW(BigInteger.valueOf(595 * 20));
}
}
Please check my answer to the same problem in the post Landscape and portrait pages in the same word document using Apache POI XWPF in Java.
According to OOXML Specification ECMA-376, Fourth Edition, Part 1 - Fundamentals And Markup Language Reference - 17.6.18 sectPr (Section Properties), in a document with multiple sections, section properties (the sectPr element) are stored as the child element of :
the last paragraph in the section, for all sections except the final
section,
the body element, for the final section.
You can use addNewSectPr method of CTPPr to add a CTSectPr to it.
CTBody has a CTSectPr at end of it. You can get it using getSectPr method.
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