How to convert docx/odt to pdf/html with Java?__java

來源:互聯網
上載者:User
How to convert docx/odt to pdf/html with Java? décembre 6, 2012 angelozerr Laisser un commentaire Go to comments             31 Votes


How to convert docx/odt to pdf/html with Java? This question comes up all the time in any forum like stackoverflow. So I decided to write an article about this topic to enumerate the Java (open source) frameworks which manages that. 

Here some paid product which manages docx/odt to pdf/html converters : Aspose.Words for Java which manages only docx converter. Docmosis which manages docx and odt converters. Muhimbi PDF Converter Services.

To be honest with you, I have not tried those solution because it’s not free. I will not speak about them in this article.

Here some open source product which manages docx/odt to pdf/html converters : JODConverter : JODConverter automates conversions between office document formats using OpenOffice.org or LibreOffice. Supported formats include OpenDocument, PDF, RTF, HTML, Word, Excel, PowerPoint, and Flash. It can be used as a Java library, a command line tool, or a web application. docx4j: docx4j is a Java library for creating and manipulating Microsoft Open XML (Word docx, Powerpoint pptx, and Excel xlsx) files. It is similar to Microsoft’s OpenXML SDK, but for Java. docx4j uses JAXB to create the in-memory object representation. XDocReport which provides: docx converters which works with Apache POI XWPF and iText 2.3.7 for PDF. odt converters which works with ODFDOM and iText 2.3.7 for PDF.

Here criteria that I think which are important for converters :  best renderer : the converter must not loose some formatting information. fast : the converter must be the more fast. less memory intensive to avoid OutOfMemory problem. streaming: use InputStream/OutputStream instead of File. Using streaming instead of File, avoids some problems (hard disk is not used, no need to have write right on the hard disk) easy to install: no need to install OpenOffice/LibreOffice, MS Word on the server to manage converter.

In this article I will introduce those 3 Java frameworks converters and I will compare it to give Pros/Cons for each framework and try to be more frankly because I’m one of XDocReportdeveloper.

If you want to compare result of conversion, performance, etc of docx4j and XDocReport quickly, you can play with our live demo which provides a JAX-RS REST converter service. 

Sorry with my English!

Before starting to read this article, I would like to apologize me with my bad English. I don’t want to say « XDocReport is the best » and I don’t want to have some offence with JODConverter, docx4j, FOP guys. Goal of this article is to introduce those 3 frameworks converters and share my skills about odt and docx converters to PDF. Download

You can download samples of docx/odt converters explained in this article :  org.samples.docxconverters.jodconverter.zip : samples of conversion docx to PDF/HTML with JODConverter. org.samples.docxconverters.docx4j.zip samples of conversion docx to PDF/HTML with docx4j. org.samples.docxconverters.xdocreport.zip samples of conversion docx to PDF/HTML with XDocReport (Apache POI XWPF). How to manage PDF with Java?

Here the 3 best famous Java PDF libraries:  Apache FOP: Apache FOP (Formatting Objects Processor) is a print formatter driven by XSL formatting objects (XSL-FO) and an output independent formatter. It is a Java application that reads a formatting object (FO) tree and renders the resulting pages to a specified output. Output formats currently supported include PDF, PS, PCL, AFP, XML (area tree representation), Print, AWT and PNG, and to a lesser extent, RTF and TXT. The primary output target is PDF. Apache PDFBox: The Apache PDFBox library is an open source Java tool for working with PDF documents. This project allows creation of new PDF documents, manipulation of existing documents and the ability to extract content from documents. Apache PDFBox also includes several command line utilities. Apache PDFBox is published under the Apache License v2.0 iText: iText is a library that allows you to create and manipulate PDF documents. It enables developers looking to enhance web- and other applications with dynamic PDF document generation and/or manipulation.

With iText, there are 2 versions:  2.3.x which is MPL License. 5.x which is AGPL License. How to convert docx/odt to pdf/html with Java?

Just for information, docx and odt files are a zip which is composed with: several xml entries like word/document.xml (docx), content.xml (odt) which describes with XML the content of the document, styles.xml which describes used styles, etc. binary data for image.

To compare performance between JODConverter, docx4j, XDocReport framework converters, tests must follow 2 rules:  logs must be disabled to ignore time of generated log (ex: docx4j generates a lot of logs which degrade the performance). convert twice the docx/odt to html/pdf, to ignore time of the initialization of the framework converter (ex: ignore time of connection to LibreOffice with JODConverter, ignore time of the load of JAXB classes of docx4j, etc). To compare our converters frameworks, we will convert twice the docx and will retain the last elapsed time.

To compare the result quality of the conversion, I have tried to use on each samples converters project, several docx which are designed with Table (border, rows/cols span), Header/Footer, images etc. In this article we will just study simple docx HelloWorld.docx :

But you can launch the other docx of each Java Eclipse Project to see the result of html and pdf conversion. JODConverter with docx

