|
|
@@ -4,6 +4,7 @@ import cn.hutool.core.util.ArrayUtil;
|
|
|
import cn.hutool.core.util.StrUtil;
|
|
|
import com.aspose.words.Document;
|
|
|
import com.aspose.words.FontSettings;
|
|
|
+import com.aspose.words.PdfSaveOptions;
|
|
|
import com.aspose.words.SaveFormat;
|
|
|
import com.deepoove.poi.XWPFTemplate;
|
|
|
import com.itextpdf.text.BaseColor;
|
|
|
@@ -11,6 +12,7 @@ import com.itextpdf.text.DocumentException;
|
|
|
import com.itextpdf.text.pdf.*;
|
|
|
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
|
|
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
|
|
+import org.springframework.core.io.ClassPathResource;
|
|
|
|
|
|
import java.io.*;
|
|
|
import java.nio.file.Files;
|
|
|
@@ -130,6 +132,35 @@ public class WordUtils {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ // 初始化字体目录(只执行一次)
|
|
|
+ private static final String FONT_DIR;
|
|
|
+
|
|
|
+ static {
|
|
|
+ try {
|
|
|
+ // 创建临时字体目录
|
|
|
+ File tempFontDir = Files.createTempDirectory("fonts").toFile();
|
|
|
+ FONT_DIR = tempFontDir.getAbsolutePath();
|
|
|
+
|
|
|
+ // 把 resources/fonts 下的字体文件复制到临时目录
|
|
|
+ String[] fontFiles = { "simsun.ttc", "SimSun.ttf", "msyh.ttc" };
|
|
|
+ for (String fontFile : fontFiles) {
|
|
|
+ ClassPathResource resource = new ClassPathResource("fonts/" + fontFile);
|
|
|
+ if (resource.exists()) {
|
|
|
+ File targetFile = new File(tempFontDir, fontFile);
|
|
|
+ try (InputStream in = resource.getInputStream()) {
|
|
|
+ Files.copy(in, targetFile.toPath());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 设置 Aspose 全局字体目录
|
|
|
+ FontSettings fontSettings = FontSettings.getDefaultInstance();
|
|
|
+ fontSettings.setFontsFolders(new String[]{FONT_DIR}, true);
|
|
|
+
|
|
|
+ } catch (IOException e) {
|
|
|
+ throw new RuntimeException("初始化字体目录失败", e);
|
|
|
+ }
|
|
|
+ }
|
|
|
/*
|
|
|
* @Description: word文件转pdf文件(生成临时文件)
|
|
|
* @Param:
|
|
|
@@ -140,14 +171,18 @@ public class WordUtils {
|
|
|
FileOutputStream fileOS = null;
|
|
|
try {
|
|
|
Document doc = new Document(wordFile.getAbsolutePath());
|
|
|
- // 创建临时PDF文件
|
|
|
+
|
|
|
+ // PDF 保存选项,嵌入字体,保证跨平台显示一致
|
|
|
+ PdfSaveOptions saveOptions = new PdfSaveOptions();
|
|
|
+ saveOptions.setEmbedFullFonts(true);
|
|
|
+
|
|
|
+ // 创建临时 PDF 文件
|
|
|
File pdfFile = File.createTempFile("converted_", ".pdf");
|
|
|
fileOS = new FileOutputStream(pdfFile);
|
|
|
- // 保存转换的pdf文件
|
|
|
- doc.save(fileOS, SaveFormat.PDF);
|
|
|
+ doc.save(fileOS, saveOptions);
|
|
|
return pdfFile;
|
|
|
} catch (Exception e) {
|
|
|
- throw new RuntimeException("转换Word文档为PDF失败: " + e.getMessage());
|
|
|
+ throw new RuntimeException("转换Word文档为PDF失败: " + e.getMessage(), e);
|
|
|
} finally {
|
|
|
try {
|
|
|
if (fileOS != null) {
|