若依生成报表pdf itext

依赖

   <!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>4.2.2</version>
            <type>pom</type>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.11</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

工具类

   package com.ruoyi.common;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.*;
import java.util.*;

/**
 * @ClassName pdfUtils
 * @description: TODO
 * @author: MaYuanbo
 * @date 2023年06月15日
 * @version: 1.0
 */
public class PdfUtils
{
    /**
     * @param fields
     * @param data
     * @throws IOException
     * @throws DocumentException
     */
    private static void fillData(AcroFields fields, Map<String, String> data) throws IOException, DocumentException {
        List<String> keys = new ArrayList<String>();
        Map<String, AcroFields.Item> formFields = fields.getFields();
        for (String key : data.keySet()) {
            if(formFields.containsKey(key)){
                String value = data.get(key);
                fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
                keys.add(key);
            }
        }
        Iterator<String> itemsKey = formFields.keySet().iterator();
        while(itemsKey.hasNext()){
            String itemKey = itemsKey.next();
            if(!keys.contains(itemKey)){
                fields.setField(itemKey, " ");
            }
        }
    }
    /**
     * @param templatePdfName
     *            模板pdf名称
     * @param generatePdfPath
     *            生成pdf路径
     * @param data
     *            数据
     */
    public static String generatePDF(String templatePdfName, String generatePdfPath, Map<String, String> data) {
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        try {
            byte[] bytes =generatePDF(templatePdfName,data);
            fos = new FileOutputStream(generatePdfPath);
            fos.write(bytes);
            fos.flush();
            return generatePdfPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * @param templatePdfName
     *            模板pdf名称
     * @param data
     *            数据
     */
    public static byte[] generatePDF(String templatePdfName,  Map<String, String> data) {
        ByteArrayOutputStream bos = null;
        try {
            InputStream istemplate = 
            					PdfUtils.class.getClassLoader()
            								  .getResourceAsStream(templatePdfName);
            PdfReader reader = new PdfReader(istemplate);
            bos = new ByteArrayOutputStream();
            /* 将要生成的目标PDF文件名称 */
            PdfStamper ps = new PdfStamper(reader, bos);
            /* 使用中文字体 */
            BaseFont bf = BaseFont.createFont("STSong-Light",
            								 "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);
            /* 取出报表模板中的所有字段 */
            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            fillData(fields, data);
            /* 必须要调用这个,否则文档不会生成的  如果为false那么生成的PDF文件还能编辑,一定要设为true*/
            ps.setFormFlattening(true);
            ps.close();
            return bos.toByteArray();
            // return bos;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

controller

 @GetMapping("/pdf")
    public void createPdf() throws IOException
    {
        CheckCertificate checkCertificate = getCheckCertificate();
        //文本填充
        Map<String ,String> map = new HashMap<>();
        map.put("ctificateNumber",checkCertificate.getCertificateNumber());
        map.put("liqName",checkCertificate.getLiqName());
        map.put("checkName",checkCertificate.getCheckTime());
        map.put("bottleBodyCode",checkCertificate.getBottleBodyCode());
        map.put("liqYear",checkCertificate.getLiqYear());
        map.put("bottoleMouthCode",checkCertificate.getBottleMouthCode());
        map.put("productionDate",checkCertificate.getProductionDate());
        map.put("liqSku",checkCertificate.getLiqSku());
        map.put("liqStore",checkCertificate.getLiqStore());
        map.put("checkProject",checkCertificate.getCheckProject());
        map.put("genuineStandardDetails",checkCertificate.getGenuineStandardDetails());
        map.put("positiveStandard",checkCertificate.getPositiveStandard());
        map.put("backLabelBarcode",checkCertificate.getBackLabelBarCode());
        map.put("organicCodeSimilarity",checkCertificate.getOrganicCodeSimilarity());
        map.put("backLabelDetailsGenuine",checkCertificate.getBackLabelDetailGenuine());
        map.put("backLabelBrandAuthentic",checkCertificate.getBackLabelBrandAuthentic());
        map.put("plasticCapInkjetCodegGenuine",checkCertificate.getPlasticCapInkjetCodegGenuine());
        map.put("rubberCapGearCharacteristics",checkCertificate.getRubberCapGearCharacteristics());
        map.put("remark","");
        map.put("liqReult",checkCertificate.getLiqResult());

        String s = PdfUtils.generatePDF("PDFTemplate.pdf", getPDFpath(), map);
        System.out.println(s);

    private CheckCertificate getCheckCertificate()
    {
        //获取ctificateNumber
        String ctificateNumber = getCtificateNumber();
        CheckCertificate checkCertificate = new CheckCertificate();
        checkCertificate.setCertificateNumber(ctificateNumber);
        checkCertificate.setLiqName("茅台");
        checkCertificate.setCheckTime("2020.02.14");
        checkCertificate.setBottleBodyCode("631d1592090");
        checkCertificate.setLiqYear("2021");
        checkCertificate.setBottleMouthCode("stg-5124");
        checkCertificate.setProductionDate("2021.12.13");
        checkCertificate.setLiqSku("500ml/53vol");
        checkCertificate.setCheckProject("外观视觉检测");
        checkCertificate.setLiqStore("陕西中泰长安北路酒行");
        checkCertificate.setGenuineStandardDetails("相似度99%");
        checkCertificate.setPositiveStandard("正似度99%");
        checkCertificate.setBackLabelBarCode("度99%");
        checkCertificate.setOrganicCodeSimilarity("标似度99%");
        checkCertificate.setBackLabelDetailGenuine("标度99%");
        checkCertificate.setBackLabelBrandAuthentic("胶品相似度99%");
        checkCertificate.setPlasticCapInkjetCodegGenuine("胶相似度99%");
        checkCertificate.setRubberCapGearCharacteristics("相似度99%");
        checkCertificate.setRemark("");
        checkCertificate.setLiqResult("真");
     return checkCertificate;
    }

    /**
     * 生成合格证书的唯一
     * @return
     */
    private String getCtificateNumber()
    {
        UUID uuid = UUID.randomUUID();
        String randomString = uuid.toString().replace("-", "").toUpperCase();
        return "JM" + randomString.substring(0, 5)
                + "-" + randomString.substring(5, 10)
                + "-" + randomString.substring(10, 15);
    }

     /**
     *  生成文件路径
     * @return
     */
    private String getPDFpath()
    {
       return profile + "/"+ IdUtils.fastSimpleUUID()+ ".pdf";
    }

模板文件

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: itext是一个用于生成PDF文档的Java库,提供了丰富的功能和灵活的API,可以满足各种PDF文档的生成需求。itext 5.5.6是其一个版本,下面将简要介绍如何使用itext 5.5.6生成PDF文档。 首先,需要引入itext库的依赖,可以从官方网站下载jar包,并将其添加到你的Java项目中。 在生成PDF之前,你需要创建一个Document对象,这是itext中的一个核心概念。 Document对象代表了一个PDF文档,你可以将内容添加到其中。 接下来,可以通过创建一个PdfWriter对象将Document对象与文件关联起来。 PdfWriter是itext中负责将Document内容写入PDF文件的类。 在Document中添加内容时,可以使用Paragraph、Chunk等元素来设置文本的格式和样式。可以设置字体、颜色、对齐方式等等。 此外,还可以添加图片、表格等其他类型的元素到Document中。可以使用Image类来插入图片,使用PdfPTable类来创建表格。 添加完所有内容后,需要调用Document的close()方法来关闭文档,以确保内容写入完整。 最后,通过以上步骤,你就可以成功使用itext 5.5.6生成PDF文档了。 总结来说,使用itext 5.5.6生成PDF文档的步骤包括:引入itext库的依赖、创建Document对象、创建PdfWriter对象、设置文本格式和样式、添加其他类型的元素、关闭文档。通过这些步骤,你可以方便地生成符合自己需求的PDF文档。 ### 回答2: iText 5.5.6是一个用于生成PDF文件的开源Java库。使用iText 5.5.6可以通过编写Java代码动态地创建PDF文档,包括添加文本、图片、表格、链接等元素,并且可以进行页面布局和样式设置。 在使用iText 5.5.6生成PDF时,首先需要创建一个Document对象,该对象代表最终生成PDF文档。然后可以向Document对象中添加各种内容,例如使用Paragraph类添加段落文字,使用Image类添加图片等等。使用Chunk类可以设置字体、大小、颜色等文本样式。使用Table类可以创建表格,并设置单元格的内容和样式。 在生成PDF时,可以使用iText 5.5.6提供的各种API来实现更高级的功能,例如添加页面编号、页眉页脚、书签等。还可以在生成PDF的过程中进行文本操作,例如修改字体、大小、颜色等。 最后,使用PdfWriter将Document对象写入到文件或输出流中,完成PDF文档的生成。除了生成PDF文档,iText 5.5.6还可以用于操作已有的PDF文件,例如合并多个PDF文件、添加水印、提取文本等。 总之,iText 5.5.6是一个功能强大的Java库,可以方便地生成和操作PDF文档,适用于各种需要生成PDF的场景,例如生成报表、发票、合同等。 ### 回答3: iText 5.5.6是一种用于生成PDF文档的Java库。它提供了许多功能和方法来创建、编辑和处理PDF文件。 首先,你需要创建一个Document对象,它是PDF文档的主要容器。然后,你可以添加各种元素到文档中,例如段落、标题、图像和表格等。你可以使用Paragraph、Chapter和Section等类来划分文档的结构。 在添加文本时,你可以使用Font类来设置字体、颜色和样式。使用Chunk类可以对文本进行更精细的处理,例如添加下划线、删除线和超链接等。 对于图像,你可以使用Image类来插入图像文件PDF中。你可以设置图像的位置、大小和对齐方式等属性。 除了基本的文本和图像,iText还提供了Table类来创建表格。你可以设置表格的行数和列数,并添加单元格和内容到表格中。 一旦完成了文档的内容,你可以使用PdfWriter类将文档写入到PDF文件中。你可以选择将文档保存到文件系统中,或将其输出到浏览器端。 此外,iText还支持对现有的PDF文件进行编辑和修改。你可以提取、合并和拆分PDF页面,添加水印和书签,以及加密和解密PDF文件。 总之,iText 5.5.6是一个功能强大的Java库,用于生成和处理PDF文档。它提供了各种方法和类来创建、编辑和管理PDF文件的内容。无论是从头开始创建PDF文档,还是对现有的PDF进行修改,iText都能够满足你的需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值