前言
应用场景
需要根据word模板生成报告文档或者将已有的图片、文字、pdf、word等多种附件整合成一个word文档
使用的插件
poi-tl
- 说明:word文档操作插件,使用说明参见 https://deepoove.com/poi-tl/
- 优点:简单易学,可满足基础的word生成,免费
- 缺点:多个word合并文档、插入页码等功能没有,表格的动态生成等需要自定义diamante实现
插件引入
<!--word操作工具-->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.6</version>
</dependency>
spire.doc.free
- 说明:word文档操作插件,使用说明参见 https://www.e-iceblue.cn/
- 优点:简单易学,功能强大,可满足基础的word生成,多个word合并、插入页码等
- 缺点:分为免费版和收费版,免费版,对于word页数、字数等有限制,如果需要生成的word内容很大,建议购买收费版
插件引入
要先在repositories中配置源,再依赖项中引入插件
<repositories>
<repository>
<id>public</id>
<name>aliyun nexus</name>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
<repository>
<id>iceblue-public</id>
<name>iceblue nexus</name>
<url>https://repo.e-iceblue.cn/repository/maven-public</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<!--word操作工具-->
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.3.2</version>
</dependency>
pdfbox
说明:处理pdf文件的插件,主要用于将pdf转换成图片,插入word文档使用
插件引入
<!--pdf操作工具-->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>3.0.3</version>
</dependency>
imgscalr-lib
说明:图片处理插件,主要用于图片缩放,适应word页面大小
插件引入
<!--图片缩放操作工具-->
<dependency>
<groupId>org.imgscalr</groupId>
<artifactId>imgscalr-lib</artifactId>
<version>4.2</version>
</dependency>
功能实现
组合使用poi-tl和spire.doc.free插件,使用poi-tl创建word文档,spire.doc.free实现文档的合并、页码插入等
poi-tl关键代码
package com.kcwx.docUtils;
import com.deepoove.poi.data.RenderData;
import lombok.Data;
/**
*poi-tl图片渲染类的扩展
* */
@Data
public class CustPictureRenderData implements RenderData
{
/**
* 图片宽度
*/
private int width;
/**
* 图片高度
*/
private int height;
/**
* 图片路径
*/
private String path;
/**
* 图片二进制数据
*/
private transient byte[] data;
/**
* 当图片不存在时,显示的文字
*/
private String altMeta = "";
/**
* 左偏移量
*/
private int leftOffset;
/**
* 上偏移量
*/
private int topOffset;
/**
* 图片在文字的位置 1:图片在文字上方 2:图片在文字下方 默认 1
* */
private int behindType=1;
}
package com.kcwx.docUtils;
import com.deepoove.poi.exception.RenderException;
import com.deepoove.poi.policy.AbstractRenderPolicy;
import com.deepoove.poi.render.RenderContext;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;
import java.io.*;
/**
*poi-tl自定义图片渲染策略
* */
public class CustPictureRenderPolicy extends AbstractRenderPolicy<CustPictureRenderData>
{
@Override
protected boolean validate(CustPictureRenderData data)
{
return (null != data && (null != data.getData() || null != data.getPath()));
}
@Override
public void doRender(RenderContext<CustPictureRenderData> context) throws Exception
{
Helper.renderPicture(context.getRun(), context.getData());
}
@Override
protected void afterRender(RenderContext<CustPictureRenderData> context)
{
clearPlaceholder(context, false);
}
@Override
protected void reThrowException(RenderContext<CustPictureRenderData> context, Exception e)
{
logger.info("Render picture {}, error: {}", context.getEleTemplate(), e.getMessage());
context.getRun().setText(context.getData().getAltMeta(), 0);
}
public static class Helper
{
public static final int EMU = 9525;
public static void renderPicture(XWPFRun run, CustPictureRenderData picture) throws Exception
{
int suggestFileType = suggestFileType(picture.getPath());
InputStream ins = null;
try
{
ins = null == picture.getData() ? new FileInputStream(picture.getPath())
: new ByteArrayInputStream(picture.getData());
// String numberCode =RandomUtil.createNumberCode(4);
run.addPicture(ins, suggestFileType, "Generated", picture.getWidth() * EMU,
picture.getHeight() * EMU);
CTDrawing drawing = run.getCTR().getDrawingArray(0);
CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
//拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性
CTAnchor anchor = getAnchorWithGraphic(graphicalobject,
Units.toEMU(picture.getWidth()), Units.toEMU(picture.getHeight()),
Units.toEMU(picture.getLeftOffset()), Units.toEMU(picture.getTopOffset()),picture.getBehindType());
//添加浮动属性
drawing.setAnchorArray(new CTAnchor[]{anchor});
//删除行内属性
drawing.removeInline(0);
}
finally
{
IOUtils.closeQuietly(ins);
}
}
/**
* @param ctGraphicalObject 图片数据
* @param width 宽
* @param height 高
* @param leftOffset 水平偏移 left
* @param topOffset 垂直偏移 top
* @param behindType 图片在文字的位置 1:图片在文字上方 2:图片在文字下方 默认 1
* @return CTAnchor
*/
private static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, int width, int height, int leftOffset, int topOffset,int behindType)
throws Exception
{
String anchorXML =
"<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
+ "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\""+ (behindType==1 ? 1 : 0) + "\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
+ "<wp:simplePos x=\"0\" y=\"0\"/>"
+ "<wp:positionH relativeFrom=\"column\">"
+ "<wp:posOffset>" + leftOffset + "</wp:posOffset>"
+ "</wp:positionH>"
+ "<wp:positionV relativeFrom=\"paragraph\">"
+ "<wp:posOffset>" + topOffset + "</wp:posOffset>" +
"</wp:positionV>"
+ "<wp:extent cx=\"" + width + "\" cy=\"" + height + "\"/>"
+ "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
+ "<wp:wrapNone/>"
+ "<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\"G:/11.png\"/><wp:cNvGraphicFramePr/>"
+ "</wp:anchor>";
CTDrawing drawing = CTDrawing.Factory.parse(anchorXML);//XmlException
CTAnchor anchor = drawing.getAnchorArray(0);
anchor.setGraphic(ctGraphicalObject);
return anchor;
}
/**
* 支持的图片类型
* imgFile 图片
* */
public static int suggestFileType(String imgFile)
{
int format = 0;
if (imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF;
else if (imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF;
else if (imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT;
else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg"))
format = XWPFDocument.PICTURE_TYPE_JPEG;
else if (imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG;
else if (imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB;
else if (imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF;
else if (imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF;
else if (imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS;
else if (imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP;
else if (imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG;
else {
throw new RenderException("Unsupported picture: " + imgFile + ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
}
return format;
}
}
}
package com.kcwx.docUtils;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.*;
import java.lang.reflect.Field;
import java.nio.file.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;
import java.text.SimpleDateFormat;
/**
* 附件归档合成帮助类
* */
@Component
public class DocHelper {
/**根目录*/
public static final String TEM_ROOT_PATH="D:/uploadPath";
/**日志*/
private static final Logger log = LoggerFactory.getLogger(DocHelper.class);
/**
* 获取归档文件文件夹根目录
* @return Path绝对路径
* */
public Path getDocDir(){
try
{
Path targetDir = Paths.get(TEM_ROOT_PATH, "archiveFiles", new SimpleDateFormat("yyyyMMdd").format(new Date());
//判断目标文件夹路径是否存在,不存在则创建文件夹
if (!Files.exists(targetDir)) {
Files.createDirectories(targetDir);
}
return targetDir;
}
catch (Exception e) {
return null;
}
}
/**
* 获取归档文件的相对路径
* @param filePath 归档文件绝对路径
* @return String相对路径
* */
public String getRelativePath(Path filePath)
{
Path basePath = Paths.get(TEM_ROOT_PATH);
try
{
Path relativePath = basePath.relativize(filePath);
return "/"+relativePath.toString().replaceAll("\\\\", "/");
}
catch (Exception e)
{
return "";
}
}
/**
* 获取完整的文件路径
* @param fileName 文件名称
* @param extension 文件后缀(不带.)
* */
public Path getFilePath(String fileName,String extension){
try
{
Path targetDir=getDocDir();
Path targetFilePath=Paths.get(targetDir.toString(), fileName+"."+extension);
if(Files.exists(targetFilePath)){
Files.delete(targetFilePath);
}
return targetFilePath;
}
catch (Exception ex){
return null;
}
}
/**
* 拷贝word模板生成新的模板
* @param docTemplatePath Word模板路径
* @return 新的模板绝对路径
* */
public String copyDocTemplate(String docTemplatePath)
{
try
{
Path targetDir = getDocDir();
//获取源文件后缀
String extension = FilenameUtils.getExtension(docTemplatePath);
//目标文件名称
String targetFileName = String.valueOf(System.currentTimeMillis()) + "."+ extension;
String targetFilePath = Paths.get(targetDir.toString(), targetFileName).toString();
//拷贝word模板到目标路径
Files.copy(Paths.get(docTemplatePath), Paths.get(targetFilePath), StandardCopyOption.REPLACE_EXISTING);
return targetFilePath;
}
catch (Exception ex)
{
log.error("拷贝word模板错错误:{}", Arrays.toString(ex.getStackTrace()));
return "";
}
}
/**
* 创建图片数据信息
* @param imgPath 图片路径
* @param width 图片宽度
* @param height 图片高度
* @param leftOffset 左偏移量
* @param topOffset 上偏移量
* @param altMeta 当图片不存在时,显示的文字
* */
public static CustPictureRenderData createPictureDate(String imgPath,int width, int height, int leftOffset, int topOffset,String altMeta)
{
CustPictureRenderData pictureData=new CustPictureRenderData();
pictureData.setPath(imgPath);
pictureData.setWidth(width);
pictureData.setHeight(height);
pictureData.setAltMeta(altMeta);
pictureData.setLeftOffset(leftOffset);
pictureData.setTopOffset(topOffset);
return pictureData;
}
/**
* 模板替换生成文档
* @param docTemplatePath word模板路径
* @param targetFileName 目标文件名称
* @param datas 模板中需要替换的数据内容
* @param tableConfig table表格循环行config
* */
public String createWord(String docTemplatePath,String targetFileName,Map<String,Object> datas,Configure tableConfig)
{
try
{
//拷贝word模板到新的模板路径
String newDocTemPath =copyDocTemplate(docTemplatePath);
XWPFTemplate template =null;
if(tableConfig!=null){
template = XWPFTemplate.compile(newDocTemPath,tableConfig).render(datas);
}
else {
//默认文本标签为{{}}
//把图片插件注册为新标签类型 {{%}}
ConfigureBuilder builder = Configure.builder();
builder.addPlugin('%',new CustPictureRenderPolicy());
//模板内容替换
template = XWPFTemplate.compile(newDocTemPath,builder.build()).render(datas);
}
//最终目标文件名称
String extension = FilenameUtils.getExtension(docTemplatePath);//获取源文件后缀
Path targetFilePath=getFilePath(targetFileName,extension);
//最终目标文件生成
FileOutputStream out = new FileOutputStream(targetFilePath.toString());
template.write(out);
out.flush();
out.close();
template.close();
//删除新的模板
Files.delete(Paths.get(newDocTemPath));
//返回相对路径
return getRelativePath(targetFilePath);
}
catch (Exception ex)
{
log.error("模板替换生成文档【{}】失败:{}",targetFileName, Arrays.toString(ex.getStackTrace()));
return "";
}
}
/**
* 实体对象转 map
* @param entity 实体对象
* @param excludeFields 排除的字段
* @param fieldToUpper 字段名称首字母是否转成大写
* */
public static Map<String, Object> entityToMap(Object entity,List<String>excludeFields,boolean fieldToUpper)
{
Map<String, Object> map=new HashMap<>();
if(entity!=null) {
Class<?> clazz = entity.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
String fieldName;
Object fieldValue;
try {
field.setAccessible(true);
fieldName = field.getName();
fieldValue = field.get(entity);
}
catch (Exception e) {
fieldName="";
fieldValue=null;
}
if(StringUtils.isNotEmpty(fieldName)) {
String finalFieldName = fieldName;
boolean isExclude=excludeFields.stream().anyMatch(g->g.equals(finalFieldName));
if (fieldToUpper) {
fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
}
if(!isExclude) {
map.put(fieldName, fieldValue);
}
}
}
}
return map;
}
}
spire.doc.free关键代码
package com.kcwx.docUtils;
import com.kcwx.common.utils.StringUtils;
import com.spire.doc.*;
import com.spire.doc.collections.SectionCollection;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.util.Units;
import org.imgscalr.Scalr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.kcwx.opd.domain.OpdAttachFile;
/**
* SpireDoc word帮助类
* */
@Component
@RequiredArgsConstructor
public class SpireDocHelper {
private final DocHelper docHelper;
/**图片附件后缀*/
public static final String[] IMAGE_EXTENSION = { ".bmp", ".jpg", ".jpeg", ".png" };
/**word附件后缀*/
public static final String[] WORD_EXTENSION = { ".doc", ".docx" };
/**日志*/
private static final Logger log = LoggerFactory.getLogger(DocHelper.class);
/**
* 生成纯附件文档
* @param fileName 归档文件名称(不含后缀)
* @param attachFiles 附件列表
* @param isAddPage 是否设置页码
* @param isFirstPage 首页是否设置页码
* */
public String createFileDoc(String fileName, List<OpdAttachFile> attachFiles,boolean isAddPage,boolean isFirstPage)
{
String palceFilePath="";
if(!attachFiles.isEmpty()){
//获取已存在的文件
List<String> fileList=new ArrayList<>();
for (OpdAttachFile attachFile : attachFiles) {
if(StringUtils.isNotEmpty(attachFile.getFileUrl())){
String filePath=DocHelper.getFullPath(attachFile.getFileUrl());
if(Files.exists(Paths.get(filePath))){
fileList.add(filePath);
}
}
}
//文件归档处理
if(!fileList.isEmpty()){
List<String>extentionList=new ArrayList<>();
Document doc = new Document();
for(String filePath : fileList){
String exType=FilenameUtils.getExtension(filePath);
String extension = "."+ exType;//文件后缀
String preExtention = "";
if(!extentionList.isEmpty()){
preExtention = extentionList.get(extentionList.size()-1);
}
extentionList.add(extension);
//图片
if(Arrays.asList(IMAGE_EXTENSION).contains(extension)){
try
{
//如果该附件的前一个附件是word或者pdf文件,那么新增节
if(!Arrays.asList(IMAGE_EXTENSION).contains(preExtention)){
doc.addSection();
}
File fileImg = new File(filePath);
BufferedImage originalImage =ImageIO.read(fileImg);
boolean imgSuccess=insertImg(doc,originalImage,false,exType.toUpperCase());
if(!imgSuccess){
log.error("图片归档失败{}失败",filePath);
}
}
catch (Exception ex){
log.error("图片归档失败【{}】失败:{}",filePath, Arrays.toString(ex.getStackTrace()));
}
}
else if(Arrays.asList(WORD_EXTENSION).contains(extension)){
try {
boolean mergeSuccess = mergeWord(doc, filePath, 2);
}
catch (Exception ex){
log.error("Word文档归档失败{}失败",filePath);
}
}
else if(extension.equals(".pdf")){
boolean pdfSuccess=insertPdf(filePath,doc);
}
}
//最终目标文件生成
try {
//设置页码
if(isAddPage){
SectionCollection sectionCollection= doc.getSections();
int sectionCount=sectionCollection.getCount();
for(int i=0;i<sectionCount;i++){
Section section=sectionCollection.get(i);
if(!isFirstPage&&i==0){
section.getPageSetup().setDifferentFirstPageHeaderFooter(true);
HeaderFooter firstPageFooter = section.getHeadersFooters().getFirstPageFooter();
firstPageFooter.getParagraphs().clear();
Paragraph firstpg = firstPageFooter.addParagraph();
firstpg.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
section.getPageSetup().setRestartPageNumbering(true);
section.getPageSetup().setPageStartingNumber(0);
}
HeaderFooter footer = section.getHeadersFooters().getFooter();
footer.getParagraphs().clear();
Paragraph footerPara = footer.addParagraph();
footerPara.appendField("页码", FieldType.Field_Page);
//footerPara.appendText(" of ");
//footerPara.appendField("总页数", FieldType.Field_Num_Pages);
footerPara.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
}
}
Path targetFilePath = docHelper.getFilePath(fileName, "docx");
doc.saveToFile(targetFilePath.toString(), FileFormat.Docx);
doc.close();
palceFilePath =docHelper.getRelativePath(targetFilePath);
}
catch (Exception ex){
log.error("附件【{}】归档失败{}失败",fileName,Arrays.toString(ex.getStackTrace()));
}
}
}
return palceFilePath;
}
/**
*合并word文档
* @param mainDoc 合并word对象
* @param docPath 要合并的word路径
* @param mergeType 合并方式 1:路径合并 2:FileInputStream合并 3:克隆方式合并
* */
public boolean mergeWord(Document mainDoc,String docPath,int mergeType) throws IOException {
FileInputStream fis=null;
try
{
if(mergeType==1){
//路径方法
mainDoc.insertTextFromFile(docPath, FileFormat.Docx);
}
else if(mergeType==2){
//fileStream方法
fis=new FileInputStream(docPath);
mainDoc.insertTextFromStream(fis,FileFormat.Docx);
}
else if(mergeType==3){
//克隆方法
Document sourceDoc=new Document(docPath);
//在第二个文档中循环获取所有节
for (Object sectionObj : sourceDoc.getSections()) {
mainDoc.addSection();
Section sec=(Section)sectionObj;
//在所有节中循环获取所有子对象
for (Object docObj :sec.getBody().getChildObjects()) {
DocumentObject obj=(DocumentObject)docObj;
//获取第一个文档的最后一节,将所有子对象添加到第一个文档的最后一节中
Section lastSection = mainDoc.getLastSection();
lastSection.getBody().getChildObjects().add(obj.deepClone());
}
}
sourceDoc.close();
}
return true;
}
catch (Exception ex)
{
log.error("文档【{}】合并处理失败:{}",docPath, Arrays.toString(ex.getStackTrace()));
return false;
}
finally {
if(fis!=null){
fis.close();
}
}
}
/**
* 插入图片
* @param wordDoc document
* @param originalImage 图片
* @param isLandscape 是否横向文档
* @param imgType 图片类型 JPG/PNG等
* */
private boolean insertImg(Document wordDoc,BufferedImage originalImage,boolean isLandscape,String imgType)
{
BufferedImage resizeImg=reduceImg(originalImage,isLandscape);
if(resizeImg!=null){
try
{
com.spire.doc.Section section=null;
Paragraph para=null;
if(isLandscape){
//横向页面,新增节
section=wordDoc.addSection();
section.getPageSetup().setOrientation(PageOrientation.Landscape);
}
else {
//纵向页面
SectionCollection sectionCollection= wordDoc.getSections();
int count=sectionCollection.getCount();
if(count>0){
section = sectionCollection.get(count-1);
//当前页面的方向
PageOrientation curOrientation=section.getPageSetup().getOrientation();
//如果最后一节是空白节
if(section.getParagraphs().getCount()==0){
if (curOrientation == PageOrientation.Landscape){
section.getPageSetup().setOrientation(PageOrientation.Portrait);
}
}
else {
if (curOrientation == PageOrientation.Landscape)
{
section=wordDoc.addSection();
section.getPageSetup().setOrientation(PageOrientation.Portrait);
}
}
}
else {
section=wordDoc.addSection();
section.getPageSetup().setOrientation(PageOrientation.Portrait);
}
}
para=section.addParagraph();
//创建 DocPicture 类的对象
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(resizeImg, imgType, baos);
DocPicture picture = new DocPicture(wordDoc);
picture.loadImage(baos.toByteArray());
para.getChildObjects().insert(0,picture);
return true;
}
catch(Exception exception){
return false;
}
}
else {
return false;
}
}
/**
* 按比例缩小图片
* @param originalImage 图片
* @param isLandscape 是否横向页面 主要用于pdf文件处理
* */
private BufferedImage reduceImg(BufferedImage originalImage, boolean isLandscape)
{
try
{
//图片目标宽度 A4纸的宽度 points 转像素
int targetWidth=isLandscape? Units.pointsToPixel(678) :Units.pointsToPixel(414);
//图片目标高度 A4纸的高度 points 转像素
int targetHeight=isLandscape?Units.pointsToPixel(414):Units.pointsToPixel(678);
// 读取原始图片宽度 单位 Pixel
int originalWidth = originalImage.getWidth();
// 读取原始图片高度 单位 Pixel
int originalHeight = originalImage.getHeight();
//图片宽高是否超出A4纸大小
boolean widthOut=originalWidth>targetWidth;
boolean heightOut=originalHeight>targetHeight;
if(widthOut||heightOut){
// 计算新尺寸
double widthScale=(double) targetWidth / originalWidth;
double heightScale=(double) targetHeight / originalHeight;
double scale = Math.min(widthScale, heightScale);
int newWidth = (int) (originalWidth * scale);
int newHeight = (int) (originalHeight * scale);
// int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
// // 创建新的BufferedImage对象
// BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, type);
// Graphics2D g = resizedImage.createGraphics();
// g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// g.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
// g.dispose();
// // 写入新图片文件
//// File outputFile = new File("D:\\resized-image.png");
//// ImageIO.write(resizedImage, "png", outputFile);
// return resizedImage;
return Scalr.resize(originalImage, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT,newWidth,newHeight);
}
else {
return originalImage;
}
}
catch (Exception ex)
{
log.error("图片归档处理失败:{}", Arrays.toString(ex.getStackTrace()));
return null;
}
}
/**
* 插入pdf附件
* @param pdfPath pdf文件路径
* @param doc Document
* */
private boolean insertPdf(String pdfPath,Document doc)
{
int okCount=0;
try
{
File pdfFile = new File(pdfPath);
PDDocument document = Loader.loadPDF(pdfFile);
PDFRenderer renderer = new PDFRenderer(document);
int totalPages = document.getNumberOfPages();
for(int i=0;i<totalPages;i++){
//判断页面是否横向
PDPage pdfPage=document.getPage(i);
// int rotation=pdfPage.getRotation();//获取页面旋转角度
float pageWidth=pdfPage.getMediaBox().getWidth();
float pageHeight=pdfPage.getMediaBox().getHeight();
boolean isLandscape=pageWidth>pageHeight;
//当前页转换成图片
BufferedImage pdfImage= renderer.renderImage(i);
boolean isOk= insertImg(doc,pdfImage,isLandscape,"JPG");
if(isOk){
okCount++;
}
}
return okCount==totalPages;
}
catch (Exception ex)
{
log.error("pdf归档【{}】处理失败:{}",pdfPath,Arrays.toString(ex.getStackTrace()));
return false;
}
}
}
实例
public String testDemo
{
DocHelper docHelper=new DocHelper();
String filePath="";
//获取模板路径
Path docTemplatePath=Paths.get("D:/template/测试模板.docx");
if(Files.exists(docTemplatePath))
{
String signImg = "D:/template/test.jpg"
// 设置需要替换的标签内容
Map<String, Object> data = new HashMap<>();
data.put("OrgName", "测试机构名称");
data.put("ApplyCode", "20250917");
data.put("Year", "2025年");
data.put("Month", "9月");
data.put("Day", "17日");
data.put("MyPicture", DocHelper.createPictureDate(signImg,40,40,100,5,"我的图片"));
//根据模板生成文件
String targetFileName=orgName+"_"+docTempName+auditTimes;
return docHelper.createWord(docTemplatePath.toString(),"新的测试归档",data,null);
}
else {
log.error("{}模板路径{}不存在",docTempName,docTemplatePath);
}
return filePath;
}
8728



被折叠的 条评论
为什么被折叠?



