java实现导出PDF文件

由于时间问题,写的不是很好,但是实现了项目所需的功能,以后有时间会逐渐改进。
一、maven所需要的jar

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

<dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>5.5.13.2</version>
</dependency>

二、实现所需工具类
1.时间工具类

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期工具类
 */
public class DateUtils {

    public static final String SPIT_TAG=",";

    public static Date getDate(String time){
        Date date = new Date(Long.parseLong(time));
        return date;
    }

    public static String getTimeString(Long expiryData){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long currentTimeMillis = System.currentTimeMillis();
        long lastTime=currentTimeMillis-expiryData*3600*24*1000;
        String formatDateTime = sdf.format(new Date(lastTime));
        return formatDateTime;

    }

    public static String getTimeStringByLongTime(Long time){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formatDateTime = sdf.format(time);
        return formatDateTime;
    }

    public static String getTimeStringToDay(Long expiryData){
        SimpleDateFormat sdf=new SimpleDateFormat("YYYY-MM-dd");
        String formatDateTime = sdf.format(expiryData);
        return formatDateTime;

    }

}

2.PDF工具
该工具类有个改进的地方就是在合并行和合并列单独分开了,在使用的时候可以直接使用合并行和列即:getRowAndColSpan()方法

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import org.springframework.stereotype.Component;

@Component
public class PDFutil {

    /**
     * 设置标题
     * @param table PTable表格
     * @param textFont 字体样式
     * @param value 添加的内容
     * @param cols 合并几列
     * @param rows 合并几行
     * @param middleType 居中类型 0:不居中, 1:水平居中 2:垂直居中
     * @return PTable表格
     */
    public PdfPTable getTitle(PdfPTable table, Font textFont, String value, Integer cols, Integer rows, Integer middleType){
        PdfPCell cell = new PdfPCell();
        Paragraph p = new Paragraph(value, textFont);
        cell.setColspan(cols);
        cell.setRowspan(rows);
        if(middleType == 1){
            p.setAlignment(1);
            getHorizontalCenter(cell);
        }else if(middleType == 2){
            p.setAlignment(1);
            getVerticalCenter(cell);
        }
        cell.setBorderColor(BaseColor.WHITE);// 设置方向后会失效
        cell.addElement(p);
        table.addCell(cell);
        return table;
    }

    /**
     * 设置单元格
     * @param table PTable表格
     * @param textFont 字体样式
     * @param value 添加的内容
     * @param middleType 居中类型 0:不居中, 1:水平居中 2:垂直居中
     * @return PTable表格
     */
    public PdfPTable getPdfCell(PdfPTable table, Font textFont, String value, Integer middleType){
        PdfPCell cell = new PdfPCell();
        Paragraph p = new Paragraph(value, textFont);
        if(middleType == 1){
            p.setAlignment(1);
            getHorizontalCenter(cell);
        }else if(middleType == 2){
            p.setAlignment(1); // -1:未定义,0:左,1:中,2:右,3:合适的,4:上,5:中,6:下,7:底线
            getVerticalCenter(cell);
        }
        cell.addElement(p);
        table.addCell(cell);
        return table;
    }

    /**
     * 合并行(合并行(上下合并)时,设置为垂直居中)
     * @param table PTable表格
     * @param textFont 字体样式
     * @param value 添加的内容
     * @param rows 合并几行
     * @param middleType 居中类型 0:不居中, 1:水平居中 2:垂直居中
     * @return PTable表格
     */
    public PdfPTable getRowSpan(PdfPTable table, Font textFont, String value, Integer rows, Integer middleType){
        PdfPCell cell = new PdfPCell();
        Paragraph p = new Paragraph(value, textFont);
        cell.setRowspan(rows);
        if(middleType == 2){
            p.setAlignment(1);
            getVerticalCenter(cell);
        }
        cell.addElement(p);
        table.addCell(cell);
        return table;
    }

    /**
     * 合并列(合并列(左右合并)时,设置为水平居中)
     * @param table PTable表格
     * @param textFont 字体样式
     * @param value 添加的内容
     * @param cols 合并几列
     * @param middleType 居中类型 0:不居中, 1:水平居中 2:垂直居中
     * @return PTable表格
     */
    public PdfPTable getColSpan(PdfPTable table, Font textFont, String value, Integer cols, Integer middleType){
        PdfPCell cell = new PdfPCell();
        Paragraph p = new Paragraph(value, textFont);
        cell.setColspan(cols);
        if(middleType == 1){
            p.setAlignment(1);
            getHorizontalCenter(cell);
        }else if(middleType == 2){
            p.setAlignment(1);
            getVerticalCenter(cell);
        }
        cell.addElement(p);
        table.addCell(cell);
        return table;
    }

