解决xlsx转pdf方案
文章目录
一、对应版本
1.引入库配置
采用的第三方包,需要手动创建lib文件,将jar放入
对应的包下载链接:链接: Aspose包
<dependencies>
<!-- 自定义引入jar -->
<dependency>
<groupId>com.external</groupId>
<artifactId>aspose-cells</artifactId>
<version>8.5.2</version>
<scope>system</scope>
<systemPath>${pom.basedir}/lib/aspose-cells-8.5.2.jar</systemPath>
</dependency>
<dependency>
<groupId>com.external</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
<scope>system</scope>
<systemPath>${pom.basedir}/lib/aspose-words-15.8.0.jar</systemPath>
</dependency>
</dependencies>
因导入的包类型为system 需要手动设置读取本地包文件
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!--设置为true,以便把本地的system的jar也包括进来-->
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
</plugins>
</build>
包括还有license.xml 不然导出的pdf文件会有水印
<License>
<Data>
<Products>
<Product>Aspose.Total 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>
二、代码部分
代码调用
/**
* linux文字存放地址
*/
@Value("${fontPath}")
private String fontPath;
public static void main(String[] args) {
//pathResource 为读的xlsx文件位置
//fontPath 为字体路径
//outputFileName 文件生成存放位置
//生成的pdf文件
String outputFileName = outputFileLocation + System.currentTimeMillis() + ".pdf";
//读取到已经生成的xls文件进行读取生成pdf文件
PdfAsposeUtil.excel2pdf(pathResource,outputFileName,fontPath);
}
}
PDF转换工具类
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.words.FontSettings;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.*;
import java.util.Map;
@Slf4j
public class PdfAsposeUtil {
public static boolean getLicenseExcel() {
boolean result = false;
InputStream is = null;
try {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
org.springframework.core.io.Resource[] resources = resolver.getResources("classpath:license.xml");
is = resources[0].getInputStream();
com.aspose.cells.License aposeLic = new com.aspose.cells.License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* excel转pdf
*
* @param inpath excel文件地址
* @param outPath pdf地址
*/
public static boolean excel2pdf(String inpath, String outPath,String fontPath) {
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getLicenseExcel()) {
return false;
}
FileOutputStream outputStream = null;
try {
String os = System.getProperty("os.name");
//当前环境:linux系统
if (os != null && os.toLowerCase().startsWith("linux")) {
FontSettings.setFontsFolder(fontPath+File.separator,true);
log.info("linux 执行力设置字体");
}
long old = System.currentTimeMillis();
File file = new File(outPath); // 新建一个空白pdf文档
outputStream = new FileOutputStream(file);
Workbook wb = new Workbook(inpath);// 原始excel路径
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
//当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放,不分页。
pdfSaveOptions.setOnePagePerSheet(true);
wb.save(outputStream, pdfSaveOptions);
long now = System.currentTimeMillis();
System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
return true;
}
/**
* ftl转xsl
* @param templateDir
* @param templateName
* @param excelPath
* @param data
* @throws IOException
* @throws TemplateException
*/
public static void parse(String templateDir, String templateName, String excelPath, Map<String,Object> data) throws IOException, TemplateException {
//初始化工作
Configuration cfg = new Configuration();
//设置默认编码格式为UTF-8
cfg.setDefaultEncoding("UTF-8");
//全局数字格式
cfg.setNumberFormat("0.00");
//设置模板文件位置
cfg.setDirectoryForTemplateLoading(new File(templateDir));
cfg.setObjectWrapper(new DefaultObjectWrapper());
//加载模板
Template template = cfg.getTemplate(templateName,"utf-8");
OutputStreamWriter writer = null;
try{
//填充数据至Excel
writer = new OutputStreamWriter(new FileOutputStream(excelPath),"UTF-8");
template.process(data, writer);
writer.flush();
}finally{
writer.close();
}
}
}
这里会遇到个问题就是关于LINUX环境下 会导致转换时缺少字体的问题需要配置对应的字体
这个时候我们就需要手动配置字体路径
打印字体存放位置
fontPath: /usr/share/fonts/chinese
文字下载链接: 字体下载链接
相关可查看这篇文章: Aspose转pdf乱码问题