欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用iText来生成PDF

程序员文章站 2022-06-01 08:36:04
...

首先导入pom依赖

 <!-- itext-->
 <dependency>
     <groupId>com.itextpdf</groupId>
     <artifactId>itextpdf</artifactId>
     <version>5.4.2</version>
 </dependency>
 <dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>5.4.1</version>
 </dependency>
 <dependency>
     <groupId>com.itextpdf</groupId>
     <artifactId>itext-asian</artifactId>
     <version>5.2.0</version>
 </dependency>
 <dependency>
     <groupId>org.xhtmlrenderer</groupId>
     <artifactId>flying-saucer-pdf</artifactId>
     <version>9.0.3</version>
 </dependency>
package cn.wideth.util;

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 java.io.File;
import java.io.FileOutputStream;

/**
 * 这个类是维护一些用来生成PDF
 * 的辅助函数,主要使用的是
 * itextpdf组件
 */
public class PDFUtil {

    Document document = null;// 建立一个Document对象

    private static Font headFont;
    private static Font keyFont;
    private static Font middleFont;
    private static Font textfont_H;
    private static Font textfont_B;
    private static Font textfont_BOLD;

    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);
            middleFont = new Font(bfChinese_H, 14, Font.BOLD);
            keyFont = new Font(bfChinese_H, 18, Font.BOLD);
            textfont_H = new Font(bfChinese_H, 10, Font.NORMAL);
            textfont_B = new Font(bfChinese_H, 12, Font.NORMAL);
            textfont_BOLD = new Font(bfChinese_H, 10, Font.BOLD);

        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    /**
     * 设置页面属性,创
     * 建一个文档对象
     * @param file
     */
    public PDFUtil(File file) {

        //产生一个文档对象
        document = new Document();

        try {
            PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 建表格(以列的数量建)
     *
     * @param colNumber
     * @return
     */
    public PdfPTable createTable(int colNumber) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
            table.setSpacingBefore(10);
            table.setWidthPercentage(100);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 建表格(以列的宽度比建)
     * @param widths
     * @return
     */
    public PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths);
        try {

            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
            table.setSpacingBefore(10);
            table.setWidthPercentage(100);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 表格中单元格
     * @param value
     * @param font
     * @param align
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 表格中单元格
     * @param value
     * @param font
     * @param align_v
     * @param align_h
     * @param colspan
     * @param rowspan
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align_v, int align_h, int colspan, int rowspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(align_v);
        cell.setHorizontalAlignment(align_h);
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 建短语
     * @param value
     * @param font
     * @return
     */
    public 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 Paragraph createParagraph(String value, Font font, int align) {
        Paragraph paragraph = new Paragraph();
        paragraph.add(new Phrase(value, font));
        paragraph.setAlignment(align);
        return paragraph;
    }

    public void generatePDF() throws Exception {

            document.add(createParagraph("健康体检表", keyFont, Element.ALIGN_CENTER));

            StringBuffer healtyInfo = new StringBuffer();
            healtyInfo.append("姓名:张三");
            healtyInfo.append("                                                                  ");
            healtyInfo.append("                                                                  ");
            healtyInfo.append("编号:10001");

            document.add(createParagraph(healtyInfo.toString(),headFont, Element.ALIGN_LEFT));
            //表格信息
            float[] healty = {10f, 10f, 10f, 10f, 10f, 10f, 10f, 10f, 10f, 10f, 10f};
            //创建健康体检表
            PdfPTable healtyTable = createTable(healty);
            StringBuffer time = new StringBuffer();
            time.append("年").append("           ");
            time.append("月").append("           ");
            time.append("日");

            healtyTable.addCell(createCell("体检日期", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 1));
            healtyTable.addCell(createCell(time.toString(), textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 5, 1));
            healtyTable.addCell(createCell("责任医生", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 1));
            healtyTable.addCell(createCell("", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 1));

            healtyTable.addCell(createCell("内 容", textfont_BOLD, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 1, 1));
            healtyTable.addCell(createCell("检   查   项   目", textfont_BOLD, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 10, 1));
            StringBuffer  content = new StringBuffer();
            content.append("1   无症状       ").append("2   头痛       ").append("3   头晕       ").append("4   心悸       ").append("5   胸闷       ").append("6   胸痛       ").append("7   慢性咳嗽       ").append("8   咳嗽       ").append("9   呼吸困难").append("\n");
            content.append("10   多饮        ").append("11   多尿        ").append("12   体重下降        ").append("13   乏力        ").append("14   关节肿痛        ").append("15   视力模糊        ").append("16    手脚麻木").append("\n");
            content.append("17   尿急        ").append("18   尿痛        ").append("19   便秘        ").append("20   腹泻        ").append("21   恶心呕吐        ").append("22   眼花        ").append("23    耳鸣      ").append("24    乳房肿胀").append("\n");
            content.append("25   其他:");
            healtyTable.addCell(createCell("症状", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 1, 4));
            healtyTable.addCell(createCell(content.toString(), textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, 10, 4));

            //一般状况部分
            healtyTable.addCell(createCell("一般状况", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 1, 13));

            healtyTable.addCell(createCell("体  温", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 1));
            healtyTable.addCell(createCell("℃", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_RIGHT, 3, 1));
            healtyTable.addCell(createCell("脉  率", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 1));
            healtyTable.addCell(createCell("次/分钟", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 3, 1));

            healtyTable.addCell(createCell("呼吸频率", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 2));
            healtyTable.addCell(createCell("次/分钟", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_RIGHT, 3, 2));
            healtyTable.addCell(createCell("血  压", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 2));
            healtyTable.addCell(createCell("左侧", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 1, 1));
            healtyTable.addCell(createCell("118/78 mmHg", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 1));
            healtyTable.addCell(createCell("右侧", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 1, 1));
            healtyTable.addCell(createCell("/  mmHg", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 1));

            healtyTable.addCell(createCell("身  高", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 1));
            healtyTable.addCell(createCell("cm", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_RIGHT, 3, 1));
            healtyTable.addCell(createCell("体  重", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 1));
            healtyTable.addCell(createCell("kg", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 3, 1));

            healtyTable.addCell(createCell("腰  围", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 1));
            healtyTable.addCell(createCell("cm", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_RIGHT, 3, 1));
            healtyTable.addCell(createCell("体质指数(BMI)", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 1));
            healtyTable.addCell(createCell("kg/m^2", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 3, 1));

            healtyTable.addCell(createCell("老年人健康\n状态自我评估", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 2));
            StringBuffer s = new StringBuffer();
            s.append("1   满意     ").append("2   基本满意     ").append("3   说不清楚     ").append("4   不太满意     ").append("5   不满意");
            healtyTable.addCell(createCell(s.toString(), textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, 8, 2));

            healtyTable.addCell(createCell("老年人生活自理\n能力自我评估", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 2));
            StringBuffer ss = new StringBuffer();
            ss.append("1   可自理(0~3分)     ").append("2   轻度依赖(4~8分)").append("\n").append("3   中度依赖(9~18分)     ").append("4   不能自理(>18分)");
            healtyTable.addCell(createCell(ss.toString(), textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, 8, 2));

            healtyTable.addCell(createCell("老年人\n认知功能", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 2));
            healtyTable.addCell(createCell("1   粗筛阴性\n2   粗筛阳性,简易智力状态检查,总分:", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, 8, 2));

            healtyTable.addCell(createCell("老年人\n情感状态", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER, 2, 2));
            healtyTable.addCell(createCell("1   粗筛阴性\n2   粗筛阳性,老年人抑郁评分检查,总分:", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, 8, 2));

            document.add(healtyTable);
            document.newPage();

        document.close();
    }

    public static void main(String[] args) throws Exception {

        File file = new File("d:/体检报告单.pdf");
        file.createNewFile();
        new PDFUtil(file).generatePDF();
        System.out.println("PDF生产完成");
    }

}

效果图

使用iText来生成PDF