Java利用itext实现导出PDF文件

因为工作中要用到,导出不同的PDF,所以学习了Itext

我两天创建的PDF如下所示,主要是简单的表格类的

1、引包

       <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.11</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.11</version>
        </dependency>
        <!-- 支持中文 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!-- 支持css样式渲染 -->
        <dependency>
            <groupId>org.xhtmlrenderer</groupId>
            <artifactId>flying-saucer-pdf-itext5</artifactId>
            <version>9.1.16</version>
        </dependency>
        <!-- 转换html为标准xhtml包 -->
        <dependency>
            <groupId>net.sf.jtidy</groupId>
            <artifactId>jtidy</artifactId>
            <version>r938</version>
        </dependency>

2、工具类

package pdfdemo.pdfdemo.demoOne;



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

import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Description iTextPDFUtil
 * @author 小帅丶
 * @className iTextPDFUtil
 * @Date 2019/7/18-11:26
 **/
public class iTextPDFUtil {
    /*
     * @Description 蓝色背景色标题内容行添加
     * @Author 小帅丶
     * @Date  2019/7/12 14:56
     * @param table 表格
     * @param cell  列
     * @param text  文本
     * @return void
     **/
    public static void addTableGroupTitle(PdfPTable table, PdfPCell cell, String text) {
        cell = new PdfPCell(new Phrase(text,getColorFont(BaseColor.WHITE)));
        table.addCell(addTitleCell(cell,25,new BaseColor(69,153,241),2,false));
    }
    /**
     * @Description 蓝色背景色标题内容行添加
     * @Author 小帅丶
     * @Date  2019/7/12 14:56
     * @param table 表格
     * @param cell  列
     * @param text  文本
     * @param colspan 需要合并的列
     * @return void
     **/
    public static void addTableGroupTitle(PdfPTable table, PdfPCell cell, String text,int colspan) {
        cell = new PdfPCell(new Phrase(text,getColorFont(BaseColor.WHITE)));
        table.addCell(addTitleCell(cell,25,new BaseColor(69,153,241),colspan,false));
    }
    /**
     * @Description 核查建议
     * @Author 小帅丶
     * @Date  2019/7/12 14:43
     * @param table 表格
     * @param cell 列
     * @param suggestText 核查建议内容
     * @param fontColor 核查建议内容文字颜色
     * @return com.itextpdf.text.Element
     **/
    public static void addSuggestLine(PdfPTable table,PdfPCell cell,String suggestText,BaseColor fontColor) throws Exception {
        addSuggestLine(table, cell, suggestText, fontColor, 0,10f,30f);
    }
    /**
     * @Description 核查建议
     * @Author 小帅丶
     * @Date  2019/7/12 14:43
     * @param table 表格
     * @param cell 列
     * @param suggestText 核查建议内容
     * @param fontColor 核查建议内容文字颜色
     * @param colspan 合并的列
     * @param widths 列所占宽
     * @return com.itextpdf.text.Element
     **/
    public static void addSuggestLine(PdfPTable table,PdfPCell cell,String suggestText,BaseColor fontColor,int colspan,float...widths) throws Exception {
        cell = new PdfPCell(new Phrase("核查建议:",getColorFont()));
        cell.setColspan(1);
        table.addCell(addBaseCell(cell,23,new BaseColor(238,238,238),false));
        cell = new PdfPCell(new Phrase(suggestText,getColorFont(fontColor)));
        if(colspan>0){
            cell.setColspan(colspan);
        }
        table.addCell(addBaseCell(cell,23,new BaseColor(238,238,238),false));
        table.setWidths(getColumnWiths(widths));
    }
    /**
     * @Description 信息分组table
     * @Author 小帅丶
     * @Date  2019/7/12 14:43
     * @param groupText 文本内容
     * @return com.itextpdf.text.Element
     **/
    public static Element addTableGroupLine(String groupText) {
        PdfPTable tableBaseInfoIndex = new PdfPTable(1);
        tableBaseInfoIndex.setWidthPercentage(20);
        PdfPCell cellBaseInfo = new PdfPCell(new Phrase(groupText,getColorFont()));
        cellBaseInfo.setHorizontalAlignment(Element.ALIGN_CENTER);
        tableBaseInfoIndex.addCell(addTitleCell(cellBaseInfo,28,new BaseColor(238,238,238),2,false));
        tableBaseInfoIndex.addCell(addBlankLine(10,1));
        return tableBaseInfoIndex;
    }
    public static Element addHeadLine(String groupText) {
        PdfPTable tableBaseInfoIndex = new PdfPTable(1);
        tableBaseInfoIndex.setWidthPercentage(100);

        PdfPCell cellBaseInfo = new PdfPCell(new Phrase(groupText,getHeadFont()));
        cellBaseInfo.setBorderWidth(0);
        cellBaseInfo.setMinimumHeight(80);
        cellBaseInfo.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellBaseInfo.setVerticalAlignment(Element.ALIGN_MIDDLE);
        tableBaseInfoIndex.addCell(cellBaseInfo);
        return tableBaseInfoIndex;
    }




