How to center a paragraph vertically in Apache POI Java? - java

I am currently build a word formatter tool and have some problems with Apache POI.
I am using org.apache.poi version 5.2.0
Have a look at this picture:
I need it centered both horizontally and vertically.
Currently it only centers horizontally but not vertically.
And I dont know why. Here is the code I am using:
for (XWPFParagraph p : docx.getParagraphs()) {
System.out.println(p.getText());
boolean setBold = false;
boolean setItalic = false;
int fontSizeToSet = 16;
if (counter == 0) {
p.setAlignment(ParagraphAlignment.CENTER);
p.setVerticalAlignment(TextAlignment.CENTER);
}
if (counter == 1) {
p.setPageBreak(true);
}
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
if (counter == 0) {
r.setFontSize(14);
r.setBold(true);
r.setFontFamily("Bookman Old Style");
}
}
}
counter++;
}
What am I doing wrong?

XWPFParagraph.setVerticalAlignment is not made for vertical aligning a paragraph on the page. It sets the vertical alignment within the text line. This is similar to what vertical-align does in CSS. It only takes effect if the text line is higher than the single elements in that line. For example if there is text having various font sizes in one text line.
TextAlignment has following enum constants:
AUTO
Specifies that all text in the parent object shall be aligned automatically when displayed.
BASELINE
Specifies that all text in the parent object shall be aligned to the baseline of each character when displayed.
BOTTOM
Specifies that all text in the parent object shall be aligned to the bottom of each character when displayed.
CENTER
Specifies that all text in the parent object shall be aligned to the center of each character when displayed.
TOP
Specifies that all text in the parent object shall be aligned to the top of each character when displayed.
The following complete code sample shows the effect of the different text alignment settings.
To vertically center a paragraph (or more) on the page, those paragraphs must be on a single page. And there must be section properties set for this page. In section properties one then can set VAlign for the section above.
Unfortunately does apche poi not provide setting section properties up to now. So the low level org.openxmlformats.schemas.wordprocessingml.x2006.main.* classes must be used to achieve the same.
The folowing complete example also shows this. It puts a paragraph with section break next page for section above. So the first paragraph is on it's own page. Then it sets page vertical align to center for page above (section above).
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.*;
public class CreateWordParagraphAndPageAlignment {
static void createSomeRichTextContent(XWPFParagraph paragraph) {
XWPFRun run = paragraph.createRun();
run.setText("Aligned ");
run.setFontSize(11);
run = paragraph.createRun();
run.setText("paragraph ");
run.setFontSize(22);
run = paragraph.createRun();
run.setText("having ");
run.setFontSize(33);
run = paragraph.createRun();
run.setText("various ");
run.setFontSize(22);
run = paragraph.createRun();
run.setText("font sizes");
run.setFontSize(11);
}
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Default paragraph in first page, which has page vertical alignment set.");
run.setFontSize(44);
paragraph = document.createParagraph();
//paragraph with section break next page for section above
paragraph = document.createParagraph();
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr ctSectPr = paragraph.getCTP().addNewPPr().addNewSectPr();
ctSectPr.addNewType().setVal(org.openxmlformats.schemas.wordprocessingml.x2006.main.STSectionMark.NEXT_PAGE);
//set page vertical align center for page above (section above)
ctSectPr.addNewVAlign().setVal(org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc.CENTER);
//page size setting (A4) for the section above
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageSz ctPageSz = ctSectPr.addNewPgSz();
ctPageSz.setW(java.math.BigInteger.valueOf(Math.round(8.27d*72d*20d))); //A4 = 8.27" * 72 * 20 = Twips
ctPageSz.setH(java.math.BigInteger.valueOf(Math.round(11.69d*72d*20d))); //A4 = 11.69" * 72 * 20 = Twips
paragraph = document.createParagraph();
run = paragraph.createRun();
run.setText("Default paragraph");
paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
paragraph.setVerticalAlignment(TextAlignment.AUTO);
createSomeRichTextContent(paragraph);
paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
paragraph.setVerticalAlignment(TextAlignment.BASELINE);
createSomeRichTextContent(paragraph);
paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
paragraph.setVerticalAlignment(TextAlignment.BOTTOM);
createSomeRichTextContent(paragraph);
paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
paragraph.setVerticalAlignment(TextAlignment.CENTER);
createSomeRichTextContent(paragraph);
paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
paragraph.setVerticalAlignment(TextAlignment.TOP);
createSomeRichTextContent(paragraph);
paragraph = document.createParagraph();
// page size setting (A4) for the last section above must be at last in body
ctSectPr = document.getDocument().getBody().addNewSectPr();
ctPageSz = ctSectPr.addNewPgSz();
ctPageSz.setW(java.math.BigInteger.valueOf(Math.round(8.27d*72d*20d))); //A4 = 8.27" * 72 * 20 = Twips
ctPageSz.setH(java.math.BigInteger.valueOf(Math.round(11.69d*72d*20d))); //A4 = 11.69" * 72 * 20 = Twips
FileOutputStream out = new FileOutputStream("./CreateWordParagraphAndPageAlignment.docx");
document.write(out);
out.close();
document.close();
}
}

