java实现页面另存为word

第一篇文章已经记下了我的点击按钮页面,这儿只写一下连接页面就可以了。
点击生成word时,连接到了creatWord.jsp页面:
<%@ page language="java" import="java.util.*,java.net.*" pageEncoding="utf-8"%>
<%@page contentType="application/vnd.ms-word"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'creatWord.jsp' starting page</title>
   
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<%
    String fileName = "结题报告.doc"; 
    //对中文文件名编码 
    fileName = URLEncoder.encode(fileName, "utf-8"); 
    byte[] yte = fileName.getBytes("GB2312"); 
    String unicoStr = new String(yte, "utf-8");
    response.setHeader("Content-disposition", "attachment; filename=" + unicoStr);     
%>
  </head>
 
  <body>
    中秋快乐!
  </body>
</html>
就可以生成word文档了,里面的内容是中秋快乐!
**********************************************
生成pdf的探索过程有些复杂,只是测试的一个用例,注意的几点:
1.在要生成的html页面的body中使用你设置的字体才可以实现中文的输出
<body style="font-family:'Arial Unicode MS'"> 
2.如果计算机上没有C:/Windows/Fonts/arialuni.ttf字体,可以联网安装
ITextRenderTest.java文件:
package testPdf;

import java.io.File;
import java.io.FileOutputStream; 
import java.io.OutputStream; 

import javax.servlet.http.HttpServletRequest;
 
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.pdf.BaseFont;
public class ITextRenderTest {

    public static void main(String[] args) throws Exception { 
        String outputFile = "e:/firstdoc.pdf"; 
        OutputStream os = new FileOutputStream(outputFile); 
        ITextRenderer renderer = new ITextRenderer(); 
 

String inputFile  = "E:/Myeclipse_space_data/11/WebRoot/html/test.html";  
                   
        String url = new File( inputFile ).toURI().toURL().toString();    
        System.out.print(url);
        /*String url="<html><head>aa</head><body>ssss你好ssss</body></html>";*/
        renderer.setDocument(url); 
    
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont("C:/Windows/Fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        // 解决图片的相对路径问题 
        renderer.getSharedContext().setBaseURL("file:/e:/"); 
 
        renderer.layout(); 
        renderer.createPDF(os); 
 
        os.close(); 
        System.out.println("生成成功!"); 
    } 
}

你可能感兴趣的:(java 生成pdf word)