springboot 2.3 导出pdf案例

1.添加依赖

<!--pdf依赖 -->

		<dependency>
			<groupId>com.lowagie</groupId>
			<artifactId>itext</artifactId>
			<version>2.1.7</version>
		</dependency>

		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.4.3</version>
		</dependency>

2. 创建ViewPDF类


package com.iflytek.edu.hnezzhxy.common.config;

import com.iflytek.edu.hnezzhxy.util.PdfUtil;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfWriter;
import org.springframework.web.servlet.view.document.AbstractPdfView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @version 1.0
 * @description
 * @create 2020/07/07 09:06
 */

public class ViewPDF extends AbstractPdfView {

    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,
                                    HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
        String fileName = "准考证.pdf";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition","filename=" + new String(fileName.getBytes(), "iso8859-1"));
        response.setHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes(), "iso8859-1"));
        PdfEntity bean = (PdfEntity) model.get("sheet");
        PdfUtil.createPDF(document, writer, bean);
    }
}

3.创建要打印的pdf中展示的动态数据model

/**
 * @version 1.0
 * @description
 * @create 2020/07/06 20:50
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PdfEntity {
    /** 姓名 **/
    private String name;
    /** 性别 **/
    private byte sex;
    /** 毕业学校 **/
    private String graduateSchool;
    /** 座位号 **/
    private String stuSeatNum;
    /** 班级 **/
    private String classes;
    /** 文件存储路径 **/
    private String fileUrl;
    /**审核状态**/
    private String status;

}

4.控制类

package com.iflytek.edu.hnezzhxy.controller;

import com.iflytek.edu.hnezzhxy.common.config.ExportStudentModel;
import com.iflytek.edu.hnezzhxy.common.config.PdfEntity;
import com.iflytek.edu.hnezzhxy.common.config.ViewPDF;
import com.iflytek.edu.hnezzhxy.model.ZsbmSubject;
import com.iflytek.edu.hnezzhxy.service.ExportService;
import com.iflytek.edu.hnezzhxy.util.htmToExcel.HtmlToExcelUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @version 1.0
 * @description
 * @create 2020/07/06 20:46
 */
@RestController
public class ExportController {

    @Autowired
    private ExportService exportService;

    /**
     * @description 导出pdf
     * @param sid
     * @return
     */
    @RequestMapping("/exportPdf")
    public ModelAndView exportPdf(@RequestParam(value = "sid") String sid) {
        //根据id查询导出的pdf文件信息
        PdfEntity bean=exportService.getPdfInfoBySid(sid);
        //状态未 没审核通过
        if(bean==null||!bean.getStatus().equals("1")){
        	return new ModelAndView("没审核通过,暂无准考证!");
        }
        Map<String, Object> model = new HashMap<>();
        model.put("sheet", bean);
        return new ModelAndView(new ViewPDF(), model);
    }
    
}

5.工具类也是重点,我是在此处拼pdftable打印的

	package com.iflytek.edu.hnezzhxy.util;

import com.iflytek.edu.hnezzhxy.common.config.PdfEntity;
import com.lowagie.text.*;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

import javax.imageio.ImageIO;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.StringJoiner;

/**
 * @version 1.0
 * @description
 * @create 2020/07/07 08:48
 */