To test and use JODConverter, you need to install OpenOffice or LibreOffice. In my case I have installed LibreOffice 3.5 on Windows. 

org.samples.docxconverters.jodconverter Eclipse project that you can download here is sample of docx converter with JODConverter. This project contains:  docx folder which contains several docx to convert. Those docx comes from the XDocReport Git that we use to test our converter. pdf and html folders where docx will be converted. lib folder whith JODConverter and dependencies JARs.

Download JARs

To download JODConverter JARs, download the zip jodconverter-core-3.0-beta-4-dist.zip, unzip it and copy paste the lib folder of the zip to your Eclipse Java project. Add those JARs in your classpath.

My test was done with LibreOffice 3.5 and the official distribution doesn’t work with LibreOffice 3.5 (see issue 103).
To fix this problem, I have replaced the official JARs jodconverter-core-3.0-beta-4.jar with jodconverter-core-3.0-beta-4-jahia2.jar. HTML converter

Here the JODConverter Java code which converts twice the « docx/HelloWorld.docx » to « html/HelloWorld.html »: 

 package org.samples.docxconverters.jodconverter.html;import java.io.File;import org.artofsolving.jodconverter.OfficeDocumentConverter;import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;import org.artofsolving.jodconverter.office.OfficeManager;public class HelloWorldToHTML {public static void main(String[] args) {// 1) Start LibreOffice in headless mode.OfficeManager officeManager = null;try {officeManager = new DefaultOfficeManagerConfiguration().setOfficeHome(new File("C:/Program Files/LibreOffice 3.5")).buildOfficeManager();officeManager.start();// 2) Create JODConverter converterOfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);// 3) Create HTMLcreateHTML(converter);createHTML(converter);} finally {// 4) Stop LibreOffice in headless mode.if (officeManager != null) {officeManager.stop();}}}private static void createHTML(OfficeDocumentConverter converter) {try {long start = System.currentTimeMillis();converter.convert(new File("docx/HelloWorld.docx"), new File("html/HelloWorld.html"));System.err.println("Generate html/HelloWorld.html with "+ (System.currentTimeMillis() - start) + "ms");} catch (Throwable e) {e.printStackTrace();}}}

You can notice that code uses java.io.File for docx input and html output because JODConverter cannot work with Streaming.

After running this class, you will see on the console few JODConverter logs and the elapsed time of the conversion : 

Generate html/HelloWorld.html with 12109msGenerate html/HelloWorld.html with 391ms

JODConverter converts a simple HelloWorld.docx to HTML with 391ms. The quality of the conversion is perfect.

Note that, in my case the connection to LibreOffice takes a long time (5219ms) and disconnection too. PDF converter

Here the JODConverter Java code which converts twice the « docx/HelloWorld.docx » to « pdf/HelloWorld.pdf »: 

package org.samples.docxconverters.jodconverter.pdf;import java.io.File;import org.artofsolving.jodconverter.OfficeDocumentConverter;import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;import org.artofsolving.jodconverter.office.OfficeManager;public class HelloWorldToPDF {public static void main(String[] args) {// 1) Start LibreOffice in headless mode.OfficeManager officeManager = null;try {officeManager = new DefaultOfficeManagerConfiguration().setOfficeHome(new File("C:/Program Files/LibreOffice 3.5")).buildOfficeManager();officeManager.start();// 2) Create JODConverter converterOfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);// 3) Create PDFcreatePDF(converter);createPDF(converter);} finally {// 4) Stop LibreOffice in headless mode.if (officeManager != null) {officeManager.stop();}}}private static void createPDF(OfficeDocumentConverter converter) {try {long start = System.currentTimeMillis();converter.convert(new File("docx/HelloWorld.docx"), new File("pdf/HelloWorld.pdf"));System.err.println("Generate pdf/HelloWorld.pdf with "+ (System.currentTimeMillis() - start) + "ms");} catch (Throwable e) {e.printStackTrace();}}}

After running this class, you will see on the console few JODConverter logs and the elapsed time of the conversion : 

Generate pdf/HelloWorld.pdf with 3172msGenerate pdf/HelloWorld.pdf with 468ms

JODConverter converts a simple HelloWorld.docx to PDF with 468ms. The quality of the conversion is perfect. docx4j

dox4j provides several docx converters :  docx to HTML converter. docx to PDF converter based on XSL-FO and FOP.

org.samples.docxconverters.docx4j Eclipse project that you can download here is sample of docx converter with docx4j. This project contains:  docx folder which contains several docx to convert. Those docx comes from the XDocReport Git that we use to test our converter. pdf and html folders where docx will be converted. lib folder whit docx4j and dependencies JARs.

For docx4j, logs must be disabled because it generates a lot of logs which degrade the performance. To do that :  create src/docx4j.properties like this :

docx4j.Log4j.Configurator.disabled=true
create src/log4j.properties like this :
log4j.rootLogger=ERROR
Donload with maven

To download docx4j and their dependencies JARS, the best mean is to use maven with this pom:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.samples.docxconverters.docx4j&l
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.