Java使用itextpdf7生成pdf文档

使用itextpdf7生成pdf文档,首先需要导入itextpdf7相关依赖:

bash 复制代码
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>kernel</artifactId>
    <version>7.1.16</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>io</artifactId>
    <version>7.1.16</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>layout</artifactId>
    <version>7.1.16</version>
</dependency>

由于我们要在pdf文档中写入中文内容,因此,务必引入字体文件。本文都以宋体(simsun.ttf)为例,字体文件可在系统目录 C:\Windows\Fonts 中找到,或自行百度在免费字体网下载。

亲测:如果文档中写入纯英文内容,可以不引入字体文件,如果需要写入中文内容,务必引入字体文件。

在项目的根目录创建fonts目录,并将字体文件拷贝至该目录中。目录可根据自己的需要定义。

编写方法, 返回字体文件所在位置

bash 复制代码
/**
 * 返回字体文件所在位置
 * 
 * @return
 */
private String getFontPath() {
    // 获取当前工作目录
    String projectRoot = System.getProperty("user.dir");
    String fontPath = projectRoot + "/fonts/simsun.ttf";
    return fontPath;
}

案例一:生成带有段落的PDF文件

bash 复制代码
/**
 * 生成带有段落的pdf文件
 */
public void generatePDFWithPara() {
    Document document = null;

    String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";
    String filePath = "D:/" + fileName;

    try {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        PdfWriter writer = new PdfWriter(filePath);
        PdfDocument pdfDoc = new PdfDocument(writer);
        // 设置纸张大小
        pdfDoc.setDefaultPageSize(PageSize.A4);

        document = new Document(pdfDoc);

        // 加载中文字体(确保字体文件存在)
        String fontPath = getFontPath();
        PdfFont font = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, true);

        Paragraph paragraph = new Paragraph("这是一首简单的小情歌");
        paragraph.setFontSize(16f); // 字体大小
        paragraph.setFont(font);  // 字体类型
        document.add(paragraph);
        System.out.println("内容已写入文件:" + filePath);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("生成PDF失败");
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

案例二:生成带有表格的PDF文件

bash 复制代码
/**
 * 生成带有表格的pdf文件
 */
public void generatePDFWithTable() {
    Document document = null;

    String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";
    String filePath = "D:/" + fileName;

    try {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        PdfWriter writer = new PdfWriter(filePath);
        PdfDocument pdfDoc = new PdfDocument(writer);
        // 设置纸张大小
        pdfDoc.setDefaultPageSize(PageSize.A4);

        document = new Document(pdfDoc);

        // 加载中文字体(确保字体文件存在)
        String fontPath = getFontPath();
        PdfFont font = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, true);

        String[] ids = {"1001", "1002", "1003"};
        String[] names = {"张三", "李四", "王五"};
        String[] ages = {"18", "19", "20"};

        // 创建表格,3列
        Table table = new Table(UnitValue.createPercentArray(new float[]{2, 2, 2})).useAllAvailableWidth();
        table.setBorder(new SolidBorder(ColorConstants.BLACK, 2)); // 设置边框

        // 第一列 学号
        Cell cell1 = new Cell();
        cell1.setFont(font);
        for (String text : ids) {
            cell1.add(new Paragraph(text));
        }
        table.addCell(cell1);

        // 第二列 姓名
        Cell cell2 = new Cell();
        cell2.setFont(font);
        for (String text : names) {
            cell2.add(new Paragraph(text));
        }
        table.addCell(cell2);

        // 第三列 年龄
        Cell cell3 = new Cell();
        cell3.setFont(font);
        for (String text : ages) {
            cell3.add(new Paragraph(text));
        }
        table.addCell(cell3);

        document.add(table);
        System.out.println("内容已写入文件:" + filePath);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("生成PDF失败");
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

案例三:生成带有图片的PDF文件

bash 复制代码
/**
 * 生成带有图片的pdf文件
 */
public void generatePDFWithImage() {
    Document document = null;

    String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";
    String filePath = "D:/" + fileName;

    try {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        PdfWriter writer = new PdfWriter(filePath);
        PdfDocument pdfDoc = new PdfDocument(writer);
        // 设置纸张大小
        pdfDoc.setDefaultPageSize(PageSize.A4);

        document = new Document(pdfDoc);

        // 图片路径,确保真实存在
        String imagePath = "D:/flower.png";
        ImageData imageData = ImageDataFactory.create(imagePath);
        document.add(new Image(imageData));

        System.out.println("内容已写入文件:" + filePath);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("生成PDF失败");
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

案例四:生成带有二维码的PDF文件

该功能,需要引入第三方依赖,生成二维码,以Google官方提供的zxing为例。

bash 复制代码
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.3</version>
</dependency>

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.3</version>
</dependency>

在工具类QrCodeUtils中,编写生成二维码的方法:

bash 复制代码
/**
 * 生成二维码
 *
 * @param content
 * @return
 * @throws WriterException
 * @throws IOException
 */
public static Image generateQRCode(String content) throws WriterException, IOException {
    int width = 200;
    int height = 200;
    String format = "png";
    Map<EncodeHintType, Object> hints = new HashMap<>();
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

    BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    MatrixToImageWriter.writeToStream(bitMatrix, format, baos);

    // Convert QR code to iText image and add it to the PDF
    Image img = new Image(ImageDataFactory.create(baos.toByteArray()));
    img.setMarginTop(0F);
    img.setMarginRight(0F);
    return img;
}

生成带有二维码的PDF文件:

bash 复制代码
/**
 * 生成带有二维码的pdf文件
 */
public void generatePDFWithQrcode() {
    Document document = null;

    String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";
    String filePath = "D:/" + fileName;

    try {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        PdfWriter writer = new PdfWriter(filePath);
        PdfDocument pdfDoc = new PdfDocument(writer);
        // 设置纸张大小
        pdfDoc.setDefaultPageSize(PageSize.A4);

        document = new Document(pdfDoc);

        // 二维码的内容,或url路径
        String urlContent = "https://blog.csdn.net/qq_35148205?spm=1000.2115.3001.10640";
        // 生成二维码
        Image image = QrCodeUtils.generateQRCode(urlContent);
        document.add(image);

        System.out.println("内容已写入文件:" + filePath);
    } catch (IOException | WriterException e) {
        e.printStackTrace();
        throw new RuntimeException("生成PDF失败");
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

使用Java生成PDF文件的功能,在某些业务场景中经常会被使用。例如,MES系统的生产订单功能中,通常需要将带有标题、文本、表格、二维码的生产指示单,生成PDF文件,保存在服务器或OSS的某个路径下,前端通过访问该路径,预览并打印该PDF文件。开发人员可根据实际的业务需求,从数据库中查询对应的数据,根据指定的格式和排版,插入到需要生成的PDF文档中。

相关推荐
SimonKing5 小时前
Typora 收费,开源产品Textus或可替代,还支持AI
java·后端·程序员
泡海椒5 小时前
Java 生成资金流向图 PDF:jquick-pdf 树图(JTreeChartData)节点尺寸与间距的追问记录
java·python·pdf
Rain的Java大神之路5 小时前
别再死背八股了:读完 Spring 7.0.8 源码,我学会了"改"框架
java·后端·面试
开开心心就好6 小时前
电脑禁止自动休眠工具,还能按负载定时
算法·智能手机·pdf·电脑·word·音视频·lua
云草桑7 小时前
C#入坑JAVA 潜规则 API Get 多参数 Spring Boot与Spring Cloud 区别 入门系列4
java·开发语言
头发还在的女程序员15 小时前
Java充电桩平台源码解析:枪口状态、上报时间与页面刷新怎样协同
java·开发语言·充电桩系统·充电桩管理·充电系统·充电小程序
Cosolar18 小时前
从 Java 21 升到 25、Spring Boot 3 升 4:一次可复现的迁移踩坑实录
java·后端·面试
IT空门:门主20 小时前
LangChain4j 1.24.0 深度解读:新特性、版本对比与学习路线
java·学习
用户37215742613521 小时前
Java 批量操作 Excel 超链接:添加、读取、修改和删除
java
用户3721574261351 天前
Java 将 Excel 图表导出为图片:指定图表、批量导出与图表工作表
java