1.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.
JODConverter可以將一般格式的文檔轉換爲PDF格式。
官網地址:http://code.google.com/p/jodconverter/
下載地址:http://download.csdn.net/detail/jolingogo/5074520
2.示例
這裏用的是3.0的版本
- OfficeManager officeManager = new DefaultOfficeManagerConfiguration().buildOfficeManager();
- officeManager.start();
- OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
- converter.convert(new File("test.odt"), new File("test.pdf");
- officeManager.stop();
- Exception in thread "main" java.lang.IllegalStateException: officeHome not set and could not be auto-detected
- at org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration.buildOfficeManager(DefaultOfficeManagerConfiguration.java:163)
- at org.ygy.util.PDFUtil.toPDF(PDFUtil.java:11)
- at org.ygy.util.PDFUtil.main(PDFUtil.java:21)
然後設置一下officeHome:
- public static void toPDF() {
- OfficeManager officeManager = new DefaultOfficeManagerConfiguration()
- .setOfficeHome("D:\\program files\\openoffice.org 3")
- .buildOfficeManager();
- officeManager.start();
- OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
- converter.convert(new File("E:\\demo.doc"), new File("E:\\demo_1.pdf"));
- officeManager.stop();
- }
- public static void startServer() {
- String cmd = "cmd /k soffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\" -nofirststartwizard";
- try {
- Runtime.getRuntime().exec(cmd , null , new File("D:\\program files\\openoffice.org 3\\program"));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
3.TXT轉換爲PDF
在將.txt文件轉換爲PDF的時候發現,如果TXT文件的編碼是ANSI的話,中文會產生亂碼,解決辦法是先將.txt保存爲.odt文件,再將.odt文件轉換爲PDF就可以了。
如果TXT文件的編碼是UTF-8的話,中文也可以正常轉換。
- package org.ygy.util;
- import java.io.File;
- import org.artofsolving.jodconverter.OfficeDocumentConverter;
- import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
- import org.artofsolving.jodconverter.office.OfficeManager;
- public class PDFUtil {
- public static void toPDF(String sourcePath , String targetpath) {
- if(sourcePath.endsWith(".txt")) {
- //先保存爲.odt
- StringBuffer odtPath = new StringBuffer(sourcePath.substring(0 , sourcePath.lastIndexOf(".")));
- odtPath.append(".odt");
- FileUtil.write(sourcePath , odtPath.toString());
- sourcePath = odtPath.toString();
- }
- OfficeManager officeManager = new DefaultOfficeManagerConfiguration()
- .setOfficeHome("D:\\program files\\openoffice.org 3")
- .buildOfficeManager();
- officeManager.start();
- OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
- converter.convert(new File(sourcePath), new File(targetpath));
- officeManager.stop();
- }
- public static void main(String[] args) {
- PDFUtil.toPDF("E:\\type.txt" , "E:\\type_2.pdf");
- }
- }