先講講思路:
第一步:使用 poi 將word轉換成 html,這裏代碼一搜一堆沒什麼好說的,千篇一律。
(值得注意的地方是IText 根據html生成pdf文件的時候,會驗證html文件是否標準,例如通過poi轉換的出來的html文件的一些標籤會缺少標籤閉合 ” / “ :
舉個栗子:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<img src="test/0.jpg" style="width:5.765972in;height:8.647917in;vertical-align:text-bottom;">
這是我直接用pio生成的html中的一部分, META、img 標籤明顯就沒有對應閉合標籤。如果用這種html進行轉換是沒有辦法通過itext 的校驗的。會出現以下異常
錯誤: “The element type "meta" must be terminated by the matching end-tag "</meta>".”
org.xhtmlrenderer.util.XRRuntimeException: Can't load the XML resource (using TRaX transformer). org.xml.sax.SAXParseException: The element type "meta" must be terminated by the matching end-tag "</meta>". 。
從錯誤分析也知道是我們的html不規範拉,我們採用第三方 jar 包Jsoup, 直接調用 parse方法 我們的html就標準啦!
因爲遇到這個問題讓我頭疼了半天,沒想到就這麼輕鬆的解決了,發個博文支援一下遇到該問題的小夥伴們 !
下面是pio轉換html 的代碼:
package com.smart.sys.core.service.io.poi;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.jsoup.Jsoup;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.List;
/**
* Created by Carey on 15-2-2.
*/
public class Word2Html {
public static void main(String argv[]) {
try {
convert2Html("D:\\新建 Microsoft Word 文檔.doc","D:\\1.html");
} catch (Exception e) {
e.printStackTrace();
}
}
//輸出html文件
public static void writeFile(String content, String path) {
FileOutputStream fos = null;
BufferedWriter bw = null;
org.jsoup.nodes.Document doc = Jsoup.parse(content);
content=doc.html();
try {
File file = new File(path);
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
bw.write(content);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fos != null)
fos.close();
} catch (IOException ie) {
}
}
}
//word 轉 html
public static void convert2Html(String fileName, String outPutFile)
throws TransformerException, IOException,
ParserConfigurationException {
HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));//WordToHtmlUtils.loadDoc(new FileInputStream(inputFile));
//兼容2007 以上版本
// XSSFWorkbook xssfwork=new XSSFWorkbook(new FileInputStream(fileName));
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.newDocument());
wordToHtmlConverter.setPicturesManager( new PicturesManager()
{
public String savePicture( byte[] content,
PictureType pictureType, String suggestedName,
float widthInches, float heightInches )
{
return "test/"+suggestedName;
}
} );
wordToHtmlConverter.processDocument(wordDocument);
//save pictures
List pics=wordDocument.getPicturesTable().getAllPictures();
if(pics!=null){
for(int i=0;i<pics.size();i++){
Picture pic = (Picture)pics.get(i);
System.out.println();
try {
pic.writeImageContent(new FileOutputStream("D:/test/"
+ pic.suggestFullFileName()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Document htmlDocument = wordToHtmlConverter.getDocument();
ByteArrayOutputStream out = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "HTML");
serializer.transform(domSource, streamResult);
out.close();
writeFile(new String(out.toByteArray()), outPutFile);
}
}
好了第二步生成pdf ,我直接上代碼了 !
package com.smart.sys.core.service.io.itext;
import com.lowagie.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* Created by Carey on 15-2-2.
*/
public class Html2Pdf {
public boolean convertHtmlToPdf(String inputFile, String outputFile)
throws Exception {
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
String url = new File(inputFile).toURI().toURL().toString();
renderer.setDocument(url);
// 解決中文支持問題
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("C:/Windows/Fonts/simsunb.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//解決圖片的相對路徑問題
renderer.getSharedContext().setBaseURL("file:/D:/test");
renderer.layout();
renderer.createPDF(os);
os.flush();
os.close();
return true;
}
public static void main(String [] args){
Html2Pdf html2Pdf =new Html2Pdf();
try {
html2Pdf.convertHtmlToPdf("D:\\1.html","D:\\index.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
}
pdf 的轉換的詳細細節也是參考了一位大神的代碼,人家寫的非常詳細,我這裏也不再贅述 、這裏附上鍊接 :
http://www.open-open.com/lib/view/open1341881830588.html
所需jar包
iText-2.0.8.jar
core-renderer.jar
iTextAsian.jar
iTextAsianCmaps.jar
jsoup-1.8.1.jar
下載地址:
http://yunpan.cn/cKMuZ9yQynRHu 提取碼 3f4c