    /**
     * 合并行和列
     * @param table PTable表格
     * @param textFont 字体样式
     * @param value 添加的内容
     * @param cols 合并几列
     * @param rows 合并几行
     * @param middleType 居中类型 0:不居中, 1:水平居中 2:垂直居中
     * @return PTable表格
     */
    public PdfPTable getRowAndColSpan(PdfPTable table, Font textFont, String value,
                                      Integer cols, Integer rows, Integer middleType){
        PdfPCell cell = new PdfPCell();
        Paragraph p = new Paragraph(value, textFont);
        cell.setColspan(cols);
        cell.setRowspan(rows);
        if(middleType == 1){
            p.setAlignment(1);
            getHorizontalCenter(cell);
        }else if(middleType == 2){
            p.setAlignment(1);
            getVerticalCenter(cell);
        }
        cell.addElement(p);
        table.addCell(cell);
        return table;
    }

    /**
     * 水平居中
     * @param cell PdfPCell单元格
     * @return PdfPCell单元格
     */
    public PdfPCell getHorizontalCenter(PdfPCell cell){
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);// 水平居中
        return cell;
    }

    /**
     * 垂直居中
     * @param cell PdfPCell单元格
     * @return PdfPCell单元格
     */
    public PdfPCell getVerticalCenter(PdfPCell cell){
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setPaddingTop(-2f);//把字垂直居中
        cell.setPaddingBottom(8f);//把字垂直居中
        return cell;
    }
}

三、Controller类

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.ys.pdf.PdfEvent;
import com.ys.utils.DateUtils;
import com.ys.utils.PDFutil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RequestMapping("/exportPDF")
@Controller
public class CateringManagement {

    @Resource
    private PDFutil pdFutil;

