PDF预览

/*** pdf文件预览* @param request* @param response* @return* @throws IOException*/
@RequestMapping(value = "reviewPriceData")
public void reviewPriceData(String priceId , HttpServletRequest request, HttpServletResponse response) throws Exception, TemplateException, DocumentException {// 获取pdf文件路径(包括文件名)String tempPrintPdfFile = "D:/test.pdf";FileInputStream inStream = new FileInputStream(tempPrintPdfFile);// 设置输出的格式response.setContentType( "application/pdf");OutputStream outputStream= response.getOutputStream();int count = 0;byte[] buffer = new byte[1024 * 1024];while ((count =inStream.read(buffer)) != -1){outputStream.write(buffer, 0,count);}outputStream.flush();
}
1.其他文件转PDF

在项目中有这样的需求就是,对一些word、excel、ppt文档进行预览,但是这个无法直接预览,这边可以实现这么个思路,就是先将这些文件转换为pdf然后就可以预览了

<dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>18.6</version><scope>system</scope><systemPath>${project.basedir}/lib/aspose-words-18.6-jdk16.jar</systemPath></dependency><!-- ppt转pdf --><dependency><groupId>com.aspose</groupId><artifactId>aspose-slides</artifactId><version>15.9.0</version><scope>system</scope><systemPath>${project.basedir}/lib/aspose-slides-15.9.0.jar</systemPath></dependency><!-- excel转pdf --><dependency><groupId>com.aspose</groupId><artifactId>aspose-cells</artifactId><version>8.5.2</version><scope>system</scope><systemPath>${project.basedir}/lib/aspose-cells-8.5.2.jar</systemPath></dependency>
package file;
import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.*;class FileTransForUtils {private static final Logger logger = LoggerFactory.getLogger(FileTransForUtils.class);//word转PDFpublic synchronized static boolean word3Pdf(String wordPath, String pdfPath) {if (!getLicense("word")) {          // 验证License 若不验证则转化出的pdf文档会有水印产生return false;}try {long old = System.currentTimeMillis();File file = new File(pdfPath);  //新建一个pdf文档FileOutputStream os = new FileOutputStream(file);Document doc = new Document(wordPath);  //Address是将要被转化的word文档doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB,// XPS, SWF 相互转换long now = System.currentTimeMillis();os.close();logger.info("word共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时return true;} catch (Exception e) {logger.error(String.valueOf(e));e.printStackTrace();return false;}}//excel转PDFpublic synchronized static boolean excel3pdf(String excelPath, String pdfPath) {if (!getLicense("excel")) { // 验证License 若不验证则转化出的pdf文档会有水印产生return false;}try {long old = System.currentTimeMillis();File pdfFile = new File(pdfPath);  //新建一个pdf文档FileOutputStream os = new FileOutputStream(pdfFile);Workbook wb = new Workbook(excelPath);// 原始excel路径wb.save(os,com.aspose.cells.SaveFormat.PDF);long now = System.currentTimeMillis();os.close();logger.info("excel共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时return true;} catch (Exception e) {logger.error(String.valueOf(e));e.printStackTrace();return false;}}//ppt转PDFpublic synchronized static boolean ppt3pdf(String pptPath, String pdfPath) {// 验证Licenseif (!getLicense("ppt")) {return false;}FileOutputStream os = null;try {long old = System.currentTimeMillis();File pdfFile = new File(pdfPath);  //新建一个pdf文档os = new FileOutputStream(pdfFile);Presentation pres = new Presentation(pptPath);//输入ppt路径//IFontsManager fontsManager = pres.getFontsManager();pres.save(os,com.aspose.slides.SaveFormat.Pdf);long now = System.currentTimeMillis();logger.info("ppt共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时return true;} catch (Exception e) {logger.error(String.valueOf(e));e.printStackTrace();return false;}finally {try {os.close();} catch (IOException e) {e.printStackTrace();}}}//剔除水印private static boolean getLicense(String type) {boolean result = false;try {// 凭证String license ="<License>\n" +"  <Data>\n" +"    <Products>\n" +"      <Product>Aspose.Total for Java</Product>\n" +"      <Product>Aspose.Words for Java</Product>\n" +"    </Products>\n" +"    <EditionType>Enterprise</EditionType>\n" +"    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +"    <LicenseExpiry>20991231</LicenseExpiry>\n" +"    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +"  </Data>\n" +"  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +"</License>";InputStream is = new ByteArrayInputStream(license.getBytes("UTF-8"));if(type.equals("word")){License asposeLic = new License();asposeLic.setLicense(is);}else if (type.equals("excel")){com.aspose.cells.License asposeLic = new com.aspose.cells.License();asposeLic.setLicense(is);}else if (type.equals("ppt")){com.aspose.slides.License aposeLic = new com.aspose.slides.License();aposeLic.setLicense(is);}result = true;} catch (Exception e) {logger.error(String.valueOf(e));e.printStackTrace();return false;}return result;}/*** 判断资源类型文档类*/private static String getResourceTypesDocument(String suffix) {String type = null;switch (suffix) {//文档类型case ".doc":case ".docx":case ".txt":type = "word";break;case ".xls":case ".xlsx":type = "excel";break;case ".ppt":case ".pptx":type = "ppt";break;}return type;}public static void main(String[] args) {String inputPath = "E:/test/测试.xlsx";String outputPath = "E:/test/11.pdf";String suffix = inputPath.substring(inputPath.lastIndexOf("."));String type = getResourceTypesDocument(suffix);if("word".equals(type)){word3Pdf(inputPath,outputPath);}else if("excel".equals(type)){excel3pdf(inputPath,outputPath);}else if("ppt".equals(type)){ppt3pdf(inputPath,outputPath);}}
}
2.实现PDF在线预览(四种方法)
    @RequestMapping("/preview1")public void er(HttpServletResponse response){File file = new File("G:\\桌面\\Thymeleaf3.0中文翻译文档@www.java1234.com.pdf");if (file.exists()){byte[] data = null;try {FileInputStream input = new FileInputStream(file);data = new byte[input.available()];input.read(data);response.getOutputStream().write(data);input.close();} catch (Exception e) {System.out.println(e);}}else{return;}}@ResponseBody@RequestMapping("/preview2")public void findPdf( HttpServletResponse response) throws IOException{response.setContentType("application/pdf");FileInputStream in = new FileInputStream(new File("G:\\桌面\\Thymeleaf3.0中文翻译文档@www.java1234.com.pdf"));OutputStream out = response.getOutputStream();byte[] b = new byte[512];while ((in.read(b))!=-1) {out.write(b);}out.flush();in.close();out.close();}@ResponseBody@RequestMapping("/preview3")public void devDoc(HttpServletRequest request, HttpServletResponse response, String storeName) throws Exception {request.setCharacterEncoding("UTF-8");String ctxPath = request.getSession().getServletContext().getRealPath("");String downLoadPath = "G:\\桌面\\Thymeleaf3.0中文翻译文档@www.java1234.com.pdf";response.setContentType("application/pdf");FileInputStream in = new FileInputStream(new File(downLoadPath));OutputStream out = response.getOutputStream();byte[] b = new byte[1024];while ((in.read(b))!=-1) {out.write(b);}out.flush();in.close();out.close();}@ResponseBody@RequestMapping("/preview")public void download( HttpServletResponse response) throws IOException {String filePath = "G:\\桌面\\Thymeleaf3.0中文翻译文档@www.java1234.com.pdf";System.out.println("filePath:" + filePath);File f = new File(filePath);if (!f.exists()) {response.sendError(404, "File not found!");return;}BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));byte[] bs = new byte[1024];int len = 0;response.reset(); // 非常重要if (true) { // 在线打开方式URL u = new URL("file:///" + filePath);String contentType = u.openConnection().getContentType();response.setContentType(contentType);response.setHeader("Content-Disposition", "inline;filename="+ "2019年上半年英语四级笔试准考证(戴林峰).pdf");// 文件名应该编码成utf-8,注意:使用时,我们可忽略这句} else {// 纯下载方式response.setContentType("application/x-msdownload");response.setHeader("Content-Disposition", "attachment;filename="+ "2019年上半年英语四级笔试准考证(戴林峰).pdf");}OutputStream out = response.getOutputStream();while ((len = br.read(bs)) > 0) {out.write(bs, 0, len);}out.flush();out.close();br.close();}
