Java利用POI生成Word、Excel文档转换成PDF,PDF转换成图片

摘要

本篇文章带大家使用Java来实现生成Word、Excel文档,然后将Word或Excel文档转换成PDF,最后再将PDF转换成图片,这里是根据我业务需求进行开发(我这边是对接第三方公司将检测数据同步的时候入库并且生成检测报告,首先是将检测报告的数据生成Word模板,然后将Word转换成PDF最后转换成图片显示在页面查看),有需要的伙伴可以参考借鉴一下。

准备

  1. 引入相关的jar包(POI相关jar包大家网上下载)

    word转pdf需要引入 aspose-words-15.8.0-jdk16.jar。 点击下载 (提取码:0vth)

    Excel转PDF需要引入aspose-cells-8.5.2.jar。 点击下载 (提取码:pnqw)

  2. 引入license.xml文件(备注:license文件只能破解Word版本)
    Java利用POI生成Word、Excel文档转换成PDF,PDF转换成图片_第1张图片

    <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>
    

步骤

第一步:创建工具类
Java利用POI生成Word、Excel文档转换成PDF,PDF转换成图片_第2张图片

第二步:开发工具类所需方法(每个方法都有注释说明)

package com.hontek.detectiondevice.comm;

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.hontek.comm.util.DirectoryUtil;
import com.hontek.detectiondevice.pojo.CheckEquipment;
import com.hontek.detectiondevice.pojo.CheckInfo;
import com.hontek.detectiondevice.pojo.CheckInfoDetail;
import org.apache.log4j.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;


/**
 * 检测报告工具类
 * @Description: TODO
 * @Author: yang
 * @Date 2020/12/21 11:37
 */
public class DetectionReportUtils {

	private static Logger logger = Logger.getLogger(DetectionReportUtils.class);

