一.背景

项目中有个需求大体意思是,上传一个word模板,根据word模板合成word文件,再将word文件转为pdf。

二.方案选择

1.Spire.Doc for Java方案

Spire.Doc for Java这个是商用收费的,不过API文档丰富且集成简单,免费版仅支持3页转换。类似的还有ITEXT,这个商用也是受限制的。

2.docx4j方案

开源可商用,仅支持docx格式的word。

3.jodconverter LibreOffice 方案

开源可商用,调用本地office服务,进行pdf转换,类似的还有jodconverter openOffice。

4.其他

至于其他的由于不支持跨平台不做考虑。

三.实操

1.docx4j

首先尝试了docx4j,因为docx4j本身支持模板替换的操作,可一次性做替换及文档类型转换,而且仅支持docx类型,对于本次需求问题不大。

1.依赖仅需要一个即可

<dependency>
    <groupId>org.docx4j</groupId>
    <artifactId>docx4j-export-fo</artifactId>
    <version>6.1.0</version>
</dependency>

2.主要代码

@Slf4j
public class PdfUtil {
    public static <T> void exportByLocalPath(HttpServletResponse response, String fileName, String path, Map<String,String> params){
        try (InputStream in = PdfUtil.class.getClassLoader().getResourceAsStream(path)) {
            convertDocxToPdf(in, response,fileName,params);
        } catch (Exception e) {
            log.error("docx文档转换为PDF失败", e.getMessage());
        }
    }
    /**
     * docx文档转换为PDF
     * @param in
     * @param response
     * @return
     */
    public static void convertDocxToPdf(InputStream in, HttpServletResponse response, String fileName, Map<String,String> params) throws Exception {
        response.setContentType("application/pdf");
         String fullFileName = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);
        response.setHeader("Content-disposition", "attachment;filename="   fullFileName   ".pdf");
        WordprocessingMLPackage wmlPackage = WordprocessingMLPackage.load(in);
        if (params!=null&&!params.isEmpty()) {
            MainDocumentPart documentPart = wmlPackage.getMainDocumentPart();
            cleanDocumentPart(documentPart);
            documentPart.variableReplace(params);
        }
        setFontMapper(wmlPackage);
        Docx4J.toPDF(wmlPackage,response.getOutputStream());
    }
    /**
     * 清除文档空白占位符
     * @param documentPart
     * @return {@link boolean}
     */
    public static boolean cleanDocumentPart(MainDocumentPart documentPart) throws Exception {
        if (documentPart == null) {
            return false;
        }
        Document document = documentPart.getContents();
        String wmlTemplate =
                XmlUtils.marshaltoString(document, true, false, Context.jc);
        document = (Document) XmlUtils.unwrap(DocxVariableClearUtil.doCleanDocumentPart(wmlTemplate, Context.jc));
        documentPart.setContents(document);
        return true;
    }
    /**
     * 设置字体样式
     * @param mlPackage
     */
    private static void setFontMapper(WordprocessingMLPackage mlPackage) throws Exception {
        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("simsun-extB"));
        fontMapper.put("仿宋", PhysicalFonts.get("FangSong"));
        fontMapper.put("仿宋_GB2312", PhysicalFonts.get("FangSong_GB2312"));
        fontMapper.put("幼圆", PhysicalFonts.get("YouYuan"));
        fontMapper.put("华文宋体", PhysicalFonts.get("STSong"));
        fontMapper.put("华文中宋", PhysicalFonts.get("STZhongsong"));
        mlPackage.setFontMapper(fontMapper);
    }
}

清除工具类,用于处理占位符替换不生效的问题,这里参考文章