public class PdfUtil {
    public static void createPDF(Document document, PdfWriter writer, PdfEntity bean) throws IOException {
        try {
            document.addTitle("准考证");
            document.addAuthor("scurry");
            document.addSubject("product sheet.");
            document.addKeywords("product.");
            document.add(new Chunk(("\n")));
            document.open();
            PdfPTable table = createTable(writer,bean,document);
            document.add(table);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }

    public static PdfPTable createTable(PdfWriter writer, PdfEntity bean,Document document) throws IOException{
        //生成一个7列的表格
        PdfPTable table = new PdfPTable(7);
        table.setWidthPercentage(100);
        table.setSpacingBefore(10);
        try {
            BaseFont bfChinese = BaseFont.createFont("/fonts/simsun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            int size = 30;
            Font title = new Font(bfChinese, 12, Font.BOLD);
            Font cellTitle = new Font(bfChinese, 8, Font.BOLD);
            Font cellContent = new Font(bfChinese, 8, Font.NORMAL);

            Paragraph docTitle = new Paragraph("2020年淮南二中钱学森班招招生面试准考证\n", title);
            docTitle.setAlignment(Element.ALIGN_CENTER);
            docTitle.setSpacingBefore(20);
            document.add(docTitle);

            PdfPCell cell = new PdfPCell(new Paragraph("姓名",cellTitle));
            cell.setColspan(1);
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(bean.getName(),cellContent));
            cell.setColspan(1);
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("性别",cellTitle));
            cell.setColspan(1);
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph((bean.getSex()==0?"男":"女"),cellContent));
            cell.setColspan(1);
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("班级",cellTitle));
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("",cellContent));
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            java.net.URL imgurl = new java.net.URL(bean.getFileUrl());
            java.awt.Image awtImage = ImageIO.read(imgurl);
            if(null!=awtImage){
                Image img = Image.getInstance(awtImage,null);
                img.scaleAbsolute((float) 30, (float) 30);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell = new PdfPCell(img,true);
                cell.setPadding(1);
                cell.setRowspan(3);
                table.addCell(cell);
            }else{
                cell = new PdfPCell(new Paragraph("相册",cellContent));
                cell.setRowspan(3);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell);
            }

            document.add(new Chunk(("\n")));
            cell = new PdfPCell(new Paragraph("毕业学校",cellTitle));
            cell.setColspan(1);
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(bean.getGraduateSchool(),cellContent));
            cell.setColspan(5);
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            document.add(new Chunk(("\n")));
            cell = new PdfPCell(new Paragraph("考场座位号\n(此栏由淮南二中填写)",cellTitle));
            cell.setColspan(1);
            cell.setFixedHeight(40);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(bean.getStuSeatNum(),cellContent));
            cell.setColspan(5);
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
            StringJoiner s=new StringJoiner("\n");
            s.add("    1、7月18日上午7:20,通过报名审核并符合疫情防控要求的考生,持准考生,佩戴口罩经体温测量正常后进入考场,对号入座。");
            s.add("    2、面试时间安排。上午:语文7:40-9:40,数学10:00-12:00;下午英语14:00-15:20,物理15:40-17:10,历史17:30-18:50。面试科目及分值:必考科目:语文100分,数学100分,英语100分(无听力)。选考科目:物理100分(理科倾向),历史100分(文科倾向),两科可以简报。");
            s.add("    3、请考生准备0.5毫米黑色水笔、2B铅笔、橡皮。");
            document.add(new Chunk(("\n")));
            cell = new PdfPCell(new Paragraph(s.toString(),cellContent));
            cell.setColspan(7);
            cell.setFixedHeight(200);
            table.addCell(cell);

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return table;
    }
}

6.下载simsun.ttf字体,是因为导出数据是中文,那么导出的pdf不显示
下载好字体后,在项目的resources下面创建一个fonts文件夹,将下载好的文字放进去
7.运行程序,请求接口下载pdf
在这里插入图片描述
8.看似没问题了,此时执行maven打包命令,mvn clean package后,再次运行项目,再次请求该接口报错
是因为maven打包,编译字体,损坏了原型的字体
在这里插入图片描述
9.解决办法

	pom.xml加入如下配置、
			<!-- 解决maven 打包 ttf文件损坏的问题 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<configuration>
					<nonFilteredFileExtensions>
						<nonFilteredFileExtension>ttf</nonFilteredFileExtension>
					</nonFilteredFileExtensions>
				</configuration>
			</plugin>

Guess you like

Origin blog.csdn.net/qq_40974235/article/details/107220046