    public static PdfPCell addOneLineBox(String groupText,int col) {
        PdfPCell cell;
        cell = new PdfPCell(new Phrase(groupText, iTextPDFUtil.getColorFont()));
        cell.setColspan(col);
        cell.setMinimumHeight(35);
        cell.setRowspan(1);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        return cell;
    }
    public static PdfPCell addTwoLineBox(String groupText,int col) {
        PdfPCell cell;
        cell = new PdfPCell(new Phrase(groupText, iTextPDFUtil.getColorFont()));
        cell.setColspan(col);
        cell.setMinimumHeight(45);
        cell.setRowspan(2);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        return cell;
    }
    /**
     * @Description 指定颜色字体 默认处理中文显示
     * @Author 小帅丶
     * @Date  2019/7/12 14:05
     * @param color 字体颜色
     * @param fontSize 字体大小
     * @param fontFamily 字体
     * @return com.itextpdf.text.Font
     **/
    public static Font getColorFont(BaseColor color, int fontSize, String fontFamily) {
        Font font = new Font(getFont());
        font.setColor(color);
        if(fontSize>0&&(null!=fontFamily||!"".equals(fontFamily))){
            font.setSize(fontSize);
            font.setFamily(fontFamily);
        }
        return font;
    }
    /**
     * @Description 指定颜色字体 默认处理中文显示
     * @Author 小帅丶
     * @Date  2019/7/12 14:05
     * @param color 字体颜色
     * @return com.itextpdf.text.Font
     **/
    public static Font getColorFont(BaseColor color) {
        return getColorFont(color, 0, null);
    }
    /**
     * @Description  默认处理中文显示
     * @Author 小帅丶
     * @Date  2019/7/12 14:05
     * @return com.itextpdf.text.Font
     **/
    public static Font getColorFont() {
        Font font = new Font(getFont());

        return font;
    }
    public static Font getHeadFont() {
        Font font = new Font(getFont());
        font.setSize(25);
        return font;
    }
    /**
     * @Description 指定列宽度
     * @Author 小帅丶
     * @Date  2019/7/12 11:59
     * @param widths 一个或多个
     * @return float[]
     **/
    public static float[] getColumnWiths(float...widths){
        float[] columnWidths = new float[widths.length];
        for (int i = 0; i < widths.length; i++) {
            columnWidths[i]=widths[i];
        }
        return columnWidths;
    }
    /**
     * @Description 添加表头cell
     * @Author 小帅丶
     * @Date  2019/7/12 11:36
     * @param titleCell 要操作的cell
     * @param fixedHeight 行高度
     * @param baseColor 背景色
     * @param colspan  合并的列数
     * @param isBottomBorder 是否有下边框 true 有 fasle 没有
     * @return com.itextpdf.text.pdf.PdfPCell
     **/
    public static PdfPCell addTitleCell(PdfPCell titleCell,int fixedHeight,BaseColor baseColor,int colspan,boolean isBottomBorder){
        titleCell.setColspan(colspan);
        titleCell.setFixedHeight(fixedHeight);
        titleCell.setUseVariableBorders(true);
        titleCell.setUseAscender(true);
        titleCell.setUseDescender(true);
        titleCell.setBackgroundColor(baseColor);
        if(isBottomBorder){
            titleCell.setBorder(Rectangle.BOTTOM);
            titleCell.setBorderColorBottom(BaseColor.LIGHT_GRAY);
        }else{
            titleCell.setBorder(Rectangle.NO_BORDER);
        }
        titleCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        return titleCell;
    }

