草庐IT

Java 根据模板导出PDF

wind-seems-crying 2023-03-28 原文

前言

本文为我搜集的根据模板导出PDF的方法整理而来,所以贴了好多帖子的链接。有的方法仅适合特殊的业务场景,可以根据业务需求选择合适的方法。写的不好请轻喷。

思路一:直接导出pdf

使用itext模板导出pdf


思路二:先导出word再转成pdf

1)导出word

2)word转pdf


最终方案

docx4j spire.doc.free + freemarker

  1. 模板准备

    将占位变量名写在模板 testTemplate.docx的对应位置上,用 ${}包起来。

    把复制一份副本,将副本 .docx 的后缀名重命名为 .zip。解压后找到 /word/document.xml,编译器打开文件,代码格式化后,对比例如 ${repliedUserId} 的占位参数是否被拆开(如果拆开需手动修改),修改名字为 testDocument.xml。

    将源模板 testTemplate.docx 和 testDocument.xml 放到相应位置。

  2. maven依赖

        <dependencies>
            <!--        动态生成word-->
            <dependency>
                <groupId>org.freemarker</groupId>
                <artifactId>freemarker</artifactId>
                <version>2.3.22</version>
            </dependency>
    
            <!--        docx转pdf-->
            <dependency>
                <groupId>org.docx4j</groupId>
                <artifactId>docx4j-JAXB-Internal</artifactId>
                <version>8.2.4</version>
            </dependency>
            <dependency>
                <groupId>org.docx4j</groupId>
                <artifactId>docx4j-export-fo</artifactId>
                <version>8.2.4</version>
            </dependency>
    
            <!--        https://www.e-iceblue.cn/spiredocforjava/spire-doc-for-java-program-guide-content.html-->
            <!-- https://mvnrepository.com/artifact/e-iceblue/spire.doc.free -->
            <dependency>
                <groupId>e-iceblue</groupId>
                <artifactId>spire.doc.free</artifactId>
                <version>5.2.0</version>
            </dependency>
        </dependencies>
    
        <repositories>
            <repository>
                <id>com.e-iceblue</id>
                <name>e-iceblue</name>
                <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
            </repository>
        </repositories>
    
    
  3. Controller

    @PostMapping("/pdfExport")
    public ResponseEntity exportPdf(@RequestParam Map<String, Object> params) {
        try {
            // 查找业务数据
            TestEntity testEntity = testService.querySheet(params);
            // 格式转换时的暂存文件名
            String fileUuid = UUID.randomUUID().toString().replaceAll("-", "");
            String toDocxPath = "E://project//test//ToPDF//word//" + fileUuid + ".docx";
            String toPdfPath = "E://project//test//ToPDF//pdf//" + fileUuid + ".pdf";
            String toXmlPath = "E://project//test//ToPDF//xml//" + fileUuid + ".xml";
            String docxTemplate = "E://project//test//ToPDF//template//testTemplate.docx";
    
            // .xml转.docx(testDocument.xml表示在项目的相对路径下)
            XmlToDocx.toDocx("testDocument.xml",docxTemplate, toXmlPath, toDocxPath, testEntity);
            // .docx转.pdf
            WordToPdf.docxToPdf(toDocxPath, toPdfPath);
    
            // 下载pdf并删除本地pdf
            ResponseEntity response = WordToPdf.downloadPdf("这是PDF的名字啊", toPdfPath);
            return response;
        } catch (Exception e) {
            throw new BusinessException("下载PDF失败!" + e.getMessage());
        }
    }
    
  4. XmlToDocx类

    import java.io.*;
    import java.util.Enumeration;
    import java.util.Map;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipException;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipOutputStream;
    
    /**
     * 其实docx属于zip的一种,这里只需要操作word/document.xml中的数据,其他的数据不用动
     *
     * @author
     *
     */
    public class XmlToDocx {
    
        /**
         *
         * @param xmlTemplate xml的文件名
         * @param docxTemplate docx的路径和文件名(.docx模板)
         * @param xmlTemp  填充完数据的临时xml
         * @param toFilePath  目标文件名
         * @param object  需要动态传入的数据
         */
        public static void toDocx(String xmlTemplate, String docxTemplate, String xmlTemp, String toFilePath, Object object)  {
            try {
                // 1.object是动态传入的数据
                // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
    //            Writer w1 = new OutputStreamWriter(new FileOutputStream(xmlTemp), "gb2312");
                Writer w1 = new OutputStreamWriter(new FileOutputStream(xmlTemp), "utf-8");
                // 2.把object中的数据动态由freemarker传给xml
                XmlTplUtil.process(xmlTemplate, object, w1);
                // 3.把填充完成的xml写入到docx中
                XmlToDocx xtd = new XmlToDocx();
                File xmlTempFile = new File(xmlTemp);
                xtd.outDocx(xmlTempFile, docxTemplate, toFilePath);
                // 删除临时xml文件
                xmlTempFile.delete();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         *
         * @param documentFile 动态生成数据的docunment.xml文件
         * @param docxTemplate docx的模板
         * @param toFilePath  需要导出的文件路径
         * @throws ZipException
         * @throws IOException
         */
        public void outDocx(File documentFile, String docxTemplate, String toFilePath) throws ZipException, IOException {
    
            try {
                File docxFile = new File(docxTemplate);
                ZipFile zipFile = new ZipFile(docxFile);
                Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();
                ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(toFilePath));
                int len = -1;
                byte[] buffer = new byte[1024];
                while (zipEntrys.hasMoreElements()) {
                    ZipEntry next = zipEntrys.nextElement();
                    InputStream is = zipFile.getInputStream(next);
                    // 把输入流的文件传到输出流中 如果是word/document.xml由我们输入
                    zipout.putNextEntry(new ZipEntry(next.toString()));
                    if ("word/document.xml".equals(next.toString())) {
                        InputStream in = new FileInputStream(documentFile);
                        while ((len = in.read(buffer)) != -1) {
                            zipout.write(buffer, 0, len);
                        }
                        in.close();
                    } else {
                        while ((len = is.read(buffer)) != -1) {
                            zipout.write(buffer, 0, len);
                        }
                        is.close();
                    }
                }
                zipout.close();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
  5. WordToPdf类

    import org.apache.commons.io.IOUtils;
    import org.docx4j.Docx4J;
    import org.docx4j.fonts.IdentityPlusMapper;
    import org.docx4j.fonts.Mapper;
    import org.docx4j.fonts.PhysicalFonts;
    import org.docx4j.openpackaging.exceptions.Docx4JException;
    import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    
    import java.io.*;
    import java.net.URLEncoder;
    
    public class WordToPdf {
    
        /**
         * (Docx4J).docx转.pdf(当docx的一行全是英文以及标点符号时转换的Pdf那一行会超出范围 https://segmentfault.com/q/1010000043372748)
         * @param docxPath docx文件路径
         * @param pdfPath 输出的pdf文件路径
         * @throws Exception
         */
        @Deprecated
        public static boolean docxToPdf(String docxPath, String pdfPath) throws Exception {
            FileOutputStream out = null;
            try {
                File docxfile = new File(docxPath);
                WordprocessingMLPackage pkg = Docx4J.load(docxfile);
                Mapper fontMapper = new IdentityPlusMapper();
                fontMapper.put("隶书", PhysicalFonts.get("LiSu"));
                fontMapper.put("宋体", PhysicalFonts.get("SimSun"));
                fontMapper.put("微软雅黑", PhysicalFonts.get("Microsoft Yahei"));
                fontMapper.put("黑体", PhysicalFonts.get("SimHei"));
                fontMapper.put("楷体", PhysicalFonts.get("KaiTi"));
                fontMapper.put("新宋体", PhysicalFonts.get("NSimSun"));
                fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai"));
                fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong"));
                fontMapper.put("仿宋", PhysicalFonts.get("FangSong"));
                fontMapper.put("幼圆", PhysicalFonts.get("YouYuan"));
                fontMapper.put("华文宋体", PhysicalFonts.get("STSong"));
                fontMapper.put("华文中宋", PhysicalFonts.get("STZhongsong"));
                fontMapper.put("等线", PhysicalFonts.get("SimSun"));
                fontMapper.put("等线 Light", PhysicalFonts.get("SimSun"));
                fontMapper.put("华文琥珀", PhysicalFonts.get("STHupo"));
                fontMapper.put("华文隶书", PhysicalFonts.get("STLiti"));
                fontMapper.put("华文新魏", PhysicalFonts.get("STXinwei"));
                fontMapper.put("华文彩云", PhysicalFonts.get("STCaiyun"));
                fontMapper.put("方正姚体", PhysicalFonts.get("FZYaoti"));
                fontMapper.put("方正舒体", PhysicalFonts.get("FZShuTi"));
                fontMapper.put("华文细黑", PhysicalFonts.get("STXihei"));
                fontMapper.put("宋体扩展", PhysicalFonts.get("simsun-extB"));
                fontMapper.put("仿宋_GB2312", PhysicalFonts.get("FangSong_GB2312"));
                fontMapper.put("新細明體", PhysicalFonts.get("SimSun"));
                pkg.setFontMapper(fontMapper);
    
                out = new FileOutputStream(pdfPath);
                //docx4j  docx转pdf
                FOSettings foSettings = Docx4J.createFOSettings();
    //            foSettings.setWmlPackage(pkg);
                foSettings.setOpcPackage(pkg);
                Docx4J.toFO(foSettings, out, Docx4J.FLAG_EXPORT_PREFER_XSL);
    //            Docx4J.toPDF(pkg, out);
                // 删除源.docx文件
                docxfile.delete();
                return true;
    
    //        } catch (FileNotFoundException e) {
    //            e.printStackTrace();
    //        } catch (Docx4JException e) {
    //            e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        /**
         * https://www.e-iceblue.cn/spiredocforjavaconversion/java-convert-word-to-pdf.html
         * (spire.doc.free:
         *             免费版有篇幅限制。在加载或保存 Word 文档时,要求 Word 文档不超过 500 个段落,25 个表格。
         *             同时将 Word 文档转换为 PDF 和 XPS 等格式时,仅支持转换前三页。)
         * (spire.doc.free)word转pdf
         * @param wordInPath word输入路径
         * @param pdfOutPath Pdf输出路径
         * @return
         */
        public static boolean convertWordToPdf(String wordInPath, String pdfOutPath) {
            try {
                //实例化Document类的对象
                Document doc = new Document();
                //加载Word
                doc.loadFromFile(wordInPath);
                //保存为PDF格式
                doc.saveToFile(pdfOutPath, FileFormat.PDF);
                return true;
            } catch (Exception e) {
    //            e.printStackTrace();
                return false;
            } finally {
                // 删除源word文件
                File docxfile = new File(wordInPath);
                if (docxfile.exists()) {
                    docxfile.delete();
                }
            }
        }
    }
    
    

有关Java 根据模板导出PDF的更多相关文章

  1. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  2. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  3. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  4. ruby-on-rails - Prawn PDF : I need to generate nested tables - 2

    我需要一个表,其中行实际上是2行表,一个嵌套表是..我怎样才能在Prawn中做到这一点?也许我需要延期..但哪一个? 最佳答案 现在支持子表:Prawn::Document.generate("subtable.pdf")do|pdf|subtable=pdf.make_table([["sub"],["table"]])pdf.table([[subtable,"original"]])end 关于ruby-on-rails-PrawnPDF:Ineedtogeneratenested

  5. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  6. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  7. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  8. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

  9. 【Java 面试合集】HashMap中为什么引入红黑树,而不是AVL树呢 - 2

    HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候

  10. ruby-on-rails - Mandrill API 模板 - 2

    我正在使用Mandrill的RubyAPIGem并使用以下简单的测试模板:testastic按照Heroku指南中的示例,我有以下Ruby代码:require'mandrill'm=Mandrill::API.newrendered=m.templates.render'test-template',[{:header=>'someheadertext',:main_section=>'Themaincontentblock',:footer=>'asdf'}]mail(:to=>"JaysonLane",:subject=>"TestEmail")do|format|format.h

随机推荐