    @GetMapping("/cateringmanagement")
    public void exportPDF(){
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = requestAttributes.getResponse();

            String pdfName = "基本信息("+ DateUtils.getTimeStringToDay(System.currentTimeMillis()) +")";

            // 设置页面编码格式
            response.setContentType("application/vnd.ms-pdf");
            response.setContentType("text/plain;charaset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((pdfName).getBytes(), "ISO-8859-1") + ".pdf");

            // 1).定义A4纸
            Document document = new Document(PageSize.A4, 48, 48, 60, 65);
            // 2).建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
            ServletOutputStream os = response.getOutputStream();
            PdfWriter contentWriter = PdfWriter.getInstance(document, os);

            // 创建页面事件
            PdfEvent event = new PdfEvent();
            contentWriter.setPageEvent(event);

            // 3).写入数据之前要打开文档
            document.open();
            // 设置字体
            String fontPath = "E:\\pdf\\simsun.ttf"; // 宋体
            BaseFont bfCN = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            // 正文的字体
            Font headFont = new Font(bfCN, 12f);
            Font textFont = new Font(bfCN, 10f);

            //建立一个17列的表格
            PdfPTable table = new PdfPTable(17);
            table = pdFutil.getTitle(table,headFont,"基本信息",17,2,2);

            table = getFoodInspection(table,textFont);

            table = getDayConsumption(table,textFont);

            table = getFoodAcceptance(table,textFont);
            document.add(table);
            document.close();
            os.close();

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * @param table PTable表格
     * @param textFont 字体样式
     * @return PTable表格
     */
    private PdfPTable getFoodInspection(PdfPTable table,Font textFont){
        table = pdFutil.getRowSpan(table,textFont,"这里是一部分",7,2);
        table = pdFutil.getPdfCell(table,textFont,"时间",2);
        table = pdFutil.getColSpan(table,textFont,"说明",2,2);
        table = pdFutil.getColSpan(table,textFont,"类型",12,2);
        table = pdFutil.getPdfCell(table,textFont,"签名",2);

        table = pdFutil.getRowSpan(table,textFont,"早",2,2);
        table = pdFutil.getRowAndColSpan(table,textFont," ",2,2,2);
        table = pdFutil.getColSpan(table,textFont," ",12,0);
        table = pdFutil.getPdfCell(table,textFont," ",1);

        table = pdFutil.getColSpan(table,textFont," ",12,0);
        table = pdFutil.getPdfCell(table,textFont," ",1);

        table = pdFutil.getRowSpan(table,textFont,"中",2,2);
        table = pdFutil.getRowAndColSpan(table,textFont," ",2,2,2);
        table = pdFutil.getColSpan(table,textFont," ",12,0);
        table = pdFutil.getPdfCell(table,textFont," ",1);

        table = pdFutil.getColSpan(table,textFont," ",12,0);
        table = pdFutil.getPdfCell(table,textFont," ",1);

        table = pdFutil.getRowSpan(table,textFont,"晚",2,2);
        table = pdFutil.getRowAndColSpan(table,textFont," ",2,2,2);
        table = pdFutil.getColSpan(table,textFont," ",12,0);
        table = pdFutil.getPdfCell(table,textFont," ",1);

        table = pdFutil.getColSpan(table,textFont," ",12,0);
        table = pdFutil.getPdfCell(table,textFont," ",1);
        return table;
    }

    /**
     * @param table PTable表格
     * @param textFont 字体样式
     * @return PTable表格
     */
    private PdfPTable getDayConsumption(PdfPTable table,Font textFont){
        table = pdFutil.getRowSpan(table,textFont,"类型",2,2);
        table = pdFutil.getColSpan(table,textFont,"领导签名",3,1);
        table = pdFutil.getColSpan(table,textFont,"员工签名",13,1);

        String [] titleName = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
        for(int i=0; i<titleName.length; i++){
            table = pdFutil.getPdfCell(table,textFont,titleName[i],1);
        }

        table = pdFutil.getPdfCell(table,textFont,"早",1);
        String [] morning = new String[16];
        for(int i=0; i<morning.length; i++){
            table = pdFutil.getPdfCell(table,textFont," ",1);
        }

        table = pdFutil.getPdfCell(table,textFont,"中",1);
        String [] midday = new String[16];
        for(int i=0; i<midday.length; i++){
            table = pdFutil.getPdfCell(table,textFont," ",1);
        }

        table = pdFutil.getPdfCell(table,textFont,"晚",1);
        String [] evening = new String[16];
        for(int i=0; i<evening.length; i++){
            table = pdFutil.getPdfCell(table,textFont," ",1);
        }

        table = pdFutil.getPdfCell(table,textFont,"100",1);
        String [] total = new String[16];
        for(int i=0; i<total.length; i++){
            table = pdFutil.getPdfCell(table,textFont," ",1);
        }

        table = pdFutil.getColSpan(table,textFont,"1000",4,1);
        String [] average = new String[13];
        for(int i=0; i<average.length; i++){
            table = pdFutil.getPdfCell(table,textFont," ",1);
        }

        return table;
    }

    /**
     * @param table PTable表格
     * @param textFont 字体样式
     * @return PTable表格
     */
    private PdfPTable getFoodAcceptance(PdfPTable table,Font textFont){
        table = pdFutil.getColSpan(table,textFont,"最后一部分",17,1);

        String [] classify = {"1","11","111","1111"};
        table = getLoopAssignment(classify,table,textFont);
        table = pdFutil.getColSpan(table,textFont,"3",3,1);
        table = getLoopAssignment(classify,table,textFont);
        table = pdFutil.getColSpan(table,textFont,"4",4,1);

        for(int i=0; i<7; i++){
            String [] specification = new String[3];
            table = pdFutil.getColSpan(table,textFont," ",2,1);
            table = getFootSpecification(specification,table,textFont);
            table = pdFutil.getColSpan(table,textFont," ",3,1);
            table = pdFutil.getColSpan(table,textFont," ",2,1);
            table = getFootSpecification(specification,table,textFont);
            table = pdFutil.getColSpan(table,textFont," ",4,1);
        }

        return table;
    }

    /**
     * @param classify 标题数组
     * @param table PTable表格
     * @param textFont 字体样式
     * @return PTable表格
     */
    private PdfPTable getLoopAssignment(String [] classify, PdfPTable table,Font textFont){
        for(int i=0; i<classify.length; i++){
            if(classify[i].equals("1")){
                table = pdFutil.getColSpan(table,textFont,"1",2,1);
            }else{
                table = pdFutil.getPdfCell(table,textFont,classify[i],1);
            }
        }
        return table;
    }

    /**
     * @param specification 数据数组
     * @param table PTable表格
     * @param textFont 字体样式
     * @return PTable表格
     */
    private PdfPTable getFootSpecification(String [] specification, PdfPTable table,Font textFont){
        for(int i=0; i<specification.length; i++){
            table = pdFutil.getPdfCell(table,textFont,specification[i],1);
        }
        return table;
    }

}

四、字体
这里使用的字体为宋体,需要从外部引入
https://download.csdn.net/download/weixin_45267345/20359072
五、效果显示
在浏览器请求接口实现下载
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值