java-导出pdf

发布时间 2023-12-08 16:38:27作者: Aa从心

前言:

  纯代码画pdf格式

        <!-- iText PDF -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.2</version>
        </dependency>
        <!-- pdf 字体需要 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

 

示例代码:

 

生成PDF文件(无表格版)

  Controller

@PostMapping("exportPDF")
    public void registrationNoticeExport(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        //防止日志记录获取session异常
        request.getSession();

        HashMap<String, String> dataMap = new HashMap<>();

        dataMap.put("year","2023");
        dataMap.put("sort","12");
        dataMap.put("inspectionCompany","这是第一行的标题");
        dataMap.put("planName","这是第二行的标题xxxxxxxxx");
        dataMap.put("qymc","这是发文公司/人");
        dataMap.put("kdmc","内容测试");
        dataMap.put("attachmentNameStr","attachmentNameStr测试");
        dataMap.put("date","日期测试");
        dataMap.put("inspectionTeamLeaderInfo","落款测试");

        //导出pdf
        PdfUtil.setResponseContentType(response,  "文件名称测试" );
        PdfUtil.downloadPdf(dataMap,response);

    }

  Util

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.draw.LineSeparator;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

public class PdfUtil {

    public static void setResponseContentType(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        response.setContentType("application/pdf");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".pdf");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    }


    public static void downloadPdf(Map<String,String> dataMap, HttpServletResponse response){
        // 定义全局的字体静态变量
        Font titlefont;
        Font headfont;
        Font keyfont = null;
        Font textfont = null;
        Font content = null;
        Font space = null;
        Font space1 = null;
        Font space2 = null;
        Font space3 = null;
        // 最大宽度
        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, 22, Font.BOLD);
            textfont = new Font(bfChinese, 15, Font.NORMAL);
            content = new Font(bfChinese, 16, Font.NORMAL);
            space = new Font(bfChinese, 5, Font.NORMAL);
            space1 = new Font(bfChinese, 20, Font.NORMAL);
            space2 = new Font(bfChinese, 20, Font.NORMAL);
            space3 = new Font(bfChinese, 3, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
        BaseFont bf;
        Font font = null;
        try {
            //可以引用自己想要的字体
            bf = BaseFont.createFont("D:\\cbd-marketSurvey-service\\src\\main\\resources\\templates\\simsun.ttc,1",
                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            //创建字体 
//            bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",
//                    BaseFont.NOT_EMBEDDED);
            //使用字体并给出颜色
            font = new Font(bf,36,Font.BOLD, BaseColor.RED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Document document = new Document(new Rectangle(com.itextpdf.text.PageSize.A4));

        try {
            com.itextpdf.text.pdf.PdfWriter.getInstance(document, response.getOutputStream());
            //打开PDF文件
            document.open();
            //设置内容
            Paragraph paragraph = new Paragraph("标题内容测试", font);
            //居中设置
            paragraph.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph);

            //页眉横线
            document.add(new Paragraph("\n", space2));
            LineSeparator line = new LineSeparator(3f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
            document.add(line);
            document.add(new Paragraph("\n", space3));
            LineSeparator lineStart = new LineSeparator(1f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
            document.add(lineStart);

            document.add(new Paragraph("\n", space));
            String text = "标注测试〔" + dataMap.get("year") + "〕" + dataMap.get("sort") + "号";
            Paragraph paragraph0 = new Paragraph(text, content);
            paragraph0.setAlignment(Element.ALIGN_RIGHT);
            document.add(paragraph0);

            document.add(new Paragraph("\n"));
            Paragraph paragraph1 = new Paragraph(dataMap.get("inspectionCompany"), keyfont);
            paragraph1.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph1);

            document.add(new Paragraph("\n", space));
            String concent = dataMap.get("planName");
            Paragraph paragraph2 = new Paragraph(concent, keyfont);
            paragraph2.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph2);

            document.add(new Paragraph("\n"));
            Paragraph paragraph3 = new Paragraph(dataMap.get("qymc") + ":", content);
            paragraph3.setAlignment(Element.ALIGN_LEFT);
            document.add(paragraph3);

            document.add(new Paragraph("\n", space));
            String concent1 = "             现将" + dataMap.get("kdmc")
                    + "这是一段内容测试:知识密集型行业往往有着这样的特点,一方面对于从业者有着高度专业化的知识要求,需要具备高度专业化的背景和经验,准入门槛较高;同时,知识密集型行业往往也是文档密集型行业,文档的厚度和复杂性较高,让行业的数字化转型与应用创新面临更大挑战。。";
            Paragraph paragraph4 = new Paragraph(concent1, content);
            //设置首行缩进
            paragraph4.setIndentationRight(2);
            document.add(paragraph4);

            document.add(new Paragraph("\n", space));
            Paragraph paragraph5 = new Paragraph("              特此通知。", content);
            //右缩进2格
            paragraph5.setIndentationRight(2);
            document.add(paragraph5);

            document.add(new Paragraph("\n", space1));
            document.add(new Paragraph("\n", space1));
            //附件
            Paragraph paragraph6 = new Paragraph("              附件:", content);
            //右缩进2格
            paragraph6.setIndentationRight(2);
            document.add(paragraph6);

            document.add(new Paragraph("\n", space));
            Paragraph paragraph7 = new Paragraph("              "+dataMap.get("attachmentNameStr"), content);
            document.add(paragraph7);

            document.add(new Paragraph("\n", space1));
            document.add(new Paragraph("\n", space1));
            document.add(new Paragraph("\n", space1));

            //日期
            Paragraph paragraph8 = new Paragraph(dataMap.get("date"), content);
            //向右
            paragraph8.setAlignment(Element.ALIGN_RIGHT);
            document.add(paragraph8);

            document.add(new Paragraph("\n", space1));
            //落款
            Paragraph paragraph9 = new Paragraph(dataMap.get("inspectionTeamLeaderInfo"), content);
            paragraph9.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph9);

            //页尾横线
            document.add(new Paragraph("\n", space2));
            document.add(new Paragraph("\n", space2));
            LineSeparator lineEnd = new LineSeparator(3f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
            document.add(lineEnd);
            document.add(new Paragraph("\n", space3));
            LineSeparator lineEnd1 = new LineSeparator(1f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
            document.add(lineEnd1);
            
            //关闭文档
            document.close();

        } catch (Exception e) {
            e.printStackTrace();
            //log.error("导出pdf失败:{}", e);
        }

    }
}

  效果图

 

生成PDF文件(表格版)

  Controller

    @PostMapping("/download")
    public void download(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 防止日志记录获取session异常
        request.getSession();
        // 设置编码格式
        response.setContentType("application/pdf;charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("下载的PDF名称", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".pdf");
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(String.valueOf(i));
        }
        PdfUtil.download(list, response);
    }

  Util



    public static void download(List<String> list, HttpServletResponse response) throws IOException {
        //要下载的数据查询数据部分我去掉了有需要自己根据业务取

        // 定义全局的字体静态变量
        Font content = null;
        // 最大宽度
        try {
            // 不同字体(这里定义为同一种字体:包含不同字号、不同style) 
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            content = new Font(bfChinese, 10, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
        BaseFont bf;
        Font font = null;
        try {
            //创建字体
            bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
            //使用字体并给出颜色
            font = new Font(bf,20,Font.BOLD, BaseColor.BLACK);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Document document = new Document(new RectangleReadOnly(842F, 595F));
        try {
            PdfWriter.getInstance(document,response.getOutputStream());
            //打开生成的pdf文件
            document.open();
            //设置内容
            Paragraph paragraph = new Paragraph("主题名称",font);
            paragraph.setAlignment(1);
            //引用字体
            document.add(paragraph);

            // 设置表格的列宽和列数
            float[] widths = {25f,25f,25f,25f,25f,25f};
            PdfPTable table = new PdfPTable(widths);
            table.setSpacingBefore(20f);
            // 设置表格宽度为100%
            table.setWidthPercentage(100.0F);
            table.setHeaderRows(1);
            table.getDefaultCell().setHorizontalAlignment(1);
            PdfPCell cell = null;
            //第一行
            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(30);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            //第二行
            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(30);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            //第三行
            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(30);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

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

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

            // 设置表格的列宽和列数
            float[] widths2 = {25f,25f,25f,25f,25f,25f};
            PdfPTable table2 = new PdfPTable(widths2);
            table2.setSpacingBefore(20f);
            // 设置表格宽度为100%
            table2.setWidthPercentage(100.0F);
            table2.setHeaderRows(1);
            table2.getDefaultCell().setHorizontalAlignment(1);

            //人员列表-第四行
            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(20);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);
            //人员列表数据-第五行
            if(list.size() > 0){
                for (String prople : list) {
                    PdfPCell cell1 = new PdfPCell(new Paragraph(prople, content));
                    PdfPCell cell2 = new PdfPCell(new Paragraph(prople, content));
                    PdfPCell cell3 = new PdfPCell(new Paragraph(prople, content));
                    PdfPCell cell4 = new PdfPCell(new Paragraph(prople, content));
                    PdfPCell cell5 = new PdfPCell(new Paragraph(prople, content));
                    PdfPCell cell6 = new PdfPCell(new Paragraph(prople, content));

                    //单元格对齐方式
                    cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    cell1.setFixedHeight(20);
                    //单元格垂直对齐方式
                    cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    table2.addCell(cell1);
                    table2.addCell(cell2);
                    table2.addCell(cell3);
                    table2.addCell(cell4);
                    table2.addCell(cell5);
                    table2.addCell(cell6);
                }
            }

            document.add(new Paragraph("\n"));
            document.add(new Paragraph("▋ 基本信息",content));
            document.add(new Paragraph("\n"));

            document.add(table);

            document.add(new Paragraph("\n"));
            document.add(new Paragraph("▋ 基本信息",content));
            document.add(new Paragraph("\n"));

            document.add(table2);

            //关闭文档
            document.close();
            
        } catch (DocumentException e) {
            e.printStackTrace();
            log.error("导出pdf失败:{}",e);
        }
    }

  效果图