Java OpenOffice converts uploaded Word documents to Html format

Source: Internet
Author: User

Why do we remember to convert the uploaded word documents into html format? Imagine that if all the documents to be published on A system page come from word documents, the following process is generally executed: use word to open the document, Ctrl + A, enter the post page, and press Ctrl + V. It does not seem troublesome, but what if the document contains a large number of images? The embarrassing thing is that all images need to be uploaded again, right?

If you can upload the prepared Word documents to the server and then display them on the corresponding page, it will be a pleasant task. At least the information publishers will be very happy. The programmer may not think so ,? Why? /P>

The principle of converting Word to Html is as follows:

1. The customer uploads a Word document to the server.

2. The server calls the OpenOffice program to open the uploaded Word document.

3. OpenOffice saves word documents in Html format

4. Over

Now, we can see that this requires the server to install OpenOffice software, which can also be MS Office. However, the advantage of OpenOffice is cross-platform, you know. Well, explain, the test based on MS Win7 Ultimate X64 system.

The following describes how to implement compliance.

1. Download OpenOffice,Http://download.openoffice.org/index.htmlSo easy...

2. Download JodconverterHttp://www.artofsolving.com/opensource/jodconverterThis is a third-party jar package that enables OpenOffice format conversion.

3. Make a cup of hot tea and wait for download.

4. Install OpenOffice. After the installation is complete, call cmd to start a service of OpenOffice: C: Program Files (x86) OpenOffice.org 3 program> soffice-headless-accept = "socket, port = 8100; urp ;"

5. Open eclipse

6. Have a cup of hot tea and wait for eclipse to open.

7. Create an eclipse project and import the jar package under Jodconverter/lib.

8. Coding...

The code is as follows: Copy code

Package com.mzule.doc 2html. util;

Import java. io. BufferedReader;
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. FileNotFoundException;
Import java. io. IOException;
Import java. io. InputStreamReader;
Import java.net. ConnectException;
Import java. util. Date;
Import java. util. regex. Matcher;
Import java. util. regex. Pattern;

Import com. artofsolving. jodconverter. DocumentConverter;
Import com. artofsolving. jodconverter. openoffice. connection. OpenOfficeConnection;
Import com. artofsolving. jodconverter. openoffice. connection. SocketOpenOfficeConnection;
Import com. artofsolving. jodconverter. openoffice. converter. OpenOfficeDocumentConverter;

/**
* Tool class for converting Word documents into html strings
 *
* @ Author MZULE
 *
*/
Public class Doc2Html {

Public static void main (String [] args ){
System. out
. Println (toHtmlString (new File ("C:/test/test.doc"), "C:/test "));
    }

/**
* Convert a Word document to an html document
     *
* @ Param docFile
* Word documents to be converted
* @ Param filepath
* Html storage path after conversion
* @ Return: html file converted
*/
Public static File convert (File docFile, String filepath ){
// Create an html file
File htmlFile = new File (filepath + "/" + new Date (). getTime ()
+ ". Html ");
// Create an Openoffice connection
OpenOfficeConnection con = new SocketOpenOfficeConnection (8100 );
Try {
// Connection
Con. connect ();
} Catch (ConnectException e ){
System. out. println ("An error occurred while obtaining the OpenOffice connection ...");
E. printStackTrace ();
    }
// Create a converter
DocumentConverter converter = new OpenOfficeDocumentConverter (con );
// Convert the document to html
Converter. convert (docFile, htmlFile );
// Close the openoffice connection
Con. disconnect ();
Return htmlFile;
    }

/**
* Convert word to an html file and obtain the html file code.
     *
* @ Param docFile
* Document to be converted
* @ Param filepath
* Saved image location in the document
* @ Return: html code converted successfully
*/
Public static String toHtmlString (File docFile, String filepath ){
// Convert Word documents
File htmlFile = convert (docFile, filepath );
// Obtain the html file stream
StringBuffer htmlSb = new StringBuffer ();
Try {
BufferedReader br = new BufferedReader (new InputStreamReader (
New FileInputStream (htmlFile )));
While (br. ready ()){
HtmlSb. append (br. readLine ());
        }
Br. close ();
// Delete a temporary file
HtmlFile. delete ();
} Catch (FileNotFoundException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
    }
// HTML file string
String htmlStr = htmlSb. toString ();
// Return the cleaned html text
Return clearFormat (htmlStr, filepath );
    }

/**
* Clear unnecessary html tags
     *
* @ Param htmlStr
* Html statements with complex html tags
* @ Return remove the statements that do not require html tags
*/
Protected static String clearFormat (String htmlStr, String docImgPath ){
// Obtain the regular expression of the body content
String bodyReg = "<BODY. * </BODY> ";
Pattern bodyPattern = Pattern. compile (bodyReg );
Matcher bodyMatcher = bodyPattern. matcher (htmlStr );
If (bodyMatcher. find ()){
// Obtain the BODY content and convert the BODY tag to DIV
HtmlStr = bodyMatcher. group (). replaceFirst ("<BODY", "<DIV ")
. ReplaceAll ("</BODY>", "</DIV> ");
    }
// Adjust the image address
HtmlStr = htmlStr. replaceAll ("+ "/");
// Convert <P> </P> to </div> retain the style
// Content = content. replaceAll ("(<P) ([^>] *> .*?) (<\/P> )",
// "<Div $2 </div> ");
// Convert <P> </P> to </div> and delete the style.
HtmlStr = htmlStr. replaceAll ("(<P) ([^>] *) (> .*?) (<\/P>) "," <p $3 </p> ");
// Delete unnecessary tags
HtmlStr = htmlStr
. ReplaceAll (
"<[/]? (Font | FONT | span | SPAN | xml | XML | del | DEL | ins | INS | meta | META | [ovwxpOVWXP]: \ w +) [^>] *?> ",
"");
// Delete unnecessary attributes
HtmlStr = htmlStr
. ReplaceAll (
"<([^>] *) (? : Lang | LANG | class | CLASS | style | STYLE | size | SIZE | face | FACE | [ovwxpOVWXP]: \ w +) = (? : '[^'] * '| "" [^ ""] * "" | [^>] +) ([^>] *)> ",
"<$1 $2> ");
Return htmlStr;
    }

}

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.