I am creating a word document using POI. I have created a table and a header. I want to give left margin to table so I used this code:
CTSectPr getSectPr = doc.getDocument().getBody().getSectPr();
CTPageMar addNewPgMar = getSectPr.addNewPgMar();
addNewPgMar.setLeft(BigInteger.valueOf(200));
addNewPgMar.setRight(BigInteger.valueOf(200));
addNewPgMar.setFooter(BigInteger.valueOf(0));
addNewPgMar.setHeader(BigInteger.valueOf(0));
[![enter image description here][1]][1]
But this code also give 200 margin to header from left. I Want only for table.
Thanks in Advance.
The page margins, you set using the code shown, are margins for the whole page. Headers and footers also are part of the page as well as the body. The additional settings setFooter and setHeader in page margins are settings for distances of the header from top and the footer from bottom of the page. There are no special settings to set left distance only for body or header/footer. So changed left page margins also affect the header and footer.
All you could do is set additional indentations for paragraphs and tables in the body.
Example:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
import java.math.BigInteger;
public class CreateWordHeaderFooter {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
// the body content
XWPFParagraph paragraph = document.createParagraph();
// set indentation of the paragraph
paragraph.setIndentationLeft(720); //720 TWentieths of an Inch Point (Twips) = 720/20 = 36 pt = 36/72 = 0.5"
XWPFRun run=paragraph.createRun();
run.setText("The Body:");
paragraph = document.createParagraph();
// set indentation of the paragraph
paragraph.setIndentationLeft(720);
run=paragraph.createRun();
run.setText("Lorem ipsum.... page 1");
// create table
XWPFTable table = document.createTable(3,3);
// set indentation of the table
CTTblWidth tableIndentation = table.getCTTbl().getTblPr().addNewTblInd();
tableIndentation.setW(BigInteger.valueOf(720));
tableIndentation.setType(STTblWidth.DXA);
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
table.getRow(row).getCell(col).setText("row " + row + ", col " + col);
}
}
paragraph = document.createParagraph();
// set indentation of the paragraph
paragraph.setIndentationLeft(720);
// create header start
XWPFHeader header = document.createHeader(HeaderFooterType.DEFAULT);
paragraph = header.getParagraphArray(0);
if (paragraph == null) paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setText("The Header");
// create footer start
XWPFFooter footer = document.createFooter(HeaderFooterType.DEFAULT);
paragraph = footer.getParagraphArray(0);
if (paragraph == null) paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setText("The Footer");
// create page margins
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("CreateWordHeaderFooter.docx");
document.write(out);
out.close();
document.close();
}
}
This code is tested using apache poi 4.1.0 and needs the the full ooxml-schemas-1.4.jar as mentioned in FAQ-N10025.
Related
I have a Word table with custom first row, but the following rows aren't adjusted. Please tell me why, and how to do the same widths of cells of the second row?
XWPFDocument document = new XWPFDocument();
CTDocument1 doc = document.getDocument();
CTBody body = doc.getBody();
if (!body.isSetSectPr()) {
body.addNewSectPr();
}
CTSectPr section = body.getSectPr();
if(!section.isSetPgSz()) {
section.addNewPgSz();
}
CTPageSz pageSize = section.getPgSz();
pageSize.setW(BigInteger.valueOf(15840));
pageSize.setH(BigInteger.valueOf(12240));
XWPFParagraph paragraph = document.createParagraph();
CTSectPr ctSectPr = section ;//paragraph.getCTP().addNewPPr().addNewSectPr();
CTColumns ctColumns = ctSectPr.addNewCols();
ctColumns.setNum(BigInteger.valueOf(1));
paragraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun test = paragraph.createRun();
test.setFontSize(15);
test.setBold(true);
test.setFontFamily("Times New Roman");
test.setText("Перечни документов, необходимые для применения и исполнения технических регламентов (форма № 21)");
test.addBreak();
XWPFTable supergroupTable = document.createTable();
supergroupTable.setWidth(15200);
//supergroupTable.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(1*720));
//supergroupTable.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(12*720));
CTTblWidth tblWidth = supergroupTable.getRow(0).getCell(0).getCTTc().addNewTcPr().addNewTcW();
tblWidth.setW(BigInteger.valueOf(400));
supergroupTable.getRow(0).getCell(0).setText("№");
//STTblWidth.DXA is used to specify width in twentieths of a point.
tblWidth.setType(STTblWidth.DXA);
XWPFTableRow supegroupRow = supergroupTable.getRow(0);
XWPFTableCell supergroupCell = supegroupRow.createCell();
tblWidth = supergroupTable.getRow(0).getCell(1).getCTTc().addNewTcPr().addNewTcW();
tblWidth.setW(BigInteger.valueOf(1700));
tblWidth.setType(STTblWidth.DXA);
supergroupCell.setText("Обозначение технического регламента");
supergroupCell = supegroupRow.createCell();
tblWidth = supergroupTable.getRow(0).getCell(2).getCTTc().addNewTcPr().addNewTcW();
tblWidth.setW(BigInteger.valueOf(1700));
tblWidth.setType(STTblWidth.DXA);
supergroupCell.setText("Наименование на русском языке ");
supergroupCell = supegroupRow.createCell();
tblWidth = supergroupTable.getRow(0).getCell(3).getCTTc().addNewTcPr().addNewTcW();
tblWidth.setW(BigInteger.valueOf(880));
tblWidth.setType(STTblWidth.DXA);
supergroupCell.setText("Статус");
supergroupCell = supegroupRow.createCell();
tblWidth = supergroupTable.getRow(0).getCell(4).getCTTc().addNewTcPr().addNewTcW();
tblWidth.setW(BigInteger.valueOf(1700));
tblWidth.setType(STTblWidth.DXA);
supergroupCell.setText("Обозначение документа");
supergroupCell = supegroupRow.createCell();
tblWidth = supergroupTable.getRow(0).getCell(5).getCTTc().addNewTcPr().addNewTcW();
tblWidth.setW(BigInteger.valueOf(1700));
tblWidth.setType(STTblWidth.DXA);
supergroupCell.setText("Наименование на русском языке");
supergroupCell = supegroupRow.createCell();
tblWidth = supergroupTable.getRow(0).getCell(6).getCTTc().addNewTcPr().addNewTcW();
tblWidth.setW(BigInteger.valueOf(880));
tblWidth.setType(STTblWidth.DXA);
supergroupCell.setText("Статус");
supegroupRow = supergroupTable.createRow();
supergroupCell = supegroupRow.getCell(0);
supergroupCell.setText("cell 1");
supergroupCell = supegroupRow.getCell(1);
supergroupCell.setText("cell 2");
supergroupCell = supegroupRow.getCell(2);
supergroupCell.setText("cell 3");
supergroupCell = supegroupRow.getCell(3);
supergroupCell.setText("cell 4");
supergroupCell = supegroupRow.getCell(4);
supergroupCell.setText("cell 5");
supergroupCell = supegroupRow.getCell(5);
supergroupCell.setText("cell 6");
supergroupCell = supegroupRow.getCell(6);
supergroupCell.setText("cell 7");
When I trying to set width of the second row in the same manner that it is set up for the first row the document come to mess and I can't do it the same manner.
Current versions of apache poi provide setWidth methods on high level, so the low level CT... classes are not needed. Using the low level CT... classes one needs special knowledge of the exact XML which needs to be created, else one creates wrong XML very fast. This seems to be the case in your case.
Using current apache poi 5.0.0 creating a table as yours is as simple as this:
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.CTPageSz;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STPageOrientation;
import java.math.BigInteger;
public class CreateWordTableCellWidths {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
//page settings are not provided high level on apache poi until now.
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
CTPageSz pageSz = sectPr.addNewPgSz();
pageSz.setW(BigInteger.valueOf(15840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11"
pageSz.setH(BigInteger.valueOf(12240)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5"
pageSz.setOrient(STPageOrientation.LANDSCAPE);
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Header line...");
//create table having first row having 7 columns
XWPFTable table = document.createTable(1, 7);
table.setWidth("100%");
//set cell width and content for first row
table.getRow(0).getCell(0).setText("Nr.");
table.getRow(0).getCell(0).setWidth("400");
table.getRow(0).getCell(1).setText("Loremipsumsemitdolor dolorsemitloremipsum semitdolor");
table.getRow(0).getCell(1).setWidth("1700");
table.getRow(0).getCell(2).setText("Lorem ipsum semit dolor dolor semit lorem");
table.getRow(0).getCell(2).setWidth("1700");
table.getRow(0).getCell(3).setText("Lorem ipsum");
table.getRow(0).getCell(3).setWidth("880");
table.getRow(0).getCell(4).setText("Lorem ipsum semit dolor dolor semit lorem");
table.getRow(0).getCell(4).setWidth("1700");
table.getRow(0).getCell(5).setText("Lorem ipsum semit dolor dolor semit lorem");
table.getRow(0).getCell(5).setWidth("1700");
table.getRow(0).getCell(6).setText("Lorem ipsum");
table.getRow(0).getCell(6).setWidth("880");
//create further row
XWPFTableRow row = table.createRow();
row.getCell(0).setText("cell 1");
row.getCell(0).setWidth("400");
row.getCell(1).setText("cell 2");
row.getCell(1).setWidth("1700");
row.getCell(2).setText("cell 3");
row.getCell(2).setWidth("1700");
row.getCell(3).setText("cell 4");
row.getCell(3).setWidth("880");
row.getCell(4).setText("cell 5");
row.getCell(4).setWidth("1700");
row.getCell(5).setText("cell 6");
row.getCell(5).setWidth("1700");
row.getCell(6).setText("cell 7");
row.getCell(6).setWidth("880");
paragraph = document.createParagraph();
FileOutputStream out = new FileOutputStream("CreateWordTableCellWidths.docx");
document.write(out);
out.close();
document.close();
}
}
Only page settings are not provided high level on apache poi until now. So to set page settings using the low level CT... classes is necessary.
For usage in Microsoft Word in general you set cell widths for cells in first row only. Further rows are using those cell widths too except if there are merged cells used.
For usage in Libreoffice or OpenOffice Writer width of all cells in all rows needs to be set.
I am constructing a row with 8 columns and
Need to create exponential data(number) in single cell in apache poi WORD without using paragraph.break .
If the content (2) shall be superscript, then there are two possibilities using Microsoft Word. Either really superscript align or set the text position away from the text base line. For both the (2) must be in it's own text run.
Superscript alignment can be achieved using XWPFRun.setSubscript having VerticalAlign.SUPERSCRIPT.
Text position can be set using XWPFRun.setTextPosition where int val is of measurement unit half pt.
Example:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
public class CreateWordSuperScript {
public static void main(String[] args) throws Exception {
XWPFDocument document= new XWPFDocument();
XWPFParagraph paragraph;
XWPFRun run;
paragraph = document.createParagraph();
run = paragraph.createRun();
run.setText("6 ");
run=paragraph.createRun();
run.setText("(2)");
run.setSubscript(VerticalAlign.SUPERSCRIPT); // superscript (2)
paragraph = document.createParagraph();
run=paragraph.createRun();
run.setText("6 ");
run=paragraph.createRun();
run.setText("(2)");
run.setTextPosition(11); // (2) position = baseline + 11 half pt ~ 5.5 pt
FileOutputStream out = new FileOutputStream("word.docx");
document.write(out);
out.close();
document.close();
}
}
I am creating a poi word document . I have setup page margin 0 but their is extra space between bottom and footer image i want to remove this space. I have used this code which did not work
addNewPgMar.setLeft(BigInteger.valueOf(0));
addNewPgMar.setRight(BigInteger.valueOf(210));
addNewPgMar.setGutter(BigInteger.valueOf(0));
addNewPgMar.setFooter(BigInteger.valueOf(0));
addNewPgMar.setHeader(BigInteger.valueOf(0));
I want to remove this footer below space which is showing in image.
Your problem has nothing to do with the page margins but with the paragraph settings in the footer. A Word paragraph has settings for spacing after each paragraph as well as for spacing between the lines in the paragraph. If the picture in your footer is inline in a paragraph in the footer, then the spacing after the paragraph must be 0 and the spacing between must be 1 to avoid the spacing you are facing.
Using apache poi 4.1.0 this can be set using:
...
XWPFParagraph paragraph...
...
paragraph.setSpacingAfter(0);
paragraph.setSpacingBetween(1d, LineSpacingRule.AUTO);
...
Complete example:
import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.util.Units;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageSz;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar;
import java.math.BigInteger;
public class CreateWordHeaderFooterNullMargin {
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");
// create header start
XWPFHeader header = document.createHeader(HeaderFooterType.DEFAULT);
paragraph = header.getParagraphArray(0);
if (paragraph == null) paragraph = header.createParagraph();
paragraph.setSpacingAfter(0);
paragraph.setSpacingBetween(1d, LineSpacingRule.AUTO);
run = paragraph.createRun();
run.setText("The Header");
// create footer start
XWPFFooter footer = document.createFooter(HeaderFooterType.DEFAULT);
paragraph = footer.getParagraphArray(0);
if (paragraph == null) paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
paragraph.setSpacingAfter(0);
paragraph.setSpacingBetween(1d, LineSpacingRule.AUTO);
run = paragraph.createRun();
String imgFile="Chrysanthemum.jpg";
run.addPicture(new FileInputStream(imgFile), XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(500), Units.toEMU(25));
// create page margins
CTSectPr sectPr = document.getDocument().getBody().getSectPr();
if (sectPr == null) sectPr = document.getDocument().getBody().addNewSectPr();
CTPageSz pageSz = sectPr.addNewPgSz(); // paper format letter
pageSz.setW(BigInteger.valueOf(12240)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5"
pageSz.setH(BigInteger.valueOf(15840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11"
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(0));
pageMar.setBottom(BigInteger.valueOf(0));
pageMar.setFooter(BigInteger.valueOf(0));
pageMar.setHeader(BigInteger.valueOf(0));
pageMar.setGutter(BigInteger.valueOf(0));
FileOutputStream out = new FileOutputStream("CreateWordHeaderFooterNullMargin.docx");
document.write(out);
out.close();
document.close();
}
}
Disclaimer: In my opinion page settings where margins are 0 are not recommendable. Most printers are not able printing the full paper's size. There are printable areas with minimal spaces on left, right, top and/or bottom of the paper. If you set page margins 0, then Word's GUI will warn about this. If you ignore that warning then you possible can damage the printer while next printing. Most printers will not print into their not printable page ranges even if you told to do so. That is to avoid that damaging.
I want to generate different headers in first page and other pages in poi word, So I used XWPFHeaderFooterPolicy.FIRST and XWPFHeaderFooterPolicy.DEFAULT. when I using XWPFHeaderFooterPolicy.DEFAULT I can insert my header successfully, but when I change to XWPFHeaderFooterPolicy.FIRST, I cannot see there is a header in my first page, this is my code in below, what's wrong with it? thanks!
XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.FIRST);
paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setText("header");
There is nothing in that class to tell Word to display different first page headers. You will need the most recent version of POI, and then create the header from XWPFDocument using:
XWPFDocument.createHeader(HeaderFooterType.FIRST);
Otherwise you need to break into the CT classes and in the section properties set the titlePg property. I don't recommend this approach though as it is likely to change.
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 actual final apache poi version 3.15 this XML element titlePg can only be set using underlying low level objects using doc.getDocument().getBody().getSectPr().addNewTitlePg();.
But apache poi version 3.16 Beta 2 has doc.createHeader(HeaderFooterType.FIRST); which sets titlePg flag in XML.
Complete example:
import java.io.*;
import org.apache.poi.wp.usermodel.*;
import org.apache.poi.xwpf.usermodel.*;
public class CreateWordHeaderFooterDifferent {
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:");
paragraph = doc.createParagraph();
run=paragraph.createRun();
run.setText("Lorem ipsum.... page 1");
paragraph = doc.createParagraph();
run=paragraph.createRun();
run.addBreak(BreakType.PAGE);
run.setText("Lorem ipsum.... page 2");
paragraph = doc.createParagraph();
run=paragraph.createRun();
run.addBreak(BreakType.PAGE);
run.setText("Lorem ipsum.... page 3");
// create first page header
XWPFHeader header = doc.createHeader(HeaderFooterType.FIRST);
paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setText("The first page header:");
// create default page header
header = doc.createHeader(HeaderFooterType.DEFAULT);
paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setText("The default page header:");
// create footer
XWPFFooter footer = doc.createFooter(HeaderFooterType.DEFAULT);
paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();
run.setText("Page ");
paragraph.getCTP().addNewFldSimple().setInstr("PAGE \\* MERGEFORMAT");
run = paragraph.createRun();
run.setText(" of ");
paragraph.getCTP().addNewFldSimple().setInstr("NUMPAGES \\* MERGEFORMAT");
doc.write(new FileOutputStream("CreateWordHeaderFooterDifferent.docx"));
}
}
But in my opinion the setting titlePg flag in XML automatically while HeaderFooterType.FIRST is created is not correct. Since Word can toggle between [x] Different First Page and [] Different First Page, apache poi should also be able to do so. So the setting the titlePg flag should be a method in XWPFDocument.
I'm trying to use Apache poi word 3.8 to create word document in persian/arabic language.
My question is: how change text direction in document? ( it means changing text direction not changing just paragraph text alignment)
In MS Word we could use Right-to-left text direction to change text direction and Align Right to set alignment. What’s equivalent of the first one in poi set property?
This is bidirectional text direction support (bidi) and is not yet implemented in apache poi per default. But the underlying object org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPrBase supports this. So we must get this underlying object from the XWPFParagraph.
Example:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;
public class CreateWordRTLParagraph {
public static void main(String[] args) throws Exception {
XWPFDocument doc= new XWPFDocument();
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Paragraph 1 LTR");
paragraph = doc.createParagraph();
CTP ctp = paragraph.getCTP();
CTPPr ctppr;
if ((ctppr = ctp.getPPr()) == null) ctppr = ctp.addNewPPr();
ctppr.addNewBidi().setVal(STOnOff.ON);
run = paragraph.createRun();
run.setText("السلام عليكم");
paragraph = doc.createParagraph();
run = paragraph.createRun();
run.setText("Paragraph 3 LTR");
FileOutputStream out = new FileOutputStream("WordDocument.docx");
doc.write(out);
out.close();
doc.close();
}
}