Java使用itextpdf导出数据为PDF

导包

pom.xml引入jar包

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

字体

在resources文件夹下创建文件夹pdfFont,放入simhei.ttf(黑体)字体文件,备用
Java使用itextpdf导出数据为PDF_第1张图片

导出

ElectricityPlanDTO 类为导出数据对象
传入作为页面条件查询过滤数据

    /**
     * 导出用户信息到excel/pdf
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/exportPDF" , method = RequestMethod.GET)
    @ResponseBody
    public String delWarnPdfPrint( ElectricityPlanDTO electricityPlanDTO,HttpServletRequest req, HttpServletResponse resp) throws Exception {
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        /*******pdf文件内容生成开始*********/
        Document document = new Document(PageSize.A4, 25, 25, 25, 25);
        Subject subject = SecurityUtils.getSubject();
        SysUser sysUser = (SysUser)subject.getPrincipal();
        List<ElectricityPlanDTO> planList = electricityPlanService.getElectricByPlan(sysUser.getDeptid(),electricityPlanDTO);
        Map<String,Object> dataMap = new HashMap<String,Object>();
        List<String> titles = new ArrayList<String>();
        titles.add("序号");
        titles.add("客户名称");
        titles.add("统一社会信用代码");
        titles.add("计划电量");
        titles.add("申报年月");
        titles.add("更新时间");
        titles.add("状态");
        dataMap.put("titles", titles);
        dataMap.put("list", planList);
        dataMap.put("title_content", "电量申报");
        dataMap.put("type", "table");
        //创建文件夹
        String filePar = null;
        Date nowTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String time = sdf.format(nowTime);//获取当前时间字符串形式
        filePar = "C:" + File.separator + "electricityplan"+System.nanoTime();// 文件夹路径
        File myPath = new File( filePar );
//        file  = File.createTempFile("temp", Long.toString(System.nanoTime()));
//        file = new File(filePar+"/"+"电量申报.pdf");
        if (!myPath.exists()){
            myPath.mkdir();
        }
        file = new File(filePar + File.separator, time+".pdf");
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));// throws FileNotFoundException,
        /*
         * 设中文字体
         */
        BaseFont bfChinese = null;// FontFactory.getFont(FontFactory.COURIER,
