这是第二次使用IText导出PDF了,上一次使用就是在网上看别人的使用案例东拼西凑整出来的,这次自己记录一下开发过程。

1. pom文件所需要的jar包:
<!--IText生成PDF-->
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itextpdf</artifactId>
	<version>5.5.3</version>
</dependency>
<!--用于输出中文-->
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itext-asian</artifactId>
	<version>5.2.0</version>
</dependency>
2. 下面先生成一个简单的PDF试一下,看看jar包或者其他的一些东西有没有问题
Document document = new Document();

String path = this.getClass().getResource("/").getPath();
File file = new File("E:/test.pdf");
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:/test.pdf"));

document.open();

document.add(new Paragraph("Hello World!"));

document.close();
writer.close();
生成效果

JAXBContext 转成javabean java txt转pdf_java

3. OK没有问题,然后开始根据自己需求完善PDF,我这次的需求是做一个巡检,先来一个基本信息展示
3.1、自定义字体:
public class PDFConstants {

    public static BaseFont bf;

    static {
        try {
            bf = BaseFont.createFont("E:\\git_projects\\BridgeDataManager\\BackGroundCode\\bridge_detection\\src\\main\\java\\com\\new3s\\bridge_detection\\commons\\itext\\msyh.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
    }

    // 注册字体
    public static Font FONT_25 = new Font(bf, 25);
    public static Font FONT_20 = new Font(bf, 20);
    public static Font FONT_16 = new Font(bf, 16);
    public static Font FONT_12 = new Font(bf, 12);
    public static Font BOLD_FONT_10_GREEN = new Font(bf, 10, Font.BOLD, BaseColor.GREEN);
    public static Font BOLD_FONT_13 = new Font(bf, 13, Font.BOLD);
}

这里的字体是我从网上下载的免费字体,百度一搜就有。

3.2、修改过后的代码:
//巡检信息--是我这次需要展示的数据,根据自己的需求自行更改
        InspectionInfoDto inspectionInfoDto = (InspectionInfoDto) this.getInspectionInfo(inspectionId).getData();
        InspectionDto inspectionDto = inspectionInfoDto.getInspectionDto();
        BridgeDto bridgeDto = inspectionInfoDto.getBridgeDto();
        BridgeStructureDto bridgeStructureDto = inspectionInfoDto.getBridgeStructureDto();

        //这里是边距,可根据自己需求设置
        Document document = new Document(PageSize.A4, 50, 50, 50, 10);

        String path = this.getClass().getResource("/").getPath();
//        File file = new File(path +"检测报告.pdf");
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:/test.pdf"));
        document.open();

        //4. 顶部标题
        Paragraph topTitle = new Paragraph(bridgeDto.getRoadNo() + "  " + bridgeDto.getBridgeName(), PDFConstants.FONT_25);
        //设置标题居中
        topTitle.setAlignment(Element.ALIGN_CENTER);
        document.add(topTitle);

        //一行空格,用于拉开标题与表格距离
        document.add(new Paragraph("  ", PDFConstants.FONT_12));
        document.add(new Paragraph("  ", PDFConstants.FONT_12));
        //标题1
        Paragraph title1 = new Paragraph("1、桥梁概况", PDFConstants.FONT_20);
        document.add(title1);
        document.add(new Paragraph("  ", PDFConstants.FONT_12));
        String title1Remark = "        " + bridgeDto.getBridgeName() + "中心桩号"
                + bridgeDto.getStakeNo() + ",上部结构为"
                + bridgeStructureDto.getUpStructureSpan()
                + bridgeStructureDto.getUpStructureForm()
                + ",横向" + bridgeDto.getHorizontal() + "片,"
                + "桥长 " + bridgeStructureDto.getBridgeLength() + " 米,"
                + "桥宽 " + bridgeStructureDto.getBridgeWidth() + " 米。"
                + "下部结构为" + bridgeStructureDto.getDownStructureAbutment() + "桥墩、台。"
                + "桥面铺装为" + bridgeDto.getPavingMaterial() + "。"
                + "该桥设计汽车荷载等级为" + bridgeDto.getDesignLoad() + "。"
                + "管养单位为" + bridgeDto.getCompanyName() + "。";
        document.add(new Paragraph(title1Remark, PDFConstants.FONT_12));
        document.add(new Paragraph("        该桥基本参数见表 1,桥梁全貌见照片 1-1~照片 1-2。", PDFConstants.FONT_12));
        Paragraph table1Title = new Paragraph("表1  桥梁基本状况一览表", PDFConstants.BOLD_FONT_10_GREEN);
        table1Title.setAlignment(Element.ALIGN_CENTER);
        document.add(table1Title);


        document.close();
        writer.close();
效果展示:

JAXBContext 转成javabean java txt转pdf_jar包_02

3.3、 基本信息完成,再来一个更加直观的表格

######自定义表格util

public class PdfUtil {

    /**
     * 创建默认列宽,指定列数、水平(居中、右、左)的表格
     *
     * @param colNumber
     * @param align
     * @return
     */
    public static PdfPTable createTable(int colNumber, int align) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            // 设置表格宽度比例为%100
            table.setWidthPercentage(100);
            // 设置表格的宽度
            table.setTotalWidth(PageSize.A4.getWidth() - 60);
            // 锁住宽度
            table.setLockedWidth(true);
            // 设置表格上面空白宽度
            table.setSpacingBefore(20f);
            // 设置表格下面空白宽度
            table.setSpacingAfter(20f);
            // 设置表格默认为无边框
            table.getDefaultCell().setBorder(1);
            // 设置翻页后表格头部还继续存在
            table.setHeaderRows(1);
            // 设置水平样式
            table.setHorizontalAlignment(align);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }



    /**
     * 创建单元格(指定字体)
     *
     * @param value
     * @param font
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(align);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setFixedHeight(20f);
        return cell;
    }
}

目前只用到这两个,后面根据需求添加
新增表格后的代码:

//巡检信息--是我这次需要展示的数据,根据自己的需求自行更改
        InspectionInfoDto inspectionInfoDto = (InspectionInfoDto) this.getInspectionInfo(inspectionId).getData();
        InspectionDto inspectionDto = inspectionInfoDto.getInspectionDto();
        BridgeDto bridgeDto = inspectionInfoDto.getBridgeDto();
        BridgeStructureDto bridgeStructureDto = inspectionInfoDto.getBridgeStructureDto();

        //这里是边距,可根据自己需求设置
        Document document = new Document(PageSize.A4, 50, 50, 50, 10);

        String path = this.getClass().getResource("/").getPath();
//        File file = new File(path +"检测报告.pdf");
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:/test.pdf"));
        document.open();

        //4. 顶部标题
        Paragraph topTitle = new Paragraph(bridgeDto.getRoadNo() + "  " + bridgeDto.getBridgeName(), PDFConstants.FONT_25);
        //设置标题居中
        topTitle.setAlignment(Element.ALIGN_CENTER);
        document.add(topTitle);

        //一行空格,用于拉开标题与表格距离
        document.add(new Paragraph("  ", PDFConstants.FONT_12));
        document.add(new Paragraph("  ", PDFConstants.FONT_12));
        //标题1
        Paragraph title1 = new Paragraph("1、桥梁概况", PDFConstants.FONT_20);
        document.add(title1);
        document.add(new Paragraph("  ", PDFConstants.FONT_12));
        String title1Remark = "        " + bridgeDto.getBridgeName() + "中心桩号"
                + bridgeDto.getStakeNo() + ",上部结构为"
                + bridgeStructureDto.getUpStructureSpan()
                + bridgeStructureDto.getUpStructureForm()
                + ",横向" + bridgeDto.getHorizontal() + "片,"
                + "桥长 " + bridgeStructureDto.getBridgeLength() + " 米,"
                + "桥宽 " + bridgeStructureDto.getBridgeWidth() + " 米。"
                + "下部结构为" + bridgeStructureDto.getDownStructureAbutment() + "桥墩、台。"
                + "桥面铺装为" + bridgeDto.getPavingMaterial() + "。"
                + "该桥设计汽车荷载等级为" + bridgeDto.getDesignLoad() + "。"
                + "管养单位为" + bridgeDto.getCompanyName() + "。";
        document.add(new Paragraph(title1Remark, PDFConstants.FONT_12));
        document.add(new Paragraph("        该桥基本参数见表 1,桥梁全貌见照片 1-1~照片 1-2。", PDFConstants.FONT_12));
        Paragraph table1Title = new Paragraph("表1  桥梁基本状况一览表", PDFConstants.BOLD_FONT_10_GREEN);
        table1Title.setAlignment(Element.ALIGN_CENTER);
        document.add(table1Title);

        //生成一个4列表格
        PdfPTable table1 = PdfUtil.createTable(4, Element.ALIGN_CENTER);
        table1.addCell(PdfUtil.createCell("路线名称", PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell(bridgeDto.getRoadNo() + bridgeDto.getRoadName(), PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell("桥梁桩号", PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell(bridgeDto.getStakeNo(), PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell("桥梁名称", PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell(bridgeDto.getBridgeName(), PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell("桥长(m)", PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell(bridgeStructureDto.getBridgeLength(), PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell("桥宽(m)", PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell(bridgeStructureDto.getBridgeWidth(), PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell("跨径组合(m)", PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell(bridgeStructureDto.getUpStructureSpan(), PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell("上部结构形式", PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell(bridgeStructureDto.getUpStructureForm(), PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell("下部结构形式", PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell(bridgeStructureDto.getDownStructureForm(), PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell("设计荷载等级", PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell(bridgeDto.getDesignLoad(), PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell("通车时间", PDFConstants.FONT_12, Element.ALIGN_CENTER));
        table1.addCell(PdfUtil.createCell(bridgeDto.getOpenToTraffic(), PDFConstants.FONT_12, Element.ALIGN_CENTER));
        document.add(table1);



        document.close();
        writer.close();

看下效果:

JAXBContext 转成javabean java txt转pdf_ci_03

3.4、 下一步,配图片

新增代码:

//放入桥面图片
        for (ShootDto bridgeShoot : bridgeShoots) {
            document.add(new Paragraph(" "));
            document.add(new Paragraph(" "));
            byte[] bytes = fastDFSClient.download(bridgeShoot.getShootUrl());
            Image image = Image.getInstance(bytes);
            image.setAlignment(Element.ALIGN_CENTER);
            image.scaleAbsolute(300, 200);
            document.add(image);
            Paragraph imageTitle = new Paragraph("照片" + bridgeShoot.getShootNo() + " " + bridgeDto.getRoadNo() + " " + bridgeShoot.getShootName(), PDFConstants.BOLD_FONT_10);
            imageTitle.setAlignment(Element.ALIGN_CENTER);
            document.add(imageTitle);
            int indexOf = bridgeShoots.indexOf(bridgeShoot);
            if (indexOf == 0){
                document.newPage();
            }
        }

效果

JAXBContext 转成javabean java txt转pdf_ci_04

本次需求的功能点就只有这些了,再后面都是图片表格图片表格的重复,有可能会用到表格的单元格合并,这是单元格合并的代码

public static PdfPCell createCell(String value, Font font, int align, int colspan, int rowspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        cell.setFixedHeight(rowspan * 25f);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }