A definitive example of a simple conversion from Word files to PDF format using documents4j, please?

Pastasaurus Rex picture Pastasaurus Rex · Oct 20, 2015 · Viewed 8.6k times · Source

I have a simple Word file and I'd like to convert it to PDF using the documents4j api. Been searching for a few hours, but haven't found out how to go about writing the code. I just need a basic working code.

Answer

Nirav Patel picture Nirav Patel · Nov 2, 2015

Add required dependencies in pom.xml

i.e,

        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-api</artifactId>
            <version>0.2.1</version>
        </dependency>       

        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-util-conversion</artifactId>
            <version>0.2.1</version>
        </dependency>

        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-transformer</artifactId>
            <version>0.2.1</version>
        </dependency>

        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-util-all</artifactId>
            <version>0.2.1</version>
        </dependency>

        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-local</artifactId>
            <version>0.2.1</version>
        </dependency>

        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-local-demo</artifactId>
            <version>0.2.1</version>
        </dependency>

And use following code snippet in order to convert document into PDF. In below example, I`m converting RTF file to PDF.

        ByteArrayOutputStream bo = new ByteArrayOutputStream();

        InputStream in = new BufferedInputStream(new FileInputStream("C:\\PDF\\RichText1.rtf"));
        IConverter converter = LocalConverter.builder()
                                             .baseFolder(new File("C:\\PDF\\"))
                                             .workerPool(20, 25, 2, TimeUnit.SECONDS)
                                             .processTimeout(5, TimeUnit.SECONDS)
                                             .build();

        Future<Boolean> conversion = converter
                                        .convert(in).as(DocumentType.RTF)
                                        .to(bo).as(DocumentType.PDF)
                                        .prioritizeWith(1000) // optional
                                        .schedule();

So your required converted file will be stored into ByteArrayOutputStream object (bo) here.