2)将PDF文件通过流的形式输送到客户端的缓存。这样做的好处是不会在服务器上留下任何“遗迹”。
i)直接通过JSP页面生成
<%@ page import="java.io.*,java.awt.Color,com.lowagie.text.*,com.lowagie.text.pdf.*"%> <% response.setContentType( "application/pdf" ); Document document = new Document(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); PdfWriter writer=PdfWriter.getInstance( document, buffer ); document.open(); document.add(new Paragraph("Hello World")); document.close(); DataOutput output = new DataOutputStream( response.getOutputStream() ); byte[] bytes = buffer.toByteArray(); response.setContentLength(bytes.length); for( int i = 0; i < bytes.length; i++ ) { output.writeByte( bytes[i] ); } %>
ii)通过Servlet生成
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import com.lowagie.text.*; import com.lowagie.text.pdf.*; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException { Document document = new Document(PageSize.A4, 36,36,36,36); ByteArrayOutputStream ba = new ByteArrayOutputStream(); try { PdfWriter writer = PdfWriter.getInstance(document, ba); document.open(); document.add(new Paragraph("Hello World")); } catch(DocumentException de) { de.printStackTrace(); System.err.println("A Document error:" +de.getMessage()); } document.close(); response.setContentType("application/pdf"); response.setContentLength(ba.size()); ServletOutputStream out = response.getOutputStream(); ba.writeTo(out); out.flush(); }
我在项目中采用的是第二种方法。本文的源码在我的tomcat4上面都是调试通过的。希望可以给大家带来方便。 |