java实现word转pdf or直接生成pdf文件

 更新时间:2025年04月23日 10:17:55   作者:C__jx  
这篇文章主要介绍了java实现word转pdf or直接生成pdf文件方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

1、需要引入的maven坐标

<!-- https://mvnrepository.com/artifact/com.itextpdf/kernel -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>kernel</artifactId>
            <version>7.2.4</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.itextpdf/layout -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>layout</artifactId>
            <version>7.2.4</version>
        </dependency>

2、读取word转换为pdf

/**
     * 文件
     */
    public void createFile() {
        XWPFDocument xwpfDocument = null;
        try {
            xwpfDocument = new XWPFDocument(new FileInputStream("/Users/chenjx/Downloads/zipceshi/createYuWord.docx"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ;
        List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
        List<XWPFTable> tables = xwpfDocument.getTables();
        //   创建 一个 PdfWriter,用于定义 pdf 的路径地址
        String filename = String.format("/Users/chenjx/Downloads/zipceshi/pdf/%s.pdf", UUID.randomUUID() + "===1111");
        try {
            PdfWriter pdfWriter = new PdfWriter(filename);
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            PdfFont font = PdfFontFactory.createFont(FONTS);
            Document document = new Document(pdfDocument).setFont(font);
            //通过读取word进行转换
            //读取文本内容
            for (XWPFParagraph paragraph : paragraphs) {
                String text = paragraph.getText();
                document.add(new Paragraph(text));
            }
            //读取表格内容
            for (XWPFTable table : tables) {
                final Table[] table1 = {null};
                List<XWPFTableRow> rows = table.getRows();
                rows.forEach(row -> {
                    int i = rows.indexOf(row);
                    List<XWPFTableCell> tableCells = row.getTableCells();
                    if (i == 0) {
                        table1[0] = new Table(tableCells.size());
                    }
                    tableCells.stream().map(XWPFTableCell::getParagraphs).forEach(x -> x.stream().map(XWPFParagraph::getRuns).forEach(runs -> {
                        if (i == 0) {
                            table1[0].setWidth(500);
                            table1[0].addHeaderCell(runs.stream().map(XWPFRun::text).collect(Collectors.joining()));
                        } else {
                            table1[0].addCell(runs.stream().map(XWPFRun::text).collect(Collectors.joining()));
                        }
                    }));
                });
                document.add(table1[0]);
            }
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

生成效果:

  • word模版:

  • 生成的pdf:

3、自己设置格式生成 共有三种格式、直接上util类

package com.zjjw.jxtest.util.util;


import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFStyle;
import org.apache.poi.xwpf.usermodel.XWPFStyles;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;


/**
 * @author: chenjiaxiang
 * @create: 2022/11/21 17:00
 **/
public class FilePreviewUtil {

    private static final String FONTS1 = "/Users/chenjx/Library/Fonts/SIMFANG.TTF";
    private static final String FONTS = "/Users/chenjx/Library/Fonts/SIMSUN.TTC,1";


    public static void main(String[] args) {
        new FilePreviewUtil().createFile();
        new FilePreviewUtil().createWordTableFile();
        new FilePreviewUtil().createPictureFile();
    }


    /**
     * 文本
     */
    public void createFile() {

        //   创建 一个 PdfWriter,用于定义 pdf 的路径地址
        String filename = String.format("/Users/chenjx/Downloads/zipceshi/pdf/%s.pdf", UUID.randomUUID() + "===1111");
        try {
            PdfWriter pdfWriter = new PdfWriter(filename);
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            PdfFont font = PdfFontFactory.createFont(FONTS);
            Document document = new Document(pdfDocument).setFont(font);
            //纯英文
            document.add(new Paragraph(("Hello China")));
            document.add(new Paragraph(("Hello China 中文")));

            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * word表格
     */
    public void createWordTableFile() {
        try {
            String filename = String.format("/Users/chenjx/Downloads/zipceshi/pdf/%s.pdf", UUID.randomUUID() + "===222");
            PdfWriter pdfWriter = new PdfWriter(filename);
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);

            //这里不要搞错,找到你电脑上的这个文件,复制这个文件的绝对路径
            PdfFont font = PdfFontFactory.createFont(FONTS);
            Document document = new Document(pdfDocument).setFont(font);
            Table table = new Table(4);
            table.setWidth(500);
            table.addHeaderCell("header 1").addHeaderCell("header 2").addHeaderCell("header 3").addHeaderCell("header 4");
            for (int i = 0; i < 16; i++) {
                table.addCell("cell " + i);
            }
            document.add(table);

            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 图片
     */
    public void createPictureFile() {
        try {
            String filename = String.format("/Users/chenjx/Downloads/zipceshi/pdf/%s.pdf", UUID.randomUUID() + "===3333");

            PdfWriter pdfWriter = new PdfWriter(filename);
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            PdfFont font = PdfFontFactory.createFont(FONTS);
            Document document = new Document(pdfDocument).setFont(font);
            ImageData imageData = ImageDataFactory.create("/Users/chenjx/Downloads/图片/1616377073865测试.jpg");
            Image img = new Image(imageData);
            document.add(img.setAutoScale(true));

            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}

4、方法调用

生成纯文本pdf

/**
     * 文本
     */
    public void createFile() {

        //   创建 一个 PdfWriter,用于定义 pdf 的路径地址
        String filename = String.format("/Users/chenjx/Downloads/zipceshi/pdf/%s.pdf", UUID.randomUUID() + "===1111");
        try {
            PdfWriter pdfWriter = new PdfWriter(filename);
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            PdfFont font = PdfFontFactory.createFont(FONTS);
            Document document = new Document(pdfDocument).setFont(font);
            //纯英文
            document.add(new Paragraph(("Hello China")));
            document.add(new Paragraph(("Hello China 中文")));

            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • createFile()方法生成:

生成纯表格pdf

private static final String FONTS = "/Users/chenjx/Library/Fonts/SIMSUN.TTC,1";

/**
     * word表格
     */
    public void createWordTableFile() {
        try {
            String filename = String.format("/Users/chenjx/Downloads/zipceshi/pdf/%s.pdf", UUID.randomUUID() + "===222");
            PdfWriter pdfWriter = new PdfWriter(filename);
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);

            //这里不要搞错,找到你电脑上的这个文件,复制这个文件的绝对路径
            PdfFont font = PdfFontFactory.createFont(FONTS);
            Document document = new Document(pdfDocument).setFont(font);
            Table table = new Table(4);
            table.setWidth(500);
            table.addHeaderCell("header 1").addHeaderCell("header 2").addHeaderCell("header 3").addHeaderCell("header 4");
            for (int i = 0; i < 16; i++) {
                table.addCell("cell " + i);
            }
            document.add(table);

            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • createWordTableFile()方法生成

生成图片pdf

 /**
     * 图片
     */
    public void createPictureFile() {
        try {
            String filename = String.format("/Users/chenjx/Downloads/zipceshi/pdf/%s.pdf", UUID.randomUUID() + "===3333");

            PdfWriter pdfWriter = new PdfWriter(filename);
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            PdfFont font = PdfFontFactory.createFont(FONTS);
            Document document = new Document(pdfDocument).setFont(font);
            ImageData imageData = ImageDataFactory.create("/Users/chenjx/Downloads/图片/1616377073865测试.jpg");
            Image img = new Image(imageData);
            document.add(img.setAutoScale(true));

            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
  • createPictureFile()

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Mybatis实现分表插件

    Mybatis实现分表插件

    随着系统的发展,数据量也会越来越大,分库分表可以有效的缓解数据库的压力,本文主要介绍了Mybatis实现分表插件,感兴趣的可以了解一下
    2021-05-05
  • Java Spring详解如何配置数据源注解开发以及整合Junit

    Java Spring详解如何配置数据源注解开发以及整合Junit

    Spring 是目前主流的 Java Web 开发框架,是 Java 世界最为成功的框架。该框架是一个轻量级的开源框架,具有很高的凝聚力和吸引力,本篇文章带你了解如何配置数据源、注解开发以及整合Junit
    2021-10-10
  • Java集合框架之Map详解

    Java集合框架之Map详解

    这篇文章主要为大家详细介绍了Java集合框架之Map,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-03-03
  • JDBC使用小结

    JDBC使用小结

    JDBC是一个Java应用程序接口,作用是封装了对数据库的各种操作。JDBC由类和接口组成,使用Java开发数据库应用都需要4个主要的接口:Driver、Connection、Statement、ResultSet,这些接口定义了使用SQL访问数据库的一般架构,下面我们来详细探讨下jdbc的使用。
    2016-05-05
  • Java基础之JDBC的数据库连接与基本操作

    Java基础之JDBC的数据库连接与基本操作

    这篇文章主要介绍了Java基础之JDBC的数据库连接与基本操作,文中有非常详细的代码示例,对正在学习java基础的小伙伴们也有很好的帮助,需要的朋友可以参考下
    2021-05-05
  • Springboot如何通过路径映射获取本机图片资源

    Springboot如何通过路径映射获取本机图片资源

    项目中对图片的处理与查看是必不可少的,本文将讲解如何通过项目路径来获取到本机电脑的图片资源,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2023-08-08
  • Java SSM框架如何添加写日志功能

    Java SSM框架如何添加写日志功能

    这篇文章主要介绍了Java SSM框架如何添加写日志功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • 使用mybatis log plugin插件展示出数据库查询语句方式

    使用mybatis log plugin插件展示出数据库查询语句方式

    本文介绍了如何安装和配置MyBatis日志插件,包括集成log4j、配置log4j.xml文件和在application.properties中添加数据库打印配置,通过这些步骤,可以在调试时查看预编译的数据库语句和实际查询语句
    2024-11-11
  • SpringBoot项目实战之加载和读取资源文件

    SpringBoot项目实战之加载和读取资源文件

    在项目的开发中,我们知道的是SpringBoot框架大大减少了我们的配置文件,但是还是留下了一个application.properties文件让我们可以进行一些配置,下面这篇文章主要给大家介绍了关于SpringBoot项目实战之加载和读取资源文件的相关资料,需要的朋友可以参考下
    2021-10-10
  • Java案例分享-集合嵌套

    Java案例分享-集合嵌套

    这篇文章主要介绍了Java案例分享-集合嵌套,通过案例创建一个ArrayList集合,存储三个元素,每一个元素都是HashMap,每一个HashMap的键和值都是String,并遍历,实际操作内容需要的小伙伴可以参考一下
    2022-04-04

最新评论