- 配置pom.xml
<dependency>
<groupId>com.aspose</groupId>
<artifactId>cells</artifactId>
<version>20.4</version>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>words</artifactId>
<version>20.8</version>
</dependency>
- 加载配置文件及模板
(1)MapMailMergeDataSource.java
/**
* Map结构 IMailMergeDataSource
*/
public class MapMailMergeDataSource implements IMailMergeDataSource {
private List<Map<String, Object>> dataList;
private int index;
//word模板中的«TableStart:tableName»«TableEnd:tableName»对应
private String tableName = null;
/**
* @param dataList 数据集
* @param tableName 与模板中的Name对应
*/
public MapMailMergeDataSource(List<Map<String, Object>> dataList, String tableName) {
this.dataList = dataList;
this.tableName = tableName;
index = -1;
}
/**
* @param data 单个数据集
* @param tableName 与模板中的Name对应
*/
public MapMailMergeDataSource(Map<String, Object> data, String tableName) {
if(this.dataList == null) {
this.dataList = new ArrayList<Map<String,Object>>();
this.dataList.add(data);
}
this.tableName = tableName;
index = -1;
}
/**
* 获取结果集总数
* @return
*/
private int getCount() {
return this.dataList.size();
}
@Override
public IMailMergeDataSource getChildDataSource(String arg0) throws Exception {
return null;
}
@Override
public String getTableName() throws Exception {
return this.tableName;
}
/**
* 实现接口
* 获取当前index指向数据行的数据
* 将数据存入args数组中即可
* @return ***返回false则不绑定数据***
*/
@Override
public boolean getValue(String key, Object[] args) throws Exception {
if(index < 0 || index >= this.getCount()) {
return false;
}
if(args != null && args.length > 0) {
args[0] = this.dataList.get(index).get(key);
return true;
} else {
return false;
}
}
/**
* 实现接口
* 判断是否还有下一条记录
*/
@Override
public boolean moveNext() throws Exception {
index += 1;
if(index >= this.getCount()) {
return false;
}
return true;
}
}
(2)TemplateExportSimpleStrategy.java
@Component
public class TemplateExportSimpleStrategy implements TemplateExportStrategy {
static {
try {
com.aspose.cells.License excellicense = new com.aspose.cells.License();
String excelLicensePath = ResourceUtils.getFile("classpath:license/aspose-cells-8.5.2_license.xml").getPath();
excellicense.setLicense(URLDecoder.decode(excelLicensePath, "UTF-8")); //这是加载Aspose.cells.lic
com.aspose.words.License wordlicense = new com.aspose.words.License();
String wordLicensePath = ResourceUtils.getFile("classpath:license/aspose-words-15.8.0_license.xml").getPath();
wordlicense.setLicense(URLDecoder.decode(wordLicensePath, "UTF-8")); //这是加载Aspose.Words.lic
if (System.getProperty("os.name").toLowerCase().indexOf("windows") == -1 && System.getProperty("os.name").toLowerCase().indexOf("mac") == -1) {// 在linux下加载字体库
FontSettings.setFontsFolder("//usr//share//fonts", true);
}
} catch (Exception e) {
//e.printStackTrace();
//throw new RuntimeException(e.getMessage());
}
}
@Override
public byte[] exportWord(String templateFilePath, List<IMailMergeDataSource> dataSources) throws Exception {
if (dataSources == null ) {
return null;
}
Document doc = new Document(templateFilePath);
MailMerge mailMerge = doc.getMailMerge();
for (IMailMergeDataSource dataSource : dataSources) {
mailMerge.executeWithRegions(dataSource);
}
// 删除未使用的空白域
mailMerge.deleteFields();
ByteArrayOutputStream os = new ByteArrayOutputStream();
doc.save(os,new OoxmlSaveOptions());
return os.toByteArray();
}
}
(3)TemplateExportStrategy.java
/**
* 模板导出接口
*/
public interface TemplateExportStrategy {
/**
* word pdf 导出
* @param templateFilePath 模板文件路径
* @param dataSource 数据源
* @return 文件内容
* @throws Exception 错误信息
*/
byte[] exportWord(String templateFilePath, List<IMailMergeDataSource> dataSource) throws Exception;
}
- license文件(配置授权信息)
<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>授权编码</Signature>
</License>
- 编写工具类
public class PDFUtils {
/**
* Excel转Pdf 帮助类
*
* @author wujunquan
*/
private static boolean getCellLicense() {
boolean result = false;
try {
InputStream is = PDFUtils.class.getClassLoader().getResourceAsStream("license/aspose-cells-8.5.2_license.xml");
License license = new License();
license.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* Word转Pdf 帮助类
*
* @author wujunquan
*/
private static boolean getWordLicense() {
boolean result = false;
try {
InputStream is = PDFUtils.class.getClassLoader().getResourceAsStream("license/aspose-words-15.8.0_license.xml");
License license = new License();
license.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* PPT转Pdf 帮助类
*
* @author wujunquan
*/
private static boolean getPPTLicense() {
boolean result = false;
try {
InputStream is = PDFUtils.class.getClassLoader().getResourceAsStream("license/aspose-slides-19.3_license.xml");
License license = new License();
license.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* @param wordPath 需要被转换的word全路径带文件名
*/
public static File wordToPDF(String wordPath) throws Exception {
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getWordLicense()) {
throw new UserFriendlyException("阅览插件加载失败!");
}
String fileNameSuffix = FileHelper.getFileNameAndSuffix(wordPath);
File file = null;
if (StringUtils.isNotBlank(wordPath) && StringUtils.isNotBlank(fileNameSuffix)){
String PDFPath = wordPath.split(fileNameSuffix)[0];
String fileName = FileHelper.getFileNameByName(fileNameSuffix);
//long old = System.currentTimeMillis();
file = new File(PDFPath + fileName + ".pdf");
if(!file.exists()){
FileOutputStream os = new FileOutputStream(file);
//Address是将要被转化的word文档
Document doc = new Document(wordPath);
//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
doc.save(os, com.aspose.words.SaveFormat.PDF);
os.close();
//long now = System.currentTimeMillis();
//System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
// 返回转化后的PDF文件
}
}
return file;
}
/**
* @param excelPath 需要被转换的excel全路径带文件名
*/
public static File excelToPDF(String excelPath) throws Exception {
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getCellLicense()) {
throw new UserFriendlyException("阅览插件加载失败!");
}
String fileNameSuffix = FileHelper.getFileNameAndSuffix(excelPath);
File file = null;
if (StringUtils.isNotBlank(excelPath) && StringUtils.isNotBlank(fileNameSuffix)) {
String PDFPath = excelPath.split(fileNameSuffix)[0];
String fileName = FileHelper.getFileNameByName(fileNameSuffix);
long old = System.currentTimeMillis();
file = new File(PDFPath + fileName + ".pdf");
if(!file.exists()) {
Workbook wb = new Workbook(excelPath);
FileOutputStream fileOS = new FileOutputStream(file);
wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
fileOS.close();
long now = System.currentTimeMillis();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
// 返回转化后的PDF文件
}
}
return file;
}
/**
* @param pptPath 需要被转换的ppt全路径带文件名
*/
public static File pptToPDF(String pptPath) throws Exception {
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getPPTLicense()) {
throw new UserFriendlyException("阅览插件加载失败!");
}
String fileNameSuffix = FileHelper.getFileNameAndSuffix(pptPath);
File file = null;
if (StringUtils.isNotBlank(pptPath) && StringUtils.isNotBlank(fileNameSuffix)) {
String PDFPath = pptPath.split(fileNameSuffix)[0];
String fileName = FileHelper.getFileNameByName(fileNameSuffix);
long old = System.currentTimeMillis();
Workbook wb = new Workbook(pptPath);
file = new File(PDFPath + fileName + ".pdf");
FileOutputStream fileOS = new FileOutputStream(file);
wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
fileOS.close();
long now = System.currentTimeMillis();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
// 返回转化后的PDF文件
}
return file;
}
}