Related

Apache Poi - XWPF: How to change font color, size, style of the footer Page Number in docx

I have tried the code below, but it seems that setColor() only updates the text in the paragraph -- it does not affect the color of CTSimpleField Page Number.
CTSectPr sectPr = getSectionProperty(0);
CTHdrFtrRef footerRef = sectPr.addNewFooterReference();
XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
footerRef.setId(footer.getPackageRelationship().getId());
XWPFParagraph paragraph = footer.createParagraph();
CTSimpleField simpleField = paragraph.getCTP().addNewFldSimple().setInstr("PAGE \\* Arabic \\* MERGEFORMAT");
XWPFRun run = paragraph.createRun();
run.setText("Page ");
run.setColor("ffffff");
Is there a way to update the CTSimpleField font color, style, and size? or is there a different way to generate Page Numbers where we can update their font color?
The setColor is a method of XWPFRun. So it only affects the text in that XWPFRun.
The method XWPFParagraph paragraph ...; ... paragraph.getCTP().addNewFldSimple() ist the simplest method to add a field into a Office Open XML Word document. But as this adds a field into the paragraph outside all text runs, no text formatting is possible. This is because text formatting in Word is only possible for text runs.
If special text formatting is needed, then the field would must be within a text run. But there is no simple field possible within a text run. To store fields in text runs, there must be a special text run having field char type BEGIN, followed by a special text run having the field content as in-string text, followed by a special text run having field char type END.
Following code shows that. All used XWPFRuns provide text fromatting.
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.wp.usermodel.HeaderFooterType;
public class CreateWordHeaderFooter3 {
static XWPFRun createRunFldCharTypeBegin(XWPFParagraph paragraph) {
XWPFRun run = paragraph.createRun();
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR cTR = run.getCTR();
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFldChar cTFldChar = org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFldChar.Factory.newInstance();
cTFldChar.setFldCharType​(org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType.BEGIN);
cTR.setFldCharArray​(new org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFldChar[]{cTFldChar});
return run;
}
static XWPFRun createRunInstrText(XWPFParagraph paragraph, String instrText) {
XWPFRun run = paragraph.createRun();
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR cTR = run.getCTR();
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText cTText = org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText.Factory.newInstance();
cTText.setStringValue(instrText);
cTR.setInstrTextArray​(new org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText[]{cTText});
return run;
}
static XWPFRun createRunFldCharTypeEnd(XWPFParagraph paragraph) {
XWPFRun run = paragraph.createRun();
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR cTR = run.getCTR();
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFldChar cTFldChar = org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFldChar.Factory.newInstance();
cTFldChar.setFldCharType​(org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType.END);
cTR.setFldCharArray​(new org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFldChar[]{cTFldChar});
return run;
}
public static void main(String[] args) throws Exception {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph paragraph;
XWPFRun run;
// the body content
paragraph = doc.createParagraph();
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 header-footer
// create header start
XWPFHeader header = doc.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 header end
// create footer start
XWPFFooter footer = doc.createFooter(HeaderFooterType.DEFAULT);
paragraph = footer.getParagraphArray(0);
if (paragraph == null) paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();
run.setText("Page ");
//paragraph.getCTP().addNewFldSimple().setInstr("PAGE \\* MERGEFORMAT");
run = createRunFldCharTypeBegin(paragraph);
run.setFontSize(16);
run.setColor("FF0000");
run = createRunInstrText(paragraph, "PAGE \\* MERGEFORMAT");
run = createRunFldCharTypeEnd(paragraph);
run = paragraph.createRun();
run.setText(" of ");
//paragraph.getCTP().addNewFldSimple().setInstr("NUMPAGES \\* MERGEFORMAT");
run = createRunFldCharTypeBegin(paragraph);
run.setFontSize(16);
run.setColor("0000FF");
run = createRunInstrText(paragraph, "NUMPAGES \\* MERGEFORMAT");
run = createRunFldCharTypeEnd(paragraph);
// create footer end
FileOutputStream out = new FileOutputStream("CreateWordHeaderFooter.docx");
doc.write(out);
out.close();
doc.close();
}
}

