在Java代码中使用iTextPDF生成PDF

摘要:
1.生成PDF以加载字体统计数据{FontFactory.register(“/fonts/msyh.ttf”);FontFactory.register(“/fonts/msyhbd.ttf”生成PDFRectangler

1. 生成PDF

载入字体

    static {
        FontFactory.register("/fonts/msyh.ttf");
        FontFactory.register("/fonts/msyhbd.ttf");
        FontFactory.register("/fonts/simsun.ttc");
        FontFactory.register("/fonts/simhei.ttf");
    }

生成PDF

    Rectangle rectPageSize = new Rectangle(PageSize.A4);// A4纸张
        Document document = new Document(rectPageSize, 40, 40, 40, 40);// 上、下、左、右间距
        try {
            String filePath = StaticConfig.getConfig("file_path") + invest.getContractPath();
            String folderPath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
            File folder = new File(folderPath);
            if (!folder.exists()) {
                folder.mkdirs();
            }

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
            writer.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
            document.addCreationDate();
            document.addCreator("rockbb");
            document.addTitle("rockbbPDF");
            document.addKeywords("export");
            document.addSubject("rockbb业务文件");
            document.open();
            Font yahei9px = FontFactory.getFont("微软雅黑", BaseFont.IDENTITY_H, 9);
            Font yahei10px = FontFactory.getFont("微软雅黑", BaseFont.IDENTITY_H, 10);
            Font yahei11px = FontFactory.getFont("微软雅黑", BaseFont.IDENTITY_H, 11);
            Font yahei12px = FontFactory.getFont("微软雅黑", BaseFont.IDENTITY_H, 12);

            document.add(paragraph("编号:[" + invest.getContractSn() + "]", yahei9px, Paragraph.ALIGN_RIGHT));

            //表格
            PdfPTable table = new PdfPTable(3);
            table.setSpacingBefore(10.0f);
            table.setWidthPercentage(100);
            table.setWidths(new float[]{0.25f, 0.25f, 0.5f});

            PdfPCell cell = cell("当事方", yahei11px, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE);
            cell.setColspan(3);
            table.addCell(cell);

            cell = cell("甲方(投资者)", yahei10px);
            cell.setRowspan(3);
            table.addCell(cell);
            table.addCell(cell("姓名", yahei10px));
            table.addCell(cell(user.getRealName(), yahei10px));
            table.addCell(cell("用户ID", yahei10px));
            table.addCell(cell(user.getTel(), yahei10px));
            table.addCell(cell("身份证", yahei10px));
            table.addCell(cell(user.getIdNumber(), yahei10px));

            cell = cell("乙方", yahei10px);
            cell.setRowspan(3);
            table.addCell(cell);
            table.addCell(cell("名称", yahei10px));
            table.addCell(cell("公司", yahei10px));
            table.addCell(cell("住所", yahei10px));
            table.addCell(cell("北京市朝阳区", yahei10px));
            table.addCell(cell("注册证", yahei10px));
            table.addCell(cell("", yahei10px));
            document.add(table);

            document.add(paragraph("* 凡本协议未列示的产品信息以平台产品说明书页面显示的产品具体信息为准。", yahei9px));

            document.add(paragraph("第二部分  协议条款", yahei12px, Paragraph.ALIGN_LEFT, 10.0f));

            document.add(paragraph(agreement, yahei10px, Paragraph.ALIGN_LEFT, 5.0f));

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

        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException");
            logger.debug(e.getMessage(), e);
        } catch (IOException e) {
            logger.error("IOException");
            logger.debug(e.getMessage(), e);
        } catch (DocumentException e) {
            logger.error("DocumentException");
            logger.debug(e.getMessage(), e);
        }

工具方法

    private static PdfPCell cell(String content, Font font) {
        PdfPCell cell = new PdfPCell(new Phrase(content, font));
        cell.setBorderColor(new BaseColor(196, 196, 196));
        cell.setPadding(5.0f);
        cell.setPaddingTop(1.0f);
        return cell;
    }

    private static PdfPCell cell(String content, Font font, int hAlign, int vAlign) {
        PdfPCell cell = new PdfPCell(new Phrase(content, font));
        cell.setBorderColor(new BaseColor(196, 196, 196));
        cell.setVerticalAlignment(vAlign);
        cell.setHorizontalAlignment(hAlign);
        cell.setPadding(5.0f);
        cell.setPaddingTop(1.0f);
        return cell;
    }

    private static Paragraph paragraph(String content, Font font) {
        return new Paragraph(content, font);
    }

    private static Paragraph paragraph(String content, Font font, int hAlign) {
        Paragraph paragraph = new Paragraph(content, font);
        paragraph.setAlignment(hAlign);
        return paragraph;
    }

    private static Paragraph paragraph(String content, Font font, int hAlign, float spacingBefore) {
        Paragraph paragraph = new Paragraph(content, font);
        paragraph.setAlignment(hAlign);
        paragraph.setSpacingBefore(spacingBefore);
        return paragraph;
    }

在生成过程中加盖图片, 注意, 因为无法指定页码, 所以这段代码要放到你需要加盖图片的那页对应的代码上

            byte[] bytes = FileUtil.readResourceImage("/text/stamp.png");
            if (bytes != null) {
                Image image = Image.getInstance(bytes);
                PdfContentByte canvas = writer.getDirectContent();
                writer.getPageNumber();
                // float width = image.getScaledWidth();
                // float height = image.getScaledHeight();
                canvas.addImage(image, 150, 0, 0, 150, rectPageSize.getWidth() - 300, rectPageSize.getHeight() - 300);
            } else {
                logger.error("Failed to read /text/stamp.png");
            }

读取项目资源文件的工具方法

    /**
     * 读取项目图片资源文件
     *
     * @param filePath 以'/'开头的项目资源文件路径
     * @return
     */
    public static byte[] readResourceImage(String filePath) {
        try {
            InputStream is = FileUtil.class.getResourceAsStream(filePath);
            BufferedImage image = ImageIO.read(is);
            is.close();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(image, "png", os);
            return os.toByteArray();
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException: " + filePath);
        } catch (IOException e) {
            logger.error("IOException");
        }
        return null;
    }

    /**
     * 读取项目资源文件内容
     *
     * @param filePath 以'/'开头的项目资源文件路径
     * @return 文件内容
     */
    public static String readResourceContent(String filePath) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(FileUtil.class.getResourceAsStream(filePath)));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("
");
            }
            reader.close();
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException: " + filePath);
        } catch (IOException e) {
            logger.error("IOException");
        }
        return sb.toString();
    }

