Three ways Java converts doc files to PDF files

Source: Internet
Author: User

Http://feifei.im/archives/93

——————————————————————————————————————————————

The project to use the function of doc to PDF, some Google summed up three ways (free program), so one after another to try to do a summary record, the next time to use direct check, save the forgotten ...

Method 1.poi Read Doc + itext generate PDF (most convenient, worst-performing, cross-platform)

Method 2.jodconverter + OpenOffice (general format implementation of the effect is OK, complex format prone to dislocation, cross-platform)

Method 3.jacob + Msofficeword + saveaspdfandxps (perfect to maintain the original DOC format, the most efficient, only in the Windows environment)

Method 1: Use Jdoctopdf to implement, this is a package good package, you can convert the doc to pdf,html,xml and other formats, call very convenient
Address: http://www.maxstocker.com/jdoctopdf/downloads.php
Need to import the POI package and itext package, note that itext to import the itext-2.1.5 version, the new version because the package name is different, error
You can also write your own method according to other tutorials on the web.
The implementation method of Jdoctopdf is as follows:

Publicvoid Doc2pdf (String docfilename)Throws exception{String Path =This.getsession (). Getservletcontext (). Getrealpath ("/")+"attachment/"; Parser p =New Docparser ();Create a new parser instance fileinputstream FIS =New FileInputStream (path+"/doc/" + Docfilename +". Doc");Creating InputStream for use with parser documentelement mydoc = P.parse (FIS,TrueFALSE);Parse document from input stream Docwriter w =new pdfwriter (); //create PDF writer w.writedocument (mydoc,new fileoutputstream (path+< Span class= "string" > "/pdf/" +docfilename +  ". pdf"); //write document as PDF using writer W = new xhtmlwriter (); W.writedocument ( Mydoc,new fileoutputstream (Path+ "/pdf/" +docfilename +  ". html"); //write document as XHTML} public string materialupload () {try {doc2pdf ( Span class= "string" > "TTT"); } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); } return SUCCESS;}            

Method 1 after conversion PDF: (Itext to Chinese requires additional configuration, so ... A blank, the format is also misplaced)




Method 2: Using Jodconverter to invoke OpenOffice's service to convert, OpenOffice has a version of each platform, so this approach is as cross-platform as method 1.
Jodconverter: Http://www.artofsolving.com/opensource/jodconverter
The first thing to install is openoffice,:http://www.openoffice.org/download/index.html
After installation to start OpenOffice Services, the specific starting method please Google,

Startup method under Mac for terminal input

/Applications/OpenOffice.org.app/Contents/MacOS/soffice "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -nologo -headless

After the preparation is completed, import the downloaded package into the project and add a method to OK:

Publicvoid CreatePDF (String docfilename)Throws ioexception{String Path =This.getsession (). Getservletcontext (). Getrealpath ( "/") + "attachment/"; file inputfile = new file (path+  "/doc/" + docfilename +  ". Doc"); file outputFile = new file (path+  "/pdf/" +docfilename +  ". pdf"); //connect to a OpenOffice.org instance running on port 8100 openofficeconnection connection = 
                     
                      new socketopenofficeconnection (
                      8100); Connection.connect (); //convert documentconverter converter = new openofficedocumentconverter (connection); Converter.convert (Inputfile, outputFile); //close the Connection connection.disconnect ();     
                        

Method 2 (The format is basically the same, there is dislocation)

Method 3: One of the best methods, but requires a window environment, and the speed is the slowest need to install Msofficeword and SaveAsPDFandXPS.exe (a plugin for Word to convert Word to PDF)
The Office version is 2007 because Saveaspdfandxps is a plugin developed by Microsoft for office2007 and above
Saveaspdfandxps:http://www.microsoft.com/zh-cn/download/details.aspx?id=7
Jacob's Bag: http://sourceforge.net/projects/jacob-project/
I'm under the Jacob-1.17-m2.zip.
The downloaded Jacob jar package is imported into the project,
Jacob's DLL file is placed under your Jdk/jre/bin (no error: Java.lang.NoClassDefFoundError:Could not initialize class Com.jacob.com.Dispatch)

On the web There is also a DLL placed in the following code output path in any path directory

System.getProperty("java.library.path");

I haven't tried this, but I think I can.
Then add the method:

StaticFinalint wdformatpdf =17;PdfPublicvoid Wordtopdf (String docfilename) {System.out.println"Start Word ...");Long start = System.currenttimemillis (); Activexcomponent app =Null Dispatch doc =Nulltry {app =New Activexcomponent ("Word.Application"); App.setproperty ("Visible",New Variant (false)); Dispatch docs = App.getproperty ("Documents"). Todispatch (); String Path =This.getsession (). Getservletcontext (). Getrealpath ("/")+"attachment/"; String sFileName = path+"/doc/" + Docfilename +". Doc"; String Tofilename = path+"/pdf/" + Docfilename +". pdf"; Doc = Dispatch.Call (Docs,"Open", sFileName). Todispatch (); System.out.println"Open Document ..." + sfilename); System.out.println"Convert Document to PDF ..." + tofilename);File ToFile =NewFile (Tofilename);if (tofile.exists ()) {ToFile.Delete (); } Dispatch.Call (Doc, "SaveAs", Tofilename, //FileName wdformatpdf); long end = System.currenttimemillis (); System.out. println ( "conversion Complete: Spents: "+ (End-start) + " MS "); } catch (Exception e) {system.out. println ( "========error: Document conversion failed:" + e.getmessage ());} finally {dispatch. Call (Doc, "Close", false); System.out. println ( "close Document"); if (app! = null) app.invoke ( "Quit", new variant[] {}); } //if this is not the case, the Winword.exe process will not close comthread.release ();       

It is important to note that if you do not install SaveAsPDFandXPS.exe, you will be prompted

========Error:文档转换失败:Invoke of: SaveAsSource: Microsoft WordDescription:

Method 3pdf Final Conversion effect (format exactly):

Three ways Java converts doc files to PDF files

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.