3.CopySheet
package com.jero.server.utils;import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.NumberToTextConverter;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.*;import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;/**** @author trx*/
public final class CopySheetUtil {public CopySheetUtil() {}public static void copySheets(XSSFSheet newSheet, XSSFSheet sheet, XSSFWorkbook workbook) {copySheets(newSheet, sheet, workbook,true);}public static void copySheets(XSSFSheet newSheet, XSSFSheet sheet,XSSFWorkbook workbook,boolean copyStyle) {int maxColumnNum = 0;int numMergedRegions = sheet.getNumMergedRegions();for (int i = 0; i < numMergedRegions; i++) {CellRangeAddress mergedRegion = sheet.getMergedRegion(i);newSheet.addMergedRegion(mergedRegion);}for (int i = sheet.getFirstRowNum(); i < 74; i++) {/*long b = System.currentTimeMillis();*/XSSFRow srcRow = sheet.getRow(i);XSSFRow destRow = newSheet.createRow(i);/*if (i == 30) {System.out.println("测试表6-C31");}*/if (srcRow != null) {CopySheetUtil.copyRow(sheet, newSheet, srcRow, destRow,workbook);if (srcRow.getLastCellNum() > maxColumnNum) {maxColumnNum = srcRow.getLastCellNum();}}}for (int i = 0; i <= maxColumnNum; i++) {    //设置列宽newSheet.setColumnWidth(i, sheet.getColumnWidth(i));}}/*** 复制并合并单元格*/public static void copyRow(XSSFSheet srcSheet, XSSFSheet destSheet,XSSFRow srcRow, XSSFRow destRow,XSSFWorkbook workbook) {destRow.setHeight(srcRow.getHeight());for (int j = 0; j <= srcRow.getLastCellNum(); j++) {XSSFCell oldCell = srcRow.getCell(j); // old cellXSSFCell newCell = destRow.getCell(j); // new cellif (oldCell != null) {if (newCell == null) {newCell = destRow.createCell(j);}copyCell(oldCell, newCell,workbook);}}}/*** 把原来的Sheet中cell(列)的样式和数据类型复制到新的sheet的cell(列)中** @param oldCell* @param newCell*/public static void copyCell(XSSFCell oldCell, XSSFCell newCell, XSSFWorkbook workbook) {String sheetName = oldCell.getSheet().getSheetName();boolean flag = false;if (sheetName.equals("表2 发电量表") && oldCell.getRowIndex() == 7) {flag = true;}if (oldCell.getRowIndex() == 0 || flag) {//设置单元格样式XSSFWorkbook sheetWorkbook = newCell.getSheet().getWorkbook();XSSFCellStyle cellStyle = sheetWorkbook.createCellStyle();cellStyle.setAlignment(HorizontalAlignment.CENTER);cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);XSSFFont font = sheetWorkbook.createFont();font.setFontName("宋体");font.setFontHeightInPoints((short) 12);font.setBold(true);cellStyle.setFont(font);newCell.setCellStyle(cellStyle);}switch (oldCell.getCellType()) {case STRING:newCell.setCellValue(oldCell.getStringCellValue());break;case NUMERIC:newCell.setCellType(CellType.STRING);String s = oldCell.getCellStyle().getDataFormatString();String cellValue = getCellValue(oldCell, workbook);if (s.contains("%") && cellValue != "" && !cellValue.contains("#")) {String n = StringUtils.substringAfter(s, ".");n = StringUtils.substringBefore(n, "_");if (n.length() == 0) {n = "1";}BigDecimal bigDecimal = (new BigDecimal(cellValue)).multiply(new BigDecimal(100)).setScale(n.length()-1, RoundingMode.HALF_UP);cellValue = bigDecimal + "%";}if (!s.contains("%") && !cellValue.contains("#") && cellValue != "" && !s.equals("General")) {String n = StringUtils.substringAfter(s, ".");n = StringUtils.substringBefore(n, "_");//多位小数特殊处理BigDecimal bigDecimal2 = (new BigDecimal(cellValue)).setScale(n.length(), RoundingMode.HALF_UP);cellValue = bigDecimal2 + "";//cellValue1 = NumberToTextConverter.toText(oldCell.getNumericCellValue());}if (cellValue.equals("0") || cellValue.equals("0.0") || cellValue.equals("0.00")|| cellValue.equals("0.000") || cellValue.equals("0.0000") || cellValue.equals("0.00000")) {cellValue = "-";}newCell.setCellValue(cellValue);break;case BLANK:newCell.setCellType(CellType.BLANK);break;case BOOLEAN:newCell.setCellValue(oldCell.getBooleanCellValue());break;case ERROR:newCell.setCellErrorValue(Byte.parseByte("-"));break;case FORMULA:newCell.setCellType(CellType.STRING);String s1 = oldCell.getCellStyle().getDataFormatString();
//                int rowIndex = oldCell.getRowIndex();
//                if (rowIndex == 30) {
//                    System.out.println(s1);
//                }String cellValue1 = getCellValue(oldCell, workbook);if (s1.contains("%") && cellValue1 != "" && !cellValue1.contains("#")) {String n = StringUtils.substringAfter(s1, ".");n = StringUtils.substringBefore(n, "_");if (n.length() == 0) {n = "1";}BigDecimal bigDecimal1 = (new BigDecimal(cellValue1)).multiply(new BigDecimal(100)).setScale(n.length()-1, RoundingMode.HALF_UP);cellValue1 = bigDecimal1 + "%";}if (!s1.contains("%") && !s1.contains("¥") && !cellValue1.contains("#") && cellValue1 != "") {String n = StringUtils.substringAfter(s1, ".");n = StringUtils.substringBefore(n, "_");//多位小数特殊处理BigDecimal bigDecimal2 = (new BigDecimal(cellValue1)).setScale(n.length(), RoundingMode.HALF_UP);cellValue1 = bigDecimal2 + "";//cellValue1 = NumberToTextConverter.toText(oldCell.getNumericCellValue());}/*if (s1.contains("¥")) {System.out.println(s1);System.out.println(cellValue1);}*/if (s1.contains("¥")) {if (!cellValue1.contains("#")) {BigDecimal bigDecimal2 = (new BigDecimal(cellValue1)).setScale(2, RoundingMode.HALF_UP);cellValue1 = bigDecimal2 + "";} else {cellValue1 = "-";}}if (cellValue1.equals("0") || cellValue1.equals("0.0") || cellValue1.equals("0.00")|| cellValue1.equals("0.000") || cellValue1.equals("0.0000") || cellValue1.equals("0.00000")) {cellValue1 = "-";}if (s1.contains("¥")) {cellValue1 = "¥" + cellValue1;}if (cellValue1.contains("#")) {cellValue1 = "#REF";}newCell.setCellValue(cellValue1);break;default:break;}}public static String getCellValue(XSSFCell cell,Workbook workbook){FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();DataFormatter formatter = new DataFormatter();//单元格不设置数字格式cell.setCellStyle(null);return formatter.formatCellValue(cell,evaluator);}/*** 复制sheet* @param newSheet* @param oldSheet* @return*/private static Sheet copySheet(Sheet newSheet, Sheet oldSheet, Workbook workbook){//合并单元格int numMergedRegions = oldSheet.getNumMergedRegions();for (int i = 0; i < numMergedRegions; i++) {CellRangeAddress mergedRegion = oldSheet.getMergedRegion(i);newSheet.addMergedRegion(mergedRegion);}//增加列宽int physicalNumberOfCells = oldSheet.getRow(0).getPhysicalNumberOfCells();for (int i = 0; i <physicalNumberOfCells; i++) {newSheet.setColumnWidth(i, 256*20);}//最大获取行数int maxRowSize = oldSheet.getPhysicalNumberOfRows();for (int i = 0; i < maxRowSize; i++) {Row newrow = newSheet.createRow(i);Row oldRow = oldSheet.getRow(i);//此处需要将 cellStyle 定义在遍历行的地方,定义在外面可能出现样式渲染错误CellStyle cellStyle = workbook.createCellStyle();//水平居中/垂直居中cellStyle.setAlignment(HorizontalAlignment.CENTER);cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);cellStyle.setWrapText(true);//下边框cellStyle.setBorderBottom(BorderStyle.THIN);//左边框cellStyle.setBorderLeft(BorderStyle.THIN);//上边框cellStyle.setBorderTop(BorderStyle.THIN);//右边框cellStyle.setBorderRight(BorderStyle.THIN);//定义字体,具体自己写Font font = workbook.createFont();//获取当前行,最大列数int maxColSize = oldRow.getPhysicalNumberOfCells();for (int j = 0; j <maxColSize ; j++) {Cell newCell = newrow.createCell(j);Cell oldCell = oldRow.getCell(j);if (oldCell==null){continue;}CellType cellType = oldCell.getCellType();//此处type类型不只这两种,在此只是列举2种if ("NUMERIC".equals(cellType.name())){newCell.setCellValue(oldCell.getNumericCellValue());}else {newCell.setCellValue(oldCell.getStringCellValue());}//1.直接copy原cell的样式,猜测:会导致大量创建cellStyle对象,引起excel问题//获取原cell的样式CellStyle oldCellStyle = oldCell.getCellStyle();cellStyle.cloneStyleFrom(oldCellStyle);//2.逐行调整样式
//              if (i==0) {
//
//              }else  if(i==1){
//
//              }else {
//
//              }newCell.setCellStyle(cellStyle);}}return  newSheet;}
}
4.Excel转PDF
package com.jero.server.utils;import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.jero.common.util.SpringContextUtils;
import com.jero.config.StaticConfig;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.List;/*** @author liJiaRao* @date 2022-12-28 11:30*/
public class Excel2PdfUtil {public static void main(String[] args) throws Exception{//excel文件路径String excelFile = "E:\\Data\\Downloads\\tp-admin\\经济评价公式-调试 - 副本.xlsx";//pdf文件输出路径String out = "E:\\Data\\Downloads\\tp-admin\\out"+System.currentTimeMillis()+".pdf";
//        excelToPdf(excelFile,out);}public static byte[] excelToPdf(Workbook workbook, Integer sheetNo, String excelPath, String pdfPath) throws Exception{Sheet sheet = workbook.getSheetAt(0);ByteArrayOutputStream stream = new ByteArrayOutputStream();String sheetName = sheet.getSheetName();String sheetNames = "表1 投资估算表,表11 项目总投资使用计划与资金筹措表,表13 基本指标";Rectangle a = PageSize.A0;if (sheetNames.contains(sheetName)) {a = PageSize.A2;}Document document = new Document(a);//此处根据excel大小设置pdf纸张大小PdfWriter writer = PdfWriter.getInstance(document, stream);document.setMargins(0, 0, 15, 15);//设置也边距document.open();float[] widths = getColWidth(sheet);PdfPTable table = new PdfPTable(widths);table.setWidthPercentage(95);int colCount = widths.length;/*BaseFont baseFont = BaseFont.createFont("C:\\Windows\\Fonts\\simsun.ttc,0", BaseFont.IDENTITY_H,BaseFont.EMBEDDED);//设置基本字体*/BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);for (int r = sheet.getFirstRowNum(); r < sheet.getPhysicalNumberOfRows(); r++) {Row row = sheet.getRow(r);if (row != null) {for (int c = row.getFirstCellNum(); (c < row.getLastCellNum() || c < colCount) && c > -1; c++) {if (c >= row.getPhysicalNumberOfCells()) {PdfPCell pCell = new PdfPCell(new Phrase(""));pCell.setBorder(0);table.addCell(pCell);continue;}Cell excelCell = row.getCell(c);String value = "";if (excelCell != null) {value = excelCell.getStringCellValue();/*if (value.length() != 0){if (NumberUtil.isNumber(value)) {try {value = numFormat(value);} catch (Exception e) {value = "";}}}*/}else {value = "";}org.apache.poi.ss.usermodel.Font excelFont = getExcelFont(workbook, excelCell, excelPath);//HSSFFont excelFont = excelCell.getCellStyle().getFont(workbook);Font pdFont = new Font(baseFont, excelFont.getFontHeightInPoints(),excelFont.getBold() ? Font.BOLD : Font.NORMAL, BaseColor.BLACK);//设置单元格字体PdfPCell pCell = new PdfPCell(new Phrase(value, pdFont));//List<PicturesInfo> infos  = POIExtend.getAllPictureInfos(sheet, r, r, c, c, false);//if (!infos.isEmpty()){//    pCell = new PdfPCell(Image.getInstance(infos.get(0).getPictureData()));//    PicturesInfo info = infos.get(0);//    System.out.println("最大行:" + info.getMaxRow() + "最小行:" + info.getMinRow() + "最大列:" + info.getMaxCol() + "最小列:" + info.getMinCol());;//}boolean hasBorder = hasBorder(excelCell);if (!hasBorder){pCell.setBorder(0);}pCell.setHorizontalAlignment(getHorAglin(excelCell.getCellStyle().getAlignment()));pCell.setVerticalAlignment(getVerAglin(excelCell.getCellStyle().getVerticalAlignment()));pCell.setMinimumHeight(row.getHeightInPoints());if (isMergedRegion(sheet, r, c)) {int[] span = getMergedSpan(sheet, r, c);if (span[0] == 1 && span[1] == 1) {//忽略合并过的单元格continue;}pCell.setRowspan(span[0]);pCell.setColspan(span[1]);c = c + span[1] - 1;//合并过的列直接跳过}table.addCell(pCell);}} else {PdfPCell pCell = new PdfPCell(new Phrase(""));pCell.setBorder(0);pCell.setMinimumHeight(13);table.addCell(pCell);}}document.add(table);document.close();byte[] pdfByte = stream.toByteArray();stream.flush();stream.reset();stream.close();//        FileOutputStream outputStream = new FileOutputStream(pdfPath);
//        outputStream.write(pdfByte);
//        outputStream.flush();
//        outputStream.close();return pdfByte;}//获取字体private static org.apache.poi.ss.usermodel.Font getExcelFont(Workbook workbook, Cell cell, String excelName){if (excelName.endsWith(".xls")){return ((HSSFCell)cell).getCellStyle().getFont(workbook);}return ((XSSFCell)cell).getCellStyle().getFont();}/*** 判断excel单元格是否有边框* @param excelCell* @return*/private static boolean hasBorder(Cell excelCell) {short top = excelCell.getCellStyle().getBorderTop().getCode();short bottom = excelCell.getCellStyle().getBorderBottom().getCode();short left = excelCell.getCellStyle().getBorderLeft().getCode();short right = excelCell.getCellStyle().getBorderRight().getCode();return top + bottom + left + right > 2;}/*** 获取excel单元格数据显示格式* @param dataFormat* @return* @throws Exception*/private static String getNumStyle(String dataFormat) throws Exception {if (dataFormat == null || dataFormat.length() == 0){throw new Exception("");}if (dataFormat.contains("%")){return dataFormat;} else{return dataFormat.substring(0, dataFormat.length()-2);}}/*** 判断单元格是否是合并单元格* @param sheet* @param row* @param column* @return*/private static boolean isMergedRegion(Sheet sheet, int row, int column) {int sheetMergeCount = sheet.getNumMergedRegions();for (int i = 0; i < sheetMergeCount; i++) {CellRangeAddress range = sheet.getMergedRegion(i);int firstColumn = range.getFirstColumn();int lastColumn = range.getLastColumn();int firstRow = range.getFirstRow();int lastRow = range.getLastRow();if (row >= firstRow && row <= lastRow) {if (column >= firstColumn && column <= lastColumn) {return true;}}}return false;}/*** 计算合并单元格合并的跨行跨列数* @param sheet* @param row* @param column* @return*/private static int[] getMergedSpan(Sheet sheet, int row, int column) {int sheetMergeCount = sheet.getNumMergedRegions();int[] span = { 1, 1 };for (int i = 0; i < sheetMergeCount; i++) {CellRangeAddress range = sheet.getMergedRegion(i);int firstColumn = range.getFirstColumn();int lastColumn = range.getLastColumn();int firstRow = range.getFirstRow();int lastRow = range.getLastRow();if (firstColumn == column && firstRow == row) {span[0] = lastRow - firstRow + 1;span[1] = lastColumn - firstColumn + 1;break;}}return span;}/*** 获取excel中每列宽度的占比* @param sheet* @return*/private static float[] getColWidth(Sheet sheet) {int rowNum = getMaxColRowNum(sheet);Row row = sheet.getRow(rowNum);int cellCount = row.getPhysicalNumberOfCells();int[] colWidths = new int[cellCount];int sum = 0;for (int i = row.getFirstCellNum(); i < cellCount; i++) {Cell cell = row.getCell(i);if (cell != null) {colWidths[i] = sheet.getColumnWidth(i);sum += sheet.getColumnWidth(i);}}float[] colWidthPer = new float[cellCount];for (int i = row.getFirstCellNum(); i < cellCount; i++) {colWidthPer[i] = (float) colWidths[i] / sum * 100;}return colWidthPer;}/*** 获取excel中列数最多的行号* @param sheet* @return*/private static int getMaxColRowNum(Sheet sheet) {int rowNum = 0;int maxCol = 0;for (int r = sheet.getFirstRowNum(); r < sheet.getPhysicalNumberOfRows(); r++) {Row row = sheet.getRow(r);if (row != null && maxCol < row.getPhysicalNumberOfCells()) {maxCol = row.getPhysicalNumberOfCells();rowNum = r;}}return rowNum;}/*** excel垂直对齐方式映射到pdf对齐方式* @param aglin* @return*/private static int getVerAglin(VerticalAlignment aglin) {if (aglin.equals(VerticalAlignment.CENTER)) {return com.itextpdf.text.Element.ALIGN_MIDDLE;} else if (aglin.equals(VerticalAlignment.BOTTOM)) {return com.itextpdf.text.Element.ALIGN_BOTTOM;} else if (aglin.equals(VerticalAlignment.TOP)) {return com.itextpdf.text.Element.ALIGN_TOP;} else {return com.itextpdf.text.Element.ALIGN_MIDDLE;}}/*** excel水平对齐方式映射到pdf水平对齐方式* @param aglin* @return*/private static int getHorAglin(HorizontalAlignment aglin) {if (aglin.equals(HorizontalAlignment.CENTER)) {return com.itextpdf.text.Element.ALIGN_CENTER;}else if (aglin.equals(HorizontalAlignment.RIGHT)) {return com.itextpdf.text.Element.ALIGN_RIGHT;}else if (aglin.equals(HorizontalAlignment.LEFT)) {return com.itextpdf.text.Element.ALIGN_LEFT;}else {return com.itextpdf.text.Element.ALIGN_CENTER;}}/*** 格式化数字* @param num* @return*/private static String numFormat(String num){BigDecimal bigDecimal = new BigDecimal(num);if (bigDecimal.equals(BigDecimal.ZERO)){return "-";}DecimalFormat df = new DecimalFormat("#,##0.00");return df.format(bigDecimal);}
}
5.压缩包
package com.jero.common.util;import com.jero.common.exception.JeroBootException;
import org.springframework.http.HttpHeaders;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;/*** @author liJiaRao* @date 2022-12-27 17:36*/
public class ZipUtil {public static void exportZip(List<ZipFileVO> bytes, String zipFileName, HttpServletResponse response){try {ServletOutputStream outputStream = response.getOutputStream();response.setHeader("content-type", "application/octet-stream");response.setContentType("application/octet-stream");response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + new String(zipFileName.getBytes("GB2312"), "ISO8859-1"));response.setCharacterEncoding("UTF-8");//ZipOutputStream zos = new ZipOutputStream(outputStream, Charset.forName("GBK"));if (bytes != null && bytes.size() > 0) {for (ZipFileVO zipFileVO : bytes) {String name = zipFileVO.getName();byte[] b = zipFileVO.getBytes();// 创建ZIP实体,并添加进压缩包ZipEntry zipEntry = new ZipEntry(name);zos.putNextEntry(zipEntry);// 读取待压缩的文件并写进压缩包里zos.write(b);}}zos.closeEntry();zos.flush();zos.close();} catch (IOException e) {e.printStackTrace();throw new JeroBootException("导出失败");}}public static File fileToZip(List<ZipFileVO> bytes, String zipFilePath,String fileName) {FileOutputStream fos = null;ZipOutputStream zos = null;fileName = fileName + System.currentTimeMillis();try {File zipFile = new File(zipFilePath + "/" + fileName + ".zip");if (zipFile.exists()) {System.out.println(zipFilePath + "目录下存在名字为:" + fileName+ ".zip" + "打包文件.");} else {if (!zipFile.exists()) {zipFile.getParentFile().mkdirs();}//第一步fos = new FileOutputStream(zipFile);zos = new ZipOutputStream(new BufferedOutputStream(fos));if (bytes != null && bytes.size() > 0) {for (int i = 0; i < bytes.size(); i++) {ZipFileVO zipFileVO = bytes.get(i);String name = zipFileVO.getName();byte[] b = zipFileVO.getBytes();// 创建ZIP实体,并添加进压缩包ZipEntry zipEntry = new ZipEntry(name);zos.putNextEntry(zipEntry);// 读取待压缩的文件并写进压缩包里zos.write(b);}}}return zipFile;} catch (IOException e) {e.printStackTrace();throw new RuntimeException(e);} finally {// 关闭流try {if (null != zos) {zos.close();}} catch (IOException e) {e.printStackTrace();throw new RuntimeException(e);}}}}
@Data
public class ZipFileVO {private String name;private byte[] bytes;
}
List<ZipFileVO> zipFileVOList = zipSheets(workbook, sheetInts, type);
ZipUtil.exportZip(zipFileVOList, "结果导出.zip", response);
6.图片转PDF
<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.4.3</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency><dependency><groupId>com.itextpdf.tool</groupId><artifactId>xmlworker</artifactId><version>5.4.1</version></dependency><dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.10.1</version></dependency>
package com.hrp.util;import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;/*** @description: pdf相关的工具类*/
@Component
public class PdfUtils {/*** 图片转换PDF的公共接口** @param file     SpringMVC获取的图片文件* @param response HttpServletResponse* @throws IOException       IO异常* @throws DocumentException PDF文档异常*/public static void imageToPdf(MultipartFile file, HttpServletResponse response) throws IOException, DocumentException {File pdfFile = generatePdfFile(file);downloadPdfFile(pdfFile, response);}/*** 将图片转换为PDF文件** @param file SpringMVC获取的图片文件* @return PDF文件* @throws IOException       IO异常* @throws DocumentException PDF文档异常*/private static File generatePdfFile(MultipartFile file) throws IOException, DocumentException {String fileName = file.getOriginalFilename();String pdfFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";Document doc = new Document(PageSize.A4, 20, 20, 20, 20);PdfWriter.getInstance(doc, new FileOutputStream(pdfFileName));doc.open();doc.newPage();Image image = Image.getInstance(file.getBytes());float height = image.getHeight();float width = image.getWidth();int percent = getPercent(height, width);image.setAlignment(Image.MIDDLE);image.scalePercent(percent);doc.add(image);doc.close();File pdfFile = new File(pdfFileName);return pdfFile;}/**** 用于下载PDF文件** @param pdfFile  PDF文件* @param response HttpServletResponse* @throws IOException IO异常*/private static void downloadPdfFile(File pdfFile, HttpServletResponse response) throws IOException {FileInputStream fis = new FileInputStream(pdfFile);byte[] bytes = new byte[fis.available()];fis.read(bytes);fis.close();response.reset();response.setHeader("Content-Type", "application/pdf");response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(pdfFile.getName(), "UTF-8"));OutputStream out = response.getOutputStream();out.write(bytes);out.flush();out.close();}/*** 等比压缩,获取压缩百分比** @param height 图片的高度* @param weight 图片的宽度* @return 压缩百分比*/private static int getPercent(float height, float weight) {float percent = 0.0F;if (height > weight) {percent = PageSize.A4.getHeight() / height * 100;} else {percent = PageSize.A4.getWidth() / weight * 100;}return Math.round(percent);}
}
package com.hrp.controller;import com.hrp.util.PdfUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;/*** @description: 用于处理Pdf相关的请求*/
@Controller
@RequestMapping("pdf")
public class PdfController {@PostMapping("image/to")public void imageToPdf(@RequestParam("file") MultipartFile file,HttpServletResponse response) throws Exception{PdfUtils.imageToPdf(file,response);}}
7.PDF页眉页脚
import java.awt.*;
import java.awt.geom.Dimension2D;
import com.spire.pdf.*;
import com.spire.pdf.automaticfields.PdfAutomaticField;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.*;public class HeaderFooter {public static void main(String[] args) throws Exception {//创建 PdfDocument 对象PdfDocument doc = new PdfDocument();//创建PdfMargins对象, 并设置的页边距PdfMargins margin = new PdfMargins(60,60,40,40);//调用 addHeaderAndFooter()方法添加页眉页脚addHeaderAndFooter(doc, PdfPageSize.A4, margin);       //保存文档doc.saveToFile("output/headerFooter.pdf");doc.close();}static void addHeaderAndFooter(PdfDocument doc, Dimension2D pageSize, PdfMargins margin) {PdfPageTemplateElement header = new PdfPageTemplateElement(margin.getLeft(), pageSize.getHeight());doc.getTemplate().setLeft(header);PdfPageTemplateElement topSpace = new PdfPageTemplateElement(pageSize.getWidth(), margin.getTop());topSpace.setForeground(true);doc.getTemplate().setTop(topSpace);//添加页眉PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,10),true);PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);String label = "2018年 年度会议报告";Dimension2D dimension2D = new Dimension();dimension2D.setSize(font.measureString(label, format));float y = topSpace.getHeight() - font.getHeight() - 1;PdfPen pen = new PdfPen(new PdfRGBColor(Color.black), 0.75f);topSpace.getGraphics().setTransparency(0.5f);topSpace.getGraphics().drawLine(pen, margin.getLeft(), y, pageSize.getWidth() - margin.getRight(), y);y = y - 1 - (float) dimension2D.getHeight();topSpace.getGraphics().drawString(label, font, PdfBrushes.getBlack(), margin.getLeft(), y, format);PdfPageTemplateElement rightSpace = new PdfPageTemplateElement(margin.getRight(), pageSize.getHeight());doc.getTemplate().setRight(rightSpace);//添加显示当前页及总页数的域作为页脚PdfPageTemplateElement footer = new PdfPageTemplateElement(pageSize.getWidth(), margin.getBottom());footer.setForeground(true);doc.getTemplate().setBottom(footer);y = font.getHeight() + 1;footer.getGraphics().setTransparency(0.5f);footer.getGraphics().drawLine(pen, margin.getLeft(), y, pageSize.getWidth() - margin.getRight(), y);y = y + 1;PdfPageNumberField pageNumber = new PdfPageNumberField();PdfPageCountField pageCount = new PdfPageCountField();PdfCompositeField pageNumberLabel = new PdfCompositeField();pageNumberLabel.setAutomaticFields(new PdfAutomaticField[]{pageNumber, pageCount});pageNumberLabel.setBrush(PdfBrushes.getBlack());pageNumberLabel.setFont(font);format = new PdfStringFormat(PdfTextAlignment.Right);pageNumberLabel.setStringFormat(format);pageNumberLabel.setText("第{0}页 共{1}页");pageNumberLabel.setBounds(footer.getBounds());pageNumberLabel.draw(footer.getGraphics(), pageSize.getWidth() - margin.getLeft(), y);}
}

另一种方法:

http://www.manongjc.com/detail/26-ircnbfeycmxpyes.html

自测有用

1.PDF工具类(预览、图像,Word转PDF)
<!--操作PDF依赖,图片转PDF会用到--><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.4.3</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency><dependency><groupId>com.itextpdf.tool</groupId><artifactId>xmlworker</artifactId><version>5.4.1</version></dependency><dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.10.1</version></dependency><!--操作PDF依赖,Word转PDF会用到--><dependency><groupId>com.documents4j</groupId><artifactId>documents4j-local</artifactId><version>1.0.3</version></dependency><dependency><groupId>com.documents4j</groupId><artifactId>documents4j-transformer-msoffice-word</artifactId><version>1.0.3</version></dependency>
package com.jero.util;import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;import com.jero.common.exception.JeroBootException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;/*** @Author: liao* @Date: 2023/3/210:36* 操作PDF工具类*/
@Slf4j
public class PdfUtil {private PdfUtil(){}/** 预览PDF文件* */public static void filePreview(File file,HttpServletResponse response) {try {response.setContentType("application/pdf");FileInputStream in = new FileInputStream(file);OutputStream out = response.getOutputStream();byte[] b = new byte[1024];while ((in.read(b))!=-1) {out.write(b);}out.flush();in.close();out.close();} catch (Exception e) {throw new JeroBootException(e);}}public static void wordToPdf(MultipartFile file, HttpServletResponse response){try {response.setContentType("application/pdf");InputStream docxInputStream = file.getInputStream();ServletOutputStream outputStream = response.getOutputStream();IConverter converter = LocalConverter.builder().build();converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();outputStream.close();} catch (Exception e) {throw new JeroBootException(e);}}/*** 图片转换PDF的公共接口** @param file     SpringMVC获取的图片文件* @param response HttpServletResponse* @throws IOException       IO异常* @throws DocumentException PDF文档异常*/public static void imageToPdf(MultipartFile file, HttpServletResponse response){try {File pdfFile = generatePdfFile(file);filePreview(pdfFile,response);} catch (Exception e) {throw new JeroBootException(e);}}/*** 将图片转换为PDF文件** @param file SpringMVC获取的图片文件* @return PDF文件* @throws IOException       IO异常* @throws DocumentException PDF文档异常*/private static File generatePdfFile(MultipartFile file) throws IOException, DocumentException{String fileName = file.getOriginalFilename();if (fileName == null) {throw new JeroBootException("文件名为空");}String pdfFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";Document doc = new Document(PageSize.A4, 20, 20, 20, 20);PdfWriter.getInstance(doc, new FileOutputStream(pdfFileName));doc.open();doc.newPage();Image image = Image.getInstance(file.getBytes());float height = image.getHeight();float width = image.getWidth();int percent = getPercent(height, width);image.setAlignment(Image.MIDDLE);image.scalePercent(percent);doc.add(image);doc.close();File pdfFile = new File(pdfFileName);return pdfFile;}/*** 等比压缩,获取压缩百分比** @param height 图片的高度* @param weight 图片的宽度* @return 压缩百分比*/private static int getPercent(float height, float weight) {float percent;if (height > weight) {percent = PageSize.A4.getHeight() / height * 100;} else {percent = PageSize.A4.getWidth() / weight * 100;}return Math.round(percent);}}负载

Java操作PDF大全相关推荐

  1. JAVA操作pdf——创建表格

    JAVA操作pdf--创建表格 一.前言 在实习的时候遇到了需要将查询到的数据构建成为PDF的情况,于是在网上查找到了相关的Java操作pdf的教程,看到大部分的文章都是使用ITextPdf操作的,于 ...

  2. 【Java 代码实例 13】Java操作pdf的工具类itext

    目录 一.什么是iText? 二.引入jar 1.项目要使用iText,必须引入jar包 2.输出中文,还要引入下面```itext-asian.jar```包 3.设置pdf文件密码,还要引入下面` ...

  3. java 操作 PDF

    近来收到一个需求, 制作 PDF 制作发票. 类似于制作这样的发票 技术选型我选择java 在网上寻找了一些操作PDF的框架决定用iText制作, 因为它比较活跃, 而且后期做签章和插入图片二维码都有 ...

  4. java操作pdf制作电子签章

    #java操作pdf制作电子签章 ##电子签章简介 电子签章,与我们所使用的数字证书一样,是用来做为身份验证的一种手段,泛指所有以电子形式存在,依附在电子文件并与其逻辑关联,可用以辨识电子文件签署者身 ...

  5. java操作PDF文件,可支持分页、合并、图片转PDF等

    java操作PDF,有一个很好用的工具--pdfbox.只需要引入依赖,即可使用. <dependency><groupId>org.apache.pdfbox</gro ...

  6. Java操作PDF之iText超入门

    转自:https://www.cnblogs.com/liaojie970/p/7132475.html Java操作PDF之iText超入门 iText是著名的开放项目,是用于生成PDF文档的一个j ...

  7. java操作PDF实现简单盖章功能(未签字)

    最近有一个电子签章的功能需求,网上相关的资料比较少,我查阅了相关资料,做了一个简单的盖章功能的demo 首先需要导个依赖,这里选用的是itextpdf来操作pdf <dependencies&g ...

  8. java在模板图片中填写文字,java 操作pdf模板(向指定域添加文本内容和图片)

    项目需求涉及到操作pdf模板,根据生成好的模板向里面填充数据 用到的jar包是iText-5.0.6.jar 和iTextAsian.jar 上代码: public static void main( ...

  9. java中pdf写成base64文件流,Java操作pdf文件与Base64编码相互转换与文件流操作

    1.第一步,引入bc包的安装依赖. 在pom.xml中引入. org.bouncycastle bcprov-jdk15on 1.60 引入后reimport一下项目. 2.pdf文件转换成Base6 ...

最新文章

  1. React中跨域问题的完美解决方案
  2. rax+react hook 实现分页效果
  3. 初识 Cisco Packet Tracer 思科模拟器 入门基础教学
  4. Git廖雪峰 常用命令总结
  5. memcached-tool
  6. 秒杀功能设计思想 php,seckill-system-php
  7. VS2019配置WinPcap开发
  8. StarRocks 在中移物联网 PGW 实时会话业务领域的应用
  9. 批量提取PDF和图片发票信息 2.2
  10. 互联网应用:不以抄袭为耻,但以抄袭为常
  11. linux如何给手机刷recovery,教你修改RECOVERY文件教程---转帖原作者为小秋
  12. C++虚函数表的应用
  13. influxdb学习记录
  14. 基于Mirai框架的QQ机器人使用文档----郑大科协2021招新群
  15. Unity无缝地图研究
  16. Android绘图:360加速球
  17. 如何更改pdf文件的默认打开程序?
  18. Linux九阴真经之九阴白骨爪残卷14(备份和恢复)
  19. 翻译概论——(五)西方翻译史
  20. 小吴--毕业设计--锂电池生产环境温湿度信息管理系统

热门文章

  1. 在线报刊html代码,HTML5 虚拟现实- 3D阅读漂浮的报刊
  2. 小程序的优势和劣势有哪些?
  3. 这一次,Windows 站起来了:Windows ​ Linux 的性能 Battle
  4. 新闻稿格式以及新闻稿写作须知
  5. 巨硬招硬件了!微软 MTE 邀您一起打造世界顶级硬件产品
  6. SparkSteaming程序异常问题排查步骤
  7. javaswing 设置背景图片
  8. php移动商城源码,GitHub - longmix/shopmallmobile: 商城系统源代码移动商城版本,完整的服务器调用,商品展示/用户中心/订单/支付/购物车/功能齐全...
  9. 学校的课程表,过来人的话——没用
  10. 服装类软文有哪些写作技巧?怎样提高服装网站关键词排名?