我如何解决以下在使用Documents4j库将docx转换为pdf时遇到的异常?

时间:2016-01-11 15:36:37

标签: java pdf docx file-conversion documents4j

我使用以下代码将docx转换为pdf。

    public static void main(String[] args) {
    File inputdocxfile = new File(System.getProperty("user.dir") + "/src/test/resources/files/output/");

    File outputpdffile = new File(System.getProperty("user.dir") + "/src/test/resources/files/output/"
            + "CustomerOutputdocx.pdf");
    IConverter converter = LocalConverter.builder().baseFolder(inputdocxfile)
            .workerPool(20, 25, 2, TimeUnit.SECONDS).processTimeout(5, TimeUnit.SECONDS).build();

    Future<Boolean> conversion = converter.convert(inputdocxfile).as(DocumentType.MS_WORD).to(outputpdffile)
            .as(DocumentType.PDF).prioritizeWith(1000).schedule();
}

我得到的是以下异常。我使用的是与documents4j官方网站中提到的相同的代码。

Exception in thread "main" java.lang.IllegalStateException: The application was started without any registered or class-path discovered converters.
at com.documents4j.conversion.ExternalConverterDiscovery.validate(ExternalConverterDiscovery.java:68)
at com.documents4j.conversion.ExternalConverterDiscovery.loadConfiguration(ExternalConverterDiscovery.java:85)
at com.documents4j.conversion.DefaultConversionManager.<init>(DefaultConversionManager.java:22)
at com.documents4j.job.LocalConverter.makeConversionManager(LocalConverter.java:74)
at com.documents4j.job.LocalConverter.<init>(LocalConverter.java:47)
at com.documents4j.job.LocalConverter$Builder.build(LocalConverter.java:162)
at com.apakgroup.docgen.converters.ConvertToPdf.main(ConvertToPdf.java:19)
Exception in thread "Shutdown hook: com.documents4j.job.LocalConverter" java.lang.NullPointerException
at com.documents4j.job.LocalConverter.shutDown(LocalConverter.java:95)
at com.documents4j.job.ConverterAdapter$ConverterShutdownHook.run(ConverterAdapter.java:125)

1 个答案:

答案 0 :(得分:6)

我错过了很少的依赖,我也不得不使用较新版本的commons-io。我之前使用过commons-io 1.3但后来我才知道Documents4J使用了commons-io 1.4或更高版本,当commons-io版本被更改时,它工作了。如果有人想知道我在java中将docx文件转换为pdf的依赖关系。这些就是那些。

    <dependency>
        <groupId>com.documents4j</groupId>
        <artifactId>documents4j-api</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.documents4j</groupId>
        <artifactId>documents4j-local</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.documents4j</groupId>
        <artifactId>documents4j-transformer-msoffice-word</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>18.0</version>
    </dependency>

让我提醒你。此库仅适用于安装了MS Office的计算机;因为库使用应用程序本身将docx转换为pdf。如果有人在服务器上托管此代码,则还有一个远程转换器,您可以使用它来代替本地转换器,如here所示。