word和.txt文件转html 及pdf文件, 使用poi jsoup itext心得
word和.txt文件转html 及pdf文件, 使用poi jsoup itext心得
本人第一次写博客,有上面不足的或者需要改正的希望大家指出来,一起学习交流讨论。
由于在项目中遇到了这一个问题,在网上也找了很多方法,感觉千篇一律,总有一些问题,因此总结出word转html和pdf文件使用方法。
虽然poi功能不是很强大,但毕竟不依靠本地office软件,同样还有一种方式使用jacob也可以将word转html,不过这个方式要依靠本地office,而且只能在windows平台下,不支持unix系统。
jacob使用起来还是比较简单的,如果大家需要jacob的使用方法,我会分享给大家。
关于.txt文件转html,就是使用io操作将.txt文件读取出来然后写入到html中,也不需要额外的jar包。 注意:使用poi需要注意以下几项,由于我在做这个功能的时候没有注意这个问题的存在,一直找不出原因,还请有关大牛门指正一下为什么? 1.使用office的文档.doc和.docx格式的都没有问题,但使用wps生成的word文档时,只能转.doc格式的文件,对.docx的文档转出后没有图片,得不到img属性。
2.在使用word文档转pdf格式的文件时,生成的pdf没有中文,对中文显示不是很支持。
3.在将word转成pdf时,需要把生成的html文件转化成标准的html文件,不然解析后会出现<meta>或者<img>标签不闭合的情况。
4.使用的jar包如下,都可以在maven中央仓库下载得到。
下面就直接附上代码了,希望大家有什么问题在下面评论互相交流和学习,
使用时直接调用方法即可。如果大家觉得可以请点一个赞,谢谢大家。
package com.kqco.tools;
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.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jsoup.Jsoup;
import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.pdf.BaseFont;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths; public class FileConverter {
/*
* word文件转成html文件
* sourceFilePath:源word文件路径
* targetFilePosition:转化后生成的html文件路径
*/
public void wordToHtml(String sourceFilePath, String targetFilePosition) throws Exception {
if (".docx".equals(sourceFilePath.substring(sourceFilePath.lastIndexOf(".", sourceFilePath.length())))) {
docxToHtml(sourceFilePath, targetFilePosition);
} else if (".doc".equals(sourceFilePath.substring(sourceFilePath.lastIndexOf(".", sourceFilePath.length())))) {
docToHtml(sourceFilePath, targetFilePosition);
} else {
throw new RuntimeException("文件格式不正确");
} } /*
* doc转换为html
* sourceFilePath:源word文件路径
* targetFilePosition:生成的html文件路径
*/ private void docToHtml(String sourceFilePath, String targetFilePosition) throws Exception {
final Path imagePath = Paths.get(targetFilePosition).getParent().resolve("image");
HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(sourceFilePath));
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);
// 保存图片,并返回图片的相对路径
wordToHtmlConverter.setPicturesManager(new PicturesManager() {
@Override
public String savePicture(byte[] content, PictureType pictureType, String name, float width, float height) {
try (FileOutputStream out = new FileOutputStream(imagePath.resolve(name).toString())) {
out.write(content);
} catch (Exception e) {
e.printStackTrace();
}
return "../tmp/image/" + name;
}
});
wordToHtmlConverter.processDocument(wordDocument);
Document htmlDocument = wordToHtmlConverter.getDocument();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(new File(targetFilePosition));
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);
} /*
* docx转换为html
* sourceFilePath:源word文件路径
* targetFileName:生成的html文件路径
*/ private void docxToHtml(String sourceFilePath, String targetFileName) throws Exception {
String imagePathStr = Paths.get(targetFileName).getParent().resolve("../tmp/image/word/media").toString();
OutputStreamWriter outputStreamWriter = null;
try {
XWPFDocument document = new XWPFDocument(new FileInputStream(sourceFilePath));
XHTMLOptions options = XHTMLOptions.create();
// 存放图片的文件夹
options.setExtractor(new FileImageExtractor(new File(imagePathStr)));
// html中图片的路径
options.URIResolver(new BasicURIResolver("../tmp/image/word/media"));
outputStreamWriter = new OutputStreamWriter(new FileOutputStream(targetFileName), "UTF-8");
XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
xhtmlConverter.convert(document, outputStreamWriter, options);
} finally {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
}
} /*
* txt文档转html
filePath:txt原文件路径
htmlPosition:转化后生成的html路径 */
public void txtToHtml(String filePath, String htmlPosition) {
try {
String encoding = "GBK";
File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
// 写文件
FileOutputStream fos = new FileOutputStream(new File(htmlPosition));
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
bw.write(lineTxt + "</br>");
}
bw.close();
osw.close();
fos.close();
read.close();
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
} /*
移动图片到指定路径
sourceFilePath:原始路径
targetFilePosition:移动后存放的路径
*/ public void changeImageUrl(String sourceFilePath,String targetFilePosition) throws IOException {
FileInputStream fis = new FileInputStream(sourceFilePath);
BufferedInputStream bufis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream(targetFilePosition);
BufferedOutputStream bufos = new BufferedOutputStream(fos);
int len = 0;
while ((len = bufis.read()) != -1) {
bufos.write(len);
}
bufis.close();
bufos.close();
} /*
* html文件解析成xhtml,变成标准的html文件
* f_in:源html文件路径
* outfile: 输出后xhtml的文件路径
*/
private boolean parseToXhtml(String f_in, String outfile) {
boolean bo = false;
ByteArrayOutputStream tidyOutStream = null; // 输出流
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
ByteArrayInputStream stream = null;
DataOutputStream to = null;
try {
// Reader reader;
fis = new FileInputStream(f_in);
bos = new ByteArrayOutputStream();
int ch;
while ((ch = fis.read()) != -1) {
bos.write(ch);
}
byte[] bs = bos.toByteArray();
bos.close();
String hope_gb2312 = new String(bs, "gb2312");// 注意,默认是GB2312,所以这里先转化成GB2312然后再转化成其他的。
byte[] hope_b = hope_gb2312.getBytes();
String basil = new String(hope_b, "gb2312");// 将GB2312转化成 UTF-8
stream = new ByteArrayInputStream(basil.getBytes());
tidyOutStream = new ByteArrayOutputStream();
Tidy tidy = new Tidy();
tidy.setInputEncoding("gb2312");
tidy.setQuiet(true);
tidy.setOutputEncoding("UTF-8");
tidy.setShowWarnings(true); // 不显示警告信息
tidy.setIndentContent(true);//
tidy.setSmartIndent(true);
tidy.setIndentAttributes(false);
tidy.setWraplen(1024); // 多长换行
// 输出为xhtml
tidy.setXHTML(true);
tidy.setErrout(new PrintWriter(System.out));
tidy.parse(stream, tidyOutStream);
to = new DataOutputStream(new FileOutputStream(outfile));// 将生成的xhtml写入
tidyOutStream.writeTo(to);
bo = true;
} catch (Exception ex) {
System.out.println(ex.toString());
ex.printStackTrace();
return bo;
} finally {
try {
if (to != null) {
to.close();
}
if (stream != null) {
stream.close();
}
if (fis != null) {
fis.close();
}
if (bos != null) {
bos.close();
}
if (tidyOutStream != null) {
tidyOutStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
System.gc();
}
return bo;
} /*
* xhtml文件转pdf文件
* inputFile:xhtml源文件路径
* outputFile:输出的pdf文件路径
* imagePath:图片的存放路径 例如(file:/D:/test)
*/
private 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/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 解决图片的相对路径问题
renderer.getSharedContext().setBaseURL("imagePath");
renderer.layout();
renderer.createPDF(os);
os.flush();
os.close();
return true;
} /*
* xhtml转成标准html文件
* targetHtml:要处理的html文件路径
*/
private static void standardHTML(String targetHtml) throws IOException {
File f = new File(targetHtml);
org.jsoup.nodes.Document doc = Jsoup.parse(f, "UTF-8");
doc.select("meta").removeAttr("name");
doc.select("meta").attr("content", "text/html; charset=UTF-8");
doc.select("meta").attr("http-equiv", "Content-Type");
doc.select("meta").html(" ");
doc.select("img").html(" ");
doc.select("style").attr("mce_bogus", "1");
doc.select("body").attr("font-family", "SimSun");
doc.select("html").before("<?xml version='1.0' encoding='UTF-8'>");
/*
* Jsoup只是解析,不能保存修改,所以要在这里保存修改。
*/
FileOutputStream fos = new FileOutputStream(f, false);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(doc.html());
System.out.println(doc.html());
osw.close();
}
}
word和.txt文件转html 及pdf文件, 使用poi jsoup itext心得的更多相关文章
- PDF文件怎么修改,PDF文件编辑方法
PDF文件是一种独特的文件,在日常办公中已经成为我们使用最广泛的电子文档格式.在使用PDF文件中会遇到PDF文件有错区的时候,再从新制作一个PDF文件会比较麻烦,只能通过工具来对PDF文件进行修改,这 ...
- 轻松将CAD文件转为加密的PDF文件
对于从事设计相关工作的朋友来说,CAD肯定再熟悉不过了.一些有特殊要求的CAD文件,需要将其转换成为PDF文件以方便保存.传输.打印,同时还得保证设计图稿的安全性,所以将CAD文件直接转为加密的PDF ...
- C#将制定文件夹下的PDF文件合并成一个并输出至指定路径
/// <summary> /// 将源路径下的PDF合并至目标路径下 /// </summary> /// <param name="SourcePath&q ...
- 【文件】java生成PDF文件
package test; import java.awt.Color; import java.io.FileOutputStream; import org.junit.Test; import ...
- 递归找到多级文件夹中所有pdf文件的py程序
因个人需要,写了一个可以递归找到多级文件夹中所有pdf的小程序,发布出来供有需要的人参考或使用. import os import re import shutil from os.path impo ...
- 利用pdfJS实现以读取文件流方式在线展示pdf文件
第一步:下载源码https://github.com/mozilla/pdf.js 第二步:构建PDF.js 第三步:修改viewer.js var DEFAULT_URL = 'compressed ...
- 批量转换word文档到pdf文件
最近在整理每周的工作记录.因为每周的工作记录大都是单独的word文件,有时候忘记了也不容易找出来,一个个打开查找太费劲,因此想着把这些文件通过word2016的另存为功能转换为pdf,然后永Acrob ...
- C# 将多个office文件转换及合并为一个PDF文件
PDF文件介绍 PDF(Portable Document Format )文件源于20世纪90年代初期,如今早已成为了一种最流行的的文件格式之一.因为PDF文件有很多优点: 支持跨平台和跨设备共享 ...
- Pdf File Writer 中文应用(PDF文件编写器C#类库)
该文由小居工作室(QQ:2482052910) 翻译并提供解答支持,原文地址:Pdf File Writer 中文应用(PDF文件编写器C#类库):http://www.cnblogs.com/ ...
随机推荐
- single number i && ii && iii
Problem statement Elementary knowledge: There is a popular question when I seeked my job at Beijing: ...
- zoj 1013 Great Equipment DP
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=13 很经典的一个DP的题目 定义dp[i][num1][num2]表示 ...
- 2017最新最稳定的彩票源码PHP+mysql 新增彩种+全新界面
网站后台管理系统:新闻资讯系统 用户管理系统用户登录日志彩种规则说明玩法时间设置彩票期号管理足球对阵管理彩票方案撤单彩票出票管理开奖号码管理彩票方案查询彩票中奖查询 彩票追号查询服务支持中心财务中心管 ...
- 【JAVAWEB学习笔记】13_servlet
JavaWeb核心之Servlet 教学目标 案例一.完成用户登录功能 案例二.记录成功登录系统的人次 一.Servlet简介 1.什么是Servlet Servlet 运行在服务端的Java小程序, ...
- OpenCV探索之路(七):霍夫变换
我们如何在图像中快速识别出其中的圆和直线?一个非常有效的方法就是霍夫变换,它是图像中识别各种几何形状的基本算法之一. 霍夫线变换 霍夫线变换是一种在图像中寻找直线的方法.OpenCV中支持三种霍夫线变 ...
- bootstrap学习笔记之为导航条添加标题、二级菜单及状态 http://www.imooc.com/code/3120
为导航条添加标题.二级菜单及状态 加入导航条标题 在Web页面制作中,常常在菜单前面都会有一个标题(文字字号比其它文字稍大一些),其实在Bootstrap框架也为大家做了这方面考虑,其通过" ...
- 面试(4)-spring-Spring面试题和答案
1:69道Spring面试题和答案 转自:http://ifeve.com/spring-interview-questions-and-answers/ 目录 Spring 概述 依赖注入 Spri ...
- SG函数和SG定理【详解】
在介绍SG函数和SG定理之前我们先介绍介绍必胜点与必败点吧. 必胜点和必败点的概念: P点:必败点,换而言之,就是谁处于此位置,则在双方操作正确的情况下必败. N点:必胜点 ...
- Java经典编程题50道之十二
企业发放的奖金根据利润提成:利润(I)低于或等于10万元时,奖金可提10%:利润高于10万元,低于20万元时,低于10万元的部分按10%提成, 高于10万元的部分 ,可提成7.5%:20万到40万之间 ...
- java7增强的try语句关闭资源
java7增强的try语句关闭资源 传统的关闭资源方式 import java.io.FileInputStream; import java.io.FileOutputStream; import ...