【JAVA】PDF导出

一、问题描述

案例:工单对应的作业指导书导出pdf文档

二、解决方案:itextpdf

1. 创建文档

OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
com.itextpdf.text. Document document = new Document();
document.setPageSize(PageSize.A4);
com.itextpdf.text.pdf. PdfWriter.getInstance(document, outputStream);
document.open();

2. 设置中文字体和大小

BaseFont bfChinese = BaseFont.createFont(“STSong-Light”, “UniGB-UCS2-H”,BaseFont.NOT_EMBEDDED);
Font font = new Font(bfChinese, 11, Font.NORMAL);

3. 创建表格

PdfPTable table = new PdfPTable(2); // 表格列数2
table.setWidthPercentage(100); // 宽度100%填充
table.setSpacingAfter(10f); // 后间距
table.setSpacingBefore(10f); // 前间距
float[] columnWidths = {0.2f, 0.8f}; // 列宽的比重
table.setWidths(columnWidths);

4. 创建单元格,加入表格,表格加入文档

PdfPCell cell = new PdfPCell();
cell.setMinimumHeight(22); // 设置单元格高度
cell.setUseAscender(true); // 设置可以居中
cell.setHorizontalAlignment(Cell.ALIGN_CENTER); // 设置水平居中
cell.setVerticalAlignment(Cell.ALIGN_MIDDLE); // 设置垂直居中
cell.setPhrase(new Phrase(“作业标准名称”, font)); // 设置单元格文本内容
table.addCell(cell); // 单元格添加至表格
cell.setPhrase(new Phrase(dto.getStanName(), font));
table.addCell(cell);
document.add(table); // 表格添加至文档

5. 关闭表格,刷新输出流

document.close();
outputStream.flush();
finally outputStream.close();

三、注意事项

1. 如果一个PDF有多个表格

表格另起一页的方法:document.newPage();

2. 文档用表格进行布局

table套table
表格中直接内嵌表格,会导致表格边框无法影藏,问题如下:
红色框为PdfPCell,黑色框为PdfPTable。
在这里插入图片描述
解决办法
表格中套一个单元格,单元格中在放表格;
设置单元格内边距为0:myCell.setPadding(0);
单元格添加元素myCell.addElement(myTable);
最终效果如下:
在这里插入图片描述

四、实例代码

pom加依赖

<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itextpdf</artifactId>
	<version>5.5.3</version>
</dependency>
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itext-asian</artifactId>
	<version>5.2.0</version>
</dependency>

自动引入

package com.XXX;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.lowagie.text.Cell;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

实例代码

    @Override
    public void workExport(String orderId, HttpServletRequest request, HttpServletResponse response) {
        OutputStream outputStream = null;
        String pdfName = "作业指导书报告.PDF";
        try {
            // 防止中文乱码,针对IE或者以IE为内核的浏览器
            String userAgent = request.getHeader("User-Agent");
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                pdfName = java.net.URLEncoder.encode(pdfName, "UTF-8");
            } else {
                // 非IE浏览器的处理
                pdfName = new String(pdfName.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + pdfName + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            outputStream = new BufferedOutputStream(response.getOutputStream());

            Document document = new Document();
            document.setPageSize(PageSize.A4);
            PdfWriter.getInstance(document, outputStream);
            document.open();

            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 设置中文字体
            Font font = new Font(bfChinese, 11, Font.NORMAL);// 设置字体大小

            TaskFormRelationDTO relationDTO = new TaskFormRelationDTO();
            relationDTO.setMoudelObjectId(orderId);
            List<TaskFormRelationDTO> list = taskFormRelationService.queryList(relationDTO);

            if (list != null) {
                for (TaskFormRelationDTO taskFormRelationDTO : list) {
                    document.newPage();
                    LibWorkStandardDto dto = (LibWorkStandardDto) libWorkStandardService.queryById(taskFormRelationDTO.getTfVersionId());

                    // 标题行
                    PdfPTable table = new PdfPTable(2);
                    table.setWidthPercentage(100); // 宽度100%填充
//                    table.setSpacingAfter(10f); // 后间距
                    table.setSpacingBefore(10f); // 前间距
                    float[] columnWidths = {0.2f, 0.8f};
                    table.setWidths(columnWidths);

                    PdfPCell cell = new PdfPCell();
                    cell.setMinimumHeight(22); // 设置单元格高度
                    cell.setUseAscender(true); // 设置可以居中
                    cell.setHorizontalAlignment(Cell.ALIGN_CENTER); // 设置水平居中
                    cell.setVerticalAlignment(Cell.ALIGN_MIDDLE); // 设置垂直居中
                    cell.setPhrase(new Phrase("作业标准名称", font));
                    table.addCell(cell);
                    cell.setPhrase(new Phrase(dto.getStanName(), font));
                    table.addCell(cell);
                    document.add(table);

                    // 类别编码、作业类型、作业周期行
                    table = new PdfPTable(6);
                    table.setWidthPercentage(100); // 宽度100%填充
//                    table.setSpacingBefore(10f); // 前间距
//                    table.setSpacingAfter(10f); // 后间距
                    float[] columnWidths2 = {0.16f, 0.16f, 0.16f, 0.16f, 0.16f, 0.2f};
                    table.setWidths(columnWidths2);
                    cell.setPhrase(new Phrase("类别编码", font));
                    table.addCell(cell);
                    ClassifyVO classifyVO = libClassifyAppService.queryById(dto.getClassifyId());
                    if (classifyVO != null) {
                        cell.setPhrase(new Phrase(classifyVO.getClassifyCode(), font));
                    } else {
                        cell.setPhrase(new Phrase("", font));
                    }
                    table.addCell(cell);
                    cell.setPhrase(new Phrase("作业类型", font));
                    table.addCell(cell);
                    List<Map<String, String>> typeMaps = WorkType.toList();
                    for (Map<String, String> map : typeMaps) {
                        if (dto.getWorkType() != null && dto.getWorkType().equals(map.get("id"))) {
                            String workTypeStr = map.get("text");
                            if (workTypeStr != null) {
                                cell.setPhrase(new Phrase(workTypeStr, font));
                            } else {
                                cell.setPhrase(new Phrase("", font));
                            }
                        }
                    }
                    table.addCell(cell);
                    cell.setPhrase(new Phrase("作业周期", font));
                    table.addCell(cell);
                    List<Map<String, String>> cycleMaps = WorkCycle.toList();
                    for (Map<String, String> map : cycleMaps) {
                        if (dto.getWorkCycle() != null && dto.getWorkCycle().equals(map.get("id"))) {
                            String workCycleStr = map.get("text");
                            if (workCycleStr != null) {
                                cell.setPhrase(new Phrase(workCycleStr, font));
                            } else {
                                cell.setPhrase(new Phrase("", font));
                            }
                        }
                    }
                    table.addCell(cell);
                    document.add(table);
                }
            }
            
            // 省略中间业务一万行代码。。。
            
            document.close();
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
发布了14 篇原创文章 · 获赞 1 · 访问量 256

猜你喜欢

转载自blog.csdn.net/qq_39938236/article/details/103922207