java实现pdf模版生成并打印(多页)

一:模版准备

1画模版通过Adobe Acrobat 软件,里面有设置字体和多行,居中等

在这里插入图片描述

2模版名称必须与java中字段名一致

在这里插入图片描述

3设置模版文件居中字体等,可以单击每一个属性也可以按住shift然后鼠标左键多选进行设置

在这里插入图片描述

二代码实现

1引入依赖

      <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

2 引入工具类

package com.cpit.util;

/**
 * 金额转大写工具类
 *
 */

import java.math.BigDecimal;

public class NumberToCN {
    /**
     * 汉语中数字大写
     */
    private static final String[] CN_UPPER_NUMBER = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    /**
     * 汉语中货币单位大写,这样的设计类似于占位符
     */
    private static final String[] CN_UPPER_MONETRAY_UNIT = {"分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾",
            "佰", "仟", "兆", "拾", "佰", "仟"};
    /**
     * 特殊字符:整
     */
    private static final String CN_FULL = "整";
    /**
     * 特殊字符:负
     */
    private static final String CN_NEGATIVE = "负";
    /**
     * 金额的精度,默认值为2
     */
    private static final int MONEY_PRECISION = 2;
    /**
     * 特殊字符:零元整
     */
    private static final String CN_ZEOR_FULL = "零元" + CN_FULL;

    /**
     * 把输入的金额转换为汉语中人民币的大写
     *
     * @param numberOfMoney
     *            输入的金额
     * @return 对应的汉语大写
     */
    public static String number2CNMontrayUnit(BigDecimal numberOfMoney) {
        StringBuffer sb = new StringBuffer();
        // -1, 0, or 1 as the value of this BigDecimal is negative, zero, or
        // positive.
        int signum = numberOfMoney.signum();
        // 零元整的情况
        if (signum == 0) {
            return CN_ZEOR_FULL;
        }
        // 这里会进行金额的四舍五入
        @SuppressWarnings("deprecation")
        long number = numberOfMoney.movePointRight(MONEY_PRECISION).setScale(0, 4).abs().longValue();
        // 得到小数点后两位值
        long scale = number % 100;
        int numUnit = 0;
        int numIndex = 0;
        boolean getZero = false;
        // 判断最后两位数,一共有四中情况:00 = 0, 01 = 1, 10, 11
        if (!(scale > 0)) {
            numIndex = 2;
            number = number / 100;
            getZero = true;
        }
        if ((scale > 0) && (!(scale % 10 > 0))) {
            numIndex = 1;
            number = number / 10;
            getZero = true;
        }
        int zeroSize = 0;
        while (true) {
            if (number <= 0) {
                break;
            }
            // 每次获取到最后一个数
            numUnit = (int) (number % 10);
            if (numUnit > 0) {
                if ((numIndex == 9) && (zeroSize >= 3)) {
                    sb.insert(0, CN_UPPER_MONETRAY_UNIT[6]);
                }
                if ((numIndex == 13) && (zeroSize >= 3)) {
                    sb.insert(0, CN_UPPER_MONETRAY_UNIT[10]);
                }
                sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
                sb.insert(0, CN_UPPER_NUMBER[numUnit]);
                getZero = false;
                zeroSize = 0;
            } else {
                ++zeroSize;
                if (!(getZero)) {
                    sb.insert(0, CN_UPPER_NUMBER[numUnit]);
                }
                if (numIndex == 2) {
                    if (number > 0) {
                        sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
                    }
                } else if (((numIndex - 2) % 4 == 0) && (number % 1000 > 0)) {
                    sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
                }
                getZero = true;
            }
            // 让number每次都去掉最后一个数
            number = number / 10;
            ++numIndex;
        }
        // 如果signum == -1,则说明输入的数字为负数,就在最前面追加特殊字符:负
        if (signum == -1) {
            sb.insert(0, CN_NEGATIVE);
        }
        // 输入的数字小数点后两位为"00"的情况,则要在最后追加特殊字符:整
        if (!(scale > 0)) {
            sb.append(CN_FULL);
        }
        return sb.toString();
    }
}