public class DocxVariableClearUtil {
    /**
     * 去任意XML标签
     */
    private static final Pattern XML_PATTERN = Pattern.compile("<[^>]*>");
    private DocxVariableClearUtil() {
    }
    /**
     * start符号
     */
    private static final char PREFIX = '$';
    /**
     * 中包含
     */
    private static final char LEFT_BRACE = '{';
    /**
     * 结尾
     */
    private static final char RIGHT_BRACE = '}';
    /**
     * 未开始
     */
    private static final int NONE_START = -1;
    /**
     * 未开始
     */
    private static final int NONE_START_INDEX = -1;
    /**
     * 开始
     */
    private static final int PREFIX_STATUS = 1;
    /**
     * 左括号
     */
    private static final int LEFT_BRACE_STATUS = 2;
    /**
     * 右括号
     */
    private static final int RIGHT_BRACE_STATUS = 3;
    /**
     * doCleanDocumentPart
     *
     * @param wmlTemplate
     * @param jc
     * @return
     * @throws JAXBException
     */
    public static Object doCleanDocumentPart(String wmlTemplate, JAXBContext jc) throws JAXBException {
        // 进入变量块位置
        int curStatus = NONE_START;
        // 开始位置
        int keyStartIndex = NONE_START_INDEX;
        // 当前位置
        int curIndex = 0;
        char[] textCharacters = wmlTemplate.toCharArray();
        StringBuilder documentBuilder = new StringBuilder(textCharacters.length);
        documentBuilder.append(textCharacters);
        // 新文档
        StringBuilder newDocumentBuilder = new StringBuilder(textCharacters.length);
        // 最后一次写位置
        int lastWriteIndex = 0;
        for (char c : textCharacters) {
            switch (c) {
                case PREFIX:
                    // 不管其何状态直接修改指针,这也意味着变量名称里面不能有PREFIX
                    keyStartIndex = curIndex;
                    curStatus = PREFIX_STATUS;
                    break;
                case LEFT_BRACE:
                    if (curStatus == PREFIX_STATUS) {
                        curStatus = LEFT_BRACE_STATUS;
                    }
                    break;
                case RIGHT_BRACE:
                    if (curStatus == LEFT_BRACE_STATUS) {
                        // 接上之前的字符
                        newDocumentBuilder.append(documentBuilder.substring(lastWriteIndex, keyStartIndex));
                        // 结束位置
                        int keyEndIndex = curIndex   1;
                        // 替换
                        String rawKey = documentBuilder.substring(keyStartIndex, keyEndIndex);
                        // 干掉多余标签
                        String mappingKey = XML_PATTERN.matcher(rawKey).replaceAll("");
                        if (!mappingKey.equals(rawKey)) {
                            char[] rawKeyChars = rawKey.toCharArray();
                            // 保留原格式
                            StringBuilder rawStringBuilder = new StringBuilder(rawKey.length());
                            // 去掉变量引用字符
                            for (char rawChar : rawKeyChars) {
                                if (rawChar == PREFIX || rawChar == LEFT_BRACE || rawChar == RIGHT_BRACE) {
                                    continue;
                                }
                                rawStringBuilder.append(rawChar);
                            }
                            // 要求变量连在一起
                            String variable = mappingKey.substring(2, mappingKey.length() - 1);
                            int variableStart = rawStringBuilder.indexOf(variable);
                            if (variableStart > 0) {
                                rawStringBuilder = rawStringBuilder.replace(variableStart, variableStart   variable.length(), mappingKey);
                            }
                            newDocumentBuilder.append(rawStringBuilder.toString());
                        } else {
                            newDocumentBuilder.append(mappingKey);
                        }
                        lastWriteIndex = keyEndIndex;
                        curStatus = NONE_START;
                        keyStartIndex = NONE_START_INDEX;
                    }
                default:
                    break;
            }
            curIndex  ;
        }
        // 余部
        if (lastWriteIndex < documentBuilder.length()) {
            newDocumentBuilder.append(documentBuilder.substring(lastWriteIndex));
        }
        return XmlUtils.unmarshalString(newDocumentBuilder.toString(), jc);
    }
}

2.poi-tl jodconverter LibreOffice 方案

poi-tl这个是专门用来进行word模板合成的开源库,文档很详细。

LibreOffice 下载最新的稳定版本即可。

1.maven依赖

		<!-- word合成 -->
		<!-- 这里注意版本,1.5版本依赖的poi 3.x的版本 -->
		<dependency>
			<groupId>com.deepoove</groupId>
			<artifactId>poi-tl</artifactId>
			<version>1.5.1</version>
		</dependency>
		<!-- jodconverter  word转pdf -->
		<!-- jodconverter-core这个依赖,理论上不用加的,jodconverter-local已经依赖了,但测试的时候不添加依赖找不到 -->
		<dependency>
			<groupId>org.jodconverter</groupId>
			<artifactId>jodconverter-core</artifactId>
			<version>4.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.jodconverter</groupId>
			<artifactId>jodconverter-local</artifactId>
			<version>4.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.jodconverter</groupId>
			<artifactId>jodconverter-spring-boot-starter</artifactId>
			<version>4.2.0</version>
		</dependency>
		<!--  工具类,非必须 -->
		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>5.4.3</version>
		</dependency>

2.主要代码

JodConverterConfig配置类

@Configuration
public class JodConverterConfig {
    @Autowired
    private OfficeManager officeManager;
    @Bean
    public DocumentConverter documentConverter() {
        return LocalConverter.builder()
                .officeManager(officeManager)
                .build();
    }
}

yml配置文件

jodconverter:
  local:
    enabled: true
    office-home: "C:\\Program Files\\LibreOffice"

PdfService合成导出代码

@Slf4j
@Component
public class PdfService {
    @Autowired
    private DocumentConverter documentConverter;
    public  void docxToPDF(InputStream inputStream,HttpServletResponse response,String fileName) {
        response.setContentType("application/pdf");
        try {
            String fullFileName = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);
            response.setHeader("Content-disposition","attachment;filename=\\" fullFileName ".pdf\\");
            documentConverter
                    .convert(inputStream)
                    .as(DefaultDocumentFormatRegistry.DOCX)
                    .to(response.getOutputStream())
                    .as(DefaultDocumentFormatRegistry.PDF)
                    .execute();
        } catch (OfficeException |IOException e) {
           log.error("word转pdf失败:{}",e.getMessage());
        }
    }
    public void exportByLocalPath(HttpServletResponse response, String fileName, String path, Object params) throws Exception {
        BufferedOutputStream outputStream = null;
        BufferedInputStream wordInputStream = null;
        try (InputStream in = PdfService.class.getClassLoader().getResourceAsStream(path)) {
            // 生成临时文件
            String outPutWordPath = System.getProperty("java.io.tmpdir").replaceAll(File.separator   "$", "")   fileName ".docx";
            File tempFile = FileUtil.touch(outPutWordPath);
            outputStream = FileUtil.getOutputStream(tempFile);
            // word模板合成写到临时文件
            WordUtil.replaceWord(outputStream, in, params);
            // word 转pdf
            wordInputStream = FileUtil.getInputStream(tempFile);
            docxToPDF(wordInputStream, response,fileName);
            // 移除临时文件
            FileUtil.del(tempFile);
        } catch (Exception e) {
            log.error("docx文档转换为PDF失败", e.getMessage());
        } finally {
            IoUtil.close(outputStream);
            IoUtil.close(wordInputStream);
        }
    }