	public static void generateExcelFile(CheckEquipment equipment,CheckInfo info, CheckInfoDetail detail, HttpServletRequest request){
		try {
			
			// 第一步,创建一个webbook,对应一个Excel文件
			HSSFWorkbook wb = new HSSFWorkbook();
			// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
			HSSFSheet sheet = wb.createSheet(detail.getSampleName()+detail.getItemName()+"速测检测报告");
			// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
			HSSFCellStyle style = wb.createCellStyle();
			style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

			HSSFFont font = wb.createFont();
			font.setFontName("等线");
			font.setFontHeightInPoints((short) 20);//设置字体大小
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示

			style.setFont(font);


			sheet.addMergedRegion(new CellRangeAddress(0,0,0,7));	//跨列

			HSSFRow row = sheet.createRow((int) 0);
			row.setHeight((short) (50 * 20));
			sheet.setColumnWidth(0, (short) (30 * 50));
			sheet.setColumnWidth(1, (short) (50 * 50));
			sheet.setColumnWidth(2, (short) (50 * 65));
			sheet.setColumnWidth(3, (short) (50 * 65));
			sheet.setColumnWidth(4, (short) (50 * 55));
			sheet.setColumnWidth(5, (short) (50 * 55));
			sheet.setColumnWidth(5, (short) (50 * 55));
			sheet.setColumnWidth(7, (short) (80 * 100));
			StringBuffer lable = new StringBuffer();
			lable.append("农产品质量安全检测");

			HSSFCell cell = row.createCell(0);
			cell.setCellValue(lable.toString());
			cell.setCellStyle(style);

			HSSFFont font1 = wb.createFont();
			font1.setFontName("等线");
			font1.setFontHeightInPoints((short) 16);//设置字体大小

			HSSFCellStyle style1 = wb.createCellStyle();
			style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直
			style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style1.setWrapText(true);
			style1.setFont(font1);

			sheet.addMergedRegion(new CellRangeAddress(1,1,0,7));	//跨列

			HSSFRow row1 = sheet.createRow((int)1);
			row1.setHeight((short) (26 * 20));

			StringBuffer lable1 = new StringBuffer();
			lable1.append("速测检测报告");

			HSSFCell cell1 = row1.createCell(0);
			cell1.setCellValue(lable1.toString());
			cell1.setCellStyle(style1);

			HSSFFont font2 = wb.createFont();
			font2.setFontName("等线");
			font2.setFontHeightInPoints((short) 11);//设置字体大小

			HSSFCellStyle style2 = wb.createCellStyle();
			style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直
			style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);
			style2.setWrapText(true);
			style2.setFont(font2);

			HSSFRow row2 = sheet.createRow((int)2);
			row2.setHeight((short) (20 * 20));

			StringBuffer lable2 = new StringBuffer();
			String reportNo = info.getReportNo();
			if(reportNo.equals("")&&reportNo == null){
				lable2.append("报告编号:"+"");
			}else {
				lable2.append("报告编号:"+reportNo);
			}
			HSSFCell cell2 = row2.createCell(0);
			cell2.setCellValue(lable2.toString());
			cell2.setCellStyle(style2);
			cell2 = row2.createCell(3);
			cell2.setCellValue("");
			cell2.setCellStyle(style2);

			sheet.addMergedRegion(new CellRangeAddress(2,2,0,4));	//跨列
			sheet.addMergedRegion(new CellRangeAddress(2,2,5,7));	//跨列


			HSSFFont otherFont = wb.createFont();
			otherFont.setColor(HSSFColor.RED.index);
			otherFont.setFontName("等线");
			otherFont.setFontHeightInPoints((short) 11);//设置字体大小

			HSSFCellStyle otherStyle = wb.createCellStyle();
			otherStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直
			otherStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
			otherStyle.setWrapText(true);
			otherStyle.setFont(otherFont);



			HSSFRow row3 = sheet.createRow((int)3);
			row3.setHeight((short) (28 * 20));

			StringBuffer lable3 = new StringBuffer();
			String entName = info.getEntName();
			if(entName.equals("")&&entName == null){
				lable3.append("样品来源:"+"");
			}else {
				lable3.append("样品来源:"+entName);
			}


			HSSFCell cell3 = row3.createCell(0);
			cell3.setCellValue(lable3.toString());
			cell3.setCellStyle(style2);
			cell3 = row3.createCell(5);
			if(info.getCiType() == 1){
				cell3.setCellValue("检测类型:"+"自检");
			}else if(info.getCiType() == 2){
				cell3.setCellValue("检测类型:"+"抽检");
			}
			cell3.setCellStyle(otherStyle);

			CellRangeAddress cra1 = new CellRangeAddress(3,3,0,4);
			CellRangeAddress cra2 = new CellRangeAddress(3,3,5,7);
			sheet.addMergedRegion(cra1);	//跨列
			sheet.addMergedRegion(cra2);	//跨列

			// 使用RegionUtil类为合并后的单元格添加边框
			RegionUtil.setBorderBottom(1,cra1,sheet,wb); // 下边框
			RegionUtil.setBorderLeft(1,cra1,sheet,wb); // 左边框
			RegionUtil.setBorderRight(1,cra1,sheet,wb); // 有边框
			RegionUtil.setBorderTop(1,cra1,sheet,wb); // 上边框

			RegionUtil.setBorderBottom(1,cra2,sheet,wb); // 下边框
			RegionUtil.setBorderLeft(1,cra2,sheet,wb); // 左边框
			RegionUtil.setBorderRight(1,cra2,sheet,wb); // 有边框
			RegionUtil.setBorderTop(1,cra2,sheet,wb); // 上边框


			HSSFRow row4 = sheet.createRow((int)4);
			row4.setHeight((short) (28 * 20));

			StringBuffer lable4 = new StringBuffer();
			String ceName = equipment.getCeName();
			if(ceName.equals("")&&ceName == null){
				lable4.append("检测仪器:"+"");
			}else {
				lable4.append("检测仪器:"+ceName);
			}
			HSSFCell cell4 = row4.createCell(0);
			cell4.setCellValue(lable4.toString());
			cell4.setCellStyle(style2);
			cell4 = row4.createCell(5);
			if(info.getCiTime().equals("")&&info.getCiTime() == null){
				cell4.setCellValue("检测日期:"+"");
			}else {
				cell4.setCellValue("检测日期:"+info.getCiTime());
			}
			cell4.setCellStyle(style2);

			CellRangeAddress cra3 = new CellRangeAddress(4,4,0,4);
			CellRangeAddress cra4 = new CellRangeAddress(4,4,5,7);
			sheet.addMergedRegion(cra3);	//跨列
			sheet.addMergedRegion(cra4);	//跨列

			// 使用RegionUtil类为合并后的单元格添加边框
			RegionUtil.setBorderBottom(1,cra3,sheet,wb); // 下边框
			RegionUtil.setBorderLeft(1,cra3,sheet,wb); // 左边框
			RegionUtil.setBorderRight(1,cra3,sheet,wb); // 有边框
			RegionUtil.setBorderTop(1,cra3,sheet,wb); // 上边框

			RegionUtil.setBorderBottom(1,cra4,sheet,wb); // 下边框
			RegionUtil.setBorderLeft(1,cra4,sheet,wb); // 左边框
			RegionUtil.setBorderRight(1,cra4,sheet,wb); // 有边框
			RegionUtil.setBorderTop(1,cra4,sheet,wb); // 上边框


			HSSFCellStyle style5 = wb.createCellStyle();
			style5.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直
			style5.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style5.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style5.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            style5.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style5.setBorderTop(HSSFCellStyle.BORDER_THIN);
			style5.setWrapText(true);
			style5.setFont(font2);

			HSSFRow row5 = sheet.createRow((int)5);
			row5.setHeight((short) (32 * 20));


			HSSFCell cell5 = row5.createCell(0);
			cell5.setCellValue("序号");
			cell5.setCellStyle(style5);
			cell5 = row5.createCell(1);
			cell5.setCellValue("样品编号");
			cell5.setCellStyle(style5);
			cell5 = row5.createCell(2);
			cell5.setCellValue("样品名称");
			cell5.setCellStyle(style5);
			cell5 = row5.createCell(3);
			cell5.setCellValue("检测项目");
			cell5.setCellStyle(style5);
			cell5 = row5.createCell(4);
			cell5.setCellValue("抑制率\n(检测值)");
			cell5.setCellStyle(style5);
			cell5 = row5.createCell(5);
			cell5.setCellValue("检测\n结果");
			cell5.setCellStyle(style5);
			cell5 = row5.createCell(6);
			cell5.setCellValue("单项判\n定结果");
			cell5.setCellStyle(style5);
			cell5 = row5.createCell(7);
			cell5.setCellValue("检测标准");
			cell5.setCellStyle(style5);

			HSSFRow row6 = sheet.createRow((int)6);
			row6.setHeight((short) (80 * 20));


			HSSFCell cell6 = row6.createCell(0);
			cell6.setCellValue("1");
			cell6.setCellStyle(style5);
			cell6 = row6.createCell(1);
			cell6.setCellValue(detail.getSampleNo());
			cell6.setCellStyle(style5);
			cell6 = row6.createCell(2);
			cell6.setCellValue(detail.getSampleName());
			cell6.setCellStyle(style5);
			cell6 = row6.createCell(3);
			cell6.setCellValue(detail.getItemName());
			cell6.setCellStyle(style5);
			cell6 = row6.createCell(4);
			cell6.setCellValue(detail.getCheckValue());
			cell6.setCellStyle(style5);
			cell6 = row6.createCell(5);
			cell6.setCellValue(detail.getCheckResult());
			cell6.setCellStyle(style5);
			cell6 = row6.createCell(6);
			cell6.setCellValue(detail.getSingleResult());
			cell6.setCellStyle(style5);
			cell6 = row6.createCell(7);
			cell6.setCellValue(detail.getCheckStandard());
			cell6.setCellStyle(style5);


			HSSFRow row7 = sheet.createRow((int)7);
			row7.setHeight((short) (50 * 20));

			StringBuffer lable7 = new StringBuffer();
			String ciInfo = info.getCiInfo();
			if(ciInfo.equals("")&&ciInfo == null){
				lable7.append("备注:"+"");
			}else {
				lable7.append("备注:"+ciInfo);
			}
			HSSFCell cell7 = row7.createCell(0);
			cell7.setCellValue(lable7.toString());
			cell7.setCellStyle(style2);

			CellRangeAddress cra5 = new CellRangeAddress(7,7,0,7);
			sheet.addMergedRegion(cra5);	//跨列


			// 使用RegionUtil类为合并后的单元格添加边框
			RegionUtil.setBorderBottom(1,cra5,sheet,wb); // 下边框
			RegionUtil.setBorderLeft(1,cra5,sheet,wb); // 左边框
			RegionUtil.setBorderRight(1,cra5,sheet,wb); // 有边框
			RegionUtil.setBorderTop(1,cra5,sheet,wb); // 上边框

			HSSFRow row8 = sheet.createRow((int)8);
			row8.setHeight((short) (45 * 20));

			StringBuffer lable8 = new StringBuffer();
			String checkUnit = info.getCheckUnit();
			if(checkUnit.equals("")&&checkUnit == null){
				lable8.append("检测单位:"+"");
			}else {
				lable8.append("检测单位:"+checkUnit);
			}
			HSSFCell cell8 = row8.createCell(0);
			cell8.setCellValue(lable8.toString());
			cell8.setCellStyle(style2);

			CellRangeAddress cra6 = new CellRangeAddress(8,8,0,7);
			sheet.addMergedRegion(cra6);	//跨列


			// 使用RegionUtil类为合并后的单元格添加边框
			RegionUtil.setBorderBottom(1,cra6,sheet,wb); // 下边框
			RegionUtil.setBorderLeft(1,cra6,sheet,wb); // 左边框
			RegionUtil.setBorderRight(1,cra6,sheet,wb); // 有边框
			RegionUtil.setBorderTop(1,cra6,sheet,wb); // 上边框

			HSSFRow row9 = sheet.createRow((int)9);
			row9.setHeight((short) (45 * 20));

			StringBuffer lable9 = new StringBuffer();
			String checkMan = info.getCheckMan();
			if(checkMan.equals("")&&checkMan == null){
				lable9.append("检测人员:"+"");
			}else {
				lable9.append("检测人员:"+checkMan);
			}
			HSSFCell cell9 = row9.createCell(0);
			cell9.setCellValue(lable9.toString());
			cell9.setCellStyle(style2);

			CellRangeAddress cra7 = new CellRangeAddress(9,9,0,7);
			sheet.addMergedRegion(cra7);	//跨列


			// 使用RegionUtil类为合并后的单元格添加边框
			RegionUtil.setBorderBottom(1,cra7,sheet,wb); // 下边框
			RegionUtil.setBorderLeft(1,cra7,sheet,wb); // 左边框
			RegionUtil.setBorderRight(1,cra7,sheet,wb); // 有边框
			RegionUtil.setBorderTop(1,cra7,sheet,wb); // 上边框


			// 保存Excel文件
			try {

				long old = System.currentTimeMillis();

				File fileDir = DirectoryUtil.getDirectoryByName(request, "detectionFiles");
				String excelPath = fileDir.getAbsolutePath()+File.separator+detail.getSampleNo()+".xls";
				String pdfPath = fileDir.getAbsolutePath()+File.separator+detail.getSampleNo()+".pdf";
				String imgPath = fileDir.getAbsolutePath()+File.separator+detail.getSampleNo()+".png";
				OutputStream outputStream = new FileOutputStream(excelPath);
				wb.write(outputStream);
				outputStream.close();
				//excel转为pdf
				excel2pdf(excelPath,pdfPath);
				//pdf转为png
				pdf2png(fileDir.getAbsolutePath(),detail.getSampleNo());

				long now = System.currentTimeMillis();

				logger.info("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时

				/*String excelPath = "G:/"+sampleNo+".xls";
				String pdfPath = "G:/"+sampleNo+".pdf";
				String imgPath = "G:/"+sampleNo+".png";
				OutputStream outputStream = new FileOutputStream(excelPath);
				wb.write(outputStream);
				outputStream.close();
				//excel转为pdf
				excel2pdf(excelPath,pdfPath);
				//pdf转为png
				pdf2png("G:",sampleNo);*/

			} catch (Exception e) {
				e.printStackTrace();
				logger.error("转换异常:"+e.getMessage());
			}


		} catch (Exception e) {
			e.printStackTrace();
			logger.error("系统异常:"+e.getMessage());

		}
	}

