网上找了很多的方案,最后还是使用Apache POI + itext7适合一些,因为项目要部署在linux环境上,话不多说,直接步入整体。
一、引入相关依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<!-- 引入 itext7-core 依赖 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.16</version>
<type>pom</type>
</dependency>
二、上代码:
package com.example.filterandinterceptor.utils;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* @author xiechenyu
* @Description:
* @date 2024/5/22 9:27
*/
public class ConvertPdfUtil {
private final List<String> allowedFileExtensions = Arrays.asList("xls", "xlsx", "doc", "docx");
private void convertToPdf(MultipartFile file) throws Exception {
String originalFilename = file.getOriginalFilename();
if (Objects.isNull(originalFilename)) {
throw new RuntimeException("请上传正确文件");
}
checkFileExtensions(originalFilename);
// 转换为PDF文件
}
private void checkFileExtensions(String originalFilename) {
String fileExtension = getFileExtension(originalFilename);
if (!allowedFileExtensions.contains(fileExtension)) {
throw new RuntimeException("文件格式不正确,支持转换为PDF文件的格式有:xls、xlsx、doc、docx");
}
}
private static String getFileExtension(String filename) {
if (filename.lastIndexOf('.') != -1 && filename.lastIndexOf('.') != 0) {
return filename.substring(filename.lastIndexOf('.') + 1);
} else {
return "";
}
}
//word文件转pdf,支持doc,docx
public static void wordToPdf(String inFilePath, String outFilePath) {
try (PdfDocument pdf = new PdfDocument(new PdfWriter(Files.newOutputStream(Paths.get(outFilePath))));
Document pdfDocument = new Document(pdf, PageSize.A4.rotate());) {
//指定pdf的字体样式为STSong-Light,编码方式为UniGB-UCS2-H,不指定编码方式中文乱码
PdfFont pdfFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");
// 文件输入流读取文件
InputStream in = Files.newInputStream(Paths.get(inFilePath));
// 读取Word文档
XWPFDocument word = new XWPFDocument(in);
// 逐段写入PDF
for (XWPFParagraph paragraph : word.getParagraphs()) {
pdfDocument.add(new Paragraph(paragraph.getText()).setFont(pdfFont));
}
}catch (IOException e){
throw new RuntimeException(e);
}
}
//excel文件转pdf,支持xsl,xslx
public static void excelToPdf(String inFilePath, String outFilePath) {
try (PdfDocument pdf = new PdfDocument(new PdfWriter(Files.newOutputStream(Paths.get(outFilePath))));
Document document = new Document(pdf, PageSize.A4.rotate());) {
//指定pdf的字体样式为STSong-Light,编码方式为UniGB-UCS2-H
PdfFont pdfFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");
// 文件输入流读取文件
InputStream in = Files.newInputStream(Paths.get(inFilePath));
//excel文件类型有xls和xlsx两种,对应的构造器不一样
String fileExtension = getFileExtension(inFilePath);
Workbook workbook = Objects.equals(fileExtension, ".xsl") ? new HSSFWorkbook(in) : new XSSFWorkbook(in);
int numberOfSheets = workbook.getNumberOfSheets();
for (int k = 0; k < numberOfSheets; k++) {
Sheet sheet = workbook.getSheetAt(k);
//获取总列数
int column = getMaxColumn(sheet);
//创建一个pdf的table对象,以便在pdf中以表的形式展示,列数和excel列数一致
Table table = new Table(column);
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
for (int j = 0; j < column; j++) {
String str = "";
//获取excel单元格
Row row = sheet.getRow(i);
if (Objects.isNull(row)) {
continue;
}
org.apache.poi.ss.usermodel.Cell cell = row.getCell(j);
if (Objects.nonNull(cell)) {
if (cell.getCellTypeEnum() == CellType.NUMERIC) {
str = (int) cell.getNumericCellValue() + "";
} else {
str = cell.getStringCellValue();
}
}
//将pdf的单元格初始化并添加到pdf中
Cell cells = new Cell().setFont(pdfFont).add(new Paragraph(str));
table.addCell(cells);
}
}
//两个table之间增加一个空格
document.add(new Paragraph(" "));
document.add(table);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static int getMaxColumn(Sheet sheet) {
int maxColumn = 0;
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
if (Objects.nonNull(sheet.getRow(i))) {
maxColumn = Math.max(maxColumn, sheet.getRow(i).getLastCellNum());
}
}
return maxColumn;
}
public static void main(String[] args) {
// excelToPdf("D:\\convertfile\\慢查询SQL.xlsx", "D:\\convertfile\\慢查询SQL.pdf");
wordToPdf("D:\\convertfile\\测试 - 副本.doc", "D:\\convertfile\\测试 - 副本.pdf");
}
}