    /**
     * @Description 添加空行
     * @Author 小帅丶
     * @Date  2019/7/12 11:36
     * @param fixedHeight 空行高度
     * @param colspan  合并的列数
     * @return com.itextpdf.text.pdf.PdfPCell
     **/
    public static PdfPCell addBlankLine(int fixedHeight,int colspan){
        PdfPCell blankLine = new PdfPCell();
        blankLine.setFixedHeight(fixedHeight);
        blankLine.setBorder(Rectangle.NO_BORDER);
        blankLine.setColspan(colspan);
        return blankLine;
    }
    /**
     * @Description 添加默认cell
     * @Author 小帅丶
     * @param baseCell 要操作的cell
     * @Date  2019/7/12 11:36
     * @return com.itextpdf.text.pdf.PdfPCell
     **/
    public static PdfPCell addBaseCell(PdfPCell baseCell){
        baseCell.setFixedHeight(23);
        baseCell.setUseVariableBorders(true);
        baseCell.setUseAscender(true);
        baseCell.setUseDescender(true);
        baseCell.setBorder(Rectangle.BOTTOM);
        baseCell.setBorderColorBottom(BaseColor.LIGHT_GRAY);
        baseCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        return baseCell;
    }
    /**
     * @Description 添加cell
     * @Author 小帅丶
     * @param baseCell 要操作的cell
     * @param isBottomBorder 是否有下边框 true 有 fasle 没有
     * @Date  2019/7/12 11:36
     * @return com.itextpdf.text.pdf.PdfPCell
     **/
    public static PdfPCell addBaseCell(PdfPCell baseCell,boolean isBottomBorder){
        baseCell.setFixedHeight(23);
        baseCell.setUseVariableBorders(true);
        baseCell.setUseAscender(true);
        baseCell.setUseDescender(true);
        if(isBottomBorder){
            baseCell.setBorder(Rectangle.BOTTOM);
            baseCell.setBorderColorBottom(BaseColor.LIGHT_GRAY);
        }else{
            baseCell.setBorder(Rectangle.NO_BORDER);
        }
        baseCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        return baseCell;
    }
    /**
     * @Description 添加cell
     * @Author 小帅丶
     * @param baseCell 要操作的cell
     * @param fixedHeight 行高
     * @param color 背景色
     * @param isBottomBorder 是否有下边框 true 有 fasle 没有
     * @Date  2019/7/12 11:36
     * @return com.itextpdf.text.pdf.PdfPCell
     **/
    public static PdfPCell addBaseCell(PdfPCell baseCell,int fixedHeight,BaseColor color,boolean isBottomBorder){
        baseCell.setFixedHeight(fixedHeight);
        baseCell.setUseVariableBorders(true);
        baseCell.setUseAscender(true);
        baseCell.setUseDescender(true);
        if(null!=color){
            baseCell.setBackgroundColor(color);
        }
        if(isBottomBorder){
            baseCell.setBorder(Rectangle.BOTTOM);
            baseCell.setBorderColorBottom(BaseColor.LIGHT_GRAY);
        }else{
            baseCell.setBorder(Rectangle.NO_BORDER);
        }
        baseCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        return baseCell;
    }
    /**
     * @Description 设置中文支持
     * @Author 小帅丶
     * @Date  2019/7/11 10:33
     * @Param []
     * @return com.itextpdf.text.pdf.BaseFont
     **/
    public static BaseFont getFont() {
        BaseFont bf = null;
        try {
//
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            System.out.println("Exception = " + e.getMessage());
        }
        return bf;
    }
    /**
     * 斜角排列、全屏多个重复的花式文字水印
     *
     * @param input             需要加水印的PDF读取输入流
     * @param output            输出生成PDF的输出流
     * @param waterMarkString   水印字符
     * @param xAmout            x轴重复数量
     * @param yAmout            y轴重复数量
     * @param opacity           水印透明度
     * @param rotation          水印文字旋转角度,一般为45度角
     * @param waterMarkFontSize 水印字体大小
     * @param color             水印字体颜色
     */
    public static void stringWaterMark(InputStream input, OutputStream output, String waterMarkString, int xAmout, int yAmout, float opacity, float rotation, int waterMarkFontSize, BaseColor color) {
        try {

            PdfReader reader = new PdfReader(input);
            PdfStamper stamper = new PdfStamper(reader, output);

            // 添加中文字体
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            int total = reader.getNumberOfPages() + 1;

            PdfContentByte over;
            // 给每一页加水印
            for (int i = 1; i < total; i++) {
                Rectangle pageRect = stamper.getReader().getPageSizeWithRotation(i);
                // 计算水印每个单位步长X,Y
                float x = pageRect.getWidth() / xAmout;
                float y = pageRect.getHeight() / yAmout;

                over = stamper.getOverContent(i);
                PdfGState gs = new PdfGState();
                // 设置透明度为
                gs.setFillOpacity(opacity);

                over.setGState(gs);
                over.saveState();

                over.beginText();
                over.setColorFill(color);
                over.setFontAndSize(baseFont, waterMarkFontSize);

                for (int n = 0; n < xAmout + 1; n++) {
                    for (int m = 0; m < yAmout + 1; m++) {
                        over.showTextAligned(Element.ALIGN_CENTER, waterMarkString, x * n, y * m, rotation);
                    }
                }

                over.endText();
            }
            stamper.close();
        } catch (Exception e) {
            new Exception("NetAnd PDF add Text Watermark error"+e.getMessage());
        }
    }

