Solución:
Además de la respuesta de VivekRatanSinha, me gustaría publicar el código completo y los frascos necesarios para las personas que lo necesiten en el futuro.
Código:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class WordConvertPDF
public static void main(String[] args)
WordConvertPDF cwoWord = new WordConvertPDF();
cwoWord.ConvertToPDF("D:/Test.docx", "D:/Test.pdf");
public void ConvertToPDF(String docPath, String pdfPath)
try
InputStream doc = new FileInputStream(new File(docPath));
XWPFDocument document = new XWPFDocument(doc);
PdfOptions options = PdfOptions.create();
OutputStream out = new FileOutputStream(new File(pdfPath));
PdfConverter.getInstance().convert(document, out, options);
catch (IOException ex)
System.out.println(ex.getMessage());
y TARROS:
Disfrutar 🙂
Faltan algunas bibliotecas.
Puedo ejecutar su código agregando las siguientes bibliotecas:
Apache POI 3.15 org.apache.poi.xwpf.converter.core-1.0.6.jar org.apache.poi.xwpf.converter.pdf-1.0.6.jar fr.opensagres.xdocreport.itext.extension-2.0.0.jar itext-2.1.7.jar ooxml-schemas-1.3.jar
He convertido con éxito un documento de Word de 6 páginas (.docx) con tablas, imágenes y varios formatos.
Proporcionaré 3 métodos para convertir docx a pdf:
- Usando itext y opensagres y apache poi
Codigo:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class ConvertDocToPdfitext
public static void main(String[] args)
System.out.println( "Starting conversion!!!" );
ConvertDocToPdfitext cwoWord = new ConvertDocToPdfitext();
cwoWord.ConvertToPDF("C:/Users/avijit.shaw/Desktop/testing/docx/Account Opening Prototype Details.docx", "C:/Users/avijit.shaw/Desktop/testing/docx/Test-1.pdf");
System.out.println( "Ending conversion!!!" );
public void ConvertToPDF(String docPath, String pdfPath)
try
InputStream doc = new FileInputStream(new File(docPath));
XWPFDocument document = new XWPFDocument(doc);
PdfOptions options = PdfOptions.create();
OutputStream out = new FileOutputStream(new File(pdfPath));
PdfConverter.getInstance().convert(document, out, options);
catch (IOException ex)
System.out.println(ex.getMessage());
Dependencias: utilice Maven para resolver dependencias.
La nueva versión 2.0.2 de fr.opensagres.poi.xwpf.converter.core se ejecuta con apache poi 4.0.1 e itext 2.17. Solo necesita agregar la dependencia a continuación en Maven y luego maven descargará automáticamente todas las dependencias dependientes. (Actualizó su proyecto Maven, por lo que descargó todas estas bibliotecas y todas sus dependencias)
fr.opensagres.xdocreport
fr.opensagres.poi.xwpf.converter.pdf
2.0.2
- Usando Documents4j
Nota: Debe tener MS Office instalado en la máquina en la que se ejecuta este código.
Codigo:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
public class Document4jApp
public static void main(String[] args)
File inputWord = new File("C:/Users/avijit.shaw/Desktop/testing/docx/Account Opening Prototype Details.docx");
File outputFile = new File("Test_out.pdf");
try
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
outputStream.close();
System.out.println("success");
catch (Exception e)
e.printStackTrace();
Dependencias: utilice Maven para resolver dependencias.
com.documents4j
documents4j-local
1.0.3
com.documents4j
documents4j-transformer-msoffice-word
1.0.3
- Usando openoffice nuoil
Nota: Debe tener OpenOffice instalado en la máquina en la que se ejecuta este código.
Codigo:
import java.io.File;
import com.sun.star.beans.PropertyValue;
import com.sun.star.comp.helper.BootstrapException;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import ooo.connector.BootstrapSocketConnector;
public class App
public static void main(String[] args) throws Exception, BootstrapException
System.out.println("Stating conversion!!!");
// Initialise
String oooExeFolder = "C:\Program Files (x86)\OpenOffice 4\program"; //Provide path on which OpenOffice is installed
XComponentContext xContext = BootstrapSocketConnector.bootstrap(oooExeFolder);
XMultiComponentFactory xMCF = xContext.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, oDesktop);
// Load the Document
String workingDir = "C:/Users/avijit.shaw/Desktop/testing/docx/"; //Provide directory path of docx file to be converted
String myTemplate = workingDir + "Account Opening Prototype Details.docx"; // Name of docx file to be converted
if (!new File(myTemplate).canRead())
throw new RuntimeException("Cannot load template:" + new File(myTemplate));
XComponentLoader xCompLoader = (XComponentLoader) UnoRuntime
.queryInterface(com.sun.star.frame.XComponentLoader.class, xDesktop);
String sUrl = "file:///" + myTemplate;
PropertyValue[] propertyValues = new PropertyValue[0];
propertyValues = new PropertyValue[1];
propertyValues[0] = new PropertyValue();
propertyValues[0].Name = "Hidden";
propertyValues[0].Value = new Boolean(true);
XComponent xComp = xCompLoader.loadComponentFromURL(sUrl, "_blank", 0, propertyValues);
// save as a PDF
XStorable xStorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, xComp);
propertyValues = new PropertyValue[2];
// Setting the flag for overwriting
propertyValues[0] = new PropertyValue();
propertyValues[0].Name = "Overwrite";
propertyValues[0].Value = new Boolean(true);
// Setting the filter name
propertyValues[1] = new PropertyValue();
propertyValues[1].Name = "FilterName";
propertyValues[1].Value = "writer_pdf_Export";
// Appending the favoured extension to the origin document name
String myResult = workingDir + "letterOutput.pdf"; // Name of pdf file to be output
xStorable.storeToURL("file:///" + myResult, propertyValues);
System.out.println("Saved " + myResult);
// shutdown
xDesktop.terminate();
Dependencias: utilice Maven para resolver dependencias.
org.openoffice
unoil
3.2.1
org.openoffice
juh
3.2.1
org.openoffice
bootstrap-connector
0.1.1
Te invitamos a añadir valor a nuestra información dando tu experiencia en los informes.