how create TextBox in a cell of table in document .docx using apache poi

I used Javafx and
I created a table using apache poi:
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFTable table = document.createTable(4, 3);
and created the paragraph like the paragraph below:
XWPFParagraph p1 = table.getRow(0).getCell(2).getParagraphs().get(0);
XWPFRun r1 = p1.createRun();
r1.setText(category_number.getText() + category.toString());
Now, I want create a TextBox in a one cell of a row but don't know how address Cell and Row to a textBox and set text and alignment textBox.
Please Help me ):
A text box in a *.docx is a shape in the document content. Creating shapes is not yet implemented in XWPF. But it can be done using the underlying ooxml-schemas classes.
Example:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPicture;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTxbxContent;
import com.microsoft.schemas.vml.CTGroup;
import com.microsoft.schemas.vml.CTShape;
import org.w3c.dom.Node;
public class CreateWordTextBoxInTable {
public static void main(String[] args) throws Exception {
XWPFDocument document= new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The table:");
XWPFTable table = document.createTable(4, 3);
// table header row
for (int c = 0; c < 3; c++ ) {
paragraph = table.getRow(0).getCell(c).getParagraphArray(0);
if (paragraph == null) paragraph = table.getRow(0).getCell(c).addParagraph();
run = paragraph.createRun();
run.setText("Column " + (c+1));
}
// get run in cell for text box
XWPFTableCell cell = table.getRow(1).getCell(1);
paragraph = cell.getParagraphArray(0);
if (paragraph == null) paragraph = cell.addParagraph();
run = paragraph.createRun();
// create inline text box in run
// first crfeate group shape
CTGroup ctGroup = CTGroup.Factory.newInstance();
// now add shape to group shape
CTShape ctShape = ctGroup.addNewShape();
ctShape.setStyle("width:100pt;height:36pt");
// add text box content to shape
CTTxbxContent ctTxbxContent = ctShape.addNewTextbox().addNewTxbxContent();
XWPFParagraph textboxparagraph = new XWPFParagraph(ctTxbxContent.addNewP(), (IBody)cell);
textboxparagraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun textboxrun = textboxparagraph.createRun();
textboxrun.setText("The TextBox content...");
textboxrun.setFontSize(10);
// add group shape as picture to the run
Node ctGroupNode = ctGroup.getDomNode();
CTPicture ctPicture = CTPicture.Factory.parse(ctGroupNode);
CTR cTR = run.getCTR();
cTR.addNewPict();
cTR.setPictArray(0, ctPicture);
FileOutputStream out = new FileOutputStream("test.docx");
document.write(out);
out.close();
}
}
This code was tested using apache poi 4.0.1 and needs the ooxml-schemas-1.4.jar in class path.

Generate Inter-Document Hyperlink with Apache POI in Java

