使用itext生成pdf
如果每次都在服务端生成一个PDF文件给用户,不仅麻烦,而且浪费服务器资源,最好的方法就是以二进制流的形式输送到客户端。
1)JSP输出:
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] );
}
%>
2)servlet输出,稍微改造下就可以使用在struts中:
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();
}