// 14, Font.BOLD, new CMYKColor(0, 255, 0, 0);//大小,粗细,颜色
        try {
            bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            //加入页码
//            setFooter(writer,PDFUtil.bfChinese,10,PageSize.A4);
            document.open();

            //图片1
            String CHARACTOR_FONT_CH_BLACK = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            String realReadPath = CHARACTOR_FONT_CH_BLACK + "pdfFont/elogo.png";
            Image image1 = Image.getInstance(realReadPath);
           //设置图片位置的x轴和y周
            image1.setAbsolutePosition(50f, 780f);
             //设置图片的宽度和高度
            image1.scaleAbsolute(125, 40);
            //将图片1添加到pdf文件中
            document.add(image1);


//            // 加入文字水印
//            PdfContentByte waterMar = writer.getDirectContentUnder();
//            // 开始设置水印
//            waterMar.beginText();
//            // 设置水印透明度
//            PdfGState gs = new PdfGState();
//            // 设置填充字体不透明度为0.4f
//            gs.setFillOpacity(0.4f);
//            try {
//                // 设置水印字体参数及大小  (字体参数,字体编码格式,是否将字体信息嵌入到pdf中(一般不需要嵌入),字体大小)
//                waterMar.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 60);
//                // 设置透明度
//                waterMar.setGState(gs);
//                // 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
//                waterMar.showTextAligned(Element.ALIGN_RIGHT, "国网南京供电公司" , 500, 430, 45);
//                // 设置水印颜色
//                waterMar.setColorFill(BaseColor.GRAY);
//                //结束设置
//                waterMar.endText();
//                waterMar.stroke();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }finally {
//                waterMar = null;
//                gs = null;
//            }


//            // 加入图片水印
//            PdfContentByte waterMar = writer.getDirectContentUnder();
//            // 开始设置水印
//            waterMar.beginText();
//            // 设置水印透明度
//            PdfGState gs = new PdfGState();
//            // 设置笔触字体不透明度为0.4f
//            gs.setStrokeOpacity(0.2f);
//            try {
//                String CHARACTOR_FONT_CH_BLACK = Thread.currentThread().getContextClassLoader().getResource("").getPath();
//                String realReadPath = CHARACTOR_FONT_CH_BLACK + "pdfFont/elogo.png";
//                Image image = Image.getInstance(realReadPath);
//                // 设置坐标 绝对位置 X Y
//                image.setAbsolutePosition(200, 500);
//                // 设置旋转弧度
//                image.setRotation(30);// 旋转 弧度
//                // 设置旋转角度
//                image.setRotationDegrees(45);// 旋转 角度
//                // 设置等比缩放
//                image.scalePercent(90);// 依照比例缩放
//                // image.scaleAbsolute(125,80);//自定义大小
//                // 设置透明度
//                waterMar.setGState(gs);
//                // 添加水印图片
//                waterMar.addImage(image);
//                // 设置透明度
//                waterMar.setGState(gs);
//                //结束设置
//                waterMar.endText();
//                waterMar.stroke();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }finally {
//                waterMar = null;
//                gs = null;
//            }


            // 标题居中
            String title_content = (String) dataMap.get("title_content");
            Paragraph title = PDFUtil.getParagraph(
                    new Chunk(title_content,new Font(PDFUtil.bfChinese,16,Font.BOLD)));
            title.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(title);

            SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Paragraph now = PDFUtil.getParagraph(
                    new Chunk(DateUtils.date2Str(DateUtils.getDate(),datetimeFormat) ,new Font(PDFUtil.bfChinese,10,Font.NORMAL)));
            now.setAlignment(Paragraph.ALIGN_RIGHT);
            document.add(now);

            // 表格标题
            List<String> titless = (List<String>) dataMap.get("titles");
            int len = titless.size();
            PdfPTable table = new PdfPTable(len);
            table.setSpacingBefore(20);
            table.setSpacingAfter(30);
            for(int i=0; i<len; i++){ //设置标题
                String str = titles.get(i);
                table.addCell(PDFUtil.getParagraph(str));
            }

            // 表格数据
            String type = (String) dataMap.get("type");
            if ("table".equals(type)){
                List<ElectricityPlanDTO> logList = (List<ElectricityPlanDTO>) dataMap.get("list");
                table = logPdf(table, logList);
            }

            document.add(table);
            // 关闭
            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }

        /*******pdf文件生成结束*********/
        try {
            fin = new FileInputStream(file);
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("application/pdf");
            String filename = time;
            // 设置浏览器以下载的方式处理该文件
            if (req.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                filename = URLEncoder.encode(filename, "UTF-8");
            } else {
                filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
            }
            //下载使用 删除可用(js2方法)直接在页面显示不下载
            resp.addHeader("Content-Disposition", "attachment;filename=" + filename + ".pdf");//这里填想要的文件格式

            out = resp.getOutputStream();
            byte[] buffer = new byte[512]; // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            if (fin != null)
                fin.close();
            if (out != null)
                out.close();
            if (file != null)
                file.delete(); // 删除临时文件
            if (myPath != null)
                myPath.delete();
        }
        return null;
    }

工具包PDFUtil

package com.linksaint.defence.electricity.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;

/**
 * @ClassName: PDFUtil
 * @Description:
 * @author yangkunpeng
 * @date 2020年1月7日
 *
 */
public class PDFUtil {
    // 对参数的封装形式比如{name}
    public static final String BEGIN = "{";
    public static final String END = "}";
    // 换行形式{#}
    public static final String NEW_LINE = "#";
    // 默认的行间距、首行距离等,自己添加
    public static final float DEFAULT_LEADING = 20;
    public static final float DEFAULT_LINE_INDENT = 30;