    /**
     * 图片水印,整张页面平铺
     * @param input     需要加水印的PDF读取输入流
     * @param output    输出生成PDF的输出流
     * @param imageFile 水印图片路径
     */
    public static void imageWaterMark(InputStream input, OutputStream output, String imageFile, float opacity) {
        try {

            PdfReader reader = new PdfReader(input);
            PdfStamper stamper = new PdfStamper(reader, output);
            Rectangle pageRect = stamper.getReader().getPageSize(1);
            float w = pageRect.getWidth();
            float h = pageRect.getHeight();

            int total = reader.getNumberOfPages() + 1;

            Image image = Image.getInstance(imageFile);
            image.setAbsolutePosition(0, 0);// 坐标
            image.scaleAbsolute(w, h);

            PdfGState gs = new PdfGState();
            gs.setFillOpacity(opacity);// 设置透明度

            PdfContentByte over;
            // 给每一页加水印
            float x, y;
            Rectangle pagesize;
            for (int i = 1; i < total; i++) {
                pagesize = reader.getPageSizeWithRotation(i);
                x = (pagesize.getLeft() + pagesize.getRight()) / 2;
                y = (pagesize.getTop() + pagesize.getBottom()) / 2;
                over = stamper.getOverContent(i);
                over.setGState(gs);
                over.saveState();//没这个的话,图片透明度不起作用,必须在beginText之前,否则透明度不起作用,会被图片覆盖了内容而看不到文字了。
                over.beginText();
                // 添加水印图片
                over.addImage(image);
            }
            stamper.close();
        } catch (Exception e) {
            new Exception("NetAnd PDF add image Watermark error" + e.getMessage());
        }
    }
    /**
     * @description 顶部表格卡片形式显示格式数据组装
     * @Author 小帅丶
     * @Date  2019/7/16 15:31
     * @param tableMobileHeader 要操作的表格
     * @param cellMobileHeader 要操作的单元格
     * @param clospan 合并列 不需要合并填写0
     * @param fixedHeight 行高
     * @param padding 间距
     * @param border 边框
     * @param borderColor 边框颜色
     * @param backgroundColor 背景色
     * @param vertical 垂直对齐方式
     * @param horizontal  水平对齐方式
     * @return void
     **/
    public static void addTableHeaderData(PdfPTable tableMobileHeader, PdfPCell cellMobileHeader, int clospan, float fixedHeight, int padding, int border, BaseColor borderColor, BaseColor backgroundColor, int vertical, int horizontal) {
        cellMobileHeader.setUseBorderPadding(true);
        cellMobileHeader.setUseAscender(true);
        if(clospan>0){
            cellMobileHeader.setColspan(clospan);
        }
        cellMobileHeader.setUseDescender(true);
        cellMobileHeader.setFixedHeight(fixedHeight);
        cellMobileHeader.setPadding(padding);
        cellMobileHeader.setVerticalAlignment(vertical);
        cellMobileHeader.setHorizontalAlignment(horizontal);
        if(null!=backgroundColor){
            cellMobileHeader.setBackgroundColor(backgroundColor);
        }
        cellMobileHeader.setBorder(border);
        cellMobileHeader.setBorderColor(borderColor);
        tableMobileHeader.addCell(cellMobileHeader);
    }
    /**
     * @description 顶部表格卡片形式显示格式数据组装
     * @Author 小帅丶
     * @Date  2019/7/16 15:31
     * @param tableMobileHeader 要操作的表格
     * @param cellMobileHeader 要操作的单元格
     * @param clospan 合并列 不需要合并填写0
     * @param backgroundColor 背景色
     * @return void
     **/
    public static void addTableHeaderData(PdfPTable tableMobileHeader, PdfPCell cellMobileHeader, int clospan,BaseColor backgroundColor) {
        addTableHeaderData(tableMobileHeader, cellMobileHeader, clospan, 100, 10, 30, BaseColor.WHITE, backgroundColor, 0, 0);
    }
}

