使用Java将docx文件转换为PDF

Fer*_*son 5 java pdf docx4j

我正在寻找一些"稳定"方法将DOCX文件从MS WORD转换为PDF.从现在开始,我已经将OpenOffice作为监听器使用,但它经常挂起.问题是我们遇到许多用户想要同时将SXW,DOCX文件转换为PDF的情况.还有其他可能吗?我尝试了这个网站的例子:https://angelozerr.wordpress.com/2012/12/06/how-to-convert-docxodt-to-pdfhtml-with-java/但输出结果不好(转换后的文件)有错误和布局相当修改).

这是"源"docx文档: 在此输入图像描述

这里是用docx4j转换的文档,文档中有一些异常文本.此外,右上角的文字也丢失了.

在此输入图像描述

这个是使用OpenOffice创建的PDF,从docx转换为pdf.有些文字缺少"右上角"

在此输入图像描述

是否有其他选项将docx转换为PDF格式的pdf?

Kis*_*nCS 4

有很多方法可以进行转换,其中一种使用的方法是使用 POI 和 DOCX4j

InputStream is = new FileInputStream(new File("your Docx PAth"));
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
                    .load(is);
            List sections = wordMLPackage.getDocumentModel().getSections();
            for (int i = 0; i < sections.size(); i++) {
                wordMLPackage.getDocumentModel().getSections().get(i)
                        .getPageDimensions();
            }
            Mapper fontMapper = new IdentityPlusMapper();
            PhysicalFont font = PhysicalFonts.getPhysicalFonts().get(
                    "Comic Sans MS");//set your desired font 
            fontMapper.getFontMappings().put("Algerian", font);
            wordMLPackage.setFontMapper(fontMapper);
            PdfSettings pdfSettings = new PdfSettings();
            org.docx4j.convert.out.pdf.PdfConversion conversion = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(
                    wordMLPackage);
            //To turn off logger
            List<Logger> loggers = Collections.<Logger> list(LogManager
                    .getCurrentLoggers());
            loggers.add(LogManager.getRootLogger());
            for (Logger logger : loggers) {
                logger.setLevel(Level.OFF);
            }
            OutputStream out = new FileOutputStream(new File("Your OutPut PDF path"));
            conversion.output(out, pdfSettings);
            System.out.println("DONE!!"); 
Run Code Online (Sandbox Code Playgroud)

这非常有效,甚至在多个 DOCX 文件上进行了尝试。

  • 此答案中的代码示例使用 docx4j,而不是 POI :-) (4认同)