    // 基本字体和样式
    public static BaseFont bfChinese;
    public static Font fontChinese;
    public static Font UNDER_LINE = null;
    static{
        try {
            // SIMKAI.TTF 默认系统语言,这里没使用第三方语言包
            String CHARACTOR_FONT_CH_BLACK = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            String realReadPath = CHARACTOR_FONT_CH_BLACK + "pdfFont/simhei.ttf";
            bfChinese = BaseFont.createFont(realReadPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//            bfChinese = BaseFont.createFont("D:/home/java/contract/web/fonts/simsun.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
            //bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            fontChinese = new Font(bfChinese, 12, Font.NORMAL);
            UNDER_LINE = new Font(bfChinese, 14,Font.UNDERLINE);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    // 默认样式
    public static Paragraph getParagraph(String context){
        return getParagraph(context,fontChinese);
    }

    public static Paragraph getParagraph(Chunk chunk){
        return new Paragraph(chunk);
    }

    // 指定字体样式
    public static Paragraph getParagraph(String context,Font font){
        return new Paragraph(context,font);
    }

    // 获得新行,首行缩进,和行间距
    public static Paragraph getNewParagraph(String context,float fixedLeading,float firstLineIndent){
        Paragraph p = getParagraph(context);
        p.setLeading(fixedLeading);
        p.setFirstLineIndent(firstLineIndent);
        return p;
    }

    public static Paragraph getParagraph(String content , Font font , float fixedLeading , int alignment){
        Paragraph p = getParagraph(content);
        p.setFont(font);
        p.setLeading(fixedLeading);
        p.setAlignment(alignment);
        return p;
    }

    // 默认段落样式
    public static Paragraph getDefaultParagraph(String context){
        Paragraph p = getParagraph(context);
        // 默认行间距
        p.setLeading(DEFAULT_LEADING);
        // 默认首行空隙
        p.setFirstLineIndent(DEFAULT_LINE_INDENT);
        return p;
    }

    // 将参数和字符串内容组合成集合
    public static List<Paragraph> createParagraphs(String context ,Map<String,Object> map){
        int index = 0;
        List<Paragraph> list = new ArrayList<Paragraph>();
        Paragraph p = getDefaultParagraph(null);
        while((index  = context.indexOf(BEGIN)) > -1){
            String text = context.substring(0,index);
            context = context.substring(index, context.length());
            index = context.indexOf(END);
            String param =  null;
            if(index > 0){
                param = context.substring(BEGIN.length(),index);
            }
            p.add(text);
            if(!NEW_LINE.equals(param)){
                Object value = map.get(param);
                if(value != null){
                    p.add(new Chunk(value.toString(),UNDER_LINE));
                }else{
                    p.add(new Chunk(""));
                }
            }else{
                list.add(p);
                p = getDefaultParagraph(null);
                p.setSpacingBefore(0);
            }
            context = context.substring(index+END.length(),context.length());
        }
        list.add(p);
        list.add(getParagraph(context));
        return list;
    }
}

前端vue调用

axios请求
this.$refs.listLayout.getQueryValues()为查询过滤参数

// itextpdf
  exportPDF() {
      downFile("sys/electricityPlan/exportPDF",this.$refs.listLayout.getQueryValues() )
    },

/**
 * 下载文件
 * @param url
 * @param parameter
 * @returns {*}
 
export function downFile (url, parameter) {
  return axios({
    url: url,
    params: parameter,
    method: 'get',
    responseType: 'blob'
  }).then(response=>{
          if(response != null){
          const disposition = response.headers["content-disposition"].split(";");
          const fileName = decodeURI(
            disposition[disposition.length - 1].split("=")[1]
          ).replace(/^\"|\"$/g, "");
          const blob = new Blob([response.data])
          if (window.navigator.msSaveOrOpenBlob) {
            // 兼容IE10
            navigator.msSaveBlob(blob,fileName);
          } else {
            var a = document.createElement("a");
            a.href = URL.createObjectURL(blob);;
            a.download = fileName;
            a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
            URL.revokeObjectURL(a.href);
          }
        }
  })
}
*/

你可能感兴趣的:(Java)