3、创建一个简单的PDF

public class CreatePDFMainTest {
    public static void main(String[] args) throws Exception {
        Document document = new Document(PageSize.A4);
        //第二步,创建Writer实例
        PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
        //创建中文字体
        BaseFont bfchinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontChinese = new Font(bfchinese, 12, Font.NORMAL);
        //第三步,打开文档
        document.open();
        //第四步,写入内容
        Paragraph paragraph = new Paragraph("hello world", fontChinese);
        document.add(paragraph);
        //第五步,关闭文档
        document.close();
    }

}

4、我建的表格简单,所以用到API也简单

1、创建一个表格,表格有6列,

并且铺满屏幕

        PdfPTable goodTable = new PdfPTable(6);

        goodTable.setWidthPercentage(100);

2、创建格子

        PdfPCell cell;

        cell = new PdfPCell(new Phrase(“格子内容”, iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell.setColspan(2);
//格子高度35px
        cell.setMinimumHeight(35);
//格子纵跨1个格子
        cell.setRowspan(1);
//格子内容左右居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

3、举例如下

package pdfdemo.pdfdemo.utils;

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 pdfdemo.pdfdemo.demoOne.iTextPDFUtil;

import java.io.FileOutputStream;

/**
 * @program: pdfdemo
 * @ClassName CreatePDFMainTest
 * @description:
 * @author:蒋皓洁
 * @create: 2022-04-02 11:29
 * @Version 1.0
 **/
public class CreatePDFMainTest3 {
    public static void main(String[] args) throws Exception {
        Document document = new Document(PageSize.A4);
        //第二步,创建Writer实例
        PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
        //创建中文字体
        BaseFont bfchinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontChinese = new Font(bfchinese, 12, Font.NORMAL);
        //第三步,打开文档
        document.open();
        //第四步,写入内容
//创建一列的格子
        PdfPTable goodTable = new PdfPTable(6);

        goodTable.setWidthPercentage(100);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase("格子内容", iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell.setColspan(6);
//格子高度35px
        cell.setMinimumHeight(35);
//格子纵跨1个格子
        cell.setRowspan(1);
//格子内容左右居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        goodTable.addCell(cell);


        PdfPCell  cell2 = new PdfPCell(new Phrase("测试左边", iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell2.setColspan(3);
//格子高度35px
        cell2.setMinimumHeight(35);
//格子纵跨1个格子
        cell2.setRowspan(2);
//格子内容左右居中
        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        goodTable.addCell(cell2);
        PdfPCell  cell3= new PdfPCell(new Phrase("测试右上", iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell3.setColspan(3);
//格子高度35px
        cell3.setMinimumHeight(35);
//格子纵跨1个格子
        cell3.setRowspan(1);
//格子内容左右居中
        cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
        goodTable.addCell(cell3);
        PdfPCell cell4 = new PdfPCell(new Phrase("测试右下", iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell4.setColspan(3);
//格子高度35px
        cell4.setMinimumHeight(35);
//格子纵跨1个格子
        cell4.setRowspan(1);
//格子内容左右居中
        cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);
        goodTable.addCell(cell4);



        document.add(goodTable);
        //第五步,关闭文档
        document.close();
    }

}

出来的如下 

5、表格内嵌(一个table中内嵌宁外一个table)

 PdfPTable celltable =new PdfPTable(2);

        

  cell =new PdfPCell(celltable);

  cell.setColspan(2);//横着占用两格

  cell.setBorderWidth(1);//设置表格的边框宽度为1

  cell.setPadding(10);//设置表格与上一个表格的填充为10

  table.addCell(cell);

6、测试demo展示,有些代码可以封装,但是为了方便看且粘贴就没有封装

上面格子的代码展示如下 

package pdfdemo.pdfdemo.utils;

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 pdfdemo.pdfdemo.demoOne.iTextPDFUtil;

import java.io.FileOutputStream;

/**
 * @program: pdfdemo
 * @ClassName CreatePDFMainTest
 * @description:
 * @author:蒋皓洁
 * @create: 2022-04-02 11:29
 * @Version 1.0
 **/
public class CreatePDFMainTest3 {
    public static void main(String[] args) throws Exception {
        Document document = new Document(PageSize.A4);
        //第二步,创建Writer实例
        PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
        //创建中文字体
        BaseFont bfchinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontChinese = new Font(bfchinese, 12, Font.NORMAL);
        //第三步,打开文档
        document.open();
        //第四步,写入内容
//创建一列的格子
        PdfPTable goodTable = new PdfPTable(6);

        goodTable.setWidthPercentage(100);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase("格子内容", iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell.setColspan(6);
//格子高度35px
        cell.setMinimumHeight(35);
//格子纵跨1个格子
        cell.setRowspan(1);
//格子内容左右居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        goodTable.addCell(cell);


        PdfPCell cell2 = new PdfPCell(new Phrase("测试左边", iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell2.setColspan(3);
//格子高度35px
        cell2.setMinimumHeight(35);
//格子纵跨1个格子
        cell2.setRowspan(2);
//格子内容左右居中
        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        goodTable.addCell(cell2);
        PdfPCell cell3 = new PdfPCell(new Phrase("测试右上", iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell3.setColspan(3);
//格子高度35px
        cell3.setMinimumHeight(35);
//格子纵跨1个格子
        cell3.setRowspan(1);
//格子内容左右居中
        cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
        goodTable.addCell(cell3);
        PdfPCell cell4 = new PdfPCell(new Phrase("测试右下", iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell4.setColspan(3);
//格子高度35px
        cell4.setMinimumHeight(35);
//格子纵跨1个格子
        cell4.setRowspan(1);
//格子内容左右居中
        cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);
        goodTable.addCell(cell4);



        PdfPCell cell5 = new PdfPCell(new Phrase("内嵌表格展示", iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell5.setColspan(2);
//格子高度35px
        cell5.setMinimumHeight(35);
//格子纵跨1个格子
        cell5.setRowspan(1);
//格子内容左右居中
        cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);
        goodTable.addCell(cell5);

        PdfPTable goodTable2 = new PdfPTable(3);
        PdfPCell cell6 = new PdfPCell(new Phrase("内嵌表格抬头一", iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell6.setColspan(1);
//格子高度35px
        cell6.setMinimumHeight(35);
//格子纵跨1个格子
        cell6.setRowspan(1);
//格子内容左右居中
        cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);
        goodTable2.addCell(cell6);

        PdfPCell cell7 = new PdfPCell(new Phrase("内嵌表格抬头二", iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell7.setColspan(2);
//格子高度35px
        cell7.setMinimumHeight(35);
//格子纵跨1个格子
        cell7.setRowspan(1);
//格子内容左右居中
        cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell7.setVerticalAlignment(Element.ALIGN_MIDDLE);

        goodTable2.addCell(cell7);

        PdfPCell cell8 = new PdfPCell(new Phrase("内嵌表格抬头三", iTextPDFUtil.getColorFont()));
//格子横跨2个格子
        cell8.setColspan(3);
//格子高度35px
        cell8.setMinimumHeight(35);
//格子纵跨1个格子
        cell8.setRowspan(1);
//格子内容左右居中
        cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
//格子内容上下居中
        cell8.setVerticalAlignment(Element.ALIGN_MIDDLE);

        goodTable2.addCell(cell8);



        PdfPCell cell33 = new PdfPCell(goodTable2);

        cell33.setColspan(4);

        cell33.setBorderWidth(1);//设置表格的边框宽度为1

        cell33.setPadding(7);//设置表格与上一个表格的填充为10

        goodTable.addCell(cell33);
        document.add(goodTable);
        //第五步,关闭文档
        document.close();
    }

}

参考的几个博主内容

https://cloud.tencent.com/developer/article/1469129?from=15425icon-default.png?t=N7T8https://cloud.tencent.com/developer/article/1469129?from=15425

http://www.javashuo.com/article/p-txowdndf-ny.htmlicon-default.png?t=N7T8http://www.javashuo.com/article/p-txowdndf-ny.html

5、关于IPDF其他工具使用,说不定兄弟们还用的到

1、图片转base64编码

/**
 * 图片转换为base64编码字符串
 * @param imgPath
 */
public static String ImageToBase64(File imgPath) throws IOException {
    byte[] data = null;
    // 读取图片字节数组
    InputStream in = new FileInputStream(imgPath);
    data = new byte[in.available()];
    in.read(data);
    in.close();
    // 对字节数组Base64编码
    Base64.Encoder encoder = Base64.getEncoder();
    String i = encoder.encodeToString(data);
    //打印base64编码信息
    System.out.println(i);
    // 返回Base64编码过的字节数组字符串
    return i;
}

2、base64转图片

public static File base64ToFile(String base64, String filePath) {
    File file = new File(filePath);
    byte[] buffer;
    try {
        BASE64Decoder base64Decoder = new BASE64Decoder();
        buffer = base64Decoder.decodeBuffer(base64);
        FileOutputStream out = new FileOutputStream(filePath);
        out.write(buffer);
        out.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return file;
}

 

3、网络地址图片放到表格中(我这里用,scaleAbsolute()绝对的高宽

 

public static PdfPCell addOneLineFileReformImage(String url, int col) throws IOException, BadElementException {
    Image img1 = Image.getInstance(url);
    img1.scaleAbsolute(180, 180);
    PdfPCell cell;
    cell = new PdfPCell(img1);
    cell.setColspan(col);
    cell.setMinimumHeight(35);
    cell.setPaddingBottom(10);
    cell.setPaddingTop(10);
    cell.setRowspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    return cell;
}

4、base64图片放到表格中 (我存储的是小程序签名base64图片)

(1)、我数据存储的base64数据 x为=“”data:image/png;base64,ivBC“”,要将前缀去掉所以使用,x.substring(22)

(2)、图片采用scaleToFit(50, 50),浮动的图片

byte[] imageBytes = Base64.getDecoder().decode(x.substring(22)); // 将base64编码字符串解码为字节数
    img2 = Image.getInstance(imageBytes);
    img2.scaleToFit(50, 50);
    imgTable.addCell(iTextPDFUtil.addOneLineFile(img2, 1));

5、附件分页 和设置table下边距

document.newPage();
TableDetails.setSpacingAfter(10f); // 设置表格下边距

6、关闭文档,实现文档下载

//第五步,关闭文档
document.close();
response.setContentType("application/pdf");
// 设置响应头,指定返回的内容为attachment,表示附件
response.setHeader("Content-Disposition", "attachment; filename=\"test.pdf\"");

// 获取输出流
OutputStream outputStream = response.getOutputStream();
File file = new File(fileName + ".pdf");
FileInputStream fileInputStream = new FileInputStream(file);
// 将PDF文件流写入输出流
byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer)) > 0) {
    outputStream.write(buffer, 0, length);
}

// 关闭流
outputStream.flush();
outputStream.close();
fileInputStream.close();
file.delete();

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值