maven需要的jar包
<!-- excel转pdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
<!-- hutool工具类 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.7</version>
</dependency>
excel转pdf需要的工具类
package com.fehorizon.oversea.oa.util.ecxelToPdf;
import com.itextpdf.text.pdf.BaseFont;
import java.util.HashMap;
import java.util.Map;
/**
* 读取字体
*/
public class FontGenerater {
// 符号
public final static String EMPTY = "";
public final static String FXG = "\\";
public final static String DIAN = ".";
//for report
public final static String HG = "-";
public final static String REPORT_UNDERLINE = "<r_u>";
public final static String REPORT_UNDERLINE_SUFFIX = "</r_u>";
public final static String NORMAL_CHAR_SET = "UTF-8";
// font
public static final short FONT_SMALL_SIZE = 8;
public static final int FONT_SMALL_VALUELENGTH = 12;
public static String FONT_URL = EMPTY;
public static Map FONTMAP = null;
public static final String FONT_HWXK_NAME = "华文行楷";
public static final String FONT_HWXK = "/STXINGKA.TTF";
public static final String FONT_FS_NAME = "仿宋";
public static final String FONT_FS_NAME_PINYIN = "FangSong";
public static final String FONT_FS = "\\simfang.ttf";
public static final String FONT_CALIBRI_NAME = "Calibri";
public static final String FONT_CALIBRI = "\\calibri.ttf";
public static final String FONT_CONSOLAS_NAME = "Consolas";
public static final String FONT_CONSOLAS = "\\consola.ttf";
public static final String FONT_DENGXIAN_NAME = "等线";
public static final String FONT_DENGXIAN = "\\Deng.ttf";
public static final String FONT_SONTI_NAME = "宋体";
public static final String FONT_SONTI = "\\simsun.ttc,0";
public static BaseFont getFont(String name) {
if (FONTMAP == null) {
FONT_URL = "C:\\Windows\\Fonts";
FONTMAP = new HashMap<String, BaseFont>() {{
try {
put(FONT_SONTI_NAME, BaseFont.createFont(FONT_URL + FONT_SONTI, BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
put(FONT_HWXK_NAME, BaseFont.createFont(FONT_URL + FONT_HWXK, BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
put(FONT_FS_NAME, BaseFont.createFont(FONT_URL + FONT_FS, BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
put(FONT_FS_NAME_PINYIN, BaseFont.createFont(FONT_URL + FONT_FS, BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
put(FONT_CALIBRI_NAME, BaseFont.createFont(FONT_URL + FONT_CALIBRI, BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
put(FONT_CONSOLAS_NAME, BaseFont.createFont(FONT_URL + FONT_CONSOLAS, BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
put(FONT_DENGXIAN_NAME, BaseFont.createFont(FONT_URL + FONT_DENGXIAN, BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
} catch (Exception e) {
}
}};
}
return (BaseFont) FONTMAP.get(name);
}
}
package com.fehorizon.oversea.oa.util.ecxelToPdf;
public class PicturesInfo {
private int minRow;
private int maxRow;
private int minCol;
private int maxCol;
private String ext;
private byte[] pictureData;
public PicturesInfo(int minRow, int maxRow, int minCol, int maxCol, byte[] pictureData, String ext) {
this.minRow = minRow;
this.maxRow = maxRow;
this.minCol = minCol;
this.maxCol = maxCol;
this.ext = ext;
this.pictureData = pictureData;
}
public byte[] getPictureData() {
return pictureData;
}
public void setPictureData(byte[] pictureData) {
this.pictureData = pictureData;
}
public int getMinRow() {
return minRow;
}
public void setMinRow(int minRow) {
this.minRow = minRow;
}
public int getMaxRow() {
return maxRow;
}
public void setMaxRow(int maxRow) {
this.maxRow = maxRow;
}
public int getMinCol() {
return minCol;
}
public void setMinCol(int minCol) {
this.minCol = minCol;
}
public int getMaxCol() {
return maxCol;
}
public void setMaxCol(int maxCol) {
this.maxCol = maxCol;
}
public String getExt() {
return ext;
}
public void setExt(String ext) {
this.ext = ext;
}
}
package com.fehorizon.oversea.oa.util.ecxelToPdf;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.*;
import java.util.ArrayList;
import java.util.List;
public class POIExtend {
public static List<PicturesInfo> getAllPictureInfos(Sheet sheet, boolean onlyInternal) throws Exception {
return getAllPictureInfos(sheet, null, null, null, null, onlyInternal);
}
public static List<PicturesInfo> getAllPictureInfos(Sheet sheet, Integer minRow, Integer maxRow, Integer minCol,
Integer maxCol, boolean onlyInternal) throws Exception {
if (sheet instanceof HSSFSheet) {
return getXLSAllPictureInfos((HSSFSheet) sheet, minRow, maxRow, minCol, maxCol, onlyInternal);
} else if (sheet instanceof XSSFSheet) {
return getXLSXAllPictureInfos((XSSFSheet) sheet, minRow, maxRow, minCol, maxCol, onlyInternal);
} else {
throw new Exception("未处理类型,没有为该类型添加:GetAllPicturesInfos()扩展方法!");
}
}
private static List<PicturesInfo> getXLSAllPictureInfos(HSSFSheet sheet, Integer minRow, Integer maxRow,
Integer minCol, Integer maxCol, Boolean onlyInternal) {
List<PicturesInfo> picturesInfoList = new ArrayList<>();
HSSFShapeContainer shapeContainer = sheet.getDrawingPatriarch();
if (null != shapeContainer) {
List<HSSFShape> shapeList = shapeContainer.getChildren();
for (HSSFShape shape : shapeList) {
if (shape instanceof HSSFPicture && shape.getAnchor() instanceof HSSFClientAnchor) {
HSSFPicture picture = (HSSFPicture) shape;
HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
if (isInternalOrIntersect(minRow, maxRow, minCol, maxCol, anchor.getRow1(), anchor.getRow2(),
anchor.getCol1(), anchor.getCol2(), onlyInternal)) {
picturesInfoList.add(
new PicturesInfo(anchor.getRow1(), anchor.getRow2(), anchor.getCol1(), anchor.getCol2(),
picture.getPictureData().getData(), picture.getPictureData().getMimeType()));
}
}
}
}
return picturesInfoList;
}
private static List<PicturesInfo> getXLSXAllPictureInfos(XSSFSheet sheet, Integer minRow, Integer maxRow,
Integer minCol, Integer maxCol, Boolean onlyInternal) {
List<PicturesInfo> picturesInfoList = new ArrayList<>();
List<POIXMLDocumentPart> documentPartList = sheet.getRelations();
for (POIXMLDocumentPart documentPart : documentPartList) {
if (documentPart instanceof XSSFDrawing) {
XSSFDrawing drawing = (XSSFDrawing) documentPart;
List<XSSFShape> shapes = drawing.getShapes();
for (XSSFShape shape : shapes) {
if (shape instanceof XSSFPicture) {
XSSFPicture picture = (XSSFPicture) shape;
// XSSFClientAnchor anchor = picture.getPreferredSize();
XSSFClientAnchor anchor = picture.getClientAnchor();
if (isInternalOrIntersect(minRow, maxRow, minCol, maxCol, anchor.getRow1(), anchor.getRow2(),
anchor.getCol1(), anchor.getCol2(), onlyInternal)) {
picturesInfoList.add(new PicturesInfo(anchor.getRow1(), anchor.getRow2(), anchor.getCol1(),
anchor.getCol2(), picture.getPictureData().getData(),
picture.getPictureData().getMimeType()));
}
}
}
}
}
return picturesInfoList;
}
private static boolean isInternalOrIntersect(Integer rangeMinRow, Integer rangeMaxRow, Integer rangeMinCol,
Integer rangeMaxCol, int pictureMinRow, int pictureMaxRow, int pictureMinCol, int pictureMaxCol,
Boolean onlyInternal) {
int _rangeMinRow = rangeMinRow == null ? pictureMinRow : rangeMinRow;
int _rangeMaxRow = rangeMaxRow == null ? pictureMaxRow : rangeMaxRow;
int _rangeMinCol = rangeMinCol == null ? pictureMinCol : rangeMinCol;
int _rangeMaxCol = rangeMaxCol == null ? pictureMaxCol : rangeMaxCol;
if (onlyInternal) {
return (_rangeMinRow <= pictureMinRow && _rangeMaxRow >= pictureMaxRow && _rangeMinCol <= pictureMinCol
&& _rangeMaxCol >= pictureMaxCol);
} else {
return ((Math.abs(_rangeMaxRow - _rangeMinRow) + Math.abs(pictureMaxRow - pictureMinRow) >= Math
.abs(_rangeMaxRow + _rangeMinRow - pictureMaxRow - pictureMinRow))
&& (Math.abs(_rangeMaxCol - _rangeMinCol) + Math.abs(pictureMaxCol - pictureMinCol) >= Math
.abs(_rangeMaxCol + _rangeMinCol - pictureMaxCol - pictureMinCol)));
}
}
}
调用工具类生成pdf后返回给前端
package com.fehorizon.oversea.oa.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fehorizon.oversea.oa.po.excelToPdf.RentalOrders;
import com.fehorizon.oversea.oa.po.excelToPdf.SalesOrders;
import com.fehorizon.oversea.oa.po.excelToPdf.SalesOrdersRepeatingTable;
import com.fehorizon.oversea.oa.util.ecxelToPdf.ExcelToPdfUtil;
import com.fehorizon.oversea.oa.util.http.FilesUtils;
import com.fehorizon.oversea.oa.util.http.HttpUtils;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.commons.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@Slf4j
@RequestMapping("/api/ExcelToPdf")
public class ExcelToPdf {
private final Logger logger = LoggerFactory.getLogger(ExcelToPdf.class);
/**
*
* @param fileCtrl
* @param account 上传文件的用户账号
* @param taskId 上传文件的任务ID
* @param activityId 上传文件的流程节点ID
* @param stepName 上传文件的流程流程节点名称
* @param salesOrders 表格所需要的数据对象
* @return
*/
@RequestMapping(value = "/getSalesPdfFileUrl" , method =RequestMethod.POST)
public String getSalesPdfFileUrl(@RequestParam(value = "fileCtrl") String fileCtrl ,
@RequestParam(value = "account") String account,
@RequestParam(value = "taskId") String taskId,
@RequestParam(value = "activityId") String activityId,
@RequestParam(value = "stepName") String stepName,
@RequestBody(required = false) SalesOrders salesOrders,
HttpServletResponse response ){
//String classpath = this.getClass().getClassLoader().getResource("templates").getPath();
InputStream inputStreamTemplate = this.getClass().getResourceAsStream("/templates/Sales Orders.xlsx");
//logger.info(classpath);
XSSFWorkbook workbook = null;
// try {
// classpath = URLDecoder.decode(classpath,"utf-8"); //显示中文了
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException(e);
// }
try {
workbook = new XSSFWorkbook(inputStreamTemplate);
//获取第一个sheet 的excel文本
Sheet sheet0 = workbook.getSheetAt(0);
// 第1个参数是指要开始插入的行,第2个参数是结尾行数,第三个参数表示动态添加的行数
// sheet.getLastRowNum() 可以自动的根据新增行数代码进行后移,maven poi jar包版本可能会影响,本项目版本为4.1.1
// 如果第二个参数结尾行数填的行数大小小于内容行数,位新增行后面的内容可能会被覆盖
sheet0.shiftRows(15, sheet0.getLastRowNum() , salesOrders.getDatas().size() -3, true, false);
//设置参数样式
CellStyle cellStyle = workbook.createCellStyle();
//设置边框样式
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
//循环给excel中赋值以及添加样式
for (int i = 0; i < salesOrders.getDatas().size(); i++) {
Row creRow = sheet0.createRow(14 + i);
Cell cell0 = creRow.createCell(0);
Cell cell1 = creRow.createCell(1);
Cell cell2 = creRow.createCell(2);
Cell cell3 = creRow.createCell(3);
Cell cell4 = creRow.createCell(4);
Cell cell5 = creRow.createCell(5);
Cell cell6 = creRow.createCell(6);
Cell cell7 = creRow.createCell(7);
cell0.setCellValue(salesOrders.getDatas().get(i).getNO());
cell1.setCellValue(salesOrders.getDatas().get(i).getModel());
cell2.setCellValue(salesOrders.getDatas().get(i).getSerialNumber());
cell3.setCellValue(salesOrders.getDatas().get(i).getDescription());
cell4.setCellValue(salesOrders.getDatas().get(i).getMOY());
cell5.setCellValue(salesOrders.getDatas().get(i).getQTY());
cell6.setCellValue(salesOrders.getDatas().get(i).getUnitPrice());
cell7.setCellValue(salesOrders.getDatas().get(i).getAmount());
cell0.setCellStyle(cellStyle);
cell1.setCellStyle(cellStyle);
cell2.setCellStyle(cellStyle);
cell3.setCellStyle(cellStyle);
cell4.setCellStyle(cellStyle);
cell5.setCellStyle(cellStyle);
cell6.setCellStyle(cellStyle);
cell7.setCellStyle(cellStyle);
}
// 通过占位符添加数据 遍历行和列,查找并替换占位符
for (Row row : sheet0) {
for (Cell cell : row) {
if (cell.getCellType() == CellType.STRING) {
String cellValue = cell.getStringCellValue();
if (cellValue.contains("${invoiceNo}")) {
cellValue = cellValue.replace("${invoiceNo}", salesOrders.getInvoiceNo());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${date}")) {
cellValue = cellValue.replace("${date}", salesOrders.getDate());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${contractCurrency}")) {
cellValue = cellValue.replace("${contractCurrency}", salesOrders.getContractCurrency());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${totalAmountSay}")) {
cellValue = cellValue.replace("${totalAmountSay}", salesOrders.getTotalAmountSay());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${totalAmount}")) {
cellValue = cellValue.replace("${totalAmount}", salesOrders.getTotalAmount());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${ourAccount}")) {
cellValue = cellValue.replace("${ourAccount}", salesOrders.getOurAccount());
cell.setCellValue(cellValue);
}
}
}
}
// try (FileOutputStream fileOut = new FileOutputStream(classpath+"/"+"Sales Orders Test.xlsx")) {
//
// }
//workbook.write(fileOut);
//加载转换方法
excelToPdf(workbook,"Document Sales Orders Test.xlsx","Sales Orders.pdf",response);
// 设置响应头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.setContentDispositionFormData("attachment", "Sales Orders.pdf");
//return ResponseEntity.ok().headers(headers).contentLength(bytes.length).body(bytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
return "";
}
/**
*
* @param fileCtrl
* @param account 上传文件的用户账号
* @param taskId 上传文件的任务ID
* @param activityId 上传文件的流程节点ID
* @param stepName 上传文件的流程流程节点名称
* @param rentalOrders 表格所需要的数据对象
* @return
*/
@RequestMapping(value = "/getRentalPdfFileUrl" ,method = RequestMethod.POST)
public void getRentalPdfFileUrl(@RequestParam(value = "fileCtrl") String fileCtrl ,
@RequestParam(value = "account") String account,
@RequestParam(value = "taskId") String taskId,
@RequestParam(value = "activityId") String activityId,
@RequestParam(value = "stepName") String stepName,
@RequestBody(required = false) RentalOrders rentalOrders,
HttpServletResponse response){
//String classpath = this.getClass().getClassLoader().getResource("templates").getPath();
InputStream inputStreamTemplate = this.getClass().getResourceAsStream("/templates/Rental Orders.xlsx");
XSSFWorkbook workbook = null;
// try {
// classpath = URLDecoder.decode(classpath,"utf-8"); //显示中文了
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException(e);
// }
try {
workbook = new XSSFWorkbook(inputStreamTemplate);
//获取第一个sheet 的excel文本
Sheet sheet0 = workbook.getSheetAt(0);
// 第1个参数是指要开始插入的行,第2个参数是结尾行数,第三个参数表示动态添加的行数
// sheet.getLastRowNum() 可以自动的根据新增行数代码进行后移,maven poi jar包版本可能会影响,本项目版本为4.1.1
// 如果第二个参数结尾行数填的行数大小小于内容行数,位新增行后面的内容可能会被覆盖
sheet0.shiftRows(6, sheet0.getLastRowNum() , rentalOrders.getDatas().size() -4, true, false);
//设置参数样式
CellStyle cellStyle = workbook.createCellStyle();
//设置边框样式
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
//循环给excel中赋值以及添加样式
for (int i = 0; i < rentalOrders.getDatas().size(); i++) {
Row creRow = sheet0.createRow(5 + i);
Cell cell0 = creRow.createCell(0);
Cell cell1 = creRow.createCell(1);
Cell cell2 = creRow.createCell(2);
Cell cell3 = creRow.createCell(3);
Cell cell4 = creRow.createCell(4);
Cell cell5 = creRow.createCell(5);
Cell cell6 = creRow.createCell(6);
Cell cell7 = creRow.createCell(7);
Cell cell8 = creRow.createCell(8);
cell0.setCellValue(rentalOrders.getDatas().get(i).getDescriptions());
cell1.setCellValue(rentalOrders.getDatas().get(i).getPlatformHeightOrMaximumLiftingCapacity());
cell2.setCellValue(rentalOrders.getDatas().get(i).getModel());
cell3.setCellValue(rentalOrders.getDatas().get(i).getQty());
cell4.setCellValue(rentalOrders.getDatas().get(i).getDeliveryDate());
cell5.setCellValue(rentalOrders.getDatas().get(i).getUnitCostOfRent());
cell6.setCellValue(rentalOrders.getDatas().get(i).getEstimatedLeasePeriod());
cell7.setCellValue(rentalOrders.getDatas().get(i).getMinimumLeasePeriod());
cell8.setCellValue(rentalOrders.getDatas().get(i).getUnit());
cell0.setCellStyle(cellStyle);
cell1.setCellStyle(cellStyle);
cell2.setCellStyle(cellStyle);
cell3.setCellStyle(cellStyle);
cell4.setCellStyle(cellStyle);
cell5.setCellStyle(cellStyle);
cell6.setCellStyle(cellStyle);
cell7.setCellStyle(cellStyle);
cell8.setCellStyle(cellStyle);
}
// 通过占位符添加数据 遍历行和列,查找并替换占位符
for (Row row : sheet0) {
for (Cell cell : row) {
if (cell.getCellType() == CellType.STRING) {
String cellValue = cell.getStringCellValue();
if (cellValue.contains("${invoiceNo}")) {
cellValue = cellValue.replace("${invoiceNo}", rentalOrders.getInvoiceNo());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${date}")) {
cellValue = cellValue.replace("${date}", rentalOrders.getDate());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${contractCurrency}")) {
cellValue = cellValue.replace("${contractCurrency}", rentalOrders.getContractCurrency());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${totalAmount}")) {
cellValue = cellValue.replace("${totalAmount}", rentalOrders.getTotalAmount());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${deliveryLocation}")) {
cellValue = cellValue.replace("${deliveryLocation}", rentalOrders.getDeliveryLocation());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${locationOfReturn}")) {
cellValue = cellValue.replace("${locationOfReturn}", rentalOrders.getLocationOfReturn());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${transportOfEquipment}")) {
cellValue = cellValue.replace("${transportOfEquipment}", rentalOrders.getTransportOfEquipment());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${settlementAndPayment}")) {
cellValue = cellValue.replace("${settlementAndPayment}", rentalOrders.getSettlementAndPayment());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${ourAccount}")) {
cellValue = cellValue.replace("${ourAccount}", rentalOrders.getOurAccount());
cell.setCellValue(cellValue);
}
if (cellValue.contains("${lessor}")) {
cellValue = cellValue.replace("${lessor}", rentalOrders.getLessor());
cell.setCellValue(cellValue);
}
}
}
}
// try (FileOutputStream fileOut = new FileOutputStream(classpath+"/"+"Rental Orders Test.xlsx")) {
// workbook.write(fileOut);
// }
//加载转换方法
excelToPdf(workbook, "Document Rental Orders Test.xlsx", "Rental Orders.pdf",response);
//return ResponseEntity.ok().headers(headers).contentLength(bytes.length).body(bytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 把MultipartFile 类型的文件转为File类型的文件
* @param multipartFile
* @return
*/
public File transferToFile(MultipartFile multipartFile) {
// 选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
File file = null;
try {
String originalFilename = multipartFile.getOriginalFilename();
String[] filename = originalFilename.split("\\.");
file=File.createTempFile(filename[0], filename[1] + ".");
multipartFile.transferTo(file);
file.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
public static String inputStreamToString(InputStream in)throws IOException {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for(int n; (n=in.read(b))!=-1;){
out.append(new String(b,0,n));
}
return out.toString();
}
/**
* eccel转pdf
* fileName 需要处理的文件名称 需要带上文件后缀
* documentName 存到document 中的文件名称
* pdfFileName pdf文件的名称
*/
public void excelToPdf(XSSFWorkbook workbook ,String documentName , String pdfFileName, HttpServletResponse response){
// 1.获取excel文件
//XSSFWorkbook temp = null;
Document document =null;
ByteArrayOutputStream stream = null;
byte[] pdfByte = null;
String classpath = this.getClass().getClassLoader().getResource("templates").getPath();
try {
classpath = URLDecoder.decode(classpath,"utf-8"); //显示中文了
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
try {
// = new XSSFWorkbook(classpath + "/" +fileName);
// 2.新建一个stream,用于绑定document
stream = new ByteArrayOutputStream();
// 3.A4大小
RectangleReadOnly shuban = new RectangleReadOnly(PageSize.A4);
document = new Document(shuban);
// 4.获取一个pdfwriter实例
PdfWriter writer = PdfWriter.getInstance(document, stream);
// 5.打开document
document.open();
// 6.设置页边距
document.setMargins(20, 20, 30, 30);
// 7.新增页
document.newPage();
// 8.excel转pdf,并将处理后的内容添加到document中
document.add(ExcelToPdfUtil.excelToPdf(workbook, documentName, PageSize.A4.getWidth() - 150, 0));
} catch (Exception e) {
throw new RuntimeException(e);
}
// 9.关闭workbook document
try {
workbook.close();
document.close();
// 10.以byte[]方式获取pdf
pdfByte = stream.toByteArray();
stream.flush();
stream.reset();
stream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
// 11.保存pdf
// String newPdfFileName = pdfFileName;
//String filePath = "templates/";
String filePath = classpath +"/";
(new File(filePath)).mkdirs();
File file = new File(filePath + pdfFileName);
if (file.exists()) {
file.delete();
}
FileOutputStream outputStream = null;
FileInputStream fileInputStream = null;
byte[] bytes = null;
BufferedInputStream bufferedInputStream = null;
OutputStream buffOutputStream = null;
InputStream inputStream = null;
try {
// outputStream = new FileOutputStream(filePath + "/"+pdfFileName);
// outputStream.write(pdfByte);
// 读到流中
// inputStream = new FileInputStream(filePath + "/"+ pdfFileName);// 文件的存放路径
response.reset();
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(pdfFileName.replaceAll(" +",""), "UTF-8"));
ServletOutputStream outputStream1 = response.getOutputStream();
outputStream1.write(pdfByte);
// byte[] b = new byte[1024];
// int len;
//从输入流中读取一定数量的字节,并将其存储在缓冲区字节数组中,读到末尾返回-1
// while ((len = inputStream.read(b)) > 0) {
// outputStream1.write(b, 0, len);
// }
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
try {
outputStream.close();
fileInputStream.close();
bufferedInputStream.close();
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
实体类
package com.fehorizon.oversea.oa.po.excelToPdf;
import lombok.Data;
import java.util.List;
@Data
public class RentalOrders {
//流程编号
private String invoiceNo;
//订单签订日期
private String date;
//本次合同币种
private String contractCurrency;
//总金额大写TOTAL AMOUNT SAY
// private String totalAmountSay;
//总金额
private String totalAmount;
//交付地址
private String deliveryLocation;
//归还地址
private String locationOfReturn;
//设备运输
private String transportOfEquipment;
//结算付款内容
private String settlementAndPayment;
//我方账户
private String ourAccount;
//归属公司
private String lessor;
//重复表数据
private List<RentalOrdersRepeatingTable> datas;
}
package com.fehorizon.oversea.oa.po.excelToPdf;
import lombok.Data;
@Data
public class RentalOrdersRepeatingTable {
//货物名称
private String descriptions;
//平台高度/最大起重量
private String platformHeightOrMaximumLiftingCapacity;
//型号
private String model;
//数量
private String qty;
//预计交付日期
private String deliveryDate;
//租金单位单价
private String unitCostOfRent;
//预计租赁期
private String estimatedLeasePeriod;
//最短租赁期(天)
private String minimumLeasePeriod;
//物流费单价
private String unit;
}
package com.fehorizon.oversea.oa.po.excelToPdf;
import lombok.Data;
import java.util.List;
/**
* SalesOrders 表格需要的参数说明
*/
@Data
public class SalesOrders {
//流程编号
private String invoiceNo;
//订单签订日期
private String date;
//本次合同币种
private String contractCurrency;
//总金额大写TOTAL AMOUNT SAY
private String totalAmountSay;
//总金额
private String totalAmount;
//我方账户
private String ourAccount;
//重复表数据
private List<SalesOrdersRepeatingTable> datas;
}
package com.fehorizon.oversea.oa.po.excelToPdf;
import lombok.Data;
/**
* SalesOrders 重复表需要的参数说明
*/
@Data
public class SalesOrdersRepeatingTable {
//序列号
private String NO;
//型号
private String Model;
//物料编号/序列号
private String serialNumber;
//货物名称
private String description;
//年份
private String MOY;
//数量
private String QTY;
//单价
private String unitPrice;
//总价
private String amount;
}