java生成pdf文件

  1. pom添加依赖

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

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
  1. util工具类

package com.susu.util;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;

/**
 * pdf工具类
 */
public class PdfUtil extends PdfPageEventHelper {

    /**
     * 定义静态变量,用于生成水印文件名称
     */
    private final static String RESULT_FILE = "D:/pdf/a.pdf";
    /**
     * 页眉
     */
    public String header = "xxxx";

    /**
     * 文档字体大小,页脚页眉最好和文本大小一致
     */
    public int presentFontSize = 12;

    /**
     * 文档页面大小,最好前面传入,否则默认为A4纸张
     */
    public Rectangle pageSize = PageSize.A4;
    /**
     * 基础字体对象
     */
    public BaseFont bf = null;
    /**
     * 利用基础字体生成的字体对象,一般用于生成中文文字
     */
    public Font fontDetail = null;
    // 模板
    public PdfTemplate total;

    /**
     *  返回一个暂无数据的pdf文件
     **/
    public static void nullPdf(OutputStream out)throws MalformedURLException, IOException, DocumentException {
        //①建立com.lowagie.text.Document对象的实例。
        Document doc = new Document(PageSize.A4,20,20,30,30);
        PdfWriter instance = PdfWriter.getInstance(doc, out);
        //③打开文档。
        doc.open();

        //创建字体
        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
        //字体对象
        //大小为10的正常字体
        Font size10font = new Font(baseFont,10,Font.NORMAL);
        //大小为12的粗体
        Font size14bold = new Font(baseFont,12,Font.BOLD);

        // 准备工作结束,进行文档内容填充:
        // 第一页,结算汇总信息
        doc.newPage();
        doc.add(new Paragraph("暂无数据",size10font));
        doc.close();
        instance.close();
    }

    /**
     *
     * @param str 字符串
     * @param font 字体
     * @param high 表格高度
     * @Param alignCenter 是否水平居中
     * @Param alignMidde  是否垂直居中
     * @return
     */
    public static PdfPCell mircoSoftFont(String str, Font font, int high, boolean alignCenter, boolean alignMidde){
        PdfPCell pdfPCell  = new PdfPCell(new Phrase(str,font));
        pdfPCell.setMinimumHeight(high);
        // 设置可以居中
        pdfPCell.setUseAscender(true);
        if (alignCenter){
            // 设置水平居中
            pdfPCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        }
        if (alignMidde){
            // 设置垂直居中
            pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        }
        return pdfPCell;
    }