3核心代码 注意由于Adobe Acrobat设置左对齐同时不能垂直居中,因此需要手动设置

    @PostMapping(value = "/pdfBatchPrint")
    public void pdfBatchPrint(HttpServletResponse response, @RequestBody VchPrepareVerchurHeadCondition condition) {
        ByteArrayOutputStream pdf = null;
        OutputStream os= null;
        try {
            //查询数据头行结构,可忽略
            List<VchPrepareVerchurHead> headList = vchPrepareVerchurHeadService.findVchPrepareVerchurHeadListFromADS(condition);
            if(CollectionUtils.isEmpty(headList)){
                setHttpResponse(response, "批量打印异常!\n" + "无打印数据");
            }
            List<VchPrepareHeadAndDetailVO> list = vchPrepareVerchurHeadService.findVchPrepareVerchurHeadAndDetailList2FromADS(headCondition);
            //头行分组 忽略
            Map<String, List<VchPrepareHeadAndDetailVO>> listMap = list.stream().collect(Collectors.groupingBy(e -> e.getHeadId() + ""));
            Map<String, List<VchPrepareVerchurHead>> headListMap = headList.stream().collect(Collectors.groupingBy(e -> e.getId() + ""));
            //设置pdf格式,文件名称
            response.setHeader("Content-Disposition", "attachment;filename=test_report.pdf");
            response.setContentType("application/pdf");
            //生成pdf 核心
             pdf = createPdf(listMap, headListMap);
            // 将最终合并的 PDF 数据写入 HttpServletResponse 的 OutputStream
             os = response.getOutputStream();
            os.write(pdf.toByteArray());
            os.flush();
        } catch (Exception e) {
            log.error("pdfBatchPrint异常", e);
            setHttpResponse(response, "批量打印异常!\n" + e.getLocalizedMessage());
        }finally {
            IOUtils.closeQuietly(os);
            IOUtils.closeQuietly(pdf);
        }
    }


    public ByteArrayOutputStream createPdf(Map<String, List<VchPrepareHeadAndDetailVO>> listMap, Map<String, List<VchPrepareVerchurHead>> headListMap) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Document document = new Document();
        // 创建一个新的 PdfCopy 对象
        PdfCopy copy = new PdfCopy(document, baos);
        document.open();
        for (Map.Entry<String, List<VchPrepareHeadAndDetailVO>> entry : listMap.entrySet()) {
            List<VchPrepareHeadAndDetailVO> value = entry.getValue();
            //处理总金额
            BigDecimal debitAmount = value.stream().filter(e -> "DR".equals(e.getDirection()))
                    .map(VchPrepareHeadAndDetailVO::getAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            BigDecimal creditAmount = value.stream().filter(e -> "CR".equals(e.getDirection()))
                    .map(VchPrepareHeadAndDetailVO::getAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            //获取头信息
            List<VchPrepareVerchurHead> vchPrepareVerchurHeads = headListMap.get(entry.getKey());
            VchPrepareVerchurHead vchPrepareVerchurHead = vchPrepareVerchurHeads.get(0);
            DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");

            String createdBy = vchPrepareVerchurHead.getCreatedBy().equals("system") ? "系统集成" : vchPrepareVerchurHead.getCreatedBy();
            List<List<VchPrepareHeadAndDetailVO>> partition = Lists.partition(value, 10);
            String pageSize = String.valueOf(partition.size());
            //页码
            int i = 0;
            //核心代码
            for (List<VchPrepareHeadAndDetailVO> palist : partition) {
                //获取模板文件通过oss获取 
                //测试可用本地文件
                //PdfReader templateReader = new  PdfReader("D:\\Documents\\打印模板完整版.pdf");
                S3Object s3Object = ossTemplate.getObject(bucketName, OssPathCst.XK_BACKUPCOL12_EXPORT_TEMP_PATH);
                PdfReader templateReader = new PdfReader(s3Object.getObjectContent());
                // 创建一个临时的 ByteArrayOutputStream,用于暂存单个页面的 PDF 数据
                ByteArrayOutputStream singlePageBaos = new ByteArrayOutputStream();
                PdfStamper stamper = new PdfStamper(templateReader, singlePageBaos);
                AcroFields fields = stamper.getAcroFields();
                // 设置中文字体宋体
                BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                fields.addSubstitutionFont(font);
                //数据填充
                i++;
                String pageNo = String.valueOf(i);
                if (pageSize.equals(pageNo)) {
                    fields.setField("debitAmountStr", decimalFormat.format(debitAmount));
                    fields.setField("creditAmountStr", decimalFormat.format(creditAmount));
                    String valueStr = "合计:" + NumberToCN.number2CNMontrayUnit(debitAmount);
                    String key = "amountStr";
                    addTextToPdfCenter(fields, stamper, valueStr, key, font);

                }
                fields.setField("pageNo", pageNo + "/" + pageSize);
                fields.setField("acctUser", "test");
                fields.setField("createdBy", createdBy);
                Map<String, String> map = new HashMap();
                Map<String, String> stringStringMap = turnMap(vchPrepareVerchurHead);
                Map<String, String> stringStringMap1 = listTurnMap(palist);
                map.putAll(stringStringMap1);
                //设置单元格格式--垂直居中,水平居中等
                for (String key : map.keySet()) {
                    String valueStr = map.get(key);
                    addTextToPdfCenter(fields, stamper, valueStr, key, font);

                }
                fillData(fields, stringStringMap);
                stamper.setFormFlattening(true);
                stamper.close();
                // 创建 PdfImportedPage 对象,并将已填充数据的页面添加到 PdfCopy 对象
                PdfImportedPage filledPage = copy.getImportedPage(new PdfReader(singlePageBaos.toByteArray()), 1); // 1 表示要导入的页码
                copy.addPage(filledPage);
            }
        }
        // 关闭 document 对象
        document.close();
        return baos;
    }

    private void setHttpResponse(HttpServletResponse response, String msg) throws BadRequestException {
        try {
            response.setHeader("Content-type", "text/json;charset=UTF-8");
            response.setHeader("IsAlert", "1");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.println(String.format("{\"code\":\"-1\", \"msg\":\"%s\"}", msg));
            out.flush();
            out.close();
        } catch (IOException e) {
            throw new BadRequestException("msg");
        }
    }

    public static void fillData(AcroFields fields, Map<String, String> data) throws IOException, DocumentException {
        Map<String, AcroFields.Item> formFields = fields.getFields();
        for (String key : data.keySet()) {
            if (formFields.containsKey(key)) {
                String value = data.get(key);
                // 为字段赋值,注意字段名称是区分大小写的
                if (StringUtils.isBlank(value)) {
                    fields.setField(key, "");
                } else {
                    fields.setField(key, value);
                }
            }
        }
    }

    public static Map<String, String> listTurnMap(List listValue) {
        Map<String, String> map = new HashMap<>();
        List<Object> list = (List) listValue;
       //注意这里可以设置自己模版想要的值
        String sb = "lineSummary,accountsNo,accountsNoName,debitAmountStr,creditAmountStr,";
        for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            Map<String, Object> stringObjectMap = BeanUtil.beanToMap(o);
            for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (sb.contains(key) && Objects.nonNull(value)) {
                    map.put(StrUtil.format("{}.{}{}", "xkList", key, i), String.valueOf(value));

                }
            }
        }
        return map;
    }

    public static Map<String, String> turnMap(Object object) {
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(object);
        Map<String, String> map = new HashMap<>();
        //将需要的转为map
        for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
                   //注意这里可以设置自己模版想要的值
            String sb = "compName,microAppName,voucherHeadCode,accountDate,backupCol12";
            if (ObjectUtil.isNotEmpty(value)) {
                //基本类型和封装类型
                if (isPrimitiveOrWrapper(value.getClass()) && sb.contains(key)) {
                    if (key.equals("backupCol12")) {
                        map.put(key, "记-" + String.valueOf(value));
                    } else {
                        map.put(key, String.valueOf(value));
                    }
                } else if ("accountDate".equals(key)) {
                    String accountDate = DateUtil.getLocalDateStr((Date) value, FormatEnum.FORMAT_DATE_CH);
                    map.put(key, accountDate);
                }
            }
        }
        return map;
    }

    private static boolean isPrimitiveOrWrapper(Class<?> clazz) {
        return clazz.isPrimitive() || clazz.getName().startsWith("java.lang");
    }


    private static void addTextToPdfCenter(AcroFields form, PdfStamper stamper, String text, String fieldName, BaseFont baseFont) {
        // 通过模板表单单元格名获取所在页和坐标,左下角为起点
        int pageNo = form.getFieldPositions(fieldName).get(0).page;
        Rectangle signRect = form.getFieldPositions(fieldName).get(0).position;
        // 获取操作的页面
        PdfContentByte contentByte = stamper.getOverContent(pageNo);
        //创建表单
        PdfPTable table = new PdfPTable(1);
        //获取当前模板表单宽度
        float totalWidth = signRect.getRight() - signRect.getLeft() - 1;
        //设置新表单宽度
        table.setTotalWidth(totalWidth);
        // 设置中文格式(7号字体,普通)
        Font font = new Font(baseFont, 7, Font.NORMAL);
        //设置单元格格式
        PdfPCell cell = new PdfPCell(new Phrase(text, font));
        //设置单元格高度
        cell.setFixedHeight(signRect.getTop() - signRect.getBottom() - 1);
        cell.setBorderWidth(0);
        //设置垂直居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

        if (fieldName.contains("lineSummary") || fieldName.contains("debitAmountStr") || fieldName.contains("creditAmountStr")) {
            //设置水平居中
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        }
        //添加到表单中
        table.addCell(cell);
        //写入pdf
        table.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), contentByte);
    }

