基础技术调查参考网站:
https://angelozerr.wordpress.com/2012/12/06/how-to-convert-docxodt-to-pdfhtml-with-java/ ---- docx转化为pdf工具的介绍和比较分析
https:///opensagres/xdocreport/wiki/XDocReport103 --XDocReport maven依赖引用介绍
https://stackoverflow.com/questions/38913283/broken-pdf-after-conversion-with-xdocreport ---示例
https://www.programcreek.com/java-api-examples/index.php?api=org.docx4j.openpackaging.packages.WordprocessingMLPackage ---docx4j 示例
http://www.javafind.net/gate.jsp?q=/library/162/docx4j-3.1.0-javadoc/org/docx4j/openpackaging/parts/WordprocessingML/MainDocumentPart.html --------docx4j api 该网站需要才可访问
www.javafind.net/gate.jsp?q=/library/162/docx4j-3.1.0-javadoc/org/docx4j/convert/out/pdf/viaXSLFO/PdfSettings.html
首先创建一个maven工程
在pom文件中配置依赖
<!-- word 格式为docx转成pdf -->
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.converter.docx.xwpf</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.2</version>
</dependency>
工具类 CreateWordUtils
package cn.sh.cx.ce.maint.biz.pdf.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.docx4j.Docx4J;
import org.docx4j.TextUtils;
import org.docx4j.convert.out.FOSettings;
import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.finders.RangeFinder;
import org.docx4j.fonts.BestMatchingMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFonts;
import .TrHeight;
import org.docx4j.model.structure.SectionWrapper;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.exceptions.InvalidFormatException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.FooterPart;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.relationships.Relationship;
import org.docx4j.utils.BufferUtil;
import org.docx4j.wml.BooleanDefaultTrue;
import ;
import org.docx4j.wml.CTBookmark;
import org.docx4j.wml.CTBorder;
import org.docx4j.wml.CTHeight;
import org.docx4j.wml.CTShd;
import org.docx4j.wml.CTVerticalJc;
import org.docx4j.wml.Color;
import org.docx4j.wml.ContentAccessor;
import org.docx4j.wml.Drawing;
import org.docx4j.wml.FldChar;
import org.docx4j.wml.FooterReference;
import org.docx4j.wml.Ftr;
import org.docx4j.wml.HdrFtrRef;
import org.docx4j.wml.HpsMeasure;
import org.docx4j.wml.Jc;
import org.docx4j.wml.JcEnumeration;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.P;
import org.docx4j.wml.PPr;
import org.docx4j.wml.PPrBase.Ind;
import org.docx4j.wml.PPrBase.PBdr;
import org.docx4j.wml.PPrBase.Spacing;
import org.docx4j.wml.R;
import org.docx4j.wml.RFonts;
import org.docx4j.wml.RPr;
import org.docx4j.wml.STBorder;
import org.docx4j.wml.STBrType;
import org.docx4j.wml.STFldCharType;
import org.docx4j.wml.STHint;
import org.docx4j.wml.STLineSpacingRule;
import org.docx4j.wml.STVerticalJc;
import org.docx4j.wml.SectPr;
import org.docx4j.wml.SectPr.PgMar;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.TblBorders;
import org.docx4j.wml.TblGrid;
import org.docx4j.wml.TblGridCol;
import org.docx4j.wml.TblPr;
import org.docx4j.wml.TblWidth;
import ;
import Pr;
import PrInner.GridSpan;
import PrInner.HMerge;
import PrInner.TcBorders;
import PrInner.VMerge;
import org.docx4j.wml.Text;
import org.docx4j.wml.TextDirection;
import ;
import Pr;
import org.docx4j.wml.U;
import org.docx4j.wml.UnderlineEnumeration;
public class CreateWordUtils {
/**
* 创建word文件创建对象. <br/>
*
* @return 创建word对象
* @throws Exception
* @author zhouweiwei
*/
public static WordprocessingMLPackage createWordprocessingMLPackage() throws Exception {
return WordprocessingMLPackage.createPackage();
}
/**
* 保存word文档的方法. <br/>
*
* @param wordPackage 创建文档的对象
* @param file 保存路径
* @throws Exception
* @author zhouweiwei
*/
public static void saveWordPackage(WordprocessingMLPackage wordPackage, File file) throws Exception {
wordPackage.save(file);
}
public static void saveWordPackage(WordprocessingMLPackage wordPackage, OutputStream outputStream) throws Exception {
wordPackage.save(outputStream);
}
/**
* 设置段落间的间隙
*
* @param jcEnumeration
* 对齐方式
* @param isSpace
* 是否设置段前段后值
* @param before
* 段前磅数
* @param after
* 段后磅数
* @param beforeLines
* 段前行数
* @param afterLines
* 段后行数
* @param isLine
* 是否设置行距
* @param lineValue
* 行距值
* @param sTLineSpacingRule
* 自动auto 固定exact 最小 atLeast
* @author zhouweiwei
*/
public static void setParagraphSpacing(ObjectFactory factory, P p, JcEnumeration jcEnumeration, boolean isSpace,
String before, String after, String beforeLines, String afterLines, boolean isLine, String lineValue,
STLineSpacingRule sTLineSpacingRule) {
PPr pPr = p.getPPr();
if (pPr == null) {
pPr = factory.createPPr();
}
Jc jc = pPr.getJc();
if (jc == null) {
jc = new Jc();
}
jc.setVal(jcEnumeration);
pPr.setJc(jc);
Spacing spacing = new Spacing();
if (isSpace) {
if (before != null) {
// 段前磅数
spacing.setBefore(new BigInteger(before));
}
if (after != null) {
// 段后磅数
spacing.setAfter(new BigInteger(after));
}
if (beforeLines != null) {
// 段前行数
spacing.setBeforeLines(new BigInteger(beforeLines));
}
if (afterLines != null) {
// 段后行数
spacing.setAfterLines(new BigInteger(afterLines));
}
}
if (isLine) {
if (lineValue != null) {
spacing.setLine(new BigInteger(lineValue));
}
spacing.setLineRule(sTLineSpacingRule);
}
pPr.setSpacing(spacing);
p.setPPr(pPr);
}
/**
* 设置缩进 同时设置为true,则为悬挂缩进
*
* @param factory
* 工厂对象
* @param p
* 段落参数
* @param jcEnumeration
* 字体水平样式
* @param firstLine
* 是否设置首行缩进
* @param firstLineValue
* 设置首行缩进值
* @param hangLine
* 判断是否设悬挂
* @param hangValue
* 设置悬挂值
* @author zhouweiwei
*/
public static void setParagraphInd(ObjectFactory factory, P p, JcEnumeration jcEnumeration, boolean firstLine,
String firstLineValue, boolean hangLine, String hangValue) {
PPr pPr = p.getPPr();
if (pPr == null) {
pPr = factory.createPPr();
}
Jc jc = pPr.getJc();
if (jc == null) {
jc = new Jc();
}
jc.setVal(jcEnumeration);
pPr.setJc(jc);
Ind ind = pPr.getInd();
if (ind == null) {
ind = new Ind();
}
if (firstLine) {
if (firstLineValue != null) {
ind.setFirstLineChars(new BigInteger(firstLineValue));
}
}
if (hangLine) {
if (hangValue != null) {
ind.setHangingChars(new BigInteger(hangValue));
}
}
pPr.setInd(ind);
p.setPPr(pPr);
}
/**
* 创建字体样式
*
* @param isBlod
* 粗体
* @param isUnderLine
* 下划线
* @param isItalic
* 斜体
* @param isStrike
* 删除线
* @author zhouweiwei
*/
public static RPr getRPr(ObjectFactory factory, String fontFamily, String colorVal, String fontSize, STHint sTHint,
boolean isBlod, boolean isUnderLine, boolean isItalic, boolean isStrike) {
RPr rPr = factory.createRPr();
RFonts rf = new RFonts();
rf.setHint(sTHint);
rf.setAscii(fontFamily);
rf.setHAnsi(fontFamily);
rf.setEastAsia(fontFamily);
rPr.setRFonts(rf);
BooleanDefaultTrue bdt = factory.createBooleanDefaultTrue();
rPr.setBCs(bdt);
if (isBlod) {
rPr.setB(bdt);
}
if (isItalic) {
rPr.setI(bdt);
}
if (isStrike) {
rPr.setStrike(bdt);
}
if (isUnderLine) {
U underline = new U();
underline.setVal(UnderlineEnumeration.SINGLE);
rPr.setU(underline);
}
Color color = new Color();
color.setVal(colorVal);
rPr.setColor(color);
HpsMeasure sz = new HpsMeasure();
sz.setVal(new BigInteger(fontSize));
rPr.setSz(sz);
rPr.setSzCs(sz);
return rPr;
}
/**
* 段落中插入文字和图片
*
* @param wordMLPackage
* word文件对象
* @param factory
* 工厂对象
* @param p
* 段落对象
* @param fileName
* 文件名称
* @param content
* 文字内容
* @param bytes
* 字节流对象
* @param jcEnumeration
* 在段落中的位置
* @return 段落对象P
* @throws Exception
* @author zhouweiwei
*
*/
public static P createImageParagraph(WordprocessingMLPackage wordMLPackage, ObjectFactory factory, P p,
String fileName, String content, byte[] bytes, JcEnumeration jcEnumeration) throws Exception {
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
// /imagePart.setImageInfo(imageInfo);
Inline inline = imagePart.createImageInline(fileName, "这是图片", 0, 1, false);
Text text = factory.createText();
text.setValue(content);
text.setSpace("preserve");
R run = factory.createR();
p.getContent().add(run);
run.getContent().add(text);
Drawing drawing = factory.createDrawing();
run.getContent().add(drawing);
drawing.getAnchorOrInline().add(inline);
PPr pPr = p.getPPr();
if (pPr == null) {
pPr = factory.createPPr();
}
Jc jc = pPr.getJc();
if (jc == null) {
jc = new Jc();
}
jc.setVal(jcEnumeration);
pPr.setJc(jc);
p.setPPr(pPr);
setParagraphSpacing(factory, p, jcEnumeration, true, "0", "0", null, null, true, "240", STLineSpacingRule.AUTO);
return p;
}
/**
* 段落添加图片
*
* @param wordMLPackage
* word文件对象
* @param factory
* 工厂对象
* @param bytes
* 字节流对象
* @param filenameHint
* 文件名称
* @param altText
* 图片说明
* @param id1
* 图片在文档中的在文档中的唯一标识
* @param id2
* 图片在文档中的在文档中其他的唯一标识
* @param isUnderLine
* @param underLineSize
* 是否设置下划线
* @param jcEnumeration
* 在段落中的位置
* @return 段落对象 P
* @throws Exception
* @author zhouweiwei
*/
public static P newImage(WordprocessingMLPackage wordMLPackage, ObjectFactory factory, byte[] bytes,
String filenameHint, String altText, int id1, int id2, boolean isUnderLine, String underLineSize,
JcEnumeration jcEnumeration) throws Exception {
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
Inline inline = imagePart.createImageInline(filenameHint, altText, id1, id2, false);
P p = factory.createP();
R run = factory.createR();
p.getContent().add(run);
Drawing drawing = factory.createDrawing();
run.getContent().add(drawing);
drawing.getAnchorOrInline().add(inline);
PPr pPr = p.getPPr();
if (pPr == null) {
pPr = factory.createPPr();
}
Jc jc = pPr.getJc();
if (jc == null) {
jc = new Jc();
}
jc.setVal(jcEnumeration);
pPr.setJc(jc);
p.setPPr(pPr);
if (isUnderLine) {
PBdr pBdr = pPr.getPBdr();
if (pBdr == null) {
pBdr = factory.createPPrBasePBdr();
}
CTBorder value = new CTBorder();
value.setVal(STBorder.SINGLE);
value.setColor("000000");
value.setSpace(new BigInteger("0"));
value.setSz(new BigInteger(underLineSize));
pBdr.setBetween(value);
pPr.setPBdr(pBdr);
}
setParagraphSpacing(factory, p, jcEnumeration, true, "0", "0", null, null, true, "240", STLineSpacingRule.AUTO);
return p;
}
/**
* 分页
*
* @param wordMLPackage
* 文档对象
* @param factory
* 工厂对象
* @param sTBrType
* 分页类型
* @author zhouweiwei
*/
public static void addPageBreak(WordprocessingMLPackage wordMLPackage, ObjectFactory factory, STBrType sTBrType) {
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
Br breakObj = new Br();
breakObj.setType(sTBrType);
P paragraph = factory.createP();
paragraph.getContent().add(breakObj);
documentPart.addObject(paragraph);
}
/**
* 得到页面宽度
*
* @param wordPackage
* @return
* @throws Exception
* @author zhouweiwei
*/
public static int getWritableWidth(WordprocessingMLPackage wordPackage) throws Exception {
return wordPackage.getDocumentModel().getSections().get(0).getPageDimensions().getWritableWidthTwips();
}
/**
* 设置word文档内容里页面的页边距
* 此处设置的为A4
*
* @param wordPackage 文档对象
* @throws Exception 异常
* @author zhouweiwei
*/
public static void setWordPage(WordprocessingMLPackage wordPackage) throws Exception {
PgMar pgSz = new PgMar();
pgSz.setLeft(new BigInteger("851"));
pgSz.setRight(new BigInteger("851"));
pgSz.setTop(new BigInteger("851"));
pgSz.setBottom(new BigInteger("851"));
// 设置页面的宽度
List<SectionWrapper> sections = wordPackage.getDocumentModel().getSections();
SectPr sectPr = sections.get(sections.size() - 1).getSectPr();
sectPr.setPgMar(pgSz);
}
/**
* 设置整列宽度
*
* @param tableWidthPercent
* 表格占页面宽度百分比
* @param widthPercent
* 各列百分比
* @author zhouweiwei
*/
public static void setTableGridCol(WordprocessingMLPackage wordPackage, ObjectFactory factory, Tbl table,
double tableWidthPercent, double[] widthPercent) throws Exception {
int width = getWritableWidth(wordPackage);
int tableWidth = (int) (width * tableWidthPercent / 100);
TblGrid tblGrid = factory.createTblGrid();
for (int i = 0; i < widthPercent.length; i++) {
TblGridCol gridCol = factory.createTblGridCol();
gridCol.setW(BigInteger.valueOf((long) (tableWidth * widthPercent[i] / 100)));
tblGrid.getGridCol().add(gridCol);
}
table.setTblGrid(tblGrid);
TblPr tblPr = table.getTblPr();
if (tblPr == null) {
tblPr = factory.createTblPr();
}
TblWidth tblWidth = new TblWidth();
tblWidth.setType("dxa");// 这一行是必须的,不自己设置宽度默认是auto
tblWidth.setW(new BigInteger(tableWidth + ""));
tblPr.setTblW(tblWidth);
table.setTblPr(tblPr);
}
/**
* 表格水平对齐方式
*
* @param factory
* 工厂对象
* @param table
* 表格对象
* @param jcEnumeration
* 表格水平对齐设置
* @author zhouweiwei
*
*/
public static void setTableAlign(ObjectFactory factory, Tbl table, JcEnumeration jcEnumeration) {
TblPr tablePr = table.getTblPr();
if (tablePr == null) {
tablePr = factory.createTblPr();
}
Jc jc = tablePr.getJc();
if (jc == null) {
jc = new Jc();
}
jc.setVal(jcEnumeration);
tablePr.setJc(jc);
table.setTblPr(tablePr);
}
/**
* 表格增加边框
*
* @param table
* 表格对象
* @param borderSize
* 表格边框宽度
* @author zhouweiwei
*/
public static void addBorders(Tbl table, String borderSize) {
table.setTblPr(new TblPr());
CTBorder border = new CTBorder();
border.setColor("auto");
border.setSz(new BigInteger(borderSize));
border.setSpace(new BigInteger("0"));
border.setVal(STBorder.SINGLE);
TblBorders borders = new TblBorders();
borders.setBottom(border);
borders.setLeft(border);
borders.setRight(border);
borders.setTop(border);
borders.setInsideH(border);
borders.setInsideV(border);
table.getTblPr().setTblBorders(borders);
}
/**
* 设置表格外边框并且去除表格将内部单元格的边框
*
* @param table
* 表格对象
* @param borderSize
* 表格边框的的值
* @param cellSize
* 设置单元格的边框值
* @author zhouweiwei
*/
public static void hideTableCellLineBorders(Tbl table, String borderSize, String cellSize) {
table.setTblPr(new TblPr());
CTBorder tableBorder = new CTBorder();
tableBorder.setColor("auto");
tableBorder.setSz(new BigInteger(borderSize));
tableBorder.setSpace(new BigInteger("0"));
tableBorder.setVal(STBorder.SINGLE);
CTBorder cellBorder = new CTBorder();
cellBorder.setColor("auto");
cellBorder.setSpace(new BigInteger("0"));
cellBorder.setVal(STBorder.NONE);
TblBorders borders = new TblBorders();
borders.setBottom(tableBorder);
borders.setLeft(tableBorder);
borders.setRight(tableBorder);
borders.setTop(tableBorder);
borders.setInsideH(cellBorder);
borders.setInsideV(cellBorder);
table.getTblPr().setTblBorders(borders);
}
/**
* 表格增加边框 可以设置上下左右四个边框样式以及横竖水平线样式
*
* @param table
* 表格对象
* @param topBorder
* 表格上边框样式
* @param bottomBorder
* 表格底边框样式
* @param leftBorder
* 表格左边框样式
* @param rightBorder
* 表格右边框样式
* @param hBorder
* 表格水平方向线的样式
* @param vBorder
* 表格垂直方向线的样式
* @author zhouweiwei
*/
public static void addBorders(Tbl table, CTBorder topBorder, CTBorder bottomBorder, CTBorder leftBorder,
CTBorder rightBorder, CTBorder hBorder, CTBorder vBorder) {
table.setTblPr(new TblPr());
TblBorders borders = new TblBorders();
borders.setBottom(bottomBorder);
borders.setLeft(leftBorder);
borders.setRight(rightBorder);
borders.setTop(bottomBorder);
borders.setInsideH(hBorder);
borders.setInsideV(vBorder);
table.getTblPr().setTblBorders(borders);
}
/**
* 单元格上下左右边框设置
*
* @param tc
* 单元格对象
* @param topBorder
* 边框样式对象
* @param bottomBorder
* 单元格底部边框样式
* @param leftBorder
* 单元格左边框样式
* @param rightBorder
* 设置单元格右边框的样式
* @param tcPr
* 单元格样式对象
* @author zhouweiwei
*/
public static void addCellBorders(Tc tc, CTBorder topBorder, CTBorder bottomBorder, CTBorder leftBorder,
CTBorder rightBorder, TcPr tcPr) {
TcBorders borders = new TcBorders();
borders.setBottom(bottomBorder);
borders.setLeft(leftBorder);
borders.setRight(rightBorder);
borders.setTop(topBorder);
tcPr.setTcBorders(borders);
tc.setTcPr(tcPr);
}
/**
* 设置行的高度
*
* @param factory
* 工程对象
* @param tr
* 行对象
* @param heigth
* 行高度
* @author zhouweiwei
*/
public static void setTableTrHeight(ObjectFactory factory, Tr tr, String heigth) {
TrPr trPr = tr.getTrPr();
if (trPr == null) {
trPr = factory.createTrPr();
}
CTHeight ctHeight = new CTHeight();
ctHeight.setVal(new BigInteger(heigth));
TrHeight trHeight = new TrHeight(ctHeight);
trHeight.set(trPr);
tr.setTrPr(trPr);
}
/**
* 新增单元格
*
* @param factory
* 工程对象
* @param tableRow
* 表格行对象
* @param content
* 填充内容
* @param rpr
* 写入样式对象
* @param jcEnumeration
* 段落位置设置
* @param hasBgColor
* 是否设置颜色
* @param backgroudColor
* 背景颜色
* @author zhouweiwei
*
*/
public static void addTableCell(ObjectFactory factory, Tr tableRow, String content, RPr rpr,
JcEnumeration jcEnumeration, boolean hasBgColor, String backgroudColor) {
Tc tableCell = factory.createTc();
P p = factory.createP();
setParagraphSpacing(factory, p, jcEnumeration, true, "0", "0", null, null, true, "240", STLineSpacingRule.AUTO);
Text t = factory.createText();
t.setValue(content);
R run = factory.createR();
// 设置表格内容字体样式
run.setRPr(rpr);
TcPr tcPr = tableCell.getTcPr();
if (tcPr == null) {
tcPr = factory.createTcPr();
}
// 设置内容垂直方向位置
setCellContentHPosition(factory, tcPr, STVerticalJc.CENTER);
run.getContent().add(t);
p.getContent().add(run);
tableCell.getContent().add(p);
if (hasBgColor) {
CTShd shd = tcPr.getShd();
if (shd == null) {
shd = factory.createCTShd();
}
shd.setColor("auto");
shd.setFill(backgroudColor);
tcPr.setShd(shd);
}
tableCell.setTcPr(tcPr);
tableRow.getContent().add(tableCell);
}
/**
* 创建一般单元格
*
* @param factory
* 工厂对象
* @param tr
* 表格行对象
* @param content
* 单元格填充对象
* @param rpr
* 内容写入对象
* @param jcEnumeration
* 设置内容在单元格的位置
* @param hasBgColor
* 是否设置背景颜色
* @param backgroudColor
* 背景颜色的值
* @param isGridSpan
* 是否设置表格跨列
* @param gridSpanSize
* 表格跨列的大小(跨几列)
* @author zhouweiwei
*/
public static void createNormalCell(ObjectFactory factory, Tr tr, String content, RPr rpr,
JcEnumeration jcEnumeration, boolean hasBgColor, String backgroudColor, boolean isGridSpan,
String gridSpanSize) {
Tc tableCell = factory.createTc();
P p = factory.createP();
setParagraphSpacing(factory, p, jcEnumeration, true, "0", "0", null, null, true, "240", STLineSpacingRule.AUTO);
Text t = factory.createText();
t.setValue(content);
R run = factory.createR();
// 设置表格内容字体样式
run.setRPr(rpr);
TcPr tcPr = tableCell.getTcPr();
if (tcPr == null) {
tcPr = factory.createTcPr();
}
// 设置内容垂直方向位置
setCellContentHPosition(factory, tcPr, STVerticalJc.CENTER);
// 设置单元格是否跨列
if (isGridSpan) {
setCellMerge(tcPr, factory, gridSpanSize);
}
run.getContent().add(t);
p.getContent().add(run);
tableCell.getContent().add(p);
if (hasBgColor) {
CTShd shd = tcPr.getShd();
if (shd == null) {
shd = factory.createCTShd();
}
shd.setColor("auto");
shd.setFill(backgroudColor);
tcPr.setShd(shd);
}
tableCell.setTcPr(tcPr);
tr.getContent().add(tableCell);
}
/**
* 创建含有边框的段落
*
* @param wordMLPackage
* @param t
* @param factory
* @param p
* @param topBorder
* @param bottomBorder
* @param leftBorder
* @param rightBorder
* @author zhouweiwei
*/
public static void createParagraghLine(WordprocessingMLPackage wordMLPackage, MainDocumentPart t,
ObjectFactory factory, P p, CTBorder topBorder, CTBorder bottomBorder, CTBorder leftBorder,
CTBorder rightBorder) {
PPr ppr = new PPr();
PBdr pBdr = new PBdr();
pBdr.setTop(topBorder);
pBdr.setBottom(bottomBorder);
pBdr.setLeft(leftBorder);
pBdr.setRight(rightBorder);
ppr.setPBdr(pBdr);
p.setPPr(ppr);
}
/**
* 设置文字方向 tbRlV 垂直
*
* @param wordPackage
* @param textDirection
* 字体方向值 设置垂直tbRlV
* @return 文字方向TextDirection
* @author zhouweiwei
*/
public static TextDirection setDocTextDirection(WordprocessingMLPackage wordPackage, String textDirection) {
SectPr sectPr = wordPackage.getDocumentModel().getSections().get(0).getSectPr();
TextDirection textDir = sectPr.getTextDirection();
if (StringUtils.isNotBlank(textDirection)) {
if (textDir == null) {
textDir = new TextDirection();
sectPr.setTextDirection(textDir);
}
textDir.setVal(textDirection);
}
return textDir;
}
/**
* 设置表格单元跨列
*
* @param tcPr
* 单元个样式对象
* @param factory
* 对象工厂
* @param gridSpanSize
* 单元格跨行数
* @return 返回单元格的样式对象
* @author zhouweiwei
*/
public static TcPr setCellMerge(TcPr tcPr, ObjectFactory factory, String gridSpanSize) {
GridSpan gr = factory.createTcPrInnerGridSpan();
gr.setVal(new BigInteger(gridSpanSize));
tcPr.setGridSpan(gr);
return tcPr;
}
/**
* 设置表格内容垂直方向的位置
*
* @param factory
* 工厂对象
* @param tcPr
* 表格样式对象
* @param Value
* 表格样式垂直样式设置值
* @return tcPr 返回表格样式
* @author zhouweiwei
*/
public static TcPr setCellContentHPosition(ObjectFactory factory, TcPr tcPr, STVerticalJc Value) {
CTVerticalJc valign = factory.createCTVerticalJc();
valign.setVal(Value);
tcPr.setVAlign(valign);
return tcPr;
}
/**
* 设置单元格边框底部边框显示样式
*
* @param factory
* 工厂对象
* @param tableCell
* 单元格
* @param sTBorder
* 底部边框的线条样式
* @author zhouweiwei
*/
public static void setTableCellBoder(ObjectFactory factory, Tc tableCell, STBorder sTBorder) {
// 给下边框设置虚线
tableCell.setTcPr(factory.createTcPr());
CTBorder cellBorder = factory.createCTBorder();
cellBorder.setColor("auto");
cellBorder.setSpace(new BigInteger("1"));
cellBorder.setVal(sTBorder);
TcBorders tableBorder = new TcBorders();
tableBorder.setBottom(cellBorder);
tableCell.getTcPr().setTcBorders(tableBorder);
}
/**
* 设置单元格边框左部边框显示样式
*
* @param factory
* @param tableCell
* @param sTBorder
*/
public static void setTableCellLeftBoder(ObjectFactory factory, Tc tableCell, STBorder sTBorder) {
// 给下边框设置虚线
tableCell.setTcPr(factory.createTcPr());
CTBorder cellBorder = factory.createCTBorder();
cellBorder.setColor("auto");
cellBorder.setSpace(new BigInteger("0"));
cellBorder.setVal(sTBorder);
TcBorders tableBorder = new TcBorders();
tableBorder.setLeft(cellBorder);
tableCell.getTcPr().setTcBorders(tableBorder);
}
/**
* 跨行和并
*
* @param tbl
* 表格对象
* @param col
* 列对象
* @param fromRow
* 要合并行的开始处
* @param toRow
* 要合并行的结束处
* @author zhouweiwei
*/
public static void mergeCellsVertically(Tbl tbl, int col, int fromRow, int toRow) {
if (col < 0 || fromRow < 0 || toRow < 0) {
return;
}
for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
Tc tc = getTc(tbl, rowIndex, col);
if (tc == null) {
break;
}
TcPr tcPr = getTcPr(tc);
VMerge vMerge = tcPr.getVMerge();
if (vMerge == null) {
vMerge = new VMerge();
tcPr.setVMerge(vMerge);
}
if (rowIndex == fromRow) {
vMerge.setVal("restart");
} else {
vMerge.setVal("continue");
}
}
}
/**
* 得到单元格内容
*
* @param tc
* @return
* @throws Exception
* @author zhouweiwei
*/
public static String getTcContent(Tc tc) throws Exception {
return getElementContent(tc);
}
public static String getElementContent(Object obj) throws Exception {
StringWriter stringWriter = new StringWriter();
TextUtils.extractText(obj, stringWriter);
return stringWriter.toString();
}
/**
* @Description:得到指定位置的单元格
* @author zhouweiwei
*/
public static Tc getTc(Tbl tbl, int row, int cell) {
if (row < 0 || cell < 0) {
return null;
}
List<Tr> trList = getTblAllTr(tbl);
if (row >= trList.size()) {
return null;
}
List<Tc> tcList = getTrAllCell(trList.get(row));
if (cell >= tcList.size()) {
return null;
}
return tcList.get(cell);
}
/**
* @Description:得到所有表格
* @author zhouweiwei
*/
public static List<Tbl> getAllTbl(WordprocessingMLPackage wordMLPackage) {
MainDocumentPart mainDocPart = wordMLPackage.getMainDocumentPart();
List<Object> objList = getAllElementFromObject(mainDocPart, Tbl.class);
if (objList == null) {
return null;
}
List<Tbl> tblList = new ArrayList<Tbl>();
for (Object obj : objList) {
if (obj instanceof Tbl) {
Tbl tbl = (Tbl) obj;
tblList.add(tbl);
}
}
return tblList;
}
/**
* @Description:得到指定类型的元素
* @author zhouweiwei
*/
public static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
List<Object> result = new ArrayList<Object>();
if (obj instanceof JAXBElement<?>)
obj = ((JAXBElement<?>) obj).getValue();
if (obj.getClass().equals(toSearch))
result.add(obj);
else if (obj instanceof ContentAccessor) {
List<?> children = ((ContentAccessor) obj).getContent();
for (Object child : children) {
result.addAll(getAllElementFromObject(child, toSearch));
}
}
return result;
}
/**
* @Description: 得到表格所有的行
* @param tbl
* 表格对象
* @author zhouweiwei
*/
public static List<Tr> getTblAllTr(Tbl tbl) {
List<Object> objList = getAllElementFromObject(tbl, Tr.class);
List<Tr> trList = new ArrayList<Tr>();
if (objList == null) {
return trList;
}
for (Object obj : objList) {
if (obj instanceof Tr) {
Tr tr = (Tr) obj;
trList.add(tr);
}
}
return trList;
}
/**
* @Description: 获取所有的单元格
* @author zhouweiwei
*/
public static List<Tc> getTrAllCell(Tr tr) {
List<Object> objList = getAllElementFromObject(tr, Tc.class);
List<Tc> tcList = new ArrayList<Tc>();
if (objList == null) {
return tcList;
}
for (Object tcObj : objList) {
if (tcObj instanceof Tc) {
Tc objTc = (Tc) tcObj;
tcList.add(objTc);
}
}
return tcList;
}
public static TcPr getTcPr(Tc tc) {
TcPr tcPr = tc.getTcPr();
if (tcPr == null) {
tcPr = new TcPr();
tc.setTcPr(tcPr);
}
return tcPr;
}
/**
* @Description: 跨列合并
* @author zhouweiwei
*/
public static void mergeCellsHorizontalByGridSpan(Tbl tbl, int row, int fromCell, int toCell) {
if (row < 0 || fromCell < 0 || toCell < 0) {
return;
}
List<Tr> trList = getTblAllTr(tbl);
if (row > trList.size()) {
return;
}
Tr tr = trList.get(row);
List<Tc> tcList = getTrAllCell(tr);
for (int cellIndex = Math.min(tcList.size() - 1, toCell); cellIndex >= fromCell; cellIndex--) {
Tc tc = tcList.get(cellIndex);
TcPr tcPr = getTcPr(tc);
if (cellIndex == fromCell) {
GridSpan gridSpan = tcPr.getGridSpan();
if (gridSpan == null) {
gridSpan = new GridSpan();
tcPr.setGridSpan(gridSpan);
}
gridSpan.setVal(BigInteger.valueOf(Math.min(tcList.size() - 1, toCell) - fromCell + 1));
} else {
tr.getContent().remove(cellIndex);
}
}
}
/**
* @Description: 跨列合并
* @author zhouweiwei
*
*/
public static void mergeCellsHorizontal(Tbl tbl, int row, int fromCell, int toCell) {
if (row < 0 || fromCell < 0 || toCell < 0) {
return;
}
List<Tr> trList = getTblAllTr(tbl);
if (row > trList.size()) {
return;
}
Tr tr = trList.get(row);
List<Tc> tcList = getTrAllCell(tr);
for (int cellIndex = fromCell, len = Math.min(tcList.size() - 1, toCell); cellIndex <= len; cellIndex++) {
Tc tc = tcList.get(cellIndex);
TcPr tcPr = getTcPr(tc);
HMerge hMerge = tcPr.getHMerge();
if (hMerge == null) {
hMerge = new HMerge();
tcPr.setHMerge(hMerge);
}
if (cellIndex == fromCell) {
hMerge.setVal("restart");
} else {
hMerge.setVal("continue");
}
}
}
/**
* @Description: 添加段落内容
* @author zhouweiwei
*/
public static void appendParaRContent(P p, RPr runProperties, String content) {
if (content != null) {
R run = new R();
p.getContent().add(run);
String[] contentArr = content.split("\n");
Text text = new Text();
text.setSpace("preserve");
text.setValue(contentArr[0]);
run.setRPr(runProperties);
run.getContent().add(text);
for (int i = 1, len = contentArr.length; i < len; i++) {
Br br = new Br();
run.getContent().add(br);// 换行
text = new Text();
text.setSpace("preserve");
text.setValue(contentArr[i]);
run.setRPr(runProperties);
run.getContent().add(text);
}
}
}
/**
* 设置表格之间的间隙
*
* @param factory
* 工厂对象
* @param t
* 页面内容对象
* @param jcEnumeration
* 位置设置
* @param before
* 距离段前的距离或者与之前表格的距离
* @param after
* 距离段后的距离或者与之后表格的距离
* @author zhouweiwei
*/
public static void setTableSpace(ObjectFactory factory, MainDocumentPart t, JcEnumeration jcEnumeration,
String before, String after) {
P para = new P();
RPr contentRpr = getRPr(factory, "宋体", "000000", "18", STHint.EAST_ASIA, false, false, false, false);
setParagraphSpacing(factory, para, jcEnumeration, true, before, after, null, null, true, "240",
STLineSpacingRule.AUTO);
R rp = new R();
Text txtp = new Text();
txtp.setValue("");
rp.getContent().add(txtp);
rp.setRPr(contentRpr);
para.getContent().add(rp);
t.addObject(para);
}
/**
* 创建页脚页数部分
*
* @param wordprocessingMLPackage
* @param t
* @param factory
* @param isUnderLine
* @param underLineSz
* @param jcEnumeration
* @return
* @throws Exception
* @author zhouweiwei
*/
public static Relationship createFooterPageNumPart(WordprocessingMLPackage wordprocessingMLPackage,
MainDocumentPart t, ObjectFactory factory, boolean isUnderLine, String underLineSz,
JcEnumeration jcEnumeration) throws Exception {
FooterPart footerPart = new FooterPart();
footerPart.setPackage(wordprocessingMLPackage);
footerPart.setJaxbElement(createFooterWithPageNr(wordprocessingMLPackage, factory, isUnderLine, underLineSz,
jcEnumeration));
return t.addTargetPart(footerPart);
}
public static Ftr createFooterWithPageNr(WordprocessingMLPackage wordprocessingMLPackage, ObjectFactory factory,
boolean isUnderLine, String underLineSz, JcEnumeration jcEnumeration) throws Exception {
Ftr ftr = factory.createFtr();
P paragraph = factory.createP();
RPr fontRPr = getRPr(factory, "宋体", "000000", "20", STHint.EAST_ASIA, false, false, false, false);
R run = factory.createR();
run.setRPr(fontRPr);
paragraph.getContent().add(run);
addPageTextField(
factory,
paragraph,
"SE-01-FM10,版本号:2 奥的斯电梯(中国)投资有限公司 第一联客户存档 第二联OTIS存档",
fontRPr);
/*
* addPageTextField(factory, paragraph, "第",fontRPr);
* addFieldBegin(factory, paragraph,fontRPr);
* addPageNumberField(factory, paragraph,fontRPr); addFieldEnd(factory,
* paragraph,fontRPr); addPageTextField(factory, paragraph,
* "页",fontRPr);
* addPageTextField(factory, paragraph, " 总共",fontRPr);
* addFieldBegin(factory, paragraph,fontRPr);
* addTotalPageNumberField(factory, paragraph,fontRPr);
* addFieldEnd(factory, paragraph,fontRPr); addPageTextField(factory,
* paragraph, "页",fontRPr);
*/
setParagraphSpacing(factory, paragraph, jcEnumeration, true, "100", "0", null, null, true, "240",
STLineSpacingRule.AUTO);
PPr pPr = paragraph.getPPr();
if (pPr == null) {
pPr = factory.createPPr();
}
Jc jc = pPr.getJc();
if (jc == null) {
jc = new Jc();
}
jc.setVal(jcEnumeration);
pPr.setJc(jc);
if (isUnderLine) {
PBdr pBdr = pPr.getPBdr();
if (pBdr == null) {
pBdr = factory.createPPrBasePBdr();
}
CTBorder value = new CTBorder();
value.setVal(STBorder.SINGLE);
value.setColor("000000");
value.setSpace(new BigInteger("0"));
value.setSz(new BigInteger(underLineSz));
pBdr.setBetween(value);
pPr.setPBdr(pBdr);
paragraph.setPPr(pPr);
}
ftr.getContent().add(paragraph);
if (isUnderLine) {
ftr.getContent().add(
createHeaderAndFooterBlankP(wordprocessingMLPackage, factory, underLineSz, jcEnumeration));
}
return ftr;
}
/**
* 添加页脚内容开始
*
* @param factory
* 工厂对象
* @param paragraph
* 段落对象
* @author zhouweiwei
*/
public static void addFieldBegin(ObjectFactory factory, P paragraph, RPr rPr) {
R run = factory.createR();
FldChar fldchar = factory.createFldChar();
fldchar.setFldCharType(STFldCharType.BEGIN);
run.setRPr(rPr);
run.getContent().add(fldchar);
paragraph.getContent().add(run);
}
/**
* 添加页脚内容结束
*
* @param factory工厂对象
* @param paragraph
* 段落对象
* @author zhouweiwei
*/
public static void addFieldEnd(ObjectFactory factory, P paragraph, RPr rPr) {
FldChar fldcharend = factory.createFldChar();
fldcharend.setFldCharType(STFldCharType.END);
R run3 = factory.createR();
run3.setRPr(rPr);
run3.getContent().add(fldcharend);
paragraph.getContent().add(run3);
}
/**
* 添加页面页数
*
* @param factory
* 工厂对象
* @param paragraph
* 段落对象
*
* @author zhouweiwei
*/
public static void addPageNumberField(ObjectFactory factory, P paragraph, RPr rPr) {
R run = factory.createR();
Text txt = new Text();
txt.setSpace("preserve");
txt.setValue("PAGE \\* MERGEFORMAT ");
run.setRPr(rPr);
run.getContent().add(factory.createRInstrText(txt));
paragraph.getContent().add(run);
}
/**
* 总页数
*
* @param factory
* 工厂对象
* @param paragraph
* 段落对象
* @author zhouweiwei
*/
public static void addTotalPageNumberField(ObjectFactory factory, P paragraph, RPr rPr) {
R run = factory.createR();
Text txt = new Text();
txt.setSpace("preserve");
txt.setValue("NUMPAGES \\* MERGEFORMAT ");
run.setRPr(rPr);
run.getContent().add(factory.createRInstrText(txt));
paragraph.getContent().add(run);
}
/**
* 添加页数的数字的内容
*
* @param factory
* 工厂对象
* @param paragraph
* 段落对象
* @param value
* 页数值
* @author zhouweiwei
*
*/
private static void addPageTextField(ObjectFactory factory, P paragraph, String value, RPr rPr) {
R run = factory.createR();
Text txt = new Text();
txt.setSpace("preserve");
txt.setValue(value);
run.setRPr(rPr);
run.getContent().add(txt);
paragraph.getContent().add(run);
}
/**
* 创建 页眉或者页脚 段落对象
*
* @param wordMLPackage
* 文档对象
* @param factory
* 工厂对象
* @param underLineSz
* 设置段落边框宽度
* @param jcEnumeration
* 段落显示位置
* @return 返回段落对象 P
* @throws Exception
* @author zhouweiwei
*/
public static P createHeaderAndFooterBlankP(WordprocessingMLPackage wordMLPackage, ObjectFactory factory,
String underLineSz, JcEnumeration jcEnumeration) throws Exception {
P p = factory.createP();
R run = factory.createR();
p.getContent().add(run);
PPr pPr = p.getPPr();
if (pPr == null) {
pPr = factory.createPPr();
}
Jc jc = pPr.getJc();
if (jc == null) {
jc = new Jc();
}
jc.setVal(jcEnumeration);
pPr.setJc(jc);
PBdr pBdr = pPr.getPBdr();
if (pBdr == null) {
pBdr = factory.createPPrBasePBdr();
}
CTBorder value = new CTBorder();
value.setVal(STBorder.SINGLE);
value.setColor("000000");
value.setSpace(new BigInteger("0"));
value.setSz(new BigInteger(underLineSz));
pBdr.setBetween(value);
pPr.setPBdr(pBdr);
p.setPPr(pPr);
setParagraphSpacing(factory, p, jcEnumeration, true, "0", "0", null, null, true, "240", STLineSpacingRule.AUTO);
return p;
}
/**
* 创建页脚
*
* @param wordprocessingMLPackage
* word文档对象
* @param t
* 页面内容对象
* @param factory
* 工厂对象
* @param relationship
* @throws InvalidFormatException
* @author zhouweiwei
*/
public static void createFooterReference(WordprocessingMLPackage wordprocessingMLPackage, MainDocumentPart t,
ObjectFactory factory, Relationship relationship) throws InvalidFormatException {
List<SectionWrapper> sections = wordprocessingMLPackage.getDocumentModel().getSections();
SectPr sectPr = sections.get(sections.size() - 1).getSectPr();
// There is always a section wrapper, but it might not contain a sectPr
if (sectPr == null) {
sectPr = factory.createSectPr();
t.addObject(sectPr);
sections.get(sections.size() - 1).setSectPr(sectPr);
}
FooterReference footerReference = factory.createFooterReference();
footerReference.setId(relationship.getId());
footerReference.setType(HdrFtrRef.DEFAULT);
sectPr.getEGHdrFtrReferences().add(footerReference);
}
/**
* 将word转化为pdf
*
* @param inPath
* 要转换的word文件路径
* @param OutPath
* 转化为pdf后的文件路径
*/
public static void wordToPdf(String inPath, String OutPath) {
OutputStream os = null;
try {
WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(new File(inPath));
// Mapper fontMapper = new IdentityPlusMapper();
Mapper fontMapper = new BestMatchingMapper();
// fontMapper.getFontMappings().put("华文行楷",
// PhysicalFonts.getPhysicalFonts().get("STXingkai"));
// fontMapper.getFontMappings().put("华文仿宋",
// PhysicalFonts.getPhysicalFonts().get("STFangsong"));
// fontMapper.getFontMappings().put("隶书",
// PhysicalFonts.getPhysicalFonts().get("LiSu"));
// uu.getMsFontsFilenames().put("黑体", value)
fontMapper.getFontMappings().put("黑体", PhysicalFonts.getPhysicalFonts().get("SimHei"));
fontMapper.getFontMappings().put("宋体", PhysicalFonts.getPhysicalFonts().get("SimSun"));
fontMapper.getFontMappings().put("MS Gothic", PhysicalFonts.getPhysicalFonts().get("MS Gothic"));
mlPackage.setFontMapper(fontMapper);
os = new java.io.FileOutputStream(OutPath);
FOSettings foSettings = Docx4J.createFOSettings();
foSettings.setWmlPackage(mlPackage);
Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
// Docx4J.toFO(settings, outputStream, flags);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
IOUtils.closeQuietly(os);
}
}
/**
* 将字体设置为黑体 四号 用于文档标题
*
* @param factory
* 工厂对象
* @return 字体样式设置 Rpr
* @author zhouweiwei
*/
public static RPr getTitleFontBoldType(ObjectFactory factory) {
// 黑体四号字体
RPr titleRPr = getRPr(factory, "黑体", "000000", "28", STHint.EAST_ASIA, false, false, false, false);
return titleRPr;
}
/**
* 将字体设置为黑体 五号 用于文档项目项标题
*
* @param factory
* 工厂对象
* @return 字体样式设置 Rpr
* @author zhouweiwei
*/
public static RPr getSeconedTitleFontBoldType(ObjectFactory factory) {
// 黑体五号字体
RPr seconedTitleRPr = getRPr(factory, "黑体", "000000", "21", STHint.EAST_ASIA, false, false, false, false);
return seconedTitleRPr;
}
/**
* 黑体 小五 多用于每一列表格头部标题
*
* @param factory
* 工厂对象 br
* @return 字体样式RPr
* @author zhouweiwei
*/
public static RPr getContentFontBoldType(ObjectFactory factory) {
// 黑体五号字体
RPr rPr = getRPr(factory, "黑体", "000000", "18", STHint.EAST_ASIA, false, false, false, false);
return rPr;
}
/**
* 宋体小五字体不加粗
*
* @param factory
* 工厂对象
* @return 字体样式对象 Rpr
* @author zhouweiwei
*
*/
public static RPr getContentFontSong(ObjectFactory factory) {
// 宋体小五不加粗
RPr contentRPr = getRPr(factory, "宋体", "000000", "18", STHint.EAST_ASIA, false, false, false, false);
return contentRPr;
}
/**
* 宋体小五加粗
*
* @param factory
* 工厂对象
* @return 字体样式对象 Rpr
* @author zhouweiwei
*/
public static RPr getContentFontSongBold(ObjectFactory factory) {
// 宋体小五加粗
RPr contentRPr = getRPr(factory, "宋体", "000000", "18", STHint.EAST_ASIA, true, false, false, false);
return contentRPr;
}
/**
* 宋体8号字体不加粗 用于JHA 表格内容信息
*
* @param factory
* 工厂对象
* @return 字体样式对象 Rpr
* @author zhouweiwei
*/
public static RPr getContentFontSongEigth(ObjectFactory factory) {
// 宋体8号字体
RPr rPr = getRPr(factory, "宋体", "000000", "16", STHint.EAST_ASIA, false, false, false, false);// 宋体
// 8号字体不加粗
return rPr;
}
/**
* 宋体8号字体加粗 用于JHA 表格列的头信息 和行的头的信息
*
* @param factory
* 工厂对象
* @return 字体样式对象 Rpr
* @author zhouweiwei
*/
public static RPr getContentFontSongBoldEigth(ObjectFactory factory) {
// 宋体8号字体加粗
RPr rPr = getRPr(factory, "宋体", "000000", "16", STHint.EAST_ASIA, true, false, false, false);
return rPr;
}
/**
* 设置处理特殊字符的样式 (防止在word转化为pdf时出现乱码 复选框)
*
* @param factory
* 工厂对象
* @return 返回字体样式设置对象
* @author zhouweiwei
*/
public static RPr getSpecialCharacterFont(ObjectFactory factory) {
// 设置特殊字符
RPr rPr = getRPr(factory, "MS Gothic", "000000", "18", STHint.EAST_ASIA, true, false, false, false);
return rPr;
}
/**
* 根据书签获取表格对象 并且不清空对象包含的单元格信息
*
* @param factory 对象工厂
* @param rt 书签游标
* @param marker 目标书签名
* @return 表格对象
* @author zhouweiwei
*/
public static Tbl getTbl(ObjectFactory factory, RangeFinder rt, String marker) {
Tbl tbl = factory.createTbl();
for (CTBookmark bm : rt.getStarts()) {
// 这儿可以对单个书签进行操作,也可以用一个map对所有的书签进行处理
if (bm.getName().equals(marker)) {
// 获取该书签的父级段落
P p = (P) (bm.getParent());
Tc tc = (Tc) (p.getParent());
Tr tr = (Tr) (tc.getParent());
Tbl table = (Tbl) (tr.getParent());
tbl = table;
}
}
return tbl;
}
/**
* 根据书签获取表格对象 并且清空对象包含的单元格信息
*
* @param factory 对象工厂
* @param rt 书签游标
* @param marker 目标书签名
* @return 表格对象
* @author zhouweiwei
*/
public static Tbl getTblNotContent(ObjectFactory factory, RangeFinder rt, String marker) {
Tbl tbl = factory.createTbl();
for (CTBookmark bm : rt.getStarts()) {
// 这儿可以对单个书签进行操作,也可以用一个map对所有的书签进行处理
if (bm.getName().equals(marker)) {
// 获取该书签的父级段落
P p = (P) (bm.getParent());
Tc tc = (Tc) (p.getParent());
Tr tr = (Tr) (tc.getParent());
Tbl table = (Tbl) (tr.getParent());
if (null != table.getContent() && table.getContent().size() > 0) {
table.getContent().clear();
}
tbl = table;
return tbl;
} else {
tbl = null;
}
}
return tbl;
}
/**
* 获取文档中单元格对象
*
* @param factory 对象工厂
* @param rt 书签游标
* @param marker 书签
* @return 单元格对象
*/
public static Tc getTc(ObjectFactory factory, RangeFinder rt, String marker) {
Tc tc = factory.createTc();
for (CTBookmark bm : rt.getStarts()) {
// 这儿可以对单个书签进行操作,也可以用一个map对所有的书签进行处理
if (bm.getName().equals(marker)) {
// 获取该书签的父级段落
P p = (P) (bm.getParent());
Tc cell = (Tc) (p.getParent());
/*
* if(null!=tc .getContent()&& tc .getContent().size()>0 ){
* tc .getContent().clear();
* }
*/
tc = cell;
return tc;
} else {
tc = null;
}
}
return tc;
}
/**
* 获取 段落对象
*
* @param factory 工厂对象
* @param rt 书签游标
* @param marker 书签标记
* @return 返回段落对象
* @author zhouweiwei
*/
public static P getP(ObjectFactory factory, RangeFinder rt, String marker) {
P p = factory.createP();
for (CTBookmark bm : rt.getStarts()) {
// 这儿可以对单个书签进行操作,也可以用一个map对所有的书签进行处理
if (bm.getName().equals(marker)) {
// 获取该书签的父级段落
p = (P) (bm.getParent());
return p;
} else {
p = null;
}
}
return p;
}
/**
* 创建word文档标题. <br/>
*
* @author zhouweiwei
* @param t 文档内容对象
* @param factory 工厂对象
* @author zhouweiwei
*/
public static void createWordTempleTitle(MainDocumentPart t, ObjectFactory factory) {
P paragraph = factory.createP();
Text txt = factory.createText();
R run = factory.createR();
setParagraphSpacing(factory, paragraph, JcEnumeration.CENTER, true, "0", "20", null, null, true, "300",
STLineSpacingRule.AUTO);
txt.setValue("${wordTitle}");
run = factory.createR();
run.getContent().add(txt);
run.setRPr(getTitleFontBoldType(factory));
paragraph.getContent().add(run);
t.addObject(paragraph);
}
/**
* 创建内容标题. <br/>
*
* @author zhouweiwei
* @param t 文档内容对象
* @param factory 工厂对象
* @param wordContentTitle 标题字符传对象
* @author zhouweiwei
*/
public static void createWordTempleContentTitle(MainDocumentPart t, ObjectFactory factory, String wordContentTitle) {
P paragraph = factory.createP();
setParagraphSpacing(factory, paragraph, JcEnumeration.LEFT, true, "0", "0", null, null, true, "240",
STLineSpacingRule.AUTO);
Text txt = factory.createText();
txt.setValue(wordContentTitle);
// txt.setSpace("preserve");
R run = factory.createR();
run.getContent().add(txt);
run.setRPr(getSeconedTitleFontBoldType(factory));
paragraph.getContent().add(run);
t.addObject(paragraph);
}
/**
* 创建文档logo <br/>
*
* @author zhouweiwei
* @param wordMLPackage 文档对象
* @param t 文档内容对象
* @param factory 工厂对象
* @param patch 图片路径
* @throws IOException
* @throws Exception
* @author zhouweiwei
*/
public static void createWordTempleLogoImage(WordprocessingMLPackage wordMLPackage, MainDocumentPart t,
ObjectFactory factory, String patch) throws IOException, Exception {
// 创建表格对象
Tbl table = factory.createTbl();
// 设置表格边框样式
addBorders(table, "0");
// 创建表格样式对象
TblPr tblPr = factory.createTblPr();
// 添加表格缩进
TblWidth tblW = factory.createTblWidth();
tblW.setW(new BigInteger("8629"));
tblW.setType(TblWidth.TYPE_DXA);
tblPr.setTblInd(tblW);
table.setTblPr(tblPr);
// 创建表格行对象
Tr tr = factory.createTr();
// 创建单元格对象
Tc tc = factory.createTc();
// 创建段落对象
P p = factory.createP();
File file = new File(patch);
InputStream is = new FileInputStream(file);
createImageParagraph(wordMLPackage, factory, p, "img_1", "", BufferUtil.getBytesFromInputStream(is),
JcEnumeration.LEFT);
tc.getContent().add(p);
tr.getContent().add(tc);
table.getContent().add(tr);
t.addObject(table);
}
/**
* 加载word模板数据
*
* @param wordTemplatePath word模板路径
* @return 返回word文档对象
* @throws FileNotFoundException
* @throws Docx4JException
* @author zhouweiwei
*/
public static WordprocessingMLPackage getWPackage(String wordTemplatePath) throws FileNotFoundException,
Docx4JException {
return WordprocessingMLPackage.load(new FileInputStream(wordTemplatePath));
}
/**
* 加载word模板流数据
*
* @param is 数据流
* @return 返回
* @throws FileNotFoundException
* @throws Docx4JException
*/
public static WordprocessingMLPackage getWPackage(InputStream is) throws FileNotFoundException, Docx4JException {
return WordprocessingMLPackage.load(is);
}
/**
* word文档转化为pdf对象流
*
* @param wPackage word文档对象
* @param wordTempPath word临时文档路径
* @return 返回pdf数据流
* @throws Exception
* @author zhouweiwei
*/
public static ByteArrayOutputStream getPdfByteArrayOutputStream(String wordTempPath) throws Exception {
// ByteArrayOutputStream pdfOut = new ByteArrayOutputStream();
// wPackage.save(pdfOut);
/*
* Mapper fontMapper = new BestMatchingMapper();
* fontMapper.getFontMappings().put("黑体", PhysicalFonts.getPhysicalFonts().get("SimHei"));
* fontMapper.getFontMappings().put("宋体", PhysicalFonts.getPhysicalFonts().get("SimSun"));
* fontMapper.getFontMappings().put("MS Gothic",
* PhysicalFonts.getPhysicalFonts().get("MS Gothic"));
* wPackage.setFontMapper(fontMapper);
* FOSettings foSettings = Docx4J.createFOSettings();
* foSettings.setWmlPackage(wPackage);
* //Docx4J.toPDF(wPackage, pdfOut);
* Docx4J.toFO(foSettings, pdfOut, Docx4J.FLAG_EXPORT_PREFER_XSL);
*/
InputStream in = new FileInputStream(new File(wordTempPath));
// 转换时间测试
/*
* long startpIx=System.currentTimeMillis();;
* IXWPFConverter<PdfOptions> po= PdfConverter.getInstance();
* System.err.println("Generate pdf with " + (System.currentTimeMillis() - startpcv) +
* "ms-------------------");
* long startpcv=System.currentTimeMillis();
* po.convert(document, pdfOut, options);
* System.err.println("Generate pdf with " + (System.currentTimeMillis() - startpcv) +
* "ms-------------------");
*/
/*
* OutputStream out = new FileOutputStream(new File(
* "E:\\test.pdf"));
* PdfConverter.getInstance().convert(document, out, options);
*/
return getPdfByteArrayOutputStream(in);
}
public static ByteArrayOutputStream getPdfByteArrayOutputStream(InputStream in) throws Exception {
ByteArrayOutputStream pdfOut = new ByteArrayOutputStream();
// 从word文档流中获取doc文档内容对象
XWPFDocument document = new XWPFDocument(in);
// 设置PDF编码信息
PdfOptions options = null;
// 进行PDF流对象转化
PdfConverter.getInstance().convert(document, pdfOut, options);
return pdfOut;
}
}
word模板的读取并且 写入数据 (由于下面的实现是从实际库中获取的数据所以你可以参照下面的实现 拿过来直接使用可能你没有对应的数据和实现类对象 来实现你的程序)下面的实现仅供参考
CreateWordTemple
package cn.sh.cx.ce.maint.biz.pdf.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.docx4j.XmlUtils;
import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.finders.RangeFinder;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.CTVerticalJc;
import org.docx4j.wml.Document;
import org.docx4j.wml.Drawing;
import org.docx4j.wml.JcEnumeration;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import org.docx4j.wml.RPr;
import org.docx4j.wml.STBorder;
import org.docx4j.wml.STHint;
import org.docx4j.wml.STLineSpacingRule;
import org.docx4j.wml.STVerticalJc;
import org.docx4j.wml.Tbl;
import ;
import Pr;
import org.docx4j.wml.Text;
import org.docx4j.wml.TextDirection;
import ;
import cn.sh.cx.ce.maint.biz.pdf.model.MaintItemInfo;
import cn.sh.cx.ce.maint.biz.pdf.model.MtrElevBaseInfoPdfData;
import cn.sh.cx.ce.maint.biz.pdf.model.MtrJhaItemDataOut;
import cn.sh.cx.ce.maint.biz.pdf.model.MtrJobEvaluationPdfData;
import cn.sh.cx.ce.maint.biz.pdf.model.MtrMaintFixOut;
import cn.sh.cx.ce.maint.biz.pdf.model.MtrMaintItemPdfData;
import cn.sh.cx.ce.maint.biz.pdf.utils.CreateWordUtils;
/**
* 类 名: CreateWordTemple <br/>
* 功能描述: 创建报文模板. <br/>
*
* @author zhouweiwei
* @version 1.0
*/
public class CreateWordTemple {
// 1:机房(扶梯上机舱);2:轿顶和井道(扶梯倾斜段);3:坑底(扶梯下机舱);
private static String GENERATORROOM = "1";
private static String CARTOPWELLROAD = "2";
private static String BOTTOM = "3";
// 1:危险内容;2:FPA项目;3:控制方法
private static String DANGEROUSITEMS = "1";
private static String FPAITEMS = "2";
private static String CONTROLMETHOD = "3";
// JHA 为“其他”的 code包含的字符串
private static String OTHER = "_99";
// jHA设置内容=====================================================================================================================
/**
* 创建JHA表格. <br/>
*
* @author zhouweiwei
* @param wordMLPackage 文档对象
* @param t 内容对象
* @param factory 工厂对象
* @throws Exception
*/
public void creatJHATable(WordprocessingMLPackage wordMLPackage, MainDocumentPart t, ObjectFactory factory,
RangeFinder rt, List<MtrJhaItemDataOut> mtrJhaPdfDatas) throws Exception {
Tbl table = CreateWordUtils.getTbl(factory, rt, "JHARFB");
// 取出表格内部线条
// CreateWordUtils.hideTableCellLineBorders(table, "2", "0");
double[] colWidthPercent = new double[] { 7, 15.5, 15.5, 15.5, 15.5, 15.5, 15.5 };// 百分比
CreateWordUtils.setTableGridCol(wordMLPackage, factory, table, 100, colWidthPercent);
if (null != mtrJhaPdfDatas && mtrJhaPdfDatas.size() > 0) {
RPr contentRpr = CreateWordUtils.getContentFontSongEigth(factory);
for (int i = 0; i < 4; i++) {
if (i == 0) {
setJHAItemContent(factory, contentRpr, mtrJhaPdfDatas, GENERATORROOM, "JHARDA", "JHARDB", "JHARFA",
"JHARFB", "JHARMA", "JHARMB", rt);
}
if (i == 1) {
setJHAItemContent(factory, contentRpr, mtrJhaPdfDatas, CARTOPWELLROAD, "JHATDA", "JHATDB",
"JHATFA", "JHATFB", "JHATMA", "JHATMB", rt);
}
if (i == 2) {
setJHAItemContent(factory, contentRpr, mtrJhaPdfDatas, BOTTOM, "JHABDA", "JHABDB", "JHABFA",
"JHABFB", "JHABMA", "JHABMB", rt);
}
}
}
}
/**
* 添加JHA内容项. <br/>
*
* @author zhouweiwei
* @param factory 工厂对象
* @param contentTitlePr 表格列头字体样式对象
* @param contentPr 表格内容字体样式
* @param jcEnumeration 内容显示位置
* @param hasBgColor 是否设置字体颜色
* @param backgroudColor 字体颜色
* @param firstTr 行对象
* @param secordTr 行对象
* @param list 内容集合
*/
public void jHATableOtherCellContent(ObjectFactory factory, RPr contentPr, Tc tc, MtrJhaItemDataOut jHAItem) {
P p = factory.createP();
CreateWordUtils.setParagraphSpacing(factory, p, JcEnumeration.LEFT, true, "0", "0", null, null, true, "240",
STLineSpacingRule.AUTO);
R run = factory.createR();
Text txt = factory.createText();
if (jHAItem.getItemCode().endsWith(OTHER)) {
// 含下划线的样式
RPr otherRpr = CreateWordUtils.getRPr(factory, "宋体", "000000", "16", STHint.EAST_ASIA, false, true, false,
false);
txt.setValue("其他:");
run.setRPr(contentPr);
run.getContent().add(txt);
p.getContent().add(run);
// 创建其他项内容信息
R runContent = factory.createR();
Text txtContent = factory.createText();
if (null != jHAItem.getItemOther()) {
runContent.setRPr(otherRpr);
txtContent.setValue(jHAItem.getItemOther());
}
else{
runContent.setRPr(contentPr);
txtContent.setValue("_____");
}
runContent.getContent().add(txtContent);
p.getContent().add(runContent);
} else {
if (jHAItem.getFlag() == 0) {
txt.setValue("□" + jHAItem.getItemName());
run.setRPr(contentPr);
run.getContent().add(txt);
p.getContent().add(run);
} else if (jHAItem.getFlag() == 1) {
txt.setValue("√" + jHAItem.getItemName());
run.setRPr(contentPr);
run.getContent().add(txt);
p.getContent().add(run);
} else {
txt.setValue("");
run.setRPr(contentPr);
run.getContent().add(txt);
p.getContent().add(run);
}
}
tc.getContent().add(p);
}
/**
* 设置JHA列的标题和行的标题
*
* @param factory 工厂对象
* @param coltitle 行的标题
* @param rpr 文本样式对象
* @param jcEnumeration
* @param tr
* @author zhouweiwei
*/
/*
* public void setJHAItemTitle(ObjectFactory factory, String coltitle, RPr rpr, JcEnumeration
* jcEnumeration, Tr tr) {
* // 第一列
* CreateWordUtils.createNormalCell(factory, tr, coltitle, rpr, jcEnumeration, false, null,
* true, "0");
* // 第二列
* CreateWordUtils.createNormalCell(factory, tr, "可能出现下列危险", rpr, jcEnumeration, false, null,
* true, "2");
* // 第三列
* CreateWordUtils.createNormalCell(factory, tr, "可能出现下列FPA项目", rpr, jcEnumeration, false, null,
* true, "2");
* // 第四列
* CreateWordUtils.createNormalCell(factory, tr, "采取的控制方法", rpr, jcEnumeration, false, null,
* true, "2");
* }
*/
/**
* 设置单元格初始化内容
*
* @param factory
* @param tc
* @author zhouweiwei
*/
public void setTcDefaultValue(ObjectFactory factory, Tc tc) {
P p = factory.createP();
CreateWordUtils.setParagraphSpacing(factory, p, JcEnumeration.LEFT, true, "0", "0", null, null, true, "240",
STLineSpacingRule.AUTO);
R run = factory.createR();
Text txt = factory.createText();
txt.setValue("");
run.getContent().add(txt);
p.getContent().add(run);
tc.getContent().add(p);
}
/**
* 给jHA内容框添加下边框
*
* @param factory
* @return 单元格对象
* @author zhouweiwei
*/
public Tc createJHAItemTc(ObjectFactory factory) {
Tc tc = factory.createTc();
// 给下边框设置虚线
CreateWordUtils.setTableCellBoder(factory, tc, STBorder.DOT_DOT_DASH);
setTcDefaultValue(factory, tc);
return tc;
}
/**
* 设置JHA内容向
*
* @param factory 工厂对象
* @param contentPr 文本样式
* @param jcEnumeration 文本显示位置
* @param table 表格
* @param mtrJhaPdfDatas
* @param workType 工作环境类型
*/
public void setJHAItemContent(ObjectFactory factory, RPr contentPr, List<MtrJhaItemDataOut> mtrJhaPdfDatas,
String workType, String dangeJHAA, String dangeJHAB, String fPAJHAA, String fPAJHAB, String methJHAA,
String methJHAB, RangeFinder rt) {
// 危险项单元格对象
Tc dangeItemTcA = CreateWordUtils.getTc(factory, rt, dangeJHAA);
Tc dangeItemTcB = CreateWordUtils.getTc(factory, rt, dangeJHAB);
// fpa项单元格对象
Tc fPAItemTcA = CreateWordUtils.getTc(factory, rt, fPAJHAA);
Tc fPAItemTcB = CreateWordUtils.getTc(factory, rt, fPAJHAB);
// 方法项单元格对象
Tc methItemTcA = CreateWordUtils.getTc(factory, rt, methJHAA);
Tc methItemTcB = CreateWordUtils.getTc(factory, rt, methJHAB);
boolean colFlg = false;
for (MtrJhaItemDataOut lst : mtrJhaPdfDatas) {
// 设置危险项
if (lst.getWorkAreaType().equals(workType) && lst.getItemType().equals(DANGEROUSITEMS)) {
// 判断将项目放到那一列
if (colFlg) {
jHATableOtherCellContent(factory, contentPr, dangeItemTcB, lst);
colFlg = false;
} else {
jHATableOtherCellContent(factory, contentPr, dangeItemTcA, lst);
colFlg = true;
}
}
// 设置FPA项
if (lst.getWorkAreaType().equals(workType) && lst.getItemType().equals(FPAITEMS)) {
// 判断将项目放到那一列
if (colFlg) {
jHATableOtherCellContent(factory, contentPr, fPAItemTcA, lst);
colFlg = false;
} else {
jHATableOtherCellContent(factory, contentPr, fPAItemTcB, lst);
colFlg = true;
}
}
// 设置方法
if (lst.getWorkAreaType().equals(workType) && lst.getItemType().equals(CONTROLMETHOD)) {
// 判断将项目放到那一列
if (colFlg) {
jHATableOtherCellContent(factory, contentPr, methItemTcA, lst);
colFlg = false;
} else {
jHATableOtherCellContent(factory, contentPr, methItemTcB, lst);
colFlg = true;
}
}
}
}
// ======================================================================================================================================
/**
* 保养项内容设置
*
* @param wordMLPackage
* @param t
* @param factory
* @throws Exception
*/
public void creatMaitItemTable(WordprocessingMLPackage wordMLPackage, MainDocumentPart t, ObjectFactory factory,
RangeFinder rt, List<MaintItemInfo> maintItemResult) throws Exception {
RPr contentRpr = CreateWordUtils.getContentFontSong(factory);
Tbl table = CreateWordUtils.getTbl(factory, rt, "maintItem");
CreateWordUtils.addBorders(table, "1");
double[] colWidthPercent = new double[] { 5, 12, 25, 8, 5, 12, 25, 8 };// 百分比
CreateWordUtils.setTableGridCol(wordMLPackage, factory, table, 100, colWidthPercent);
if (null != maintItemResult && maintItemResult.size() > 0) {
// 半年项集合
List<MaintItemInfo> halfMothItemLst = getMaintItemTypeLst(maintItemResult, (byte) 1);
// 季度项集合
List<MaintItemInfo> quarterItemLst = getMaintItemTypeLst(maintItemResult, (byte) 3);
// 半年项集合
List<MaintItemInfo> halfYearItemLst = getMaintItemTypeLst(maintItemResult, (byte) 4);
// 年度项集合
List<MaintItemInfo> yearItemLst = getMaintItemTypeLst(maintItemResult, (byte) 5);
// /设置item项行的数量内容
int itemSize = (maintItemResult.size()) / 2;
// 计算取余数
int itemInt = (maintItemResult.size()) % 2;
// 定义表格第一了内容(半月项多出的部分)
int fistItem = 0;
if (halfMothItemLst.size() > itemSize) {
if (itemInt == 0) {
fistItem = halfMothItemLst.size() - itemSize;
} else {
fistItem = halfMothItemLst.size() - (itemSize + 1);
itemSize = itemSize + 1;
}
}
// 半月项多出行的开始下标
int itemCount = halfMothItemLst.size() - fistItem;
// 季度项下标定义
int halfQuarter = 0;
// 半年项下标
int halfYear = 0;
// 年度项下标
int year = 0;
for (int i = 0; i < itemSize; i++) {
Tr itemContentRow = factory.createTr();
if (halfMothItemLst.size() > i) {
// 半月项未折行的部分
if (i > 0) {
setItemTitle(wordMLPackage, factory, null, contentRpr, itemContentRow, false, "");
} else {
setItemTitle(wordMLPackage, factory, halfMothItemLst.get(i), contentRpr, itemContentRow, false,
"");
}
setItemContent(factory, halfMothItemLst.get(i).getMaintItemCode(), contentRpr, itemContentRow);
setItemContent(factory, halfMothItemLst.get(i).getMaintItemName(), contentRpr, itemContentRow);
setItemResult(factory, contentRpr, itemContentRow, halfMothItemLst.get(i));
} else {
setItemContent(factory, null, contentRpr, itemContentRow);
setItemContent(factory, null, contentRpr, itemContentRow);
setItemContent(factory, null, contentRpr, itemContentRow);
setItemContent(factory, null, contentRpr, itemContentRow);
}
// 半月项折行的部分
if (itemCount < halfMothItemLst.size()) {
if (itemCount > halfMothItemLst.size() - fistItem) {
setItemTitle(wordMLPackage, factory, null, contentRpr, itemContentRow, false, "");
} else {
setItemTitle(wordMLPackage, factory, halfMothItemLst.get(itemCount), contentRpr,
itemContentRow, false, "");
}
// setItemTitle(wordMLPackage,factory, halfMothItemLst.get(itemCount),
// contentRpr,
// itemContentRow, false, "");
setItemContent(factory, halfMothItemLst.get(itemCount).getMaintItemCode(), contentRpr,
itemContentRow);
setItemContent(factory, halfMothItemLst.get(itemCount).getMaintItemName(), contentRpr,
itemContentRow);
setItemResult(factory, contentRpr, itemContentRow, halfMothItemLst.get(itemCount));
itemCount++;
} else if (halfQuarter < quarterItemLst.size()) {// 季度项
if (halfQuarter > 0) {
setItemTitle(wordMLPackage, factory, null, contentRpr, itemContentRow, false, "");
} else {
setItemTitle(wordMLPackage, factory, quarterItemLst.get(halfQuarter), contentRpr,
itemContentRow, false, "");
}
setItemContent(factory, quarterItemLst.get(halfQuarter).getMaintItemCode(), contentRpr,
itemContentRow);
setItemContent(factory, quarterItemLst.get(halfQuarter).getMaintItemName(), contentRpr,
itemContentRow);
setItemResult(factory, contentRpr, itemContentRow, quarterItemLst.get(halfQuarter));
halfQuarter++;
} else if (halfYear < halfYearItemLst.size()) {// 半年项
if (halfYear > 0) {
setItemTitle(wordMLPackage, factory, null, contentRpr, itemContentRow, false, "");
} else {
setItemTitle(wordMLPackage, factory, halfYearItemLst.get(halfYear), contentRpr, itemContentRow,
false, "");
}
setItemContent(factory, halfYearItemLst.get(halfYear).getMaintItemCode(), contentRpr,
itemContentRow);
setItemContent(factory, halfYearItemLst.get(halfYear).getMaintItemName(), contentRpr,
itemContentRow);
setItemResult(factory, contentRpr, itemContentRow, halfYearItemLst.get(halfYear));
halfYear++;
} else if (year < yearItemLst.size()) {// 一年项
setItemTitle(wordMLPackage, factory, yearItemLst.get(year), contentRpr, itemContentRow, true, "2");
setItemContentByObj(factory, yearItemLst.get(year), contentRpr, itemContentRow);
setItemResult(factory, contentRpr, itemContentRow, yearItemLst.get(year));
year++;
} else {
setItemContent(factory, null, contentRpr, itemContentRow);
setItemContent(factory, null, contentRpr, itemContentRow);
setItemContent(factory, null, contentRpr, itemContentRow);
setItemContent(factory, null, contentRpr, itemContentRow);
}
table.getContent().add(itemContentRow);
}
// 前一半半年项列标题合并行
CreateWordUtils.mergeCellsVertically(table, 0, 1, itemSize);
if ((halfMothItemLst.size() - fistItem) == halfMothItemLst.size()) {
CreateWordUtils.mergeCellsVertically(table, 4, 1, quarterItemLst.size());
// 半年项标题合并
CreateWordUtils.mergeCellsVertically(table, 4, quarterItemLst.size() + 1, quarterItemLst.size()
+ halfYearItemLst.size());
} else {
// 后部分半月项标题合并
CreateWordUtils.mergeCellsVertically(table, 4, 1, halfMothItemLst.size() - itemSize);
// 季度项标题合并
CreateWordUtils.mergeCellsVertically(table, 4, halfMothItemLst.size() - itemSize + 1,
(halfMothItemLst.size() - itemSize) + quarterItemLst.size());
// 半年项标题合并
CreateWordUtils.mergeCellsVertically(table, 4,
(halfMothItemLst.size() - itemSize) + quarterItemLst.size() + 1,
(halfMothItemLst.size() - itemSize) + quarterItemLst.size() + halfYearItemLst.size());
}
}
}
// 保养项设置内容==============================================================================================================
/**
* 设置保养项内容的方法
*
* @param factory 对象工厂
* @param content 保养项内容
* @param contentRpr 保养项样式
* @param itemContentRow 行对象
* @author zhouweiwei
*/
public void setItemContent(ObjectFactory factory, String content, RPr contentRpr, Tr itemContentRow) {
if (content == null) {
CreateWordUtils.addTableCell(factory, itemContentRow, "", contentRpr, JcEnumeration.LEFT, false, null);
} else {
CreateWordUtils.addTableCell(factory, itemContentRow, content, contentRpr, JcEnumeration.LEFT, false, null);
}
}
/**
* 根据保养项对象信息设置保养项内容方法
* @param factory 对象工厂
* @param obj 保养项对象
* @param contentRpr 样式对象
* @param itemContentRow 表格行对象
*/
public void setItemContentByObj(ObjectFactory factory, MaintItemInfo obj, RPr contentRpr, Tr itemContentRow) {
if (obj == null || obj.getMaintItemName()==null) {
CreateWordUtils.addTableCell(factory, itemContentRow, "", contentRpr, JcEnumeration.LEFT, false, null);
} else {
if(obj.getYearlyFlg()==0){
CreateWordUtils.addTableCell(factory, itemContentRow, obj.getMaintItemName()+"\r\n(建议在年度定期自检时进行)", contentRpr, JcEnumeration.LEFT, false, null);
}
if(obj.getYearlyFlg()==1){
CreateWordUtils.addTableCell(factory, itemContentRow, obj.getMaintItemName(), contentRpr, JcEnumeration.LEFT, false, null);
}
if(obj.getYearlyFlg()==2){
CreateWordUtils.addTableCell(factory, itemContentRow, obj.getMaintItemName(), contentRpr, JcEnumeration.LEFT, false, null);
}
if(obj.getYearlyFlg()==3){
CreateWordUtils.addTableCell(factory, itemContentRow, obj.getMaintItemName(), contentRpr, JcEnumeration.LEFT, false, null);
}
}
}
/**
* 设置保养项类别的标题
*
* @param factory 对象工厂
* @param maintItemCycle 维保项周期 1:半月;3:季度;4:半年;5:年度'
* @param contentRpr 字体样式设置
* @param itemContentRow 行对象
* @param isItemTitle 判断是否要合并列的项
* @param gridSpanSize 合并列的列数
* @param isGridSpan 是否合并列 true是 false 否
* @author zhouweiwei
*/
public void setItemTitle(WordprocessingMLPackage wordPackage, ObjectFactory factory, MaintItemInfo maintItem,
RPr contentRpr, Tr itemContentRow, boolean isGridSpan, String gridSpanSize) {
Tc tableCell = factory.createTc();
P p = factory.createP();
CreateWordUtils.setParagraphSpacing(factory, p, JcEnumeration.LEFT, true, "0", "0", null, null, true, "240",
STLineSpacingRule.AUTO);
Text t = factory.createText();
TcPr tcPr = tableCell.getTcPr();
if (tcPr == null) {
tcPr = factory.createTcPr();
}
// t.setValue(content);
if (null != maintItem) {
if (maintItem.getMaintItemCycle() == 1) {
t.setValue("半月项");
TextDirection textDire = CreateWordUtils.setDocTextDirection(wordPackage, "tbRlV");
tcPr.setTextDirection(textDire);
CTVerticalJc ctv = new CTVerticalJc();
ctv.setVal(STVerticalJc.CENTER);
tcPr.setVAlign(ctv);
} else if (maintItem.getMaintItemCycle() == 3) {
t.setValue("季度项");
TextDirection textDire = CreateWordUtils.setDocTextDirection(wordPackage, "tbRlV");
tcPr.setTextDirection(textDire);
CTVerticalJc ctv = new CTVerticalJc();
ctv.setVal(STVerticalJc.CENTER);
tcPr.setVAlign(ctv);
} else if (maintItem.getMaintItemCycle() == 4) {
t.setValue("半年项");
TextDirection textDire = CreateWordUtils.setDocTextDirection(wordPackage, "tbRlV");
tcPr.setTextDirection(textDire);
CTVerticalJc ctv = new CTVerticalJc();
ctv.setVal(STVerticalJc.CENTER);
tcPr.setVAlign(ctv);
} else if (maintItem.getMaintItemCycle() == 5 && isGridSpan) {
t.setValue(maintItem.getMaintItemCode() + "\r\n(每年一次)");
}
else {
t.setValue("");
}
} else {
t.setValue("");
TextDirection textDire = CreateWordUtils.setDocTextDirection(wordPackage, "tbRlV");
tcPr.setTextDirection(textDire);
CTVerticalJc ctv = new CTVerticalJc();
ctv.setVal(STVerticalJc.CENTER);
tcPr.setVAlign(ctv);
}
R run = factory.createR();
// 设置表格内容字体样式
run.setRPr(contentRpr);
// 设置内容垂直方向位置
CreateWordUtils.setCellContentHPosition(factory, tcPr, STVerticalJc.CENTER);
if (isGridSpan) {
CreateWordUtils.setCellMerge(tcPr, factory, gridSpanSize);
}
run.getContent().add(t);
p.getContent().add(run);
tableCell.getContent().add(p);
tableCell.setTcPr(tcPr);
itemContentRow.getContent().add(tableCell);
}
/**
* 设置保养项结果信息
*
* @param factory 工厂对象
* @param contentRpr 内容字体对象
* @param itemContentRow 行对象
* @param resultState 保养项结果
* @author zhouweiwei
*
*/
public void setItemResult(ObjectFactory factory, RPr contentRpr, Tr itemContentRow, MaintItemInfo in) {
if (null == in.getState()) {
CreateWordUtils.createNormalCell(factory, itemContentRow, "", contentRpr, JcEnumeration.CENTER, false,
null, false, null);
} else if (in.getState() == 0) {
CreateWordUtils.createNormalCell(factory, itemContentRow, "√", contentRpr, JcEnumeration.CENTER, false,
null, false, null);
} else if (in.getState() == 1) {
CreateWordUtils.createNormalCell(factory, itemContentRow, "×", contentRpr, JcEnumeration.CENTER, false,
null, false, null);
} else if (in.getState() == 2) {
CreateWordUtils.createNormalCell(factory, itemContentRow, "○", contentRpr, JcEnumeration.CENTER, false,
null, false, null);
} else if (in.getState() == 3) {
CreateWordUtils.createNormalCell(factory, itemContentRow, "/", contentRpr, JcEnumeration.CENTER, false,
null, false, null);
} else if (in.getState() == -1) {
CreateWordUtils.createNormalCell(factory, itemContentRow, "", contentRpr, JcEnumeration.CENTER, false,
null, false, null);
} else {
CreateWordUtils.createNormalCell(factory, itemContentRow, "", contentRpr, JcEnumeration.CENTER, false,
null, false, null);
}
}
/**
* 根据保养项的类别获取,对数据进行封装
*
* @param maintItemLst 保养项请求集合内容
* @param maintType 保养项类别 '维保项周期 1:半月;3:季度;4:半年;5:年度'
* @return 同一类的保养项
* @author zhouweiwei
*
*/
public List<MaintItemInfo> getMaintItemTypeLst(List<MaintItemInfo> maintItemLst, Byte maintType) {
List<MaintItemInfo> out = new ArrayList<MaintItemInfo>();
for (MaintItemInfo item : maintItemLst) {
if (item.getMaintItemCycle() == maintType) {
out.add(item);
}
}
return out;
}
// end======================================================================================================================
/**
* 创建保养项详情信息
*
* @param wordMLPackage 文档对象
* @param factory 对象工厂
* @param t 文档内容对象
* @param rt 书签游标对象
* @throws Exception
* @author zhouweiwei
*/
public void creatMaintItemdetails(WordprocessingMLPackage wordMLPackage, ObjectFactory factory, MainDocumentPart t,
RangeFinder rt, List<MtrMaintItemPdfData> maintItems) throws Exception {
// 创建表格对象
Tbl table = CreateWordUtils.getTbl(factory, rt, "itemDetail");
CreateWordUtils.addBorders(table, "2");
double[] widthPercent = new double[] { 10, 45, 45 };
CreateWordUtils.setTableGridCol(wordMLPackage, factory, table, 100, widthPercent);
// 创建文本样式显示
RPr contentRpr = CreateWordUtils.getContentFontSong(factory);
if (null != maintItems) {
for (MtrMaintItemPdfData maintItem : maintItems) {
// 创建行对象
Tr tr = factory.createTr();
CreateWordUtils.createNormalCell(factory, tr, maintItem.getMaintItemCode(), contentRpr,
JcEnumeration.LEFT, false, null, false, null);
CreateWordUtils.createNormalCell(factory, tr, maintItem.getMaintItemName(), contentRpr,
JcEnumeration.LEFT, false, null, false, null);
CreateWordUtils.createNormalCell(factory, tr, maintItem.getRequirement(), contentRpr,
JcEnumeration.LEFT, false, null, false, null);
table.getContent().add(tr);
}
}
}
/**
* 设置文档文本信息替换
*
* @param wPackage 文档对象
* @param mainDocumentPart 文档内容对象
* @param factory 对象工厂
* @param wmlDoc 文档word对象
* @param mtrJobEvaluationPdfData
* @throws Exception
* @author zhouweiwei
*/
public void setDataInfo(WordprocessingMLPackage wPackage, MainDocumentPart mainDocumentPart, ObjectFactory factory,
Document wmlDoc, MtrJobEvaluationPdfData mtrJobEvaluationPdfData, RangeFinder rt,
MtrElevBaseInfoPdfData baseInfo, MtrMaintFixOut mtrMaintFixResult) throws Exception {
// 客户签名
if (null != mtrJobEvaluationPdfData && null != mtrJobEvaluationPdfData.getSign()) {
setCustSign(factory, wPackage, rt, mtrJobEvaluationPdfData.getSign());
}
// 将word内容部分转化为String
String xml = XmlUtils.marshaltoString(wmlDoc, true, true);
HashMap<String, String> map = new HashMap<String, String>();
// 设置工作满意度
SetSatisfaction(map, mtrJobEvaluationPdfData);
// 客户姓名
if (null != mtrJobEvaluationPdfData && null != mtrJobEvaluationPdfData.getCustomerName()) {
map.put("custName", mtrJobEvaluationPdfData.getCustomerName());
} else {
map.put("custName", "");
}
// 签字日期
if (null != mtrJobEvaluationPdfData && null != mtrJobEvaluationPdfData.getSignTime()) {
map.put("signTime", StringUtils.substring(mtrJobEvaluationPdfData.getSignTime(), 0, 10));
} else {
map.put("signTime", "");
}
// 技师名
if (null != mtrJobEvaluationPdfData && null != mtrJobEvaluationPdfData.getEmplNameCh()) {
map.put("techName", mtrJobEvaluationPdfData.getEmplNameCh());
} else {
map.put("techName", "");
}
// 文档名 和 基本信息替换
if (null != baseInfo) {
map.put("wordTitle", StringUtils.defaultIfEmpty(baseInfo.getMaintSequence(), ""));
map.put("branchName", StringUtils.defaultIfEmpty(baseInfo.getBrandName(), ""));
map.put("customerCompany", StringUtils.defaultIfEmpty(baseInfo.getCustomerCompany(), ""));
map.put("elevCode", StringUtils.defaultIfEmpty(baseInfo.getElevCode(), ""));
map.put("elevModel", StringUtils.defaultIfEmpty(baseInfo.getElevModel(), ""));
map.put("contCode", StringUtils.defaultIfEmpty(baseInfo.getContCode(), ""));
} else {
map.put("wordTitle", "");
map.put("branchName", "");
map.put("customerCompany", "");
map.put("elevCode", "");
map.put("elevModel", "");
map.put("contCode", "");
}
// 本次工作中发现的问题及需要客户处理的事项 技师备注内容
if (null != mtrMaintFixResult && null != mtrMaintFixResult.getTechComment()) {
map.put("techComment", mtrMaintFixResult.getTechComment());
} else {
map.put("techComment", "");
}
// 本次工作中发现的问题及需要客户处理的事项 改造标记内容
setIsReplaceOrReform(map, mtrMaintFixResult);
// 将map中的数据替换模本里面的标签内容
Object po = XmlUtils.unmarshallFromTemplate(xml, map);
mainDocumentPart.setJaxbElement((Document) po);
wPackage.addTargetPart(mainDocumentPart);
}
/**
* 设置工作满意度
*
* @param map
* @param mtrJobEvaluationPdfData
*/
public void SetSatisfaction(HashMap<String, String> map, MtrJobEvaluationPdfData mtrJobEvaluationPdfData) {
if (null != mtrJobEvaluationPdfData) {
if (null != mtrJobEvaluationPdfData.getAttitude()) {
// 工作评价信息设置 服务态度
if (mtrJobEvaluationPdfData.getAttitude() == 1) {
map.put("veryPl", "√");
map.put("pl", "□");
map.put("notPl", "□");
}
// 工作评价信息设置 服务态度
if (mtrJobEvaluationPdfData.getAttitude() == 2) {
map.put("veryPl", "□");
map.put("pl", "√");
map.put("notPl", "□");
}
// 工作评价信息设置 服务态度
if (mtrJobEvaluationPdfData.getAttitude() == 3) {
map.put("veryPl", "□");
map.put("pl", "□");
map.put("notPl", "√");
}
} else {
map.put("veryPl", "□");
map.put("pl", "□");
map.put("notPl", "□");
}
if (null != mtrJobEvaluationPdfData.getQuality()) {
// 工作评价信息设置 服务态度
if (mtrJobEvaluationPdfData.getQuality() == 1) {
map.put("veryPl2", "√");
map.put("pl2", "□");
map.put("notPl2", "□");
}
// 工作评价信息设置 服务态度
if (mtrJobEvaluationPdfData.getQuality() == 2) {
map.put("veryPl2", "□");
map.put("pl2", "√");
map.put("notPl2", "□");
}
// 工作评价信息设置 服务态度
if (mtrJobEvaluationPdfData.getQuality() == 3) {
map.put("veryPl2", "□");
map.put("pl2", "□");
map.put("notPl2", "√");
}
} else {
map.put("veryPl2", "□");
map.put("pl2", "□");
map.put("notPl2", "□");
}
if (null != mtrJobEvaluationPdfData.getQuestion()) {
map.put("pro", mtrJobEvaluationPdfData.getQuestion());
} else {
map.put("pro", "");
}
} else {
map.put("veryPl", "□");
map.put("pl", "□");
map.put("notPl", "□");
map.put("veryPl2", "□");
map.put("pl2", "□");
map.put("notPl2", "□");
map.put("pro", "");
}
}
/**
* 设置客户签名
*
* @param factory 工厂对象
* @param wPackage 文档包对象
* @param rt 书签对象
* @throws IOException
* @throws Exception
* @author zhouweiwei
*/
public void setCustSign(ObjectFactory factory, WordprocessingMLPackage wPackage, RangeFinder rt, byte[] custStream)
throws IOException, Exception {
// 填充图片内容
// InputStream is = new FileInputStream(new File("E:\\12.png"));
// BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wPackage,
// BufferUtil.getBytesFromInputStream(is));
// 对图片二进制流进行封装和绘图
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wPackage, custStream);
// Inline inline = imagePart.createImageInline("E:\\12.png", "这是图片", 1, 2, false);
Inline inline = imagePart.createImageInline(null, "客户签名", 1, 0, 1021737, 1021737, false);
Drawing drawing = factory.createDrawing();
drawing.getAnchorOrInline().add(inline);
RPr contentRpr = CreateWordUtils.getRPr(factory, "宋体", "000000", "18", STHint.EAST_ASIA, false, false, false,
false);
Tc tc = CreateWordUtils.getTc(factory, rt, "custSign");
if (null != tc) {
tc.getContent().clear();
P para = factory.createP();
CreateWordUtils.setParagraphSpacing(factory, para, JcEnumeration.LEFT, true, "0", "0", null, null, true,
"240", STLineSpacingRule.AUTO);
R r = factory.createR();
/*
* Text txt = factory.createText();
* txt.setValue("测试使用");
*/
r.getContent().add(drawing);
r.setRPr(contentRpr);
para.getContent().add(r);
tc.getContent().add(para);
}
}
/**
* 描述:换件,改造设置(本次工作中发现的问题及需要客户处理的事项 改造和替换内容)
*
* @param map 替换内容map
* @param mtrMaintFixResult 换件,改造 对象
* @author zhouweiwei
*/
public void setIsReplaceOrReform(HashMap<String, String> map, MtrMaintFixOut mtrMaintFixResult) {
if (null != mtrMaintFixResult) {
if (null != mtrMaintFixResult.getFixFlg()) {
if (mtrMaintFixResult.getFixFlg() == 0) {
map.put("Tb1", "□");
} else if (mtrMaintFixResult.getFixFlg() == 1) {
map.put("Tb1", "√");
}
} else {
map.put("Tb1", "□");
}
if (null != mtrMaintFixResult.getReconstrFlg()) {
if (mtrMaintFixResult.getReconstrFlg() == 0) {
map.put("Tb2", "□");
}
if (mtrMaintFixResult.getReconstrFlg() == 1) {
map.put("Tb2", "√");
}
} else {
map.put("Tb2", "□");
}
} else {
map.put("Tb1", "□");
map.put("Tb2", "□");
}
}
}
下面的方法是调用 CreateWordTemple类和CreateWordUtils 并且返回流给客户端
public byte[] pdfReptDataStream(MaintainingReportPdfData in) throws Exception {
long start = System.currentTimeMillis();
// 创建word文档的类
CreateWordTemple ws = new CreateWordTemple();
// 获取文档模板
InputStream wordTemplatePathIs = this.getClass().getResourceAsStream("maintRpWordTemplate.docx");
// 载入模板文件
WordprocessingMLPackage wPackage = CreateWordUtils.getWPackage(wordTemplatePathIs);
// 提取正文
MainDocumentPart mainDocumentPart = wPackage.getMainDocumentPart();
ObjectFactory factory = Context.getWmlObjectFactory();
Document wmlDoc = (Document) mainDocumentPart.getContents();
Body body = wmlDoc.getBody();
// 提取正文中所有段落
List<Object> paragraphs = body.getContent();
// 提取书签并创建书签的游标
RangeFinder rt = new RangeFinder("CTBookmark", "CTMarkupRange");
new TraversalUtil(paragraphs, rt);
// jha项
ws.creatJHATable(wPackage, mainDocumentPart, factory, rt, in.getMtrJhaPdfDatas());
// 保养项目结果
ws.creatMaitItemTable(wPackage, mainDocumentPart, factory, rt, in.getMaintItemResult());
// 维保项目及要求pdf数据
ws.creatMaintItemdetails(wPackage, factory, mainDocumentPart, rt, in.getMaintItems());
// 模板数据替换
ws.setDataInfo(wPackage, mainDocumentPart, factory, wmlDoc, in.getMtrJobEvaluationPdfData(), rt,
in.getMtrElevBaseInfoPdfData(), in.getMtrMaintFixResult());
// 设置文档页面的内容的里页边距的大小(A4样式)
CreateWordUtils.setWordPage(wPackage);
// 定义生成的word保存为输出流的形式
ByteArrayOutputStream outStreamTempl = new ByteArrayOutputStream();
CreateWordUtils.saveWordPackage(wPackage, outStreamTempl);
// 将输出流转化为输入流
InputStream inStreamTempl = new ByteArrayInputStream(outStreamTempl.toByteArray());
// 将word流转化为pdf流
ByteArrayOutputStream pdfOut = CreateWordUtils.getPdfByteArrayOutputStream(inStreamTempl);
// 将对象流转化为二进制流对象
byte[] out = pdfOut.toByteArray();
pdfOut.flush();
// 关闭流对象
pdfOut.close();
System.err.println("Generate pdf with " + (System.currentTimeMillis() - start) + "ms");
return out;
// pdf流转成PDF文件测试
/*
* InputStream inpp = new ByteArrayInputStream(out);
* OutputStream fos = new FileOutputStream(new File(
* "E:\\HelloWorld11.pdf"));
* byte[] b = new byte[1024];
* int nRead = 0;
* while ((nRead = inpp.read(b)) != -1) {
* fos.write(b, 0, nRead);
* }
* fos.flush();
* fos.close();
* inpp.close();
*/
}