I'm generating an XWPFDocument with Apache POI (never used it before this) and I'd like to link one paragraph to another paragraph inside the same .docx document. Is this possible using POI's native functionality or do I need to deep-dive into XML Bean wrapper classes (i.e. CTP) to hand-jam this or am I out of luck? Every instance of a question regarding hyperlinks and POI that I have seen references creating either an external-type hyperlink or a link between Excel workbook sheets. I am as of now only able to generate a 'hyperlink' in the sense of ctrl-clicking the paragraph inside the finished document and it appears to simply do a text search starting from the top of the document. Here's the code I am currently using to achieve this. Thanks in advance!
public static void addInternalHyperlink(XWPFParagraph origin, String text, XWPFParagraph target) {
if (target != null) {
// Create the hyperlink itself
CTHyperlink link = origin.getCTP().addNewHyperlink();
link.setAnchor(target.getText());
// Create hyperlink text
CTText linkText = CTText.Factory.newInstance();
linkText.setStringValue(text);
CTR ctr = CTR.Factory.newInstance();
ctr.setTArray(new CTText[] {linkText});
// Format hyperlink text
CTFonts fonts = CTFonts.Factory.newInstance();
fonts.setAscii("Times New Roman");
CTRPr rpr = ctr.addNewRPr();
CTColor color = CTColor.Factory.newInstance();
color.setVal("0000FF");
rpr.setColor(color);
CTRPr rpr1 = ctr.addNewRPr();
rpr1.addNewU().setVal(STUnderline.SINGLE);
// Insert formatted text into link
link.setRArray(new CTR[] {ctr});
}
}
Please note that I'd like to use the 'origin' argument as the paragraph containing the actual link, the 'text' argument as the link text, and the 'target' argument as the actual link destination.
UPDATE: Here's an XML snippet containing a sample paragraph which I have linked to a section heading via the Word GUI.
<w:p w14:paraId="5B1C3A0C" w14:textId="659E388D" w:rsidR="00A4419C" w:rsidRDefault="00A4419C" w:rsidP="00A4419C"><w:hyperlink w:anchor="_Another_Heading" w:history="1"><w:r w:rsidRPr="00A4419C"><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t>Here is some stuff that could b</w:t></w:r><w:r w:rsidRPr="00A4419C"><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t>e</w:t></w:r><w:r w:rsidRPr="00A4419C"><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t xml:space="preserve"> the link</w:t></w:r></w:hyperlink></w:p><w:p w14:paraId="19996B78" w14:textId="5C39B081" w:rsidR="00A4419C" w:rsidRPr="00A4419C" w:rsidRDefault="00A4419C" w:rsidP="00A4419C"><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:bookmarkStart w:id="0" w:name="_Another_Heading"/><w:bookmarkEnd w:id="0"/><w:r><w:t>Another Heading</w:t></w:r><w:bookmarkStart w:id="1" w:name="_GoBack"/><w:bookmarkEnd w:id="1"/></w:p>
The solution falls into two parts.
First we need a XWPFHyperlinkRun whose target is an anchor in the document.
Second we need that target anchor, which can be a bookmark in the document for example. So we need creating such bookmark in the document.
Unfortunately both is not supported using only high level classes of apache poi until now. So we need the low level classes form ooxml-schemas too.
The following code works using apache poi 4.0.0 together with ooxml-schemas-1.4.
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink;
import java.math.BigInteger;
public class CreateWordHyperlinkBookmark {
static XWPFHyperlinkRun createHyperlinkRunToAnchor(XWPFParagraph paragraph, String anchor) throws Exception {
CTHyperlink cthyperLink=paragraph.getCTP().addNewHyperlink();
cthyperLink.setAnchor(anchor);
cthyperLink.addNewR();
return new XWPFHyperlinkRun(
cthyperLink,
cthyperLink.getRArray(0),
paragraph
);
}
static XWPFParagraph createBookmarkedParagraph(XWPFDocument document, String anchor, int bookmarkId) {
XWPFParagraph paragraph = document.createParagraph();
CTBookmark bookmark = paragraph.getCTP().addNewBookmarkStart();
bookmark.setName(anchor);
bookmark.setId(BigInteger.valueOf(bookmarkId));
XWPFRun run = paragraph.createRun();
paragraph.getCTP().addNewBookmarkEnd().setId(BigInteger.valueOf(bookmarkId));
return paragraph;
}
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
String anchor = "hyperlink_target";
int bookmarkId = 0;
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("This is a text paragraph having ");
//create hyperlink run
XWPFHyperlinkRun hyperlinkrun = createHyperlinkRunToAnchor(paragraph, anchor);
hyperlinkrun.setText("a link to an bookmark anchor");
hyperlinkrun.setColor("0000FF");
hyperlinkrun.setUnderline(UnderlinePatterns.SINGLE);
run = paragraph.createRun();
run.setText(" in it.");
//some empty paragraphs
for (int i = 0; i < 10; i++) {
paragraph = document.createParagraph();
}
//create bookmarked paragraph as the hyperlink target
paragraph = createBookmarkedParagraph(document, anchor, bookmarkId++);
run = paragraph.getRuns().get(0);
run.setText("This is the target.");
FileOutputStream out = new FileOutputStream("CreateWordHyperlinkBookmark.docx");
document.write(out);
out.close();
document.close();
}
}

How could I add spacing for my footer when generating .docx using Apache poi?