	/**
	 * 获取license.xml(去除水印)
	 * @Author yang
	 * @Date   2021/01/04 16:39
	 **/
	private static boolean getLicense() {
		boolean result = false;
		try {
			InputStream is = DetectionReportUtils.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
			License aposeLic = new License();
			aposeLic.setLicense(is);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * Word文件转PDF
	 * @param wordPath 需要被转换的word全路径带文件名
	 * @param pdfPath 转换之后pdf的全路径带文件名
	 */
	public static void doc2pdf(String wordPath, String pdfPath) {
		if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
			return;
		}
		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, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
			long now = System.currentTimeMillis();
			os.close();
			System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Excel文件转PDF
	 * @param excelPath 需要被转换的excel全路径带文件名
	 * @param pdfPath 转换之后pdf的全路径带文件名
	 */
	public static void excel2pdf(String excelPath, String pdfPath) {
		if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
			return;
		}
		try {
			Workbook wb = new Workbook(excelPath);// 原始excel路径
			PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
			pdfSaveOptions.setOnePagePerSheet(true);//把内容放在一张PDF 页面上
			FileOutputStream fileOS = new FileOutputStream(new File(pdfPath));
			wb.save(fileOS, pdfSaveOptions);
			fileOS.close();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("Excel文件转PDF出错");
		}
	}

	/**
	 * 转换PDF为图片
	 * @Author yang
	 * @Date   2021/01/04 16:39
	 **/
	public static void pdf2png(String filepath,String filename) throws IOException {
		try {
			// 将pdf装图片 并且自定义图片得格式大小
			File file = new File(filepath,filename+".pdf");

			PDDocument doc = PDDocument.load(file);
			PDFRenderer renderer = new PDFRenderer(doc);
			//BufferedImage image = renderer.renderImageWithDPI(0, 72); // Windows native DPI

			BufferedImage image = renderer.renderImage(0, 1);

			ImageIO.write(image, "png", new File(filepath,filename+".png"));
			doc.close();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("转换PDF为图片pdf2png出错:"+filename);
		}

	}

	public static void main(String[] args) {
		//generateExcelFile("2020000003","鹰嘴桃","农药残留");

	}

}

欢迎小伙伴留言评论,需要完整代码的加我QQ:450938667

你可能感兴趣的:(poi,excel,java)