    /**
     * 给pdf文件添加水印
     *
     * @param InPdfFile
     *            要加水印的原pdf文件路径
     * @param outPdfFile
     *            加了水印后要输出的路径
     * @param readpicturepath
     *            水印图片路径
     * @throws Exception
     */
    public static void addPdfMark(String InPdfFile, String outPdfFile, String readpicturepath) throws Exception {
        PdfReader reader = new PdfReader(InPdfFile);
        int pageSize = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outPdfFile));
        // 插入水印
        Image img = Image.getInstance(readpicturepath);
        img.setAbsolutePosition(0, 0);
        for (int i = 1; i <= pageSize; i++) {
            PdfContentByte under = stamp.getUnderContent(i);
            under.addImage(img);
        }
        stamp.close();// 关闭
        File tempfile = new File(InPdfFile);
        if (tempfile.exists()) {
            tempfile.delete();
        }
    }

    /**
     * paragraph的格式
     * @param paragraph
     * @param doc
     * @throws DocumentException
     */
    public static void geshi1(Paragraph paragraph, Document doc) throws DocumentException {// 段落的格式
        paragraph.setIndentationLeft(30);
        paragraph.setIndentationRight(30);
        paragraph.setFirstLineIndent(20f);
        paragraph.setSpacingAfter(10f);
        paragraph.setSpacingBefore(10f);
        doc.add(paragraph);
    }

    /**
     * 居中无边框的cell
     * @param cell
     * @param table
     * @throws DocumentException
     */
    public static void geshi2(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        table.addCell(cell);
    }

    // 不居中无边框的cell
    public static void geshi12(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);
    }

    // 居中有边框的cell
    public static void geshi22(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        table.addCell(cell);
    }

    // 居中有边框的cell
    public static void geshi32(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setColspan(3);
        cell.setBorder(0);
        table.addCell(cell);
    }

    /**
     *
     * TODO 文档打开时创建模板
     *
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
     */
    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {
        // 共 页 的矩形的长宽高
        total = writer.getDirectContent().createTemplate(50, 50);
    }

    /**
     *
     * Creates a new instance of PdfReportM1HeaderFooter 构造方法.
     *  @param yeMei
     *            页眉字符串
     * @param presentFontSize
     *            数据体字体大小
     * @param pageSize
     */
    public PdfUtil(String yeMei, int presentFontSize, Rectangle pageSize) {
        this.header = yeMei;
        this.presentFontSize = presentFontSize;
        this.pageSize = pageSize;
    }


    /**
     *
     * TODO 关闭每页的时候,写入页眉,写入'第几页'这几个字。
     *
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
     */
    @Override
    public void onEndPage(PdfWriter writer, Document document) {

        try {
            if (bf == null) {
                bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            }
            if (fontDetail == null) {
                // 数据体字体
                fontDetail = new Font(bf, presentFontSize, Font.NORMAL);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 1.写入页眉
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(header, fontDetail), document.getPageSize().getRight()/2, document.getPageSize().getTop()-36, 0);
//          没有需要写页脚的需求,先注释起来,后续有需求再调试
//        2.写入前半部分的 第 X页/共
//        int pageS = writer.getPageNumber();
//        String foot1 = "第 " + pageS + " 页";
//        Phrase footer = new Phrase(foot1, fontDetail);

//        // 3.计算前半部分的foot1的长度,后面好定位最后一部分的'Y页'这俩字的x轴坐标,字体长度也要计算进去 = len
//        float len = bf.getWidthPoint(foot1, presentFontSize);

//        // 4.拿到当前的PdfContentByte
//        PdfContentByte cb = writer.getDirectContent();

//        // 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0F 再给偏移20F适合人类视觉感受,否则肉眼看上去就太偏左了 ,y轴就是底边界-20,否则就贴边重叠到数据体里了就不是页脚了;注意Y轴是从下往上累加的,最上方的Top值是大于Bottom好几百开外的。
//        ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, (document.rightMargin() + document.right() + document.leftMargin() - document.left() - len) / 2.0F + 20F, document.bottom() - 20, 0);
//
//        // 6.写入页脚2的模板(就是页脚的Y页这俩字)添加到文档中,计算模板的和Y轴,X=(右边界-左边界 - 前半部分的len值)/2.0F + len , y 轴和之前的保持一致,底边界-20
//        // 调节模版显示的位置
//        cb.addTemplate(total, (document.rightMargin() + document.right() + document.leftMargin() - document.left()) / 2.0F + 20F, document.bottom() - 20);

    }

    /**
     *
     * TODO 关闭文档时,替换模板,完成整个页眉页脚组件
     *
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
     */
    @Override
    public void onCloseDocument(PdfWriter writer, Document document) {
        // 7.最后一步了,就是关闭文档的时候,将模板替换成实际的 Y 值,至此,page x of y 制作完毕,完美兼容各种文档size。
        total.beginText();
        // 生成的模版的字体、颜色
        total.setFontAndSize(bf, presentFontSize);
        String foot2 = " " + (writer.getPageNumber() - 1) + " 页";
        // 模版显示的内容
        total.showText(foot2);
        total.endText();
        total.closePath();
    }

    // 插入图片
    public static void addpicture(PdfPTable table, Image image, String picpath, PdfPCell cell, Document doc)
        throws MalformedURLException, IOException, DocumentException {
        image = Image.getInstance(picpath);
        cell = new PdfPCell(image);
        geshi2(cell, table);
        doc.add(table);
    }

    //非空判断
    public static String isnull(Object a) {
        if (a != null && a != "" && a != "null" && a.toString() != "null") {
            return a.toString();
        } else {
            return "";
        }
    }
}


  1. controller层,返回前端流数据,前端自己下载文件


        //①建立Document对象的实例。
        Document doc = new Document(PageSize.A4, 20, 20, 30, 30);
        //②建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
        String path = "D:\\test\\";
        String fileName = "test表.pdf";
        PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(path + fileName));
        PdfUtil pdfUtil = new PdfUtil(null, 15, PageSize.A4);
        //③打开文档。
        doc.open();
        pdfUtil.onOpenDocument(instance, doc);
        //创建字体
        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        //字体对象
        //大小为10的正常字体
        Font size10font = new Font(baseFont, 10, Font.NORMAL);
        //大小为12的粗体
        Font size12font = new Font(baseFont, 12, Font.NORMAL);

        // 进行文档内容填充   第一行标题
        String titleName = "综合列表";
        PdfPTable table = new PdfPTable(header.size());
        table.setWidthPercentage(90);
        PdfPCell cell1 = new PdfPCell(new Phrase(titleName, size12font));
        cell1.setMinimumHeight(50);
        cell1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell1.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell1.setColspan(header.size());
        cell1.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell1);
        doc.add(table);


        //添加第1行的数据
        PdfPTable firstRowTable = new PdfPTable(header.size()); //三列的意思
        firstRowTable.setWidthPercentage(90);设置标题长度占纸张比例
        float[] widths = new float[]{5, 5, 5, 5, 5, 5, 5, 15, 23, 5, 13};
        firstRowTable.setWidths(widths);
        for (Map.Entry entry : header.entrySet()) {
            firstRowTable.addCell(PdfUtil.mircoSoftFont((String) entry.getValue(), size10font, 40, true, true));
        }
        doc.add(firstRowTable);

        //循环数据
        for (Map<String, Object> d : data) {
            //添加第2行的数据
            PdfPTable secondRowTable = new PdfPTable(header.size()); //三列的意思
            secondRowTable.setWidthPercentage(90);设置标题长度占纸张比例
            secondRowTable.setWidths(widths);
            for (Map.Entry entry : d.entrySet()) {
                secondRowTable.addCell(PdfUtil.mircoSoftFont((String) entry.getValue(), size10font, 40, true, true));
            }
            doc.add(secondRowTable);
        }
        pdfUtil.onEndPage(instance, doc);
        doc.close();
        instance.close();

        //把数据返给前端
        try {
            File file = new File(path + fileName);
            InputStream in = new BufferedInputStream(new FileInputStream(file));
            String filename = new String(fileName.getBytes(), "ISO8859_1");
            response.setContentType("application/binary;charset=ISO8859_1");
            response.setHeader("Content-disposition", "attachment; filename=" + filename);// 组装附件名称和格式
            IoUtil.copy(in, response.getOutputStream());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值