1、jar包
<dependency>
<groupId>com.aspose.cells</groupId>
<artifactId>aspose-cells</artifactId>
<version>8.5.2</version>
</dependency>
2、在根目录放:license.xml
具体资源请下载:
https://download.csdn.net/download/gzc_870301/12403483
/**
*@description excel转pdf 解决折叠问题(列太多)
* @author gezc30201
* @date 2020/5/9
*/
@Slf4j
public class ExcelToPdfUtil {
/**
*@description 获取license 去除水印
* @return
* @author gezc30201
* @date 2020/5/9
*/
public static boolean getLicense() {
boolean result = false;
try {
InputStream is = ExcelToPdfUtil.class.getClassLoader().getResourceAsStream("\\license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
*@description excel 转为pdf 输出。
* @param sourceFilePath excel文件
* @param desFilePathd pad 输出文件目录
* @return void
* @author gezc30201
* @date 2020/5/9
*/
public static void excel2pdf(String sourceFilePath, String desFilePathd ){
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
Workbook wb = new Workbook(sourceFilePath); // 原始excel路径
FileOutputStream fileOS = new FileOutputStream(desFilePathd);
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(true);//缩放到一个页面(如果列太多 太长)
/**
* 自动缩放了
*/
/* int[] autoDrawSheets={3};
//当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
autoDraw(wb,autoDrawSheets);*/
/**
* 以下代码打开则只显示第一个sheet
*/
/*int[] showSheets={0};
//隐藏workbook中不需要的sheet页。
printSheetPage(wb,showSheets);*/
wb.save(fileOS, pdfSaveOptions);
fileOS.flush();
fileOS.close();
} catch (Exception e) {
log.error(ExceptionUtils.getTrace(e));
throw new RuntimeException();
}
}
/**
*@description 描述
* @param inbytes excel输入流的字节数组
* @return byte[]
* @author gezc30201
* @date 2020/5/9
*/
public static byte[] excel2pdf(byte[] inbytes ) throws IOException {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return null;
}
ByteArrayOutputStream pdfstream=null;
try {
Workbook wb = new Workbook(new ByteArrayInputStream(inbytes));// 原始excel流
pdfstream = new ByteArrayOutputStream(); //保存转成pdf的流
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(true);//缩放到一个页面(如果列太多 太长)
wb.save(pdfstream, pdfSaveOptions);
byte[] outbytes = pdfstream.toByteArray();
return outbytes;
} catch (Exception e) {
log.error(ExceptionUtils.getTrace(e));
throw new RuntimeException();
}finally {
if (pdfstream!=null){
pdfstream.close();
}
}
}
/**
*@description 设置打印的sheet 自动拉伸比例
* @param wb
* @param page 自动拉伸的页的sheet数组
* @return void
* @author gezc30201
* @date 2020/5/9
*/
public static void autoDraw(Workbook wb, int[] page){
if (null!=page&&page.length>0){
for (int i = 0; i < page.length; i++) {
wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
}
}
}
/**
* 隐藏workbook中不需要的sheet页。
* @param wb
* @param page 显示页的sheet数组
*/
public static void printSheetPage(Workbook wb, int[] page){
for (int i= 1; i < wb.getWorksheets().getCount(); i++) {
wb.getWorksheets().get(i).setVisible(false);
}
if (null==page||page.length==0){
wb.getWorksheets().get(0).setVisible(true);
}else{
for (int i = 0; i < page.length; i++) {
wb.getWorksheets().get(i).setVisible(true);
}
}
}
/*public static void main(String[] args) {
String sourceFilePath="d:/test.xlsx";
String desFilePath="d:/rest.pdf";
excel2pdf(sourceFilePath, desFilePath);
}*/
}
controller:
@GetMapping("/previewAttach")
public void previewAttach(HttpServletResponse response, @RequestParam(value = "attach_id") String attachId) {
DownloadAttach downloadAttach = sysAttachService.downloadAttach(attachId).getResult();
if (downloadAttach == null || downloadAttach.getBytes() == null) {
log.warn("附件获取为空。附件id:" + attachId.replaceAll("[\r\n]", ""));
throw new BaseBizException("-1", "附件不存在");
}
/*if (!".pdf".equals(downloadAttach.getFileSuffix())){6
throw new BaseBizException("-1", "只有PDF可以预览");
}*/
if (!DocEnum.PDF.getPointSuffix().equals(downloadAttach.getFileSuffix())&&!DocEnum.XLS.getPointSuffix().equals(downloadAttach.getFileSuffix())&&!DocEnum.XLSX.getPointSuffix().equals(downloadAttach.getFileSuffix())){
try {
downloadAttach.setBytes(Doc2PdfUtil.doc2pdf(downloadAttach.getFileSuffix().substring(1),downloadAttach.getBytes()));
} catch (Exception e) {
log.error(ExceptionUtils.getTrace(e));
throw new BaseBizException("-1", "openoffice服务连接不上或者转换pdf失败");
}
}
if (DocEnum.XLS.getPointSuffix().equals(downloadAttach.getFileSuffix())||DocEnum.XLSX.getPointSuffix().equals(downloadAttach.getFileSuffix())){
try {
downloadAttach.setBytes(ExcelToPdfUtil.excel2pdf(downloadAttach.getBytes()));
} catch (IOException e) {
log.error(ExceptionUtils.getTrace(e));
throw new BaseBizException("-1", "excel转换pdf失败");
}
}
OutputStream os = null;
try {
response.setHeader("content-length", String.valueOf(downloadAttach.getBytes().length));
// 预览
response.setContentType("application/pdf;charset=utf-8");
response.setHeader("content-disposition", "inline;filename=" +
java.net.URLEncoder.encode(downloadAttach.getFileName(), "UTF-8"));
os = response.getOutputStream();
//os.write(downloadAttach.getBytes(),0,downloadAttach.getBytes().length);
int lens = downloadAttach.getBytes().length;
int flag = 0;
while (lens > 0){
os.write(Arrays.copyOfRange(downloadAttach.getBytes(),flag * DOWNLOAD_LENS,(lens > DOWNLOAD_LENS) ? (flag + 1) * DOWNLOAD_LENS : (flag * DOWNLOAD_LENS + lens)));
flag ++;
log.info(flag);
lens -= DOWNLOAD_LENS;
}
} catch (Exception e) {
log.error("预览附件报错。附件id:" + attachId.replaceAll("[\r\n]", ""));
log.error(ExceptionUtils.getTrace(e));
} finally {
if (os != null) {
try {
os.flush();
os.close();
} catch (IOException e) {
log.error(ExceptionUtils.getTrace(e));
}
}
}
}
预览效果如下,后面的下面没有缺失数据 是我没填