<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-cells</artifactId>
<version>21.11</version>
</dependency>
<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>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>
</Data>
<Signature>2sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
package com.utils;
import cn.hutool.core.io.IoUtil;
import org.springframework.core.io.ClassPathResource;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Locale;
public class AsposeCellsUtil {
/**
* excel 转 pdf
* @param filePath
* @param outputStream
*/
public static void excelToPdf(String filePath, OutputStream outputStream){
try{
/*Path fileLocation = Paths.get(filePath);
byte[] bytes = Files.readAllBytes(fileLocation);
try (FileOutputStream simpleStream = new FileOutputStream(filePath)) {
simpleStream.write(bytes);
}*/
getCellsLicense();
//设置字体 避免 Linux 下乱码
com.aspose.cells.IndividualFontConfigs configs = new com.aspose.cells.IndividualFontConfigs();
configs.setFontFolders(new String[]{"/usr/share/fonts/", "/usr/share/fonts/chinese/", "C:/Windows/Fonts/"}, false);
com.aspose.cells.LoadOptions loadOptions = new com.aspose.cells.LoadOptions();
loadOptions.setFontConfigs(configs);
loadOptions.setLocale(Locale.CHINA);
//设定 内存设置 默认是 NORMAL
loadOptions.setMemorySetting(com.aspose.cells.MemorySetting.MEMORY_PREFERENCE);
com.aspose.cells.Workbook workbook = new com.aspose.cells.Workbook(filePath, loadOptions);
//设置 自适应行
workbook.getWorksheets().get(0).autoFitRows(true);
workbook.save(outputStream, com.aspose.cells.SaveFormat.PDF);
}catch (Throwable t){
t.printStackTrace();
}
}
public static boolean getCellsLicense() {
boolean result = false;
InputStream is = null;
try {
is = new ClassPathResource("license.xml").getInputStream();
com.aspose.cells.License cellsLic = new com.aspose.cells.License();
cellsLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
IoUtil.close(is);
}
return result;
}
}
注:
如在linux上中文显示方框;是因为linux上面没有安装字体;或者是安装了字体但是用的是docker容器;这个时候需要将字体复制到docker容器内;
1、linux上安装字体
yum install fontconfig
yum -y install ttmkfdir
ttmkfdir -e /usr/share/X11/fonts/encodings/encodings.dir
fc-cache -fv
fc-list
2、字体复制到docker
需要进入当前项目的docker内;将字体和Dockerfile同级存放
编辑dockerfile文件;最后添加字体复制
COPY msyh.ttc /usr/share/fonts/msyh.ttc
COPY simsun.ttc /usr/share/fonts/simsun.ttc
COPY msyhl.ttc /usr/share/fonts/msyhl.ttc
COPY msyhbd.ttc /usr/share/fonts/msyhbd.ttc
至此 linux中文方框可解决