Commit be2e4a17 authored by hongguangwu's avatar hongguangwu

MVP1.7.11-word转图片

parent 789cd239
......@@ -84,6 +84,7 @@ public class DateUtil {
*/
public static final String DATE_PATTERN = "yyyyMMddHHmmss";
public static final String EXPORT_PATTERN = "yyyyMMdd-HHmmss";
public static final String CHINA_PATTEN_YMD = "yyyy年MM月dd日";
protected static final float normalizedJulian(float jd) {
......
......@@ -106,6 +106,21 @@
<version>5.3.0</version>
<type>jar</type>
</dependency>
<!-- word转pdf -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local</artifactId>
<version>4.4.0</version>
</dependency>
<!-- pdf转图片 -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
</dependency>
</dependencies>
<build>
......
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the yifu4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.yifu.cloud.plus.v1.yifu.social.controller;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.DateUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.OSSUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.log.annotation.SysLog;
import com.yifu.cloud.plus.v1.yifu.social.util.WordToImageWithSeal;
import com.yifu.cloud.plus.v1.yifu.social.util.WordUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 税友word文档离职证明
*
* @author hgw
* @date 2025-5-14 18:24:58
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/tsocialfriendword")
@Tag(name = "税友word文档离职证明")
public class TSocialFriendWordController {
@Operation(description = "生成新word")
@GetMapping("/updateNewFileTest")
@SysLog("生成新word")
public void updateNewFileTest() throws Exception{
// 1:将劳动合同解除证明书.doc某些文字替换
// 2:盖章
// 3:生成新文件
String inputPath = "D:/test126.docx";
String outputPath = "D:/test126666.docx";
String outputImagePath = "D:/document_with_seal.png"; // 可以从配置中获取
replaceText(inputPath, outputPath, outputImagePath);
}
@Autowired
private OSSUtil ossUtil;
public R<String> replaceText(String inputPath, String outputPath, String outputImagePath) throws Exception {
String src = "1735185038602皖信.png";
URL url = ossUtil.getObjectUrl(null, src);
if (Common.isEmpty(url)) {
throw new RuntimeException("获取印章图片失败");
}
try (InputStream imageStream = url.openStream()) {
// 准备替换参数
Map<String, String> replacements = new HashMap<>();
replacements.put("empName", "张三丰");
replacements.put("empSex", "女");
replacements.put("empAge", "33");
replacements.put("idCard", "340826199012121212");
replacements.put("startDate", "2023年11月28日");
replacements.put("leaveReason", "个人原因");
replacements.put("leaveDate", "2025年01月20日");
replacements.put("nowDate", DateUtil.formatDatePatten(new Date(), DateUtil.CHINA_PATTEN_YMD));
// 执行替换 + 插入印章
WordUtil.replaceTextInWord(inputPath, outputPath, replacements);
WordToImageWithSeal.convertAndAddSeal(outputPath, imageStream, outputImagePath);
}
return R.ok();
}
}
package com.yifu.cloud.plus.v1.yifu.social.util;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.local.LocalConverter;
import org.jodconverter.local.office.LocalOfficeManager;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* @author hgw2
* @description word转图片
* @date 2025/5/15
*/
public class WordToImageWithSeal {
// 主方法用于测试或外部调用
/*public static void main(String[] args) {
String inputDocx = "D:/test/document.docx";
String sealImagePath = "D:/seal/seal.png";
String outputImagePath = "D:/output/document_with_seal.png";
try {
convertAndAddSeal(inputDocx, sealImagePath, outputImagePath);
System.out.println("转换并加盖公章成功!");
} catch (Exception e) {
e.printStackTrace();
}
}*/
// 在生产环境中,建议在整个应用生命周期中共享一个OfficeManager:
public static OfficeManager OFFICE_MANAGER;
static {
OFFICE_MANAGER = LocalOfficeManager.builder()
.portNumbers(2002)
.build();
try {
OFFICE_MANAGER.start();
} catch (OfficeException e) {
e.printStackTrace();
}
}
public static void convertAndAddSeal(String inputDocx, InputStream sealImagePath, String outputImagePath) throws IOException, OfficeException {
// Step 1: Word 转为 PDF(中间格式)
File pdfFile = new File(inputDocx.replace(".docx", ".pdf"));
/*converter.convert(new File(inputDocx)).as(DocumentType.DOCX)
.to(pdfFile).as(DocumentType.PDF).execute();*/
Map<String, Object> pdfProps = new HashMap<>();
pdfProps.put("FilterName", "writer_pdf_Export");
pdfProps.put("SelectPdfVersion", 1); // PDF/A-1
LocalConverter.builder()
.officeManager(OFFICE_MANAGER)
.storeProperties(pdfProps)
.build()
.convert(new File(inputDocx))
.to(pdfFile)
.execute();
// Step 2: PDF 转为 PNG 图片(可使用 Apache PDFBox 或 ImageMagick 转换)
BufferedImage pageImage = convertPdfToImage(pdfFile.getAbsolutePath());
// Step 3: 加盖公章
BufferedImage sealedImage = addSealToImage(pageImage, sealImagePath);
// Step 4: 输出图片
ImageIO.write(sealedImage, "png", new File(outputImagePath));
//ImageIO.write(sealedImage, "png", new File(outputImagePath));
}
private static BufferedImage convertPdfToImage(String pdfPath) throws IOException {
try (PDDocument document = PDDocument.load(new File(pdfPath))) {
PDFRenderer pdfRenderer = new PDFRenderer(document);
// 渲染第一页为图像,分辨率为 300 DPI
return pdfRenderer.renderImageWithDPI(0, 300, ImageType.RGB);
}
}
private static BufferedImage addSealToImage(BufferedImage image, InputStream sealImagePath) throws IOException {
BufferedImage seal = ImageIO.read(sealImagePath);
BufferedImage combined = new BufferedImage(
image.getWidth(),
image.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = combined.createGraphics();
g.drawImage(image, 0, 0, null);
// 设置公章位置(右下角)
int x = 1600;
int y = 1150;
g.drawImage(seal, x, y, null);
g.dispose();
return combined;
}
}
package com.yifu.cloud.plus.v1.yifu.social.util;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
/**
* @author hgw2
* @description word工具类
* @date 2025/5/15
*/
public class WordUtil {
public static void replaceTextInWord(String filePath, String outputFilePath, Map<String, String> replacements
) throws IOException {
try (FileInputStream fis = new FileInputStream(filePath);
XWPFDocument document = new XWPFDocument(fis)) {
// 替换段落中的文本
for (XWPFParagraph paragraph : document.getParagraphs()) {
for (String key : replacements.keySet()) {
if (paragraph.getText().contains(key)) {
String newText = paragraph.getText().replace(key, replacements.get(key));
paragraph.getRuns().clear();
XWPFRun newRun = paragraph.createRun();
newRun.setText(newText);
}
}
}
String text;
// 替换表格中的文本
for (XWPFTable table : document.getTables()) {
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph p : cell.getParagraphs()) {
for (XWPFRun run : p.getRuns()) {
text = run.getText(0);
if (Common.isNotNull(text) && replacements.get(text) != null) {
run.setText(replacements.get(text), 0);
}
}
}
}
}
}
// 保存输出文件
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
document.write(fos);
}
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment