使用docx4j生成指定页码的带水印的空白word文档
依赖==========================================
org.docx4j
docx4j
6.0.1
org.docx4j
docx4j-importXHTML
6.0.1
org.docx4j
xhtmlrenderer
3.0.0
代码===========================================
package org.example;
import org.docx4j.XmlUtils;
import org.docx4j.jaxb.Context;
import org.docx4j.model.structure.documentModel;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.PartName;
import org.docx4j.openpackaging.parts.WordprocessingML.;
import org.docx4j.openpackaging.parts.relationships.RelationshipsPart;
import org.docx4j.relationships.Relationship;
import org.docx4j.wml.;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
public class Docx4jTest {
private static final ObjectFactory factory = Context.getWmlObjectFactory();
private WordprocessingMLPackage wordMLPackage;
private MaindocumentPart maindocumentPart;
private documentModel documentModel;
public static void main(String[] args) throws Exception {
createWaterWord("这是个带水印的空word" , 5);
}
private static void createWaterWord(String fileName , Integer pageNum) throws Exception {
Docx4jTest docx4jTest = new Docx4jTest();
WordprocessingMLPackage wordprocessingMLPackage = WordprocessingMLPackage.createPackage();
//.createPackage(PageSizePaper.valueOf("A4"), false); // A4纸,//横版:true
docx4jTest.wordMLPackage = wordprocessingMLPackage;
docx4jTest.maindocumentPart = wordprocessingMLPackage.getMaindocumentPart();
docx4jTest.documentModel = wordprocessingMLPackage.getdocumentModel();
SectPr sectPr = docx4jTest.wordMLPackage.getdocumentModel().getSections().get(docx4jTest.wordMLPackage.getdocumentModel().getSections().size() - 1).getSectPr();
if (sectPr == null) {
sectPr = factory.createSectPr();
docx4jTest.maindocumentPart.addObject(sectPr);
docx4jTest.documentModel.getSections().get(docx4jTest.documentModel.getSections().size() - 1).setSectPr(sectPr);
}
//水印文字内容
String watermark = "这里是水印ssssssssss";
String hdrFtrRef = "first";
if(hdrFtrRef.equals("first")){
//给首页加水印
docx4jTest.doWaterPage(sectPr, "first", watermark);
}
//非首页
docx4jTest.doWaterPage(sectPr, "default", watermark);
for (int i = pageNum; i >1 ; i--) {
docx4jTest.maindocumentPart.addObject(makePageBr()); //新增页面
}
docx4jTest.wordMLPackage.save(new java.io.File(fileName+".docx"));
}
//加水印
private void doWaterPage(SectPr sectPr, String hdrFtrRef, String watermark) throws Exception {
App docx4jTest = new App();
HeaderPart headerPart = new HeaderPart(new PartName("/word/heade-" + hdrFtrRef + ".xml"));
Relationship relationship = docx4jTest.maindocumentPart.addTargetPart(headerPart);
docx4jTest.setWatermarkHdr(headerPart, watermark);
HeaderReference headerReference = factory.createHeaderReference();
headerReference.setType(HdrFtrRef.fromValue("default"));
headerReference.setId(relationship.getId());
sectPr.getEGHdrFtrReferences().add(headerReference);
sectPr.setTitlePg(new BooleanDefaultTrue());
}
//设置水印图片
private void setWatermarkHdr(HeaderPart headerPart, String text) throws Exception {
ImagePngPart imagePart = new ImagePngPart(new PartName("/media/background.png"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(createWaterMark(text), "png", out);
byte[] imagebytes = out.toByteArray();
imagePart.setBinaryData(imagebytes);
Relationship rel = headerPart.addTargetPart(imagePart, RelationshipsPart.AddPartBehaviour.REUSE_EXISTING);
String openXML = ""
+ ""
+ ""
+ " "
+ " "
+ ""
+ ""
+ " "
+ " "
+ ""
+ ""
+ " "
+ ""
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ ""
+ " "
+ " "
+ " "
+ " "
+ " "
+ " ";
Hdr hdr = (Hdr) XmlUtils.unmarshalString(openXML);
headerPart.setJaxbElement(hdr);
}
//设置水印字体
private static BufferedImage createWaterMark(String content) {
Integer width = 1000;
Integer height = 1360;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 获取bufferedImage对象
String fontType = "宋体";
Integer fontStyle = Font.PLAIN;
Integer fontSize = 30;
Font font = new Font(fontType, fontStyle, fontSize);
Graphics2D g2d = image.createGraphics(); // 获取Graphics2d对象
image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
g2d.dispose();
for (int i = 1; i <= 20; i += 2) {
for (int j = 1; j <= 10; j += 2) {
int px = j * 100;
int py = i * 100;
g2d = image.createGraphics();
g2d.setColor(java.awt.Color.black);
g2d.setStroke(new BasicStroke(1)); // 设置字体
g2d.setFont(font); // 设置字体类型 加粗 大小
g2d.translate(px, py);// 设置原点
g2d.rotate(Math.toRadians(-30));// 设置倾斜度
FontRenderContext context = g2d.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(content, context);
g2d.drawString(content, 0, 0);
g2d.dispose();
}
}
return image;
}
private static P makePageBr() throws Exception {
P p = factory.createP();
R r = factory.createR();
Br br = factory.createBr();
br.setType(STBrType.PAGE);
r.getContent().add(br);
p.getContent().add(r);
return p;
}
}



