容易遇到的问题之word07问题
BlogHandler.Java
public class BlogHandler extends AppBaseAction{
private Configuration configuration = null;
public Map<String,Object> dataMap = new HashMap<String,Object>();//填充的数据
public final static String TITLE = "title";
public final static String CATEGORY = "category";
public final static String CLASSIFYNAME = "classifyName";
public final static String CONTENT = "content";
public final static String ALLTAGNAME = "allTagName";
public BlogHandler() {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}
public void createDoc(Writer out) {
//设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
//模板
configuration.setClassForTemplateLoading(this.getClass(), "/com/yuqiaotech/pms/util");
Template t=null;
try {
//test.ftl为要装载的模板
t = configuration.getTemplate("blog.ftl");
t.process(dataMap, out);
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//模板
private String generateTemp(String str) {
configuration.setClassForTemplateLoading(this.getClass(), "/com/yuqiaotech/pms/util");
Template t = null;
String htmlStr = "";
try {
t = configuration.getTemplate(str);
StringWriter stringWriter = new StringWriter();
BufferedWriter writer = new BufferedWriter(stringWriter);
t.setEncoding("UTF-8");
t.process(dataMap, writer);
htmlStr = stringWriter.toString();
writer.flush();
writer.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return htmlStr;
}
/*
* <img/>标签src替换为加上域名的链接
*/
public String exchangeImg(String content){
String regex = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(content);
String src = "";
String scheme = getRequest().getScheme() + "://"
+ getRequest().getServerName() + ":" + getRequest().getServerPort();
//避免重复的图片链接
HashSet<String> set = new HashSet<String>();
while (matcher.find()) {
src = matcher.group(1);
set.add(src);
}
for(String str : set) {
if(str.contains(scheme)){
continue;
}
content = content.replace(str, scheme+str);
}
return content;
}
/*
* 去除fontfamily默认为宋体字
*
*/
public String setFamily(String content){
String regex = "font-family.*?;";
content = content.replaceAll(regex, "");
return content;
}
/*
* <img/>
* <img/> ==>
* <v:shape style=3D'width:352.5pt;height:318.75pt'>
<v:imagedata src=3D"file8676.files/image002.jpg" o:title=3D"logo"/>
</v:shape>
*/
public String exImageToD(String content) throws FileNotFoundException, IOException {
String regex = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
content = content.replaceAll("(style=)","$13D");
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(content);
String src = "";
String[] sp;
File file = null;
while (matcher.find()){
src = matcher.group(1);
sp = src.split("/");
file = new File(getRequest().getRealPath("/")+src.replace(getRequest().getContextPath(), ""));
if(isExitsImage(file)) {
content = content.replaceFirst(regex, appendShap(getImageSize(file),sp[sp.length-1]));
}
}
return content;
}
//根据内容获取图片链接
public List<String> getImageSrc(String content) throws FileNotFoundException, IOException {
String regex = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(content);
String src = "";
List<String> srcs = new ArrayList<String>();
while (matcher.find()){
src = matcher.group(1);
srcs.add(src);
}
return srcs;
}
//获得图片的base64码
public String getImageBase(String src) {
File file = new File(getRequest().getRealPath("/")+src.replace(getRequest().getContextPath(), ""));
if(!isExitsImage(file)) {
return "";
}
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
public boolean isExitsImage(File file) {
return file.exists();
}
private String appendShap(BufferedImage image,String str){
String shape = "<v:shape type=3D\"#_x0000_t75\" style=3D'width:" + image.getWidth() + ";height:" + image.getHeight() + "'>"
+ "<v:imagedata src=3D\"file8676.files/" + str + " \"o:title=3D" + str + "\"/>"
+ "</v:shape>";
return shape;
}
private BufferedImage getImageSize(File image) throws FileNotFoundException, IOException {
return ImageIO.read(new FileInputStream(image));
}
这里面要注意的一个问题是type=3D\”#_x0000_t75\ 这是一定要加上的不然在2003中能看到图片,到了2007中就看不到了
action
public void exportBlog() throws UnsupportedEncodingException {
String title = article.getTitle();
getResponse().addHeader(
“Content-Disposition”,
“attachment;filename=”
+ new String(title.getBytes(“GBK”), “iso-8859-1”)
+ “.doc”);
getResponse().setContentType(“application/x-download”);// 设置为下载application/x-download
getResponse().setCharacterEncoding(“utf-8”);
PrintWriter output = null;
try {
output = getResponse().getWriter();
BlogHandler handler = new BlogHandler();
handler.dataMap.put(BlogHandler.TITLE, article.getTitle());
handler.dataMap.put(BlogHandler.CATEGORY, article.getCategory());
handler.dataMap.put(BlogHandler.CLASSIFYNAME,
article.getClassifyName());
handler.dataMap.put(BlogHandler.CONTENT,
handler.exImageToD(article.getContent()));
String hql = “select tagName from TagMark where entityType=’Blog’ and relateEntityId = ”
+ articleId;
List alltagName = articleManager.find(hql);
if(alltagName.size() > 0){
handler.dataMap.put(BlogHandler.ALLTAGNAME, alltagName);
}
Map<String, String> imageMap = null;
List<Map<String, String>> list = new ArrayList<Map<String,String>>();
String[] sp = null;
for(String src : srcs){
sp = src.split("/");
imageMap = new HashMap<String, String>();
imageMap.put("imageName", sp[sp.length-1]);
imageMap.put("imageType", sp[sp.length-1].split("\\.")[1]);
imageMap.put("imageBase", handler.getImageBase(src));
list.add(imageMap);
}
handler.dataMap.put("imageList", list);
handler.createDoc(output);
} catch (IOException e) {
e.printStackTrace();
} finally {
output.flush();
output.close();
}
}
应该代码很明确了,我再简单说一下思路,首先从数据库中获取带css样式的content,并且content包含img,然后利用freemark生成预定的模板,将数据填充进去,而mht是携带base64格式图片的,所以这里必须进行一个转码,然后就可以生成word了,思路应该挺简单的,就是需要对图片链接进行一个处理就行了。
上一篇: VBA:word表格导入excel