iText和flying saucer结合生成pdf的技术

下面是我自己利用flying saucer技术生成pdf文档的实现代码:

Servlet方式:

html代码:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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>Html2PdfServlet</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">
	-->
  </head>
  
  <body>
    <form action="http://localhost:8081/createpdf/servlet/html2PdfServlet" method="get" >
	<table>
		<tr>
			<td>
				<input type="text" id="username" name="username" value="" />
			</td>
			<td>
				<input type="submit" id="submit" name="submit" value="submit" />
			</td>
		</tr>
	</table>
	</form>
  </body>
</html>


 

java代码:

package com.test;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.pdf.BaseFont;

public class Html2PdfServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		//pageContext.getServletContext().getRealPath("/")
		ServletContext sc = request.getSession().getServletContext();
		String path = sc.getRealPath(""); //值为D:\apache-tomcat-6.0.26\webapps\createpdf
		System.out.println("原path: " + path);
		//把路径中的反斜杠转成正斜杠
		path = path.replaceAll("\\\\", "/"); //值为D:/apache-tomcat-6.0.26/webapps/createpdf
		System.out.println(path);
		
		String path2 = sc.getRealPath("/");
		System.out.println("path2: " + path2);
		
		System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
		
		System.out.println("request.getRequestURI: " + request.getRequestURI());
		//获取使用的端口号
		System.out.println(request.getLocalPort());
		
		String path3 = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path3+"/";
		
		System.out.println("basepath: " + basePath);
		
		
		response.setContentType("application/pdf");
		//response.setHeader("Content-Disposition", "attachment; filename=WebReport.pdf");
		response.setHeader("Content-Disposition", "inline; filename=WebReport.pdf");
        
		StringBuffer html = new StringBuffer();
		//组装成符合W3C标准的html文件,否则不能正确解析
		html.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
		html.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">")
		.append("<head>")
		.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />")
		.append("<style type=\"text/css\" mce_bogus=\"1\">body {font-family: SimSun;}</style>")
		.append("<style type=\"text/css\">img {width: 700px;}</style>")
		.append("</head>")
		.append("<body>");
		
		html.append("<center><h1>统计报表</h1></center>");
		html.append("<center>");
		html.append("<img src=\"images/chart.jpg\"/>");
		html.append("</center>");
		
		html.append("</body></html>");
        
        // parse our markup into an xml Document
        try {
        	ITextRenderer renderer = new ITextRenderer();
        	/**
        	 * 引入了新的jar包,不用再导入字体了
        	ITextFontResolver fontResolver = renderer.getFontResolver();
        	fontResolver.addFont("C:/Windows/fonts/simsun.ttc",
        			BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        	*/
            renderer.setDocumentFromString(html.toString());
            // 解决图片的相对路径问题
    		//renderer.getSharedContext().setBaseURL("file:/C:/Documents and Settings/dashan.yin/workspace/createpdf/WebRoot/images");
            //renderer.getSharedContext().setBaseURL("file:/D:/apache-tomcat-6.0.26/webapps/createpdf/images");
    		renderer.getSharedContext().setBaseURL("file:/" + path + "/images");
    		renderer.layout();
            OutputStream os = response.getOutputStream();
            renderer.createPDF(os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


Struts1形式:

html代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="Config.application.*" %>
<%@ include file="/pages/common/global.jsp" %>
<%@ taglib uri="/WEB-INF/tlds/birt.tld" prefix="birt"%>
<script type="text/javascript">
	function interactivity() {
		var url = contextName + "/viewAction.do?method=viewLinkResult";
		var startDate_s = $("#startDate_s").val();
		var endDate_s = $("#endDate_s").val();
		var serviceInstance = $("#serviceInstance").val();
		var serviceInstance = encodeURIComponent(serviceInstance);
		var status = $("#status").val();
		if(startDate_s){
			url += "&startDate_s=" + startDate_s;
		}
		if(endDate_s){
			url += "&endDate_s=" + endDate_s;
		}
		if(serviceInstance){
			url += "&serviceInstance=" + serviceInstance;
		}
		if(status){
			url += "&status=" + status;
		}
		url += "&random=" + Math.random();
		//alert(url);
		retrieveURL(url,'viewResult');
		//tipsWindown("详细信息","url:get?" + url,"800","700","true","","true","text");
	}
	
	
	function viewreturn() {
		var url = contextName + "/viewAction.do?method=viewReturnResult";
		//时间参数设空
		document.getElementById("startDate_s").value = "";
		document.getElementById("endDate_s").value = "";
		url += "&random=" + Math.random();
		retrieveURL(url,'viewResult');
		//tipsWindown("详细信息","url:get?" + url,"800","700","true","","true","text");
	}
	
</script>

<html:form action="/viewAction.do?method=viewExportPDF">
	<table class="form_t" style="width:100%">
		<tr>
			<td>
				<input type="submit" id="submit" name="submit" value="导出" class="button4C"/>
			</td>
		</tr>
	</table>
</html:form>
<html:form action="/viewAction.do?method=viewResult"  >
	<table class="form_t" style="width:100%">
		<tr>
			<th class="tablelogo" colspan="3">
				统计时间
			</th>
			
		</tr>
			<tr>
				<td style="width: 175px; text-align: right;">
					开始时间
				</td>
				<td> 
					<input type="text" name="startDate_s" id="startDate_s"
						class="Wdate"
						οnclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',maxDate:'#F{$dp.$D(\'endDate_s\')||\'%y-%M-%d %H:{%m-1}:%s\'}'})" />
				</td>
				<td>
					 
					<input type="hidden" name="serviceInstance" id="serviceInstance" value=""/>
					<input type="hidden" name="status" id="status" value=""/>
				</td>
			</tr>
			<tr>
				<td style="width: 175px; text-align: right;">
					结束时间
				</td>
				<td> 
					<input type="text" name="endDate_s" id="endDate_s" class="Wdate"
						οnclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',minDate:'#F{$dp.$D(\'startDate_s\')}',maxDate:'%y-%M-%d %H:%m:%s'})" />
				</td>
				<td>
					 
				</td>
			</tr>
		<tr>
			<td style="padding-left: 175px;" colspan="2">
				<input type="button" value="查看" class="button4C"
					οnclick="javascript:viewForm(this.form,'viewResult');" />
				<input type="button" value="返回" class="button4C"
					οnclick="javascript:viewreturn();" />
			</td>
			<td> 
			</td>
		</tr>
	</table>
</html:form>
<table width="100%">
	<tr>
		<td id=
  • 4
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 28
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 28
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值