|
@@ -123,7 +123,35 @@ public class WordToPdfUtils {
|
|
|
try {
|
|
try {
|
|
|
long old = System.currentTimeMillis();
|
|
long old = System.currentTimeMillis();
|
|
|
Document doc = new Document(new ByteArrayInputStream(bytes));
|
|
Document doc = new Document(new ByteArrayInputStream(bytes));
|
|
|
- doc.save(byteArrayOutputStream, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
|
|
|
|
|
|
|
+
|
|
|
|
|
+ // 设置字体替换规则,解决中文乱码问题
|
|
|
|
|
+ FontSettings fontSettings = new FontSettings();
|
|
|
|
|
+
|
|
|
|
|
+ // 从 resources/fonts 目录加载 simsun.ttf 字体
|
|
|
|
|
+ InputStream fontInputStream = WordToPdfUtils.class.getClassLoader()
|
|
|
|
|
+ .getResourceAsStream("fonts/simsun.ttf");
|
|
|
|
|
+
|
|
|
|
|
+ if (fontInputStream != null) {
|
|
|
|
|
+ // 创建内存字体源
|
|
|
|
|
+ MemoryFontSource memoryFontSource = new MemoryFontSource(
|
|
|
|
|
+ readAllBytes(fontInputStream), 0);
|
|
|
|
|
+
|
|
|
|
|
+ // 配置字体源
|
|
|
|
|
+ FontSourceBase[] originalFontSources = fontSettings.getFontsSources();
|
|
|
|
|
+ FontSourceBase[] newFontSources = new FontSourceBase[originalFontSources.length + 1];
|
|
|
|
|
+ System.arraycopy(originalFontSources, 0, newFontSources, 0, originalFontSources.length);
|
|
|
|
|
+ newFontSources[newFontSources.length - 1] = memoryFontSource;
|
|
|
|
|
+ fontSettings.setFontsSources(newFontSources);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 应用字体设置
|
|
|
|
|
+ doc.setFontSettings(fontSettings);
|
|
|
|
|
+
|
|
|
|
|
+ // 设置PDF保存选项,嵌入完整字体
|
|
|
|
|
+ PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
|
|
|
|
|
+ pdfSaveOptions.setEmbedFullFonts(true);
|
|
|
|
|
+
|
|
|
|
|
+ doc.save(byteArrayOutputStream, pdfSaveOptions);
|
|
|
long now = System.currentTimeMillis();
|
|
long now = System.currentTimeMillis();
|
|
|
log.info("pdf转换成功,共耗时:{}秒", (now - old) / 1000.0);
|
|
log.info("pdf转换成功,共耗时:{}秒", (now - old) / 1000.0);
|
|
|
} catch (Exception e) {
|
|
} catch (Exception e) {
|
|
@@ -131,5 +159,19 @@ public class WordToPdfUtils {
|
|
|
}
|
|
}
|
|
|
return byteArrayOutputStream;
|
|
return byteArrayOutputStream;
|
|
|
}
|
|
}
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 读取输入流的所有字节
|
|
|
|
|
+ */
|
|
|
|
|
+ private static byte[] readAllBytes(InputStream inputStream) throws IOException {
|
|
|
|
|
+ ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
|
|
|
|
+ int nRead;
|
|
|
|
|
+ byte[] data = new byte[4096];
|
|
|
|
|
+ while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
|
|
|
|
|
+ buffer.write(data, 0, nRead);
|
|
|
|
|
+ }
|
|
|
|
|
+ buffer.flush();
|
|
|
|
|
+ return buffer.toByteArray();
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
}
|
|
}
|