itext PDF文件导出

maven工程可以在pom文件加入依赖:

<!--itext导出pdf相关jar-->
<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>

实例代码: 

import com.hellowin.b2c.date.SSHDateFormatUtils;
import com.hellowin.b2c.date.SSHDateUtils;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.util.Date;

/**
 * @Auther: 
 * @Date: 2018/9/17 17:26
 * @Description: 1-创建文本对象 Document
 * 2-初始化 pdf输出对象 PdfWriter
 * 3-打开 Document
 * 4-往 Document 添加内容
 * 5-关闭 Document
 */
public class BasePDFWriteUtil {
    private static Logger logger = LoggerFactory.getLogger(BasePDFWriteUtil.class);
    Document document = null;// 建立一个Document对象
    private static Font headFont;
    private static Font keyFont;
    private static Font keyFontBig;
    private static Font textfont_H;
    private static Font textfont_B;
    private static Font textfont_1;
    int maxWidth = 520;

    static {
        BaseFont bfChinese_H;
        try {
            /**
             * 新建一个字体,iText的方法 STSongStd-Light 是字体,在iTextAsian.jar 中以property为后缀
             * UniGB-UCS2-H 是编码,在iTextAsian.jar 中以cmap为后缀 H 代表文字版式是 横版, 相应的 V 代表竖版
             */
            bfChinese_H = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            headFont = new Font(bfChinese_H, 10, Font.NORMAL);
            keyFont = new Font(bfChinese_H, 18, Font.BOLD);
            keyFontBig = new Font(bfChinese_H, 22, Font.BOLD);
            textfont_H = new Font(bfChinese_H, 10, Font.NORMAL);
            textfont_B = new Font(bfChinese_H, 12, Font.NORMAL);
            textfont_1 = new Font(bfChinese_H, 16, Font.NORMAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置页面属性
     */
    public BasePDFWriteUtil(File file) {
        try {
            file.createNewFile();
            //自定义纸张
            // Rectangle rectPageSize = new Rectangle(350, 620);
            // 定义A4页面大小
            Rectangle rectPageSize = new Rectangle(PageSize.A4);
            // rectPageSize = rectPageSize.rotate();// 加上这句可以实现页面的横置
            // rectPageSize.setBackgroundColor(BaseColor.BLACK);// 背景色
            // document = new Document(rectPageSize,80, 80, 10, 40);
            // 1-创建文本对象 Document
            document = new Document(rectPageSize);
            // 2-初始化 pdf输出对象 PdfWriter
            PdfWriter.getInstance(document, new FileOutputStream(file));
            // 3-打开 Document
            document.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 建表格(以列的宽度比建)
     *
     * @param widths
     * @return
     */
    public static PdfPTable createTable(float[] widths, boolean isHalf) {
        PdfPTable table = new PdfPTable(widths);
        try {
            // 表格的总宽度
            //table.setTotalWidth(maxWidth);
            // 宽度锁定
            //table.setLockedWidth(true);
            // 对齐方式
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            // 得到默认单元格
            table.getDefaultCell().setBorder(1);
            // 设置表格上面空白行
            table.setSpacingBefore(10);
            // 表格的宽度百分比
            if (isHalf) {
                table.setWidthPercentage(50);
            } else {
                table.setWidthPercentage(100);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 表格中单元格
     *
     * @param value
     * @param font
     * @param
     * @param colspan
     * @param rowspan
     * @param border  是否需要边框
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align_v, int align_h, int colspan, int rowspan, boolean border) {
        PdfPCell cell = new PdfPCell();
        try {
            // 垂直居中
            cell.setVerticalAlignment(align_v);
            // 水平居中
            cell.setHorizontalAlignment(align_h);
            cell.setColspan(colspan);
            cell.setRowspan(rowspan);
            cell.setPhrase(new Phrase(value, font));
            if (border == false) {
                // 去掉边框
                cell.setBorder(Rectangle.NO_BORDER);
                cell.setBorderWidth(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cell;
    }

    /**
     * cell是否需要左右边框
     *
     * @param value
     * @param font
     * @param align_v
     * @param align_h
     * @param colspan
     * @param rowspan
     * @param border
     * @return
     */
    public static PdfPCell createCellNoBorder(String value, Font font, int align_v, int align_h, int colspan, int rowspan, boolean border) {
        PdfPCell cell = new PdfPCell();
        try {
            // 垂直居中
            cell.setVerticalAlignment(align_v);
            // 水平居中
            cell.setHorizontalAlignment(align_h);
            cell.setColspan(colspan);
            cell.setRowspan(rowspan);
            cell.setPhrase(new Phrase(value, font));
            if (border == false) {
                // 去掉左右边框
                cell.disableBorderSide(Rectangle.RIGHT);
                cell.disableBorderSide(Rectangle.LEFT);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cell;
    }

    /**
     * cell只保留下边框
     *
     * @param value
     * @param font
     * @param align_v
     * @param align_h
     * @param colspan
     * @param rowspan
     * @return
     */
    public static PdfPCell createCellBottom(String value, Font font, int align_v, int align_h, int colspan, int rowspan) {
        PdfPCell cell = new PdfPCell();
        try {
            // 垂直居中
            cell.setVerticalAlignment(align_v);
            // 水平居中
            cell.setHorizontalAlignment(align_h);
            cell.setColspan(colspan);
            cell.setRowspan(rowspan);
            cell.setPhrase(new Phrase(value, font));
            cell.disableBorderSide(Rectangle.RIGHT);
            cell.disableBorderSide(Rectangle.LEFT);
            cell.disableBorderSide(Rectangle.TOP);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cell;
    }

    /**
     * 建短语
     *
     * @param value
     * @param font
     * @return
     */
    public static Phrase createPhrase(String value, Font font) {
        Phrase phrase = new Phrase();
        phrase.add(value);
        phrase.setFont(font);
        return phrase;
    }

    /**
     * 建段落
     *
     * @param value
     * @param font
     * @param align
     * @return
     */
    public static Paragraph createParagraph(String value, Font font, int align) {
        Paragraph paragraph = new Paragraph();
        try {
            paragraph.add(new Phrase(value, font));
            paragraph.setAlignment(align);
            // 行间距
            // paragraph.setLeading(10f);
            // 设置段落下空白
            paragraph.setSpacingAfter(10f);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paragraph;
    }

    private static byte[] InputStream2ByteArray(String filePath) throws IOException {
        InputStream in = new FileInputStream(filePath);
        byte[] data = toByteArray(in);
        in.close();
        return data;
    }

    private static byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }

    /**
     * 插入图片
     *
     * @param filePath
     * @param isURL    是否URL
     * @return
     * @throws BadElementException
     * @throws IOException
     */
    private static Image insertImg(String filePath, boolean isURL) throws Exception {
        Image img;
        if (isURL) {
            URL url = new URL(filePath);
            img = Image.getInstance(url);
        } else {
            img = Image.getInstance(filePath);
        }
        img.setAlignment(Image.ALIGN_CENTER);
        img.setBorder(Image.BOX);
        img.setBorderWidth(10);
        img.setBorderColor(BaseColor.WHITE);
        img.scaleToFit(1000, 300);// 大小
        img.setSpacingAfter(10f);
        // img.setRotationDegrees(-30);// 旋转
        return img;
    }

    /**
     * 根据InputStream插入图片
     *
     * @param in
     * @return
     * @throws Exception
     */
    private static Image insertImgByte(InputStream in) throws Exception {
        Image img;
        byte[] bytes = toByteArray(in);
        img = Image.getInstance(bytes);
        img.setAlignment(Image.ALIGN_CENTER);
        img.setBorder(Image.BOX);
        img.setBorderWidth(10);
        img.setBorderColor(BaseColor.WHITE);
        img.scaleToFit(1000, 300);// 大小
        img.setSpacingAfter(10f);
        return img;
    }

    /**
     * 生成pdf文件
     * @param ecgChangePath 图路径
     * @param poincarePath 图路径
     * @throws Exception
     */
    public boolean createPDF(String ecgChangePath, String poincarePath) {
        try {
            // inputStream
            // InputStream inputStream = new FileInputStream(poincarePath);
            // 图片url
            // String imgPath="http://pic.58pic.com/58pic/15/57/84/70H58PICCJt_1024.jpg";

            //页头信息
            document.add(createParagraph("报告", keyFontBig, Element.ALIGN_CENTER));
            document.add(createParagraph("(专业版)", keyFont, Element.ALIGN_CENTER));

            //表格信息
            float[] widths = {35f, 30f, 35f};
            PdfPTable table = createTable(widths, false);
            table.addCell(createCell("姓名:***", textfont_1, Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, 1, 1, false));
            table.addCell(createCell("性别:男", textfont_1, Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, 1, 1, false));
            table.addCell(createCell("年龄:24", textfont_1, Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, 1, 1, false));
            table.addCell(createCell("检测时长:20.4小时", textfont_1, Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, 1, 1, false));
            table.addCell(createCell("有效数据:80% ", textfont_1, Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, 1, 1, false));
            table.addCell(createCell("检测日期:" + SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT1), textfont_1, Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, 1, 1, false));
            document.add(table);

            document.add(Chunk.NEWLINE);
            document.add(createParagraph("一、结果", keyFont, Element.ALIGN_LEFT));
            // 插入图片
            document.add(insertImg(ecgChangePath, true));

            document.add(Chunk.NEWLINE);
            document.add(createParagraph("图", keyFont, Element.ALIGN_CENTER));

            float[] widths2 = {33f, 32f, 35f};
            PdfPTable table2 = createTable(widths2, false);
            table2.addCell(createCellNoBorder("起始时间", textfont_1, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
            table2.addCell(createCellNoBorder("终止时间", textfont_1, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
            table2.addCell(createCellNoBorder("时长(小时)", textfont_1, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
            for (int i = 0; i < 5; i++) {
                if (i == 4) {
                    table2.addCell(createCellBottom(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT2), textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1));
                    table2.addCell(createCellBottom(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT2), textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1));
                    table2.addCell(createCellBottom((i + 1) + "", textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1));
                } else {
                    table2.addCell(createCell(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT2), textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
                    table2.addCell(createCell(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT2), textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
                    table2.addCell(createCell((i + 1) + "", textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
                }
            }
            document.add(table2);


            float[] widths3 = {25f, 20f, 20f, 25f};
            PdfPTable table3 = createTable(widths3, false);
            table3.addCell(createCellNoBorder("指标", textfont_1, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
            table3.addCell(createCellNoBorder("取值2", textfont_1, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
            table3.addCell(createCellNoBorder("提示2", textfont_1, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
            table3.addCell(createCellNoBorder("参考范围", textfont_1, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
            for (int i = 0; i < 5; i++) {
                if (i == 4) {
                    table3.addCell(createCellBottom(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT2), textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1));
                    table3.addCell(createCellBottom(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT2), textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1));
                    table3.addCell(createCellBottom("↑↓", textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1));
                    table3.addCell(createCellBottom((i + 1) + "", textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1));
                } else {
                    table3.addCell(createCell(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT2), textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
                    table3.addCell(createCell(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT2), textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
                    table3.addCell(createCell(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT2), textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
                    table3.addCell(createCell((i + 1) + "", textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
                }
            }
            document.add(table3);
            document.add(Chunk.NEWLINE);

            document.add(createParagraph("二、结果", keyFont, Element.ALIGN_LEFT));
            // 图
            // document.add(insertImgByte(inputStream));
            document.add(insertImg(poincarePath, true));

            document.add(createParagraph("图", keyFont, Element.ALIGN_CENTER));
            document.add(Chunk.NEWLINE);

            document.add(createParagraph("三、评估", keyFont, Element.ALIGN_LEFT));
            document.add(createParagraph("(一)评估", textfont_1, Element.ALIGN_LEFT));
            float[] widths4 = {25f, 25f};
            PdfPTable table4 = createTable(widths4, true);
            table4.addCell(createCellNoBorder("结果", textfont_1, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
            table4.addCell(createCellNoBorder("级别", textfont_1, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
            for (int i = 0; i < 3; i++) {
                if (i == 2) {
                    table4.addCell(createCellBottom("√", textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1));
                    table4.addCell(createCellBottom(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT2), textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1));
                } else {
                    table4.addCell(createCell(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT2), textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
                    table4.addCell(createCell(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT2), textfont_B, Element.ALIGN_CENTER, Element.ALIGN_CENTER, 1, 1, false));
                }
            }
            document.add(table4);
            document.add(Chunk.NEWLINE);

            document.add(createParagraph("五、*****", keyFont, Element.ALIGN_LEFT));
            Paragraph tParagraph = new Paragraph("建议", textfont_1);
            tParagraph.setAlignment(Element.ALIGN_JUSTIFIED);// 对齐方式
            tParagraph.setFirstLineIndent(24);// 首行缩进
            tParagraph.setSpacingAfter(10f);// 设置段落下空白
            document.add(tParagraph);
            document.add(Chunk.NEWLINE);
            document.add(createParagraph(SSHDateUtils.date2String(new Date(), SSHDateFormatUtils.DATE_FORMAT1), textfont_1, Element.ALIGN_RIGHT));
        } catch (Exception e) {
            return false;
        } finally {
            // 关闭Document对象
            document.close();
        }
        return true;
    }



    public static void main(String[] args) {
        try {
            File file = new File("E:\\导出PDF.pdf");
            boolean res = new BasePDFWriteUtil(file).createPDF("http://pic.58pic.com/58pic/15/57/84/70H58PICCJt_1024.jpg", "http://pic.58pic.com/58pic/15/57/84/70H58PICCJt_1024.jpg");
            if (res) {
                System.out.println("PDF创建成功!");
            } else {
                System.out.println("PDF创建失败!");
            }
        } catch (Exception e) {
            logger.info("创建pdf出现异常");
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值