免责声明:文章转载自《在Java代码中使用iTextPDF生成PDF》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇设计模式学习(22)- 状态模式解决sublime安装插件被墙失败的方法下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

C#-Ftp操作

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System; using System.Collections.Generic; using System.L...

java08 数组与集合

1 数组的定义与规范 一个变量只能存放一个数据,一个数组是一个容器,可以存放多个数据 数组的特点 1 数组是一种引用数据类型 2 数组中的多个数据,类型必须统一 3 数组的长度在程序运行期间,不可改变 数组的初始化 1 动态初始化  指定长度:  数据类型[] 数组名称 = new数据类型 [ 数组长度] 左侧的数据类型  表示数组中保存的数据类型 左侧...

java 如何在pdf中生成表格

1、目标   在pdf中生成一个可变表头的表格,并向其中填充数据。通过泛型动态的生成表头,通过反射动态获取实体类(我这里是User)的get方法动态获得数据,从而达到动态生成表格。   每天生成一个文件夹存储生成的pdf文件(文件夹的命名是年月日时间戳),如:20151110   生成的文件可能在毫秒级别,故文件的命名规则是"到毫秒的时间戳-uuid",如...

Java ---Listener监听器

在我们的web容器中,一直不断的触发着各种事件,例如:web应用启动和关闭,request请求到达和结束等。但是这些事件通常对于开发者来说是透明的,我们可以根据这些接口开发符合我们自身需求的功能。在web中常见的的几个监听事件如下: ServletContextListener:用于监听web应用的启动和关闭 ServletContextAttribut...

android源码framework下添加新资源的方法

编译带有资源的jar包,需要更改frameworks层,方法如下:   一.增加png类型的图片资源   1.将appupdate模块所有用到的png格式图片拷贝到framework/base/core/res/res/drawable-mdpi里。但是要确保没有与原生的没有重名文件。   2.在framework/base/core/res/res/...

AccountManager使用教程

API解读 这个类给用户提供了集中注冊账号的接口。用户仅仅要输入一次账户password后,就能够訪问internet资源。 不同的在线服务用不同的方式管理用户,所以account manager 为不同类型的账户提供了统一验证管理的方法,处理有效的账户的具体信息而且实现排序。比方Google,Facebook,Microsoft Exchange 各自...