四.结论

1.docx4j方案

  • 依赖少
  • 同时支持word合成及格式转换
  • 转化效率较差
  • 对于含样式及图片转换不友好,容易排版混乱

2.jodconverter LibreOffice 方案

  • 操作稳定
  • 转换效率快
  • 集成依赖设置较多
  • 依赖本地服务
  • LibreOffice打开word可能排版样式错乱
  • 最后考虑项目需求,最终选择了jodconverter LibreOffice方案。

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

SpringBoot如何实现word文档转pdf的更多相关文章

  1. 基于JavaScript编写一个图片转PDF转换器

    本文为大家介绍了一个简单的 JavaScript 项目,可以将图片转换为 PDF 文件。你可以从本地选择任何一张图片,只需点击一下即可将其转换为 PDF 文件,感兴趣的可以动手尝试一下

  2. ios – 将PDF文件附加到电子邮件 – Swift

    我想发送带有PDF附件的电子邮件.我创建了PDF文件,然后我做了以下哪些错误我相信:在发送电子邮件之前,我可以看到附带的chart.pdf,但是当我发送电子邮件时,它是在没有附件的情况下发送的,这是因为我没有正确附加文件.解决方法您将错误的mimeType传递给addAttachmentData().使用application/pdf而不是pdf.

  3. xcode – 无法在iOS8beta5中使用UIWebView打开PDF文件

    如果是,请提供一些示例代码.解决方法我找到了一种在WebView中查看PDF的解决方法

  4. iOS从UIWebview内容创建pdf

    哪个是从webview内容中获取最佳质量pdf文档的最佳选择?

  5. ios – 在Swift中将图像合并为PDF

    我想创建一个应用程序,要求用户从设备相机上传图片,然后使用swift将这些图像合并为PDF.怎么能实现这一目标?

  6. 我们可以在IOS应用程序的UIWebview中将条款和条件作为PDF加载吗?

    我在UIWebview中向我的应用添加了条款和条件.我真正想知道的是,我可以将其显示为逐页的pdf文档,还是应该使用任何其他方法?App商店会接受pdf格式吗?解决方法是的,这可以使用UIWebview完成,肯定会被Apple接受.如果您尝试从WebURL显示PDF文件,请使用以下代码.或者,如果您的应用程序中捆绑了PDF文件,请使用以下代码.

  7. ios – 通过UIDocumentInteractionController与Mail交互

    我正在通过UIDocumentInteractionController与其他应用共享PDF.在添加此功能之前,我使用MFMailComposeViewController定制了“发送到电子邮件”按钮–但现在我的UIDocumentInteractionController中还有一个Mail按钮,我想使用它来避免重复按钮.我的问题是,通过旧的邮件控制器,我曾经设置主题和内容文本,而如果我使用UID

  8. Quicklook / QLPreviewController,iOS 8的一些问题,但一切都适用于iOS 7.1

    我正在使用QuickLook查看PDF文件.它在iOS7.1中正常工作,但iOS8GM会出现一些问题.图片比文字好,我想告诉你问题:iOS7.1Xcode6使用QuickLook进行转换页面滚动,navigationBar隐藏得很好————————————————–————————而现在,iOS8GM与Xcode6使用QuickLook进行转换…页面滚动,navigationBar不隐藏,页面指示器隐藏在NavigationBar后面与iPhone模拟器,iPad模拟器,iPhone设备和iPad设备相同

  9. 如何选择PDF中的文本行然后突出显示它们? (IOS)

    我不想使用FastPDFKit,因为它显示徽标并且需要花钱,或者UIWebView,因为它对我们可以用它做的事情非常有限,而且我想学习如何自己做这些:-)谢谢!

  10. 如何在iOS上生成带有“真实”文本内容的PDF?

    我想在iOS6应用程序中生成一个好看的PDF.我试过了:>UIView在上下文中渲染>使用CoreText>使用NsstringdrawInRect>使用UILabeldrawRect这是一个代码示例:呈现的UIViews只包含UIImageView一堆UILabel.我还尝试了在stackoverflow上找到的建议:继承UILabel并执行此操作:但这也没有改变任何事情.无论我做什么,当在预览中打开PDF时,文本部分可以选择作为块,但不是每个字符的字符,并且缩放pdf显示它实际上是位图图像.有什么建议

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部