maven依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.27</version>
</dependency>
<dependency>
<groupId>com.luhuiguo</groupId>
<artifactId>aspose-pdf</artifactId>
<version>23.1</version>
</dependency>
<dependency>
<groupId>com.luhuiguo</groupId>
<artifactId>aspose-cells</artifactId>
<version>22.10</version>
</dependency>
FileUtil
import java.io.*;
public class FileUtil {
/**
* 将byte数组转换为InputStream
* @param bytes 待转换的byte数组
* @return InputStream对象
* @throws IOException 转换异常
*/
public static InputStream byteArrayToInputStream(byte[] bytes) throws IOException {
if(bytes == null) {
return null;
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
return inputStream;
}
//将文件转换成Byte数组
public static byte[] getBytesByFile(String pathStr) {
File file = new File(pathStr);
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
byte[] data = bos.toByteArray();
bos.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//将Byte数组转换成文件
public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.getParentFile().exists()){
//文件夹不存在 生成
dir.getParentFile().mkdirs();
}
file = new File(filePath + "\\" + fileName);
if (!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
DocTOPdfUtil
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.pdf.License;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
@Slf4j
public class DocTOPdfUtil {
//去除文件水印 在项目的 resources 下
private static final String FOP_EXL = "/file/excel-license.xml";
/**
* excel 转 pdf
*
* @param excelFilePath excel文件路径
*/
public static void excel2pdf(String excelFilePath) {
excel2pdf(excelFilePath, null, null);
}
/**
* excel 转 pdf
*
* @param excelFilePath excel文件路径
* @param convertSheets 需要转换的sheet
*/
public static void excel2pdf(String excelFilePath, int[] convertSheets) {
excel2pdf(excelFilePath, null, convertSheets);
}
/**
* excel 转 pdf
*
* @param excelFilePath excel文件路径
* @param pdfFilePath pdf文件路径
*/
public static void excel2pdf(String excelFilePath, String pdfFilePath) {
excel2pdf(excelFilePath, pdfFilePath, null);
}
/**
* excel 转 pdf
*
* @param inputStream exl流
* @param pdfFilePath pdf文件路径
*/
public static void excel2pdf(InputStream inputStream, String pdfFilePath) {
excel2pdf(inputStream, pdfFilePath, null);
}
/**
* excel 转 pdf
*
* @param inputStream exl流
* @param convertSheets 需要的sheet
*/
public static InputStream excel2pdf(InputStream inputStream, int[] convertSheets) {
return excel2pdf1(inputStream, convertSheets);
}
/**
* excel 转 pdf
*
* @param excelFilePath excel文件路径
* @param pdfFilePath pdf文件路径
* @param convertSheets 需要转换的sheet
*/
public static void excel2pdf(String excelFilePath, String pdfFilePath, int[] convertSheets) {
FileOutputStream fileOs = null;
try {
pdfFilePath = pdfFilePath == null ? getPdfFilePath(excelFilePath) : pdfFilePath;
// 验证 License
getLicenseExl();
Workbook wb = new Workbook(excelFilePath);
fileOs = new FileOutputStream(pdfFilePath);
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(true);
int[] autoDrawSheets={3};
autoDraw(wb,autoDrawSheets);
if (null != convertSheets) {
printSheetPage(wb, convertSheets);
}
wb.save(fileOs, pdfSaveOptions);
fileOs.flush();
System.out.println("convert success");
} catch (Exception e) {
System.out.println("convert failed");
e.printStackTrace();
} finally {
try {
assert fileOs != null;
fileOs.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
* excel 转 pdf
*
* @param inputStream exl流
* @param pdfFilePath pdf文件路径
* @param convertSheets 需要转换的sheet
*/
public static void excel2pdf(InputStream inputStream, String pdfFilePath, int[] convertSheets) {
FileOutputStream fileOs = null;
try {
// 验证 License
getLicenseExl();
Workbook wb = new Workbook(inputStream);
fileOs = new FileOutputStream(pdfFilePath);
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setMergeAreas(true);
//缩放到一个页面(如果列太多 太长)
pdfSaveOptions.setOnePagePerSheet(true);
// pdfSaveOptions.setCalculateFormula(true);
// pdfSaveOptions.setCheckFontCompatibility(true);
// pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
// pdfSaveOptions.setEmbedStandardWindowsFonts(true);
// pdfSaveOptions.setFontSubstitutionCharGranularity(true);
// pdfSaveOptions.setRefreshChartCache(true);
// pdfSaveOptions.setClearData(true);
// int[] autoDrawSheets={3};
// autoDraw(wb,autoDrawSheets);
if (null != convertSheets) {
printSheetPage(wb, convertSheets);
}
wb.save(fileOs, pdfSaveOptions);
fileOs.flush();
} catch (Exception e) {
System.out.println("convert failed");
e.printStackTrace();
} finally {
try {
inputStream.close();
assert fileOs != null;
fileOs.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
log.info("exl转pdf结束");
}
}
/**
* @param wb 设置打印的sheet自动拉伸比例
* @param page 自动拉伸的页的sheet数组
*/
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();
}
}
}
/**
* excel 转 pdf 返回文件流
*
* @param inputStream exl文件流
* @param convertSheets 需要转换的 sheet
* @return 文件流
*/
public static InputStream excel2pdf1(InputStream inputStream, int[] convertSheets) {
ByteArrayOutputStream fileOs = null;
try {
// 验证 License
getLicenseExl();
Workbook wb = new Workbook(inputStream);
fileOs = new ByteArrayOutputStream();
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(true);
if (null != convertSheets) {
printSheetPage(wb, convertSheets);
}
wb.save(fileOs, pdfSaveOptions);
fileOs.flush();
return new ByteArrayInputStream(fileOs.toByteArray());
} catch (Exception e) {
System.out.println("convert failed");
e.printStackTrace();
} finally {
try {
inputStream.close();
if (fileOs != null) {
fileOs.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
log.info("exl转pdf结束");
}
return null;
}
/**
* 获取 生成的 pdf 文件路径,默认与源文件同一目录
*
* @param excelFilePath excel文件
* @return 生成的 pdf 文件
*/
private static String getPdfFilePath(String excelFilePath) {
return excelFilePath.split(".")[0] + ".pdf";
}
/**
* 隐藏workbook中不需要的sheet页。
*
* @param sheets 显示页的sheet数组
*/
private static void printSheetPage(Workbook wb, int[] sheets) {
for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
wb.getWorksheets().get(i).setVisible(false);
}
if (null == sheets || sheets.length == 0) {
wb.getWorksheets().get(0).setVisible(true);
} else {
for (int i = 0; i < sheets.length; i++) {
wb.getWorksheets().get(i).setVisible(true);
}
}
}
/**
* 获取 license 去除水印
* 若不验证则转化出的pdf文档会有水印产生
*/
private static void getLicenseExl() {
try {
String s = "<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>";
ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
com.aspose.cells.License aposeLic = new com.aspose.cells.License();
aposeLic.setLicense(is);
} catch (Exception e) {
e.printStackTrace();
}
// InputStream is = null;
// try {
// ClassPathResource classPathResource = new ClassPathResource(FOP_EXL);
// is = classPathResource.getInputStream();
// License license = new License();
// license.setLicense(is);
// } catch (Exception e) {
// System.out.println("license verify failed");
// e.printStackTrace();
// } finally {
// try {
// if (is != null) {
// is.close();
// }
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
}
}
Pdf2JpgUtil
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class Pdf2JpgUtil {
public static List<byte[]> pdfToImageFile(byte[] inFileByte) throws Exception {
PDDocument doc = null;
ByteArrayOutputStream os = null;
InputStream stream = null;
OutputStream out = null;
List<byte[]> resultList = new ArrayList<>();
try {
// 加载解析PDF文件
doc = PDDocument.load(inFileByte);
PDFRenderer pdfRenderer = new PDFRenderer(doc);
PDPageTree pages = doc.getPages();
int pageCount = pages.getCount();
for (int i = 0; i < pageCount; i++) {
BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200);
os = new ByteArrayOutputStream();
ImageIO.write(bim, "jpg", os);
byte[] dataList = os.toByteArray();
resultList.add(dataList);
// jpg文件转出路径
// File file = new File(outFilePath+"\\"+ UUID.randomUUID() +".jpg");
// if (!file.getParentFile().exists()) {
// // 不存在则创建父目录及子文件
// file.getParentFile().mkdirs();
// file.createNewFile();
// }
// out = new FileOutputStream(file);
// out.write(dataList);
}
return resultList;
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (doc != null) doc.close();
if (os != null) os.close();
if (stream != null) stream.close();
if (out != null) out.close();
}
}
}