三最终效果:

在这里插入图片描述

Java中操作PDF模板填充数据通常是通过使用一些专门的库来完成的,比如iText或Apache PDFBox。这些库提供了丰富的API,可以帮助开发者在PDF文档中进行内容的添加、修改和提取等操作。下面我将简要介绍如何使用iText库来操作PDF模板填充数据。 1. 首先,需要将iText库的依赖添加到项目中。如果使用Maven进行项目管理,可以在pom.xml中添加以下依赖: ```xml <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext7-core</artifactId> <version>7.1.9</version> <!-- 请使用最新的稳定版本 --> </dependency> ``` 2. 使用iText库填充PDF模板的一般步骤如下: - 创建或读取PDF模板文件。 - 创建一个PdfDocument实例来操作PDF。 - 使用PdfReader读取模板文件。 - 创建一个PdfWriter实例,它将用于写入修改后的PDF内容。 - 使用PdfDocument来创建PdfFormXObject或其他相关对象,这些对象代表了PDF中的可填写区域。 - 使用PdfCanvas或者直接操作PdfFormXObject来填充数据。 - 将填充后的PDF内容写入到一个新的PDF文件中。 以下是一个简单的示例代码,展示了如何使用iText 7库来填充PDF模板中的表单字段: ```java import com.itextpdf.forms.PdfAcroForm; import com.itextpdf.forms.fields.PdfFormField; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfReader; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Paragraph; import java.io.File; import java.io.IOException; public class PdfFillExample { public static void main(String[] args) { String src = "template.pdf"; // PDF模板文件路径 String dest = "filled.pdf"; // 输出文件路径 try { PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest)); Document document = new Document(pdfDoc); PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true); // 假设模板中有一个名为"name"的字段需要填充 PdfFormField nameField = form.getField("name"); nameField.setValue("张三"); // 设置字段值 // 如果字段可以填写,需要调用下面的代码 nameField.setReadOnly(); // 设置字段为只读 nameField.setRequired(); // 设置字段为必填 nameField.setLocked(); // 锁定字段,防止被修改 // 可以使用相同的方式填充其他字段 form.flattenFields(); // 将表单域“平铺”到PDF页面上,使其不可编辑 document.close(); } catch (IOException e) { e.printStackTrace(); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值