前言
word转pdf 在网上找了很多,就这版能用,其他的试过可惜都失败了 先下载jar maven仓库找不到 链接: https://pan.baidu.com/s/13TIfBGFDgDJlxVonzUpgQQ 提取码: sbkg
一、jar放到本地仓库里面
<dependency>
<groupId>com.aspose</groupId>
<artifactId>words</artifactId>
<version>15.8.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
mvn install:install-file -Dfile="E:\安装包\Java\aspose-words-15.8.0-jdk16.jar" -DgroupId=com.aspose -DartifactId=words -Dversion=15.8.0 -Dpackaging=jar
-Dfile是你下载jar的本地路径 -DgroupId 是dependency里的groupId -DartifactId是dependency里的artifactId -Dversion是dependency里的version
二、使用步骤
1.引入license.xml
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
自己创建license.xml文件到resources下任意位置
2.pdfUtil工具类
package com.pcitc.common.util;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@Slf4j
public class PdfUtil {
/**
* 读取监听文件去水印
*
* @return boolean
*/
public static boolean getLicense() {
boolean result = false;
try {
// license.xml应放在..\WebRoot\WEB-INF\classes路径下
InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 生成pdf文档
*
* @param Address 地址
*/
public static void doc2pdf(String Address) {
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getLicense()) {
return;
}
try {
//新建一个空白pdf文档
long old = System.currentTimeMillis();
File file = new File("E:\\\\石英工作\\\\EP-SERVER\\\\ep-service\\\\ep-swm\\\\ep-swm-service\\\\src\\\\main\\\\resources\\\\template\\\\SolidWasteApplyTemplate.pdf");
FileOutputStream os = new FileOutputStream(file);
//Address是将要被转化的word文档
Document doc = new Document(Address);
//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
doc.save(os, SaveFormat.PDF);
long now = System.currentTimeMillis();
//转化用时
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 把xwpfDocument转成pdf
*
* @param xwpfDocument xwpf文档
* @param pdfPath pdf
*/
public static void docToPdf(XWPFDocument xwpfDocument, String pdfPath){
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getLicense()) {
return;
}
try {
//新建一个空白pdf文档
FileOutputStream os = new FileOutputStream(pdfPath);
//Address是将要被转化的word文档
//二进制OutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//文档写入流
xwpfDocument.write(baos);
//OutputStream写入InputStream二进制流
InputStream in = new ByteArrayInputStream(baos.toByteArray());
Document doc = new Document(in);
//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
doc.save(os, SaveFormat.PDF);
log.info("导出成功");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 导出文件为pdf
*
* @param file 文件
* @param s 年代
* @param response 响应
*/
public static void covertDocToPdf(String file, String fileName, HttpServletResponse response) {
response.setContentType("application/pdf");
try {
// 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
response.setCharacterEncoding("UTF-8");
response.setContentType("application/pdf");
//打开浏览器窗口预览文件
// response.setHeader("Content-Disposition","filename=" + new String(fileName.getBytes(), "iso8859-1"));
//直接下载
file_name = java.net.URLEncoder.encode(file_name, "UTF-8");
response.setHeader("Content-Disposition","attachment;filename=" + file_name);
} catch (Exception e) {
e.printStackTrace();
}
OutputStream os = null;
PdfStamper ps = null;
PdfReader reader = null;
try {
os = response.getOutputStream();
// 2 读入pdf表单(给予导出表单pdf的文件miing)
reader = new PdfReader(file);
// 3 根据表单生成一个新的pdf
ps = new PdfStamper(reader, os);
// 4 获取pdf表单
AcroFields form = ps.getAcroFields();
// 5给表单添加中文字体 这里采用系统字体。不设置的话,中文可能无法显示
// BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",
// BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//这边设置pdf字体,可以更改字体的格式
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
form.addSubstitutionFont(bf);
ps.setFormFlattening(true);
} catch (Exception e) {
} finally {
try {
ps.close();
reader.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
生成pdf文档测试
public static void main(String[] args) {
PdfUtil.doc2pdf("E:\\石英工作\\EP-SERVER\\ep-service\\ep-swm\\ep-swm-service\\src\\main\\resources\\template\\鹅鹅鹅固废申请信息单.docx");
}
3.word工具类
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
package com.pcitc.common.util;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
/**
* @author shengren.yan
* @create 2021-06-30
*/
public class WordlUtiles {
/**
* word 导出
*
* @param fileName
* @param response
* @param document
*/
public static void downLoadWord(String fileName, HttpServletResponse response, XWPFDocument document) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/msword");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
document.write(response.getOutputStream());
} catch (IOException e) {
//throw new NormalException(e.getMessage());
}
}
public static InputStream getResourcesFileInputStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
}
}
4.word转pdf并导出
由于没有时间研究,只能生成pdf到本地再导出
/**
* 导出(pdf) 固废申请ID”导出数据
*
* @param response
* @param solidWasteApplyId 固废申请ID
* @throws Exception
*/
@GetMapping("exportWord")
@ApiOperation(value = "导出(Word)", notes = "参数:固废申请ID")
public void getWord(HttpServletResponse response, @ApiParam(name = "solidWasteApplyId", value = "固废申请ID") @RequestParam @NotEmpty(message = "不可为空") Long solidWasteApplyId) throws Exception {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd hh:mm");
SolidWasteApplyEntity entity = solidWasteApplyAndPrcService.detail(solidWasteApplyId);
Map<String, Object> map = new HashMap<String, Object>();
map.put("deptName", entity.getDeptShow());
XWPFDocument doc = WordExportUtil.exportWord07("template/SolidWasteApplyTemplate.docx", map);
// 导出word
// WordlUtiles.downLoadWord("固废申请信息单.docx", response, doc);
// pdf 地址
String pdfPath1 = confyml.getPdfPath()+"SolidWasteApplyTemplate.pdf";
PdfUtil.docToPdf(doc,pdfPath1);
PdfUtil.covertDocToPdf(pdfPath1, entity.getSolidWasteName() + "固废申请信息单.pdf", response);
}
5.linux配置字体
主要是: FontSettings.setFontsFolder("/usr/share/fonts",true);
yum install -y fontconfig mkfontscale
cd /usr/share/fonts目录
把windows机器中 C:\Windows\Fonts里面的内容,全部拷贝到linux的上述目录(/usr/share/fonts中)
mkfontscale
mkfontdir
fc-cache
最后再linux中执行上述代码,就可以解决乱码问题。
6.我的word模板
链接: https://pan.baidu.com/s/1NE2TXqanaJsxdQw6E9yRkQ 提取码: kvmc 里面的{{fe: pList t.aproUserName 循环list放入
三、未完待续
就到这,有时间弄一个不用下载到本地直接导出pdf
|