HeavenTang

导航

导出离校单,单个word, word转pdf, word里面有图片

引入
@Autowired
private HttpServletResponse response;
@Autowired
private HttpServletRequest request;

实现类导出单个word

点击查看代码
public void exportStudentWordOld(JcsjLxxsxxDTO jcsjLxxsxxDTO){
		String schoolName = jcsjLxxsglVOMapper.querySchoolName();
		OutputStream outputStream = null;
		BufferedInputStream bis = null;
		try{
			String realPath = request.getSession().getServletContext().getRealPath("");
			String fileName = jcsjLxxsxxDTO.getXh() + "_"+jcsjLxxsxxDTO.getXm()+"离校报告单信息.doc";
			String filePath = realPath + "/" + fileName;
			response.setContentType("multipart/form-data");
			// 下载文件能正常显示中文

			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName));
			outputStream = response.getOutputStream();

			List<JcsjLxxsglVO> jcsjLxxsglVOList= jcsjLxxsglVOMapper.selectStudentLeavingInfo(jcsjLxxsxxDTO);
			Integer i = 0;
			JcsjLxxsglVO jcsjLxxsglVO = jcsjLxxsglVOList.get(0);
			//查询学生离校流程信息
			List<LcglLchjPrintVO>lcglLchjPrintVOS = jcsjLxxsglVOMapper.selectLcxxByXh(jcsjLxxsglVO.getXh());
			if(CollectionUtils.isNotEmpty(lcglLchjPrintVOS) && lcglLchjPrintVOS.size()>0 && !ObjectUtils.isEmpty(lcglLchjPrintVOS.get(0))){
				jcsjLxxsglVO.setHjxxList(lcglLchjPrintVOS);
			}
			i++;
			Document document = new Document(PageSize.A4);
			RtfWriter2 rtfWriter2 = RtfWriter2.getInstance(document,new FileOutputStream(filePath));
			document.open();
			StudentLeavingWord studentLeavingWord  = new StudentLeavingWord();
			studentLeavingWord.leavingWordTemplate(document,jcsjLxxsglVO,schoolName,jcsjLxxsxxDTO.getExportType());
			document.close();
			if (rtfWriter2 != null) {
				rtfWriter2.close();
			}
			File file = new File(filePath);
			try {
					bis = new BufferedInputStream(new FileInputStream(filePath));
					int len = 0;
					byte[] buffer = new byte[1024];
					while ((len = bis.read(buffer)) > 0) {
						outputStream.write(buffer, 0, len);
					}

			} catch (Exception e) {
				log.error("context", e);
			} finally {
				if (file.exists()) {
					boolean delete = file.delete();
					if (!delete) {
						log.error("context", file.getName()+"删除失败");
					}
				}
			}

			outputStream.flush();
		}catch (Exception e) {
			log.error("导出word失败的原因是:" + e);
		} finally {
			try {
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

实现类zip里面word转pdf

点击查看代码
public void exportStudentWord(JcsjLxxsxxDTO jcsjLxxsxxDTO){
		String schoolName = jcsjLxxsglVOMapper.querySchoolName();


		String downloadName = jcsjLxxsxxDTO.getXh() + "_"+jcsjLxxsxxDTO.getXm()+"离校报告单导出.zip";
		String filePath = request.getSession().getServletContext().getRealPath("/");
		response.setContentType("application/zip;charset=utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + Encodes.urlEncode(downloadName));
		try (
				OutputStream outputStream = response.getOutputStream();
				ZipOutputStream zos = new ZipOutputStream(outputStream)
		) {

			String fileName = jcsjLxxsxxDTO.getXh() + "_"+jcsjLxxsxxDTO.getXm()+"离校报告单信息.doc";
			File outFilePath = new File(filePath + "/" + fileName);
			File outFile = new File(filePath + "/" + fileName);
			byte[] buffer = new byte[1024];
			int len = 0;
			ZipEntry zipEntry = new ZipEntry(fileName);
			BufferedInputStream bufferedInputStream = null;
			BufferedInputStream bis = null;
			try {
				List<JcsjLxxsglVO> jcsjLxxsglVOList= jcsjLxxsglVOMapper.selectStudentLeavingInfo(jcsjLxxsxxDTO);
				Integer i = 0;
				JcsjLxxsglVO jcsjLxxsglVO = jcsjLxxsglVOList.get(0);
				//查询学生离校流程信息
				List<LcglLchjPrintVO>lcglLchjPrintVOS = jcsjLxxsglVOMapper.selectLcxxByXh(jcsjLxxsglVO.getXh());
				if(CollectionUtils.isNotEmpty(lcglLchjPrintVOS) && lcglLchjPrintVOS.size()>0 && !ObjectUtils.isEmpty(lcglLchjPrintVOS.get(0))){
					jcsjLxxsglVO.setHjxxList(lcglLchjPrintVOS);
				}
				i++;
				Document document = new Document(PageSize.A4);
				RtfWriter2 rtfWriter2 = RtfWriter2.getInstance(document,new FileOutputStream(outFilePath));
				document.open();
				StudentLeavingWord studentLeavingWord  = new StudentLeavingWord();
				studentLeavingWord.leavingWordTemplate(document,jcsjLxxsglVO,schoolName,jcsjLxxsxxDTO.getExportType());
				document.close();
				if (rtfWriter2 != null) {
					rtfWriter2.close();
				}

				bis = new BufferedInputStream(new FileInputStream(outFile));

//				bufferedInputStream = new BufferedInputStream(new FileInputStream(outFile));

				// 这里是导出word
				if (!"pdf".equals(jcsjLxxsxxDTO.getExportType())) {
					zos.putNextEntry(zipEntry);
					while ((len = bis.read(buffer)) != -1) {
						zos.write(buffer, 0, len);
					}
				}
				if ("pdf".equals(jcsjLxxsxxDTO.getExportType())) {
					// 这里是doc转pdf, 但转出来的在linux里面字体有问题
					Consumer<Writer> consumer = writer1 -> {
						try {
							writer1.write(Common.fileToCharArray(outFile));
						} catch (IOException e) {
							log.error("转化为pdf失败:{}", e);
							throw new RuntimeException(e);
						}
					};
					PdfUtil.wordToPdf(zos, "学生证明", consumer);
				}

			} catch (FileNotFoundException | TemplateException e) {
				log.error("context", e);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (null != bufferedInputStream) {
					bufferedInputStream.close();
				}
				if (outFile.exists()) {
					if (!outFile.delete()) {
						log.info("删除失败!");
					}
				}
			}

		}catch (IOException e) {
			log.error("context", e);
		}


	}

工具类画word

点击查看代码
package com.ly.education.leaving.server.util;

import com.itextpdf.text.BaseColor;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPCell;
import com.ly.education.leaving.api.vo.basicData.JcsjLxxsglVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ObjectUtils;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class StudentLeavingWord {

    //隶书
    public BaseFont baseFontLs() {
        try {
            String font = "";
            if (Common.isLinux()) {
                font = "/usr/lib/jvm/java-1.8-openjdk/jre/lib/fonts/fallback/Helvetica.ttf";
            } else {
                font = "c:\\windows\\fonts\\Helvetica.ttf";
//                font = "/Helvetica.ttf";
            }
            return BaseFont.createFont(font, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件路径
     */
    public static final String FILE_TEMPLATE_PATH = "file/已办理.png";
    public void leavingWordTemplate(Document document, JcsjLxxsglVO jcsjLxxsglVO, String schoolName,String exportType)throws DocumentException, IOException {

        BaseFont bfChinese = this.baseFontLs();// 使用系统字体
//        BaseFont bfChinese = BaseFont.createFont("/Helvetica.ttf", BaseFont.IDENTITY_H, true);// 使用系统字体

//        BaseFont bfChinese = BaseFont.createFont();
        Font contextBoldFont0 = new Font(bfChinese,10,Font.NORMAL);
        Font contextBoldFont = new Font(bfChinese,12,Font.NORMAL);
        Font contextBoldFont1 = new Font(bfChinese,12,Font.HELVETICA);
        Font contextBoldFont2 = new Font(bfChinese,9,Font.NORMAL);
//        Font zysxFontBl = FontFactory.getFont("Helvetica", 8, Color.RED);
//        Font zysxFontBl = FontFactory.getFont("/Helvetica.ttf", 8, Color.RED);
        Font zysxFontBl = new Font(bfChinese,8,Font.NORMAL,Color.RED);
//        Font zysxFontBlueBl = FontFactory.getFont("Helvetica", 8, Color.BLUE);
//        Font zysxFontBlueBl = FontFactory.getFont("/Helvetica.ttf", 8, Color.BLUE);
        Font zysxFontBlueBl = new Font(bfChinese,8,Font.NORMAL,Color.BLUE);
//        Font zysxFont = new Font(bfChinese,8,Font.NORMAL);
        Font zysxrqFont = new Font(bfChinese,8,Font.NORMAL, Color.black);


        Table table = new Table(2);
        int[] widths = new int[]{37,57};
        table.setWidths(widths);
        table.setWidth(94);
        table.setAutoFillEmptyCells(false);
        table.setOffset(0f);
        table.setPadding(8f);

        String titleDetail = schoolName;
        if(StringUtils.isBlank(jcsjLxxsglVO.getLxdttms())){
            // schoolName +jcsjLxxsglVO.getBynf()+"年"+jcsjLxxsglVO.getByyf()+"月毕业研究生离校单"
            titleDetail = titleDetail + "毕业研究生离校单";
        }else{
            titleDetail = titleDetail + jcsjLxxsglVO.getLxdttms();
        }
        // 读入流程名称的离校头部描述
        Cell cell0 = new Cell(
                new Phrase(titleDetail,
                        FontFactory.getFont(FontFactory.HELVETICA,16,new Color(0, 0, 0, 252))));
        cell0.setColspan(2);
        cell0.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell0.setBorderColor(Color.WHITE);
        table.addCell(cell0);

        document.add(table);

        Paragraph pt0 = new Paragraph("恭喜您完成研究生学业,通过学位论文答辩,顺利毕业。请到以下部门办理离校手续。祝您毕业快乐,前程似锦,母校欢迎您常回来看看。",contextBoldFont0);
        pt0.setAlignment(0);
        pt0.setIndentationLeft(20);// 左缩进
        pt0.setIndentationRight(20);// 右缩进
        pt0.setFirstLineIndent(24);// 首行缩进
        pt0.setLeading(20f);// 行间距
        pt0.setSpacingBefore(2f);// 设置上空白
//        pt0.setSpacingAfter(5f);// 设置段落下空白
        document.add(pt0);

//        Paragraph pt1 = new Paragraph("学生端:查看环节情况。导出离校单。",contextBoldFont0);
//        pt1.setAlignment(0);
//        pt1.setIndentationLeft(20);// 左缩进
//        pt1.setIndentationRight(20);// 右缩进
//        pt1.setFirstLineIndent(24);// 首行缩进
//        pt1.setLeading(20f);// 行间距
//        pt1.setSpacingBefore(5f);// 设置上空白
//        pt1.setSpacingAfter(5f);// 设置段落下空白
//        document.add(pt1);

        Table table1 = new Table(6);
        int[] widths1 = new int[]{15,16,15,16,15,17};
        table1.setWidths(widths1);
        table1.setWidth(94);
        table1.setAutoFillEmptyCells(false);
        table1.setCellsFitPage(true);

        Cell cell1 = new Cell(new Phrase("姓名",contextBoldFont));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setVerticalAlignment(Element.ALIGN_CENTER);
        cell1.setColspan(1);
        cell1.setRowspan(1);
        table1.addCell(cell1);

        Cell cell2 = new Cell(new Phrase(jcsjLxxsglVO.getXm(),contextBoldFont));
        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell2.setVerticalAlignment(Element.ALIGN_CENTER);
        cell2.setColspan(1);
        cell2.setRowspan(1);
        table1.addCell(cell2);

        Cell cell3 = new Cell(new Phrase("学院",contextBoldFont));
        cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell3.setVerticalAlignment(Element.ALIGN_CENTER);
        cell3.setColspan(1);
        cell3.setRowspan(1);
        table1.addCell(cell3);

        Cell cell4 = new Cell(new Phrase(jcsjLxxsglVO.getBmmc(),contextBoldFont2));
//        Cell cell4 = new Cell(new Phrase("马克思主义学院学院啦",contextBoldFont2));
        cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell4.setVerticalAlignment(Element.ALIGN_CENTER);
        cell4.setColspan(1);
        cell4.setRowspan(1);
        table1.addCell(cell4);

        Cell cell5 = new Cell(new Phrase("学科/专业",contextBoldFont));
        cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell5.setVerticalAlignment(Element.ALIGN_CENTER);
        cell5.setColspan(1);
        cell5.setRowspan(1);
        table1.addCell(cell5);

        Cell cell6 = new Cell(new Phrase(jcsjLxxsglVO.getZymc(),contextBoldFont));
        cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell6.setVerticalAlignment(Element.ALIGN_CENTER);
        cell6.setColspan(1);
        cell6.setRowspan(1);
        table1.addCell(cell6);

        Cell cell7 = new Cell(new Phrase("学号",contextBoldFont));
        cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell7.setVerticalAlignment(Element.ALIGN_CENTER);
        cell7.setColspan(1);
        cell7.setRowspan(1);
        table1.addCell(cell7);

        Cell cell8 = new Cell(new Phrase(jcsjLxxsglVO.getXh(),contextBoldFont));
        cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell8.setVerticalAlignment(Element.ALIGN_CENTER);
        cell8.setColspan(1);
        cell8.setRowspan(1);
        table1.addCell(cell8);

        Cell cell9 = new Cell(new Phrase("学习形式",contextBoldFont));
        cell9.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell9.setVerticalAlignment(Element.ALIGN_CENTER);
        cell9.setColspan(1);
        cell9.setRowspan(1);
        table1.addCell(cell9);

        Cell cell10= new Cell(new Phrase(jcsjLxxsglVO.getXxxsmc(),contextBoldFont));
        cell10.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell10.setVerticalAlignment(Element.ALIGN_CENTER);
        cell10.setColspan(1);
        cell10.setRowspan(1);
        table1.addCell(cell10);

        Cell cell11 = new Cell(new Phrase("指导教师",contextBoldFont));
        cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell11.setVerticalAlignment(Element.ALIGN_CENTER);
        cell11.setColspan(1);
        cell11.setRowspan(1);
        table1.addCell(cell11);

        Cell cell12 = new Cell(new Phrase(jcsjLxxsglVO.getDsmc(),contextBoldFont));
        cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell12.setVerticalAlignment(Element.ALIGN_CENTER);
        cell12.setColspan(1);
        cell12.setRowspan(1);
        table1.addCell(cell12);

        Cell cell13 = new Cell(new Phrase("政治面貌",contextBoldFont));
        cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell13.setVerticalAlignment(Element.ALIGN_CENTER);
        cell13.setColspan(1);
        cell13.setRowspan(1);
        table1.addCell(cell13);

        Cell cell14 = new Cell(new Phrase(jcsjLxxsglVO.getZzmmmc(),contextBoldFont));
        cell14.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell14.setVerticalAlignment(Element.ALIGN_CENTER);
        cell14.setColspan(1);
        cell14.setRowspan(1);
        table1.addCell(cell14);

//        Cell cell15 = new Cell(new Phrase("入党/团年月",contextBoldFont));
        Cell cell15 = new Cell(new Phrase("地区",contextBoldFont));
        cell15.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell15.setVerticalAlignment(Element.ALIGN_CENTER);
        cell15.setColspan(1);
        cell15.setRowspan(1);
        table1.addCell(cell15);

//        Cell cell16 = new Cell(new Phrase(jcsjLxxsglVO.getRdtsj(),contextBoldFont));
        Cell cell16 = new Cell(new Phrase(jcsjLxxsglVO.getXq(),contextBoldFont));
        cell16.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell16.setVerticalAlignment(Element.ALIGN_CENTER);
        cell16.setColspan(1);
        cell16.setRowspan(1);
        table1.addCell(cell16);

        Cell cell17 = new Cell(new Phrase("联系电话",contextBoldFont));
        cell17.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell17.setVerticalAlignment(Element.ALIGN_CENTER);
        cell17.setColspan(1);
        cell17.setRowspan(1);
        table1.addCell(cell17);

        Cell cell18 = new Cell(new Phrase(jcsjLxxsglVO.getSjh(),contextBoldFont));
        cell18.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell18.setVerticalAlignment(Element.ALIGN_CENTER);
        cell18.setColspan(1);
        cell18.setRowspan(1);
        table1.addCell(cell18);

        List<Cell> cell19 = new ArrayList<>();

        if(CollectionUtils.isNotEmpty(jcsjLxxsglVO.getHjxxList()) && jcsjLxxsglVO.getHjxxList().size()>0 && !ObjectUtils.isEmpty(jcsjLxxsglVO.getHjxxList().get(0))){
            int n = jcsjLxxsglVO.getHjxxList().size()-jcsjLxxsglVO.getHjxxList().size()%3+(jcsjLxxsglVO.getHjxxList().size()%3 == 0?0:3);
            for(int i=0;i<n;i++){
                if(i<jcsjLxxsglVO.getHjxxList().size()){
                    Cell cell20 = new Cell();

                    Chunk chunk0 = new Chunk((i+1)+"\n",contextBoldFont);
                    Chunk chunk1 = new Chunk(jcsjLxxsglVO.getHjxxList().get(i).getLinkName()+"\n",contextBoldFont1);
                    Chunk chunk2 = new Chunk((StringUtils.isNotEmpty(jcsjLxxsglVO.getHjxxList().get(i).getLinkDescribe())?jcsjLxxsglVO.getHjxxList().get(i).getLinkDescribe():"")+"\n",contextBoldFont0);
                    cell20.add(chunk0);
                    cell20.add(chunk1);
                    cell20.add(chunk2);

                    // 图标
                    Resource resource = new ClassPathResource(FILE_TEMPLATE_PATH);
                    InputStream is = resource.getInputStream();
                    byte[] fileByte = toByteArray(is);
                    Image image = Image.getInstance(fileByte); // 替换为图片路径
                    image.setAlignment(Image.ALIGN_RIGHT);
                    float desiredHeight = 50f; // 设置想要的图片高度为50用户单位
                    image.scaleToFit(desiredHeight, desiredHeight); // 按比例缩放图片
//                    image.setAbsolutePosition(500f,700f);
//                    image.setSpacingBefore(-10);
                    Chunk chunk3 = null;
                    if(StringUtils.equals(jcsjLxxsglVO.getHjxxList().get(i).getHandlingState(),"1")){
                        if("pdf".equals(exportType)){
                            chunk3 = new Chunk( "                     (已办理)" +"\n "   ,
                                    (StringUtils.equals(jcsjLxxsglVO.getHjxxList().get(i).getHandlingState(),"1")? zysxFontBlueBl : zysxFontBl));
                            cell20.add(chunk3);
                        }else {
                            // 转pdf时,这个图片转不了,会导致文档异常
                            Chunk chunk3_1 = new Chunk("                             ", contextBoldFont);
                            chunk3 = new Chunk(image, desiredHeight, desiredHeight);
                            Chunk chunk3_2 = new Chunk("                             " + "\n ", contextBoldFont);
                            cell20.add(chunk3_1);
                            cell20.add(chunk3);
                            cell20.add(chunk3_2);
                        }
                    }else{
                        chunk3 = new Chunk( "                     (未办理)" +"\n "   ,
                                (StringUtils.equals(jcsjLxxsglVO.getHjxxList().get(i).getHandlingState(),"1")? zysxFontBlueBl : zysxFontBl));
                         /*   Chunk chunk3 = new Chunk((StringUtils.equals(jcsjLxxsglVO.getHjxxList().get(i).getHandlingState(),"1")?"                     (已办理)":"                     (未办理)")+"\n" ,
                            (StringUtils.equals(jcsjLxxsglVO.getHjxxList().get(i).getHandlingState(),"1")? zysxFontBlueBl : zysxFontBl));
                            */
                        cell20.add(chunk3);
                    }
                    Chunk chunk4 = new Chunk( "                          签字/盖章"+"\n " ,zysxrqFont);
                    cell20.add(chunk4);
                    Chunk chunk5 = new Chunk(  "                   年     月     日",zysxrqFont);
                    cell20.add(chunk5);


                    cell19.add(i,cell20);
                    cell19.get(i).setHorizontalAlignment(Element.ALIGN_CENTER);
//                    cell19.get(i).setVerticalAlignment(Element.ALIGN_CENTER);
                    cell19.get(i).setColspan(2);
                    cell19.get(i).setRowspan(5);
                    table1.addCell(cell19.get(i));
                }else {
                    cell19.add(i,new Cell());
                    cell19.get(i).setHorizontalAlignment(Element.ALIGN_CENTER);
//                    cell19.get(i).setVerticalAlignment(Element.ALIGN_CENTER);
                    cell19.get(i).setColspan(2);
                    cell19.get(i).setRowspan(5);
                    table1.addCell(cell19.get(i));
                }


            }
        }

        document.add(table1);

//        List<String> footDetails = new ArrayList<>();
//        footDetails.add("")
        String footDetail = jcsjLxxsglVO.getLxdwbms();
        if(StringUtils.isBlank(footDetail)){
            // 默认这个话
            footDetail = "1、离校手续办理时间段:6月24日至6月28日,办理完成后,可以领取毕业证、学位证。\n" +
                    "2、学费未交清的毕业生请及时缴纳学费。缴学费需通过支付宝(登录支付宝,定位到“杭州”,选择“政务”,选择“公共支付”,选择“按执收单位”,查询要素选择“学号”,输入学号,查询金额并完成缴费);\n" +
                    "3、如您有国家助学贷款,请及时联系银行还款,否则将产生不良信用记录;\n" +
                    "4、毕业生档案一般寄发至“就业报到证”左上方的抬头单位,请本人及时查询自己的档案到达情况;\n" +
                    "5、毕业生“户口迁移证”“就业报到证”可自取、同学代领或通过挂号信邮寄,请及时查收。" ;
        }
        jcsjLxxsglVO.setLxdwbms(footDetail);

        Paragraph pt2 = new Paragraph(footDetail,contextBoldFont0);
//        Paragraph pt2 = new Paragraph("1、离校手续办理时间段:6月24日至6月28日,办理完成后,可以领取毕业证、学位证。\n" +
//                "2、学费未交清的毕业生请及时缴纳学费。缴学费需通过支付宝(登录支付宝,定位到“杭州”,选择“政务”,选择“公共支付”,选择“按执收单位”,查询要素选择“学号”,输入学号,查询金额并完成缴费);\n" +
//                "3、如您有国家助学贷款,请及时联系银行还款,否则将产生不良信用记录;\n" +
//                "4、毕业生档案一般寄发至“就业报到证”左上方的抬头单位,请本人及时查询自己的档案到达情况;\n" +
//                "5、毕业生“户口迁移证”“就业报到证”可自取、同学代领或通过挂号信邮寄,请及时查收。",contextBoldFont0);
        pt2.setAlignment(0);
        pt2.setIndentationLeft(20);// 左缩进
        pt2.setIndentationRight(20);// 右缩进
        pt2.setLeading(10f);// 行间距
        pt2.setSpacingBefore(5f);// 设置上空白
        pt2.setSpacingAfter(5f);// 设置段落下空白
        document.add(pt2);
    }


    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

}

工具类 word转pdf

点击查看代码
  package com.ly.education.leaving.server.util;

import com.aspose.words.FontSettings;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.LineSeparator;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.apache.commons.lang.StringUtils.EMPTY;

/**
 * itextpdf 表格工具类
 *
 * @Author: linjitai
 * @Date: 2019/7/6 11:46
 * @Author: update by linjitai on 20191017
 */
public class PdfUtil {

    //成绩打印 add by ljt
    private static final float borderWidth = 0.5f;//表格边框厚度


    // BaseFont 中文字体
    private static final BaseFont baseFont = createBaseFont();
    // 标题字体
    public static final Font titleFont = new Font(baseFont, 20, Font.NORMAL);
    // 小标题
    public static Font headFont = new Font(baseFont, 14, Font.BOLD);
    // 正文字体
    public static final Font normalFont = new Font(baseFont, 8, Font.NORMAL);
    // 空行
    public static final Paragraph blankRow = new Paragraph(10f, " ");

    public static final Font FONT15 = new Font(baseFont, 15, Font.NORMAL);
    public static final Font FONT14 = new Font(baseFont, 14, Font.NORMAL);
    public static final Font FONT13 = new Font(baseFont, 13, Font.NORMAL);
    public static final Font FONT12 = new Font(baseFont, 12, Font.NORMAL);
    public static final Font FONT11 = new Font(baseFont, 11, Font.NORMAL);
    public static final Font FONT10 = new Font(baseFont, 10, Font.NORMAL);
    public static final Font FONT9 = new Font(baseFont, 9, Font.NORMAL);
    public static final Font FONT8 = new Font(baseFont, 8, Font.NORMAL);
    public static final Font FONT7 = new Font(baseFont, 7, Font.NORMAL);
    public static final Font FONT6 = new Font(baseFont, 6, Font.NORMAL);
    public static final Font FONT5 = new Font(baseFont, 5, Font.NORMAL);

    // PDF最大宽度
    private static int maxWidth = 520;

    public static final String PDF_SUFFIX = ".pdf";
    public static final String DOC_SUFFIX = ".doc";
    public static final String DOCX_SUFFIX = ".docx";

    /**
     * 构造BaseFont 中文字体,静态工厂方法
     *
     * @return
     */
    private static BaseFont createBaseFont() {
        try {
            return BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static PdfPCell getCell(Phrase phrase, int border) {
        PdfPCell cell = new PdfPCell(phrase);
        cell.setBorder(border);
        return cell;
    }

    public static PdfPCell getCell(Phrase phrase, int horizontalAlignment, int verticalAlignment) {
        PdfPCell cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(horizontalAlignment);
        cell.setVerticalAlignment(verticalAlignment);
        return cell;
    }

    public static PdfPCell getCell(Phrase phrase, int border, int horizontalAlignment, int verticalAlignment) {
        PdfPCell cell = new PdfPCell(phrase);
        cell.setBorder(border);
        cell.setHorizontalAlignment(horizontalAlignment);
        cell.setVerticalAlignment(verticalAlignment);
        return cell;
    }

    public static PdfPCell getNoBorderCell(Phrase phrase) {
        PdfPCell cell = new PdfPCell(phrase);
        cell.setBorder(PdfPCell.NO_BORDER);
        return cell;
    }

    public static PdfPCell getAlignCenterCell(Phrase phrase) {
        PdfPCell cell = new PdfPCell(phrase);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        return cell;
    }

    public static PdfPCell getNoBorderAndAlignCenterCell(Phrase phrase) {
        PdfPCell cell = new PdfPCell(phrase);
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        return cell;
    }

    /**
     * 合并单元格并设值
     *
     * @param table
     * @param rowIndex
     * @param colIndex
     * @param value
     * @param font
     * @param colspan
     */
    public static void mergeCol(PdfPTable table, int rowIndex, int colIndex, String value, Font font, int colspan) {
        PdfUtil.removeBorderWidth(table, rowIndex, colIndex, colspan - 1);
        PdfUtil.setTableValueColSpan(table, rowIndex, colIndex, value, font, colspan);
    }

    /**
     * 隐藏表格边框
     *
     * @param table
     * @param rowIndex
     * @param colIndex
     */
    public static void removeBorderWidth(PdfPTable table, int rowIndex, int colIndex, int count) {
        //上侧
        for (int i = 1; i <= count; i++) {
            setTableBorderWidthTop(table, rowIndex, i + colIndex);
        }

        //下侧
        for (int i = 1; i <= count; i++) {
            setTableBorderWidthBottom(table, rowIndex, i + colIndex);
        }

        //左侧
        for (int i = 1; i <= count; i++) {
            setTableBorderWidthLeft(table, rowIndex, i + colIndex);
        }

        //右侧
        for (int i = 1; i <= count; i++) {
            setTableBorderWidthRight(table, rowIndex, i + colIndex);
        }
    }

    /**
     * 指定单元格 横向合并 赋值
     *
     * @param table
     * @param rowIndex
     * @param colIndex
     * @param value
     * @param font
     * @param colspan  合并单元格数目
     */
    public static void setTableValueColSpan(PdfPTable table, int rowIndex, int colIndex, String value, Font font, int colspan) {
        ArrayList rows = table.getRows();
        PdfPRow row = (PdfPRow) rows.get(rowIndex);
        PdfPCell[] cells = row.getCells();
        PdfPCell cell = cells[colIndex];
        Phrase newPhrase = Phrase.getInstance(2, value, font);
        cell.setColspan(colspan);
        cell.setBorderWidth(borderWidth);
        cell.setPhrase(newPhrase);
    }

    /**
     * 指定去除表格右侧线
     *
     * @param table
     * @param rowIndex
     * @param colIndex
     */
    public static void setTableBorderWidthRight(PdfPTable table, int rowIndex, int colIndex) {
        ArrayList rows = table.getRows();
        PdfPRow row = (PdfPRow) rows.get(rowIndex);
        PdfPCell[] cells = row.getCells();
        PdfPCell cell = cells[colIndex];
        cell.setBorderWidthRight(0);
    }

    /**
     * 指定去除表格上侧线
     *
     * @param table
     * @param rowIndex
     * @param colIndex
     */
    public static void setTableBorderWidthTop(PdfPTable table, int rowIndex, int colIndex) {
        ArrayList rows = table.getRows();
        PdfPRow row = (PdfPRow) rows.get(rowIndex);
        PdfPCell[] cells = row.getCells();
        PdfPCell cell = cells[colIndex];
        cell.setBorderWidthTop(0);
    }

    /**
     * 指定去除表格下侧线
     *
     * @param table
     * @param rowIndex
     * @param colIndex
     */
    public static void setTableBorderWidthBottom(PdfPTable table, int rowIndex, int colIndex) {
        ArrayList rows = table.getRows();
        PdfPRow row = (PdfPRow) rows.get(rowIndex);
        PdfPCell[] cells = row.getCells();
        PdfPCell cell = cells[colIndex];
        cell.setBorderWidthBottom(0);
    }

    /**
     * 指定去除表格左侧线
     *
     * @param table
     * @param rowIndex
     * @param colIndex
     */
    public static void setTableBorderWidthLeft(PdfPTable table, int rowIndex, int colIndex) {
        ArrayList rows = table.getRows();
        PdfPRow row = (PdfPRow) rows.get(rowIndex);
        PdfPCell cell = row.getCells()[colIndex];
        cell.setBorderWidthLeft(0);
    }


    /**
     * 指定单元格赋值(定位到row与col),相当于坐标系(x,y);row为y轴,col为x轴
     *
     * @param table
     * @param rowIndex
     * @param colIndex
     * @param value
     * @param font
     */
    public static void setTableValue(PdfPTable table, int rowIndex, int colIndex,
                                     String value, Font font) {
        PdfPCell cell = table.getRows().get(rowIndex).getCells()[colIndex];
        Phrase newPhrase = Phrase.getInstance(2, value, font);
        cell.setBorderWidth(borderWidth);
        cell.setPhrase(newPhrase);
    }

    /**
     * 填充表格
     *
     * @param table
     * @param font
     */
    public static void setAllTableValue(PdfPTable table, Font font) {
        ArrayList rows = table.getRows();
        for (int i = 1; i < rows.size(); i++) {
            PdfPRow row = (PdfPRow) rows.get(i);
            PdfPCell[] cells = row.getCells();
            for (int j = 0; j < cells.length; j++) {
                PdfPCell pdfPCell = cells[j];
                Phrase phrase = pdfPCell.getPhrase();
                Phrase newPhrase = Phrase.getInstance(2, "嘉佳" + i + j, font);
                pdfPCell.setPhrase(newPhrase);
            }
        }
    }

    /**
     * 生成一个表格并赋值
     *
     * @param value
     * @param font
     * @param align
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align) {
        return getPdfPCell(value, font, align, borderWidth);
    }

    public static PdfPCell createCell(String value, Font font, int align, float borderWidth) {
        return getPdfPCell(value, font, align, borderWidth);
    }

    private static PdfPCell getPdfPCell(String value, Font font, int align, float borderWidth) {
        PdfPCell cell = new PdfPCell();
        cell.setFixedHeight(Constant.FIXED_HEIGHT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setBorderWidth(borderWidth);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    public static PdfPCell createCell(String value, Font font, int align, float borderWidth, Integer fixedHeight) {
        return getPdfPCell(value, font, align, borderWidth, fixedHeight);
    }

    private static PdfPCell getPdfPCell(String value, Font font, int align, float borderWidth, Integer fixedHeight) {
        PdfPCell cell = new PdfPCell();
        if (null != fixedHeight) {
            cell.setFixedHeight(fixedHeight);
        }
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setBorderWidth(borderWidth);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    public static void addPdfTextMark(String InPdfFile, String outPdfFile, String textMark, int textWidth,
                                      int textHeight) throws Exception {
        Document doc = null;
        doc = new Document();
        OutputStream outputStream = null;
        PdfWriter writer = null;
        writer = PdfWriter.getInstance(doc, outputStream);

        PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));

        PdfContentByte under;

        BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", "Identity-H", true);// 使用系统字体

        // 原pdf文件的总页数
        int pageSize = reader.getNumberOfPages();
        for (int i = 1; i <= pageSize; i++) {
            // 水印在之前文本下
            under = stamp.getUnderContent(i);
            //水印在之前文本上
            // under = stamp.getOverContent(i);
            under.beginText();
            // 文字水印 颜色
            under.setColorFill(new BaseColor(211, 211, 211));
            // 文字水印 字体及字号
            under.setFontAndSize(font, 38);
            // 文字水印 起始位置
            under.setTextMatrix(textWidth, textHeight);
            under.showTextAligned(Element.ALIGN_CENTER, textMark, textWidth, textHeight, 45);
            under.endText();
        }
        // 关闭
        stamp.close();
    }

    /**
     * 添加文字水印
     *
     * @param pdfWriter
     * @param alignment 对其方式 右侧对齐:Element.ALIGN_RIGHT,左侧对齐:Element.ALIGN_LEFT
     * @param text      文本
     * @param x         x轴坐标(以对齐侧 为转轴进行旋转)
     * @param y         y轴坐标
     * @param rotation  角度
     */
    public static void setWaterMark(PdfWriter pdfWriter, final int alignment, final String text, final float x, final float y, final float rotation) {
        // 加入水印
        PdfContentByte waterMar = pdfWriter.getDirectContentUnder();
        // 开始设置水印
        waterMar.beginText();
        // 设置水印透明度
        PdfGState gs = new PdfGState();
        // 设置填充字体不透明度为0.4f
        gs.setFillOpacity(Constant.WATER_MARK_PDF_OPACITY);
        try {
            // 设置水印字体参数及大小(字体参数,字体编码格式,是否将字体信息嵌入到pdf中(一般不需要嵌入),字体大小)
            //支持中文
            BaseFont baseChina = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
//            BaseFont base = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
            waterMar.setFontAndSize(baseChina, Constant.WATER_MARK_PDF_SIZE);
            // 设置透明度
            waterMar.setGState(gs);
            // 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
            waterMar.showTextAligned(alignment, text, x, y, rotation);
            // 设置水印颜色
            waterMar.setColorFill(BaseColor.GRAY);
            //结束设置
            waterMar.endText();
            waterMar.stroke();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            waterMar = null;
            gs = null;
        }
    }

    /**
     * 设置图片水印
     *
     * @param pdfWriter
     * @param imagePath
     * @throws DocumentException
     */
    public static void setWaterMarkPic(PdfWriter pdfWriter, String imagePath) throws DocumentException {

        // 加入水印
        PdfContentByte waterMar = pdfWriter.getDirectContentUnder();
        // 开始设置水印
        waterMar.beginText();
        // 设置水印透明度
        PdfGState gs = new PdfGState();
        // 设置笔触字体不透明度为0.4f
        gs.setStrokeOpacity(0.4f);
        try {
            Image image = Image.getInstance(imagePath);
            // 设置坐标 绝对位置 X Y
            image.setAbsolutePosition(200, 300);
            // 设置旋转弧度
            image.setRotation(30);// 旋转 弧度
            // 设置旋转角度
            image.setRotationDegrees(45);// 旋转 角度
            // 设置等比缩放
            image.scalePercent(90);// 依照比例缩放
            // image.scaleAbsolute(200,100);//自定义大小
            // 设置透明度
            waterMar.setGState(gs);
            // 添加水印图片
            waterMar.addImage(image);
            // 设置透明度
            waterMar.setGState(gs);
            //结束设置
            waterMar.endText();
            waterMar.stroke();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            waterMar = null;
            gs = null;
        }
    }

    /**
     * 创建一个剧中对其的格子并赋值(有线框)
     *
     * @param info
     * @param font
     * @param horizontalAlignment 水平位置居上下左右
     * @param verticalAlignment 垂直位置居上下左右
     */
    public static PdfPCell setCell(String info, Font font,Integer horizontalAlignment,Integer verticalAlignment) {
        PdfPCell cell = new PdfPCell(new Phrase(info, font));
        cell.setPaddingTop(4.0f);
        cell.setPaddingBottom(4.0f);
        if(null == horizontalAlignment){
            horizontalAlignment = Element.ALIGN_CENTER;
        }
        cell.setHorizontalAlignment(horizontalAlignment);

        if(null == verticalAlignment){
            verticalAlignment = Element.ALIGN_MIDDLE;
        }
        cell.setVerticalAlignment(verticalAlignment);
//        cell.setFixedHeight(Constant.FIXED_HEIGHT);
        return cell;
    }

    public static PdfPCell setCell(String info, Font font,Integer horizontalAlignment,Integer verticalAlignment,Integer Height) {
        PdfPCell cell = new PdfPCell(new Phrase(info, font));
        cell.setPaddingTop(4.0f);
        cell.setPaddingBottom(4.0f);
        cell.setMinimumHeight(Height);
        if(null == horizontalAlignment){
            horizontalAlignment = Element.ALIGN_CENTER;
        }
        cell.setHorizontalAlignment(horizontalAlignment);

        if(null == verticalAlignment){
            verticalAlignment = Element.ALIGN_MIDDLE;
        }
        cell.setVerticalAlignment(verticalAlignment);
//        cell.setFixedHeight(Constant.FIXED_HEIGHT);
        return cell;
    }

    /**
     * 创建一个居中对其的格子并赋值(无线框)
     *
     * @param info
     * @param font
     * @return
     */
    public static PdfPCell setCellNoBorder(String info, Font font) {
        Phrase phrase = new Phrase(info, font);
        // 下划线
        if(StringUtils.isNotBlank(info)){
            int percentage = info.length()>7 ? 65:50;
            LineSeparator underline = new LineSeparator(1, percentage, BaseColor.GRAY, Element.ALIGN_LEFT, -2);
            phrase.add(underline);
        }

        PdfPCell cell = new PdfPCell(phrase);
        cell.setPaddingTop(7.0f);
        cell.setPaddingBottom(7.0f);
//        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
//        cell.setFixedHeight(Constant.FIXED_HEIGHT);
        cell.setBorder(PdfPCell.NO_BORDER);
        return cell;
    }

    /**
     * withs 与 infos 长度必须想等,不然得不到正确的结果
     * 表格循环遍历插入cell(无边框)
     *
     * @param withs
     * @param infos
     * @param font
     * @return
     * @throws DocumentException
     */
    public static PdfPTable fillTableNoBorder(float[] withs, String[] infos, Font font) throws DocumentException {
        PdfPTable table = new PdfPTable(withs.length);
        table.setWidths(withs);
        for (int i = 0; i < infos.length; i++) {
            table.addCell(setCellNoBorder(infos[i], font));
        }
        table.setWidthPercentage(Constant.WIDTH);
        return table;
    }

    /**
     * withs 与 infos 长度必须想等,不然得不到正确的结果
     * 表格循环遍历插入cell(有边框)
     *
     * @param withs
     * @param infos
     * @param font
     * @param horizontalAlignments 水平位置
     * @param verticalAlignments 垂直位置
     * @return
     * @throws DocumentException
     */
    public static PdfPTable fillTable(float[] withs, String[] infos, Font font, Integer[] horizontalAlignments,  Integer[] verticalAlignments) throws DocumentException {
        PdfPTable table = new PdfPTable(withs.length);
        table.setWidths(withs);
        for (int i = 0; i < infos.length; i++) {
            table.addCell(setCell(infos[i], font,horizontalAlignments[i],verticalAlignments[i]));
        }
        table.setWidthPercentage(Constant.WIDTH);
        return table;
    }
    //可以设置Cell高度
    public static PdfPTable fillTable(float[] withs, String[] infos, Font font, Integer[] horizontalAlignments,  Integer[] verticalAlignments,Integer cellHeight) throws DocumentException {
        PdfPTable table = new PdfPTable(withs.length);
        table.setWidths(withs);
        for (int i = 0; i < infos.length; i++) {
            table.addCell(setCell(infos[i], font,horizontalAlignments[i],verticalAlignments[i],cellHeight));
        }
        table.setWidthPercentage(Constant.WIDTH);
        return table;
    }

    /**
     * withs 与 infos 长度必须想等,不然得不到正确的结果
     * 嵌套表格(无边框)循环遍历插入cell
     *
     * @param withs
     * @param infos
     * @param font
     * @param horizontalAlignments 水平位置
     * @param verticalAlignments 垂直位置
     * @return
     * @throws DocumentException
     */
    public static PdfPCell fillInsideTable(float[] withs, String[] infos, Font font, Integer[] horizontalAlignments,  Integer[] verticalAlignments) throws DocumentException {
        PdfPTable table = new PdfPTable(withs.length);
        table.setWidths(withs);
        for (int i = 0; i < infos.length; i++) {
            table.addCell(setCell(infos[i], font,horizontalAlignments[i],verticalAlignments[i]));
        }
        PdfPCell cell = new PdfPCell(table);
        cell.setBorder(PdfPCell.NO_BORDER);
        return cell;
    }

    /**
     * word to pdf and compress to zip
     * 配合使用 freeMarker
     * 部分字符会丢失,比如 🐎, 一旦转换, 你🐎没了
     * 在linux系统上,如果字体缺失,中文将丢失变为小方框
     *
     * @param zos zip输出流
     */
    public static void wordToPdf(ZipOutputStream zos, String fileName, Consumer<? super Writer> action) throws Exception {
        String tempName = System.currentTimeMillis() + StringUtils.EMPTY;
        File tempDoc = File.createTempFile(tempName, DOC_SUFFIX);
        Writer fw = new FileWriter(tempDoc);
        action.accept(fw);
        fw.flush();
        fw.close();

        if (Common.isLinux()) {
            FontSettings.getDefaultInstance().setFontsFolder("/usr/lib/jvm/java-1.8-openjdk/jre/lib/fonts/fallback/", true);
        }else {
            FontSettings.getDefaultInstance().setFontsFolder("C:\\Windows\\Fonts", true);
        }

        File tempPdf = File.createTempFile(tempName, PDF_SUFFIX);
        com.aspose.words.Document doc = new com.aspose.words.Document(tempDoc.getAbsolutePath());
        OutputStream out = new FileOutputStream(tempPdf);
        doc.save(out, SaveFormat.PDF);
        out.close();

        FileInputStream fi = new FileInputStream(tempPdf);
        zos.putNextEntry(new ZipEntry(fileName + PDF_SUFFIX));
        int len = 0;
        byte[] buffer = new byte[1024 * 8];
        while ((len = fi.read(buffer)) != -1) {
            zos.write(buffer, 0, len);
        }
        fi.close();
        zos.closeEntry();
        tempDoc.delete();
        tempPdf.delete();
    }

    /**
     * word to pdf and compress to zip
     * 配合使用 freeMarker
     * 部分字符会丢失,比如 🐎, 一旦转换, 你🐎没了
     * 在linux系统上,如果字体缺失,中文将丢失变为小方框
     *
     * @param out outputStream输出流
     */
    public static void wordToOnePdf(OutputStream out, String fileName, Consumer<? super Writer> action) throws Exception {
//        String tempName = System.currentTimeMillis() + StringUtils.EMPTY;
        String tempName = fileName;
        File tempDoc = File.createTempFile(tempName, DOC_SUFFIX);
        Writer fw = new FileWriter(tempDoc);
        action.accept(fw);
        fw.flush();
        fw.close();

        File tempPdf = File.createTempFile(tempName, PDF_SUFFIX);
         com.aspose.words.Document doc = new com.aspose.words.Document(tempDoc.getAbsolutePath());
         out = new FileOutputStream(tempPdf);
        doc.save(out, SaveFormat.PDF);
        out.close();

       /* BufferedInputStream bis = new BufferedInputStream(new FileInputStream(tempPdf));
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = bis.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }*/

/*
        FileInputStream fi = new FileInputStream(tempPdf);
        zos.putNextEntry(new ZipEntry(fileName + PDF_SUFFIX));
        int len = 0;
        byte[] buffer = new byte[1024 * 8];
        while ((len = fi.read(buffer)) != -1) {
            zos.write(buffer, 0, len);
        }
        fi.close();
        zos.closeEntry();*/
//        tempDoc.delete();
//        tempPdf.delete();
    }

//    // 定义全局的字体静态变量
//    private static Font titlefont;
//    private static Font headfont = new Font(bfChinese, 14, Font.BOLD);
//    private static Font keyfont;
//    private static Font textfont;
//    // 最大宽度
//    private static int maxWidth = 520;
//    // 静态代码块
//    static {
//        try {
//            // 不同字体(这里定义为同一种字体:包含不同字号、不同style)
//            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//            titlefont = new Font(bfChinese, 16, Font.BOLD);
//            headfont = new Font(bfChinese, 14, Font.BOLD);
//            keyfont = new Font(bfChinese, 10, Font.BOLD);
//            textfont = new Font(bfChinese, 10, Font.NORMAL);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 生成pdf, 并压缩
     */
    public static void createPdfIntoZip(ZipOutputStream zos, String fileName, BiConsumer<PdfWriter, ? super Document> action)
            throws Exception {
        File tempPdf = File.createTempFile(fileName, PDF_SUFFIX);
        Document document = new Document(PageSize.A4);// 建立一个Document对象
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(tempPdf));
        document.open();
        // 自定义PDF内容
        action.accept(writer, document);
        document.close();
        // 压缩
        FileInputStream fi = new FileInputStream(tempPdf);
        zos.putNextEntry(new ZipEntry(fileName + PDF_SUFFIX));
        int len = 0;
        byte[] buffer = new byte[1024 * 8];
        while ((len = fi.read(buffer)) != -1) {
            zos.write(buffer, 0, len);
        }
        fi.close();
        zos.closeEntry();
        tempPdf.delete();
    }


    /**
     * 生成标题
     * @return
     */
    public static Paragraph generateTitle(String title){
        Paragraph paragraph = new Paragraph(title, titleFont);
        paragraph.setAlignment(Element.ALIGN_CENTER); //设置文字居中 0靠左   1,居中     2,靠右
        paragraph.setIndentationLeft(12); //设置左缩进
        paragraph.setIndentationRight(12); //设置右缩进
        paragraph.setFirstLineIndent(24); //设置首行缩进
        paragraph.setLeading(20f); //行间距
        paragraph.setSpacingBefore(5f); //设置段落上空白
        paragraph.setSpacingAfter(10f); //设置段落下空白
        return paragraph;
    }

    /**
     * 生成段落标题
     * @return
     */
    public static Paragraph generateParaTitle(String title){
        Paragraph paragraph = new Paragraph(title, headFont);
        paragraph.setAlignment(Element.ALIGN_LEFT); //设置文字居中 0靠左   1,居中     2,靠右
        paragraph.setLeading(20f); //行间距
        paragraph.setSpacingBefore(10f); //设置段落上空白
        paragraph.setSpacingAfter(10f); //设置段落下空白
        return paragraph;
    }

    /**
     * 生成段落内容
     * @return
     */
    public static Paragraph generateText(String text){
        Paragraph paragraph = new Paragraph(text, normalFont);
        paragraph.setAlignment(0); //设置文字居中 0靠左   1,居中     2,靠右
        paragraph.setSpacingAfter(10f); //设置段落下空白
        return paragraph;
    }

    /**
     * itext pdf 表格
     *
     * @param widths 列宽
     * @param align  水平(居中、右、左)的表格
     * @return
     */
    public static PdfPTable createPdfTable(float[] widths, int align) {
        PdfPTable table = new PdfPTable(widths);
        table.setTotalWidth(maxWidth);
        table.setLockedWidth(true);
        table.setHorizontalAlignment(align);
        table.getDefaultCell().setBorder(1);
        return table;

    }


    /**
     * 普通表格单元格设置
     * @param value
     * @param colspan
     * @param rowspan
     * @return
     */
    public static PdfPCell createCell(String value, int colspan, int rowspan){
        value = StringUtils.isNotEmpty(value) ? "null".equals(value) ? EMPTY : value : EMPTY;
        PdfPCell cell = new PdfPCell();
        if(rowspan > 1){
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        }
        cell.setPhrase(new Phrase(value, normalFont));
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        return cell;
    }

}

点击查看代码

package com.ly.education.leaving.server.util;

import com.ly.education.commons.exception.ServiceException;
import com.ly.education.commons.exception.SimpleErrorCode;
import com.ly.spring.boot.pagehelper.dto.PageQueryParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collection;

/**
 * @author: linjunfeng
 * @create: 2020-09-15
 */
@Slf4j
public class Common {

    public static String OS = System.getProperty("os.name").toLowerCase();

    public static boolean isLinux(){
        return OS.indexOf("linux")>=0;
    }

    public static boolean isWindows() {
        return OS.indexOf("windows") >= 0;
    }


    /**
     * 分页对象的param参数如果是空的,则赋值
     * @param dto 分页对象
     * @param tClass PageQueryParam的 param 属性类对象
     * @param <T> PageQueryParam的 param 属性类
     */
    public static <T> void pageQueryParamSetter(PageQueryParam dto, Class<T> tClass){
        if(dto.getParam() == null){
            try {
                dto.setParam(tClass.newInstance());
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断插入数量是否大于0
     * @param count
     */
    public static void validInsertCount( int count){
        validInsertCount(count,"保存失败.");
    }

    /**
     * 判断插入数量是否大于0
     * @param count
     */
    public static void validInsertCount( int count, String msg){
        if ( count < 1){
            log.warn(msg);
            throw new ServiceException(SimpleErrorCode.SaveFailure.getErrorCode(), msg );
        }
    }

    /**
     * 判断更新数量是否大于0
     * @param count
     */
    public static void validUpdateCount( int count){
        validUpdateCount(count, "更新失败.");
    }

    /**
     * 判断更新数量是否大于0
     * @param count
     */
    public static void validUpdateCount( int count, String msg){
        if ( count < 1){
            log.warn(msg);
            throw new ServiceException(SimpleErrorCode.ModifyFailure.getErrorCode(), msg);
        }
    }

    /**
     * 判断删除数量是否大于0
     * @param count
     */
    public static void validDeleteCount( int count){
        validDeleteCount(count, "删除失败.");
    }

    /**
     * 判断删除数量是否大于0
     * @param count
     */
    public static void validDeleteCount( int count, String msg){
        if ( count < 1){
            log.warn(msg);
            throw new ServiceException(SimpleErrorCode.DeleteFailure.getErrorCode(), msg);
        }
    }

    /**
     * 集合必须是空的
     * @param collection
     */
    public static void isNull( Collection<?> collection ){
        isNull(collection, "数据已存在.");
    }

    /**
     * 集合必须是空的
     * @param collection
     */
    public static void isNull( Collection<?> collection, String msg){
        if( !CollectionUtils.isEmpty(collection) ){
            log.warn(msg);
            throw new ServiceException(SimpleErrorCode.ParamsError.getErrorCode(), msg);
        }
    }

    /**
     * 对象必须是空的
     * @param object
     */
    public static void isNull( Object object ){
        isNull(object, "数据已存在.");
    }

    /**
     * 对象必须是空的
     * @param object
     */
    public static void isNull( Object object, String msg ){
        if( object != null){
            log.warn(msg);
            throw new ServiceException(SimpleErrorCode.ParamsError.getErrorCode(), msg);
        }
    }

    /**
     * 集合非空
     * @param collection
     */
    public static void notNull( Collection<?> collection ){
        notNull(collection, "数据不存在." );
    }


    /**
     * 集合非空
     * @param collection
     */
    public static void notNull( Collection<?> collection , String msg ){
        if( CollectionUtils.isEmpty( collection) ){
            log.warn(msg);
            throw new ServiceException(SimpleErrorCode.ParamsError.getErrorCode(), msg);
        }
    }
    /**
     *
     * 对象非空
     * @param object
     */
    public static void notNull( Object object ){
        notNull(object, "数据不存在.");
    }


    /**
     * 对象非空
     * @param object
     */
    public static void notNull( Object object, String msg ){
        if( object == null){
            log.warn(msg);
            throw new ServiceException(SimpleErrorCode.ParamsError.getErrorCode(), msg);
        }
    }

    /**
     * 结果为真
     */
    public static void isTrue( Boolean flag, String msg ){
        if( !flag ){
            log.warn(msg);
            throw new ServiceException(SimpleErrorCode.ParamsError.getErrorCode(), msg);
        }
    }

    public static char[] fileToCharArray(File file) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            StringBuilder stringBuilder = new StringBuilder();
            char[] buffer = new char[4096];
            int length;
            while ((length = reader.read(buffer)) != -1) {
                stringBuilder.append(buffer, 0, length);
            }
            return stringBuilder.toString().toCharArray();
        }
    }
}

文件字体,pdf需注意字体

posted on 2024-05-30 11:52  HeavenTang  阅读(6)  评论(0编辑  收藏  举报