java利用itext实现pdf展示

之前用到了在网页上展示pdf页面 先记录下来
首先需要引入三个jar包
可以去官网下载
这里直接打包好了:https://download.csdn.net/download/xiaobai_jq/12720550

我们需要先建一个PDF工具类

import com.alibaba.fastjson.JSONArray;
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.ByteArrayOutputStream;
import java.io.IOException;

public class PdfUtil {
    public byte[] generatePDF(){
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); //构建字节输出流
        Document doc = null;
        try {
            doc = new Document(new Rectangle(PageSize.A4)); //可配其余4个参数,如(rectPageSize,60,60,60,60)页面边距
            PdfWriter.getInstance(doc,baos);
            doc.open();
            if (doc!=null){
                doc.close();
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }finally {
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        byte[] b = baos.toByteArray();//pdf字节数组
        return b;
    }

    /**
     * 返回字体
     * @return
     */
    public static Font getFont(){
        try {
            BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            Font font = new Font(bfChinese,10,Font.NORMAL);
            return font;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回粗体
     * @return
     */
    public static Font getBFont(){
        try {
            BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            Font bfont = new Font(bfChinese,12,Font.BOLD);
            return bfont;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 普通表格生成
     * @param font 单元格字体
     * @param size 表格列数量
     * @param clos data
     * @param style 表格样式
     * @param widths 指定列宽
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static PdfPTable createTable(Font font, int size, JSONArray clos, PdfPCell style,float[] widths) throws DocumentException,IOException{
        PdfPTable table = new PdfPTable(size);
        if (widths==null){
            widths = new float[size];
            for (int i=0;i<clos.size();i++){
                PdfPCell cell = createCell(clos.getString(i),font,style);
                table.addCell(cell);
            }
            table.completeRow();
            table.setWidths(widths);

        }
        return table;
    }
    /**
     * 复杂表格生成
     * @param font  字体
     * @param size  列数量
     * @param clos  单元格
     * @param style 单元格样式
     * @param index 需要跨行或跨列的表格
     * @param colspan   跨列
     * @param rowspan   跨行
     * @param widths    指定列宽
     * @return
     * @throws  DocumentException
     * @throws IOException
     *
     */
    public static PdfPTable createDiffTable(Font font,int size,JSONArray clos,PdfPCell style,int[] cell_index,int[] cell_colspan,int[] cell_rowspan,float[] widths) throws DocumentException,IOException{
        PdfPTable table = new PdfPTable(size);
        if (widths==null){
            widths = new float[size];
            for (int i=0;i<size;i++){
                widths[i] = new Integer(100/size);
            }
        }
        for (int i=0;i<clos.size();i++){
            if (clos.get(i) instanceof PdfPTable){
                table.addCell((PdfPTable) clos.get(i));
            }else {
                PdfPCell cell = createCell(clos.getString(i),font,style);
                for (int j=0;j<cell_index.length;j++){
                    if (i==cell_index[j]){
                        cell.setRowspan(cell_rowspan[j]);
                        cell.setColspan(cell_colspan[j]);
                        continue;
                    }
                }
                table.addCell(cell);
            }
        }
        table.completeRow();
        table.setWidths(widths);
        return table;
    }
    /**
     * 创建单元格
     * @param lable
     * @param font
     * @param style
     * @return
     */
    public static PdfPCell createCell(String lable,Font font,PdfPCell style){
        PdfPCell cell = new PdfPCell(new Paragraph(lable,font));
        cell.setPadding(2);
        cell.setHorizontalAlignment(0);
        cell.setUseAscender(true);
        cell.setHorizontalAlignment(style.getHorizontalAlignment());//水平居中
        cell.setHorizontalAlignment(style.getVerticalAlignment());//垂直居中
        cell.setPaddingTop(style.getPaddingTop());
        cell.setPaddingBottom(style.getPaddingBottom());
        cell.setPaddingLeft(style.getPaddingLeft());
        cell.setPaddingRight(style.getPaddingRight());

        //内嵌表格需要,不需要显示边框时,可设置setBorder(0)
        if (style.getBorder()==0){
            cell.setBorder(style.getBorder());
        }
        if (!"".equals(style.getMinimumHeight())&&style.getMinimumHeight()>0){
            cell.setMinimumHeight(style.getMinimumHeight());
        }else {
            cell.setMinimumHeight(18);//设置最小高度
        }
        return cell;
    }
}

页面上的实现代码

import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.ByteArrayOutputStream;

public class PdfTest {
    public byte[] createPDF(JSONObject dyxx) throws Exception, DocumentException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Document dd = null;
        try {
            dd = new Document(new Rectangle(PageSize.A4));
            PdfWriter.getInstance(dd, baos);//将PDF文档对象写入到流
            dd.addTitle("打印测试");
            dd.setMargins(30, 30, 36, 5);
            try {
                Paragraph paragraph = new Paragraph("如果你看到了这行字,恭喜你测试成功了!", PdfUtil.getFont());
                paragraph.setAlignment(1);//居中对齐 0左 2右
                dd.add(paragraph);
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
            dd.close();
            if (dd != null) {
                dd.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (baos!=null){
                baos.close();
            }
        }
        byte[] b = baos.toByteArray();//pdf字节数组
        return b;
    }
}

主要部分实现代码就完成了
还有一种是将pdf文件下载到本地,只需要创建File 指定目录就可以了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值