Here is an image how I would like to be (spacing of footer is set to 80). How to do it with Apache Poi when generating XWPFDocument?
Your picture shows a page style dialog from Openoffice or Libreoffice Writer and not from Word which is apache poi mainly made for. But nevertheless:
The so called "Footer - Spacing" in Writer is in Word the difference between the page bottom margin and the footer margin. But take into account that there is a non printable page range on bottom which is dependent of the printer. This gap must also be considered.
Example:
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar;
import java.math.BigInteger;
public class CreateWordHeaderFooterSpacing {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
// create header-footer
XWPFHeaderFooterPolicy headerFooterPolicy = document.getHeaderFooterPolicy();
if (headerFooterPolicy == null) headerFooterPolicy = document.createHeaderFooterPolicy();
// create footer start
XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
XWPFParagraph paragraph = footer.getParagraphArray(0);
paragraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun run = paragraph.createRun();
run.setText("Footer");
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(1440)); //1440 Twips = 1440/20 = 72 pt = 72/72 = 1"
pageMar.setFooter(BigInteger.valueOf(720)); //0.5" footer margin
long notPrintableBottomPageRange = (long)(0.038888*72*20); //0.038888" gap for non printable bottom page range
pageMar.setBottom(BigInteger.valueOf(1152+720+notPrintableBottomPageRange)); //1152 Twips = 1152/20/72 = 0.8"
//bottom margin = 0.8" footer spacing + 0.5" footer margin + 0.038888" gap for non printable bottom page range
document.write(new FileOutputStream("CreateWordHeaderFooterSpacing.docx"));
document.close();
}
}
This leads in my Writer to exact 0.8" footer spacing.

How to set background color (Page Color) for word document (.doc or .docx) in Java?

By some libraries like http://poi.apache.org , we could create word document with any text color, but for background or highlight of the text, I didn't find any solution.
Page color for word in manual way!:
https://support.office.com/en-us/article/Change-the-background-or-color-of-a-document-6ce0b23e-b833-4421-b8c3-b3d637e62524
Here is my main code to create word document by poi.apache
// Blank Document
#SuppressWarnings("resource")
XWPFDocument document = new XWPFDocument();
// Write the Document in file system
FileOutputStream out = new FileOutputStream(new File(file_address));
// create Paragraph
XWPFParagraph paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.RIGHT);
XWPFRun run = paragraph.createRun();
run.setFontFamily(font_name);
run.setFontSize(font_size);
// This only set text color not background!
run.setColor(hex_color);
for (String s : text_array) {
run.setText(s);
run.addCarriageReturn();
}
document.write(out);
out.close();
Update: XWPF is the newest way to create word document files, but setting background only possible by HWPF which is for old format version (.doc)
For *.doc (i.e. POI's HWPF component):
Highlighting of text:
Look into setHighlighted()
Background color:
I suppose you mean the background of a paragraph (AFAIK, Word also allows to color the entire page which is a different matter)
There is setShading() which allows you to provide a foreground and background color (through setCvFore() and setCvBack() of SHDAbstractType) for a Paragraph. IIRC, it is the foreground that you would want to set in order to color your Paragraph. The background is only relevant for shadings which are composed of two (alternating) colors.
The underlying data structure is named Shd80 ([MS-DOC], 2.9.248). There is also SHDOperand ([MS-DOC], 2.9.249) that reflects the functionality of Word prior to Word97. [MS-DOC] is the Binary Word File format specification which is freely available on MSDN.
Edit:
Here is some code to illustrate the above:
try {
HWPFDocument document = [...]; // comes from somewhere
Range range = document.getRange();
// Background shading of a paragraph
ParagraphProperties pprops = new ParagraphProperties();
ShadingDescriptor shd = new ShadingDescriptor();
shd.setCvFore(Colorref.valueOfIco(0x07)); // yellow; ICO
shd.setIpat(0x0001); // solid background; IPAT
pprops.setShading(shd);
Paragraph p1 = range.insertBefore(pprops, StyleSheet.NIL_STYLE);
p1.insertBefore("shaded paragraph");
// Highlighting of individual characters
Paragraph p2 = range.insertBefore(new ParagraphProperties(), StyleSheet.NIL_STYLE);
CharacterRun cr = p2.insertBefore("highlighted text\r");
cr.setHighlighted((byte) 0x06); // red; ICO
document.write([...]); // document goes to somewhere
} catch (IOException e) {
e.printStackTrace();
}
ICO is a color structure
IPAT is a list of predefined shading styles
We Only need to add these 3 lines to set the background color for Word documents by XWPF. We have to set these lines after declaring XWPFRun and it's text color:
CTShd cTShd = run.getCTR().addNewRPr().addNewShd();
cTShd.setVal(STShd.CLEAR);
cTShd.setFill(hex_background_color);

Categories