您的位置:首页 > 编程语言 > Java开发

用java在网页中生成pdf文档

2008-02-19 14:55 543 查看
<%@
page import="java.io.*,
com.lowagie.text.*,
com.lowagie.text.pdf.*"
%><%
//
// Template JSP file for iText
// by Tal Liron
//

response.setContentType( "application/pdf" );

// step 1: creation of a document-object
Document document = new Document();

// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a temporary buffer
//String path1 = request.getServletPath();
//String path2 = request.getPathInfo();
//String path3 = request.getRequestURI();
//System.out.println(path1+" "+path2+" "+path3);
//下面4行是我读pdf文档的路径
String filepath = request.getParameter("filepath");
char sub1=filepath.charAt(filepath.length()-5);
char sub2=filepath.charAt(filepath.length()-6);
String path="/docstore/"+String.valueOf(sub2)+"/"+String.valueOf(sub1);

FileInputStream buffer = new FileInputStream(path+"/"+filepath.trim());

//ByteArrayOutputStream buffer = new ByteArrayOutputStream();
//PdfWriter.getInstance(document, buffer );

// step 3: we open the document
document.open();

// step 4: we add a paragraph to the document
document.add(new Paragraph("Hello World"));

// step 5: we close the document
document.close();

// step 6: we output the writer as bytes to the response output
DataOutput output = new DataOutputStream(response.getOutputStream());
int leng = buffer.available();
//byte[] temp = new byte[buffer.available()];
byte []temp = new byte[leng];
buffer.read(temp);
response.setContentLength(leng);
for( int i = 0; i < temp.length; i++ )
{ output.writeByte( temp[i] ); }

%>

两点可以用到这个页面
1.用它直接生成pdf文档,这里只是能够简单的生成一个页面。没有页面样式。
用的工具类是itext,这里只是简单入门。http://itextdocs.lowagie.com/tutorial/这是较详细的说明文档,不过是英文的,遗憾。
2.就是用读pdf文件,再显示出来。其实显示pdf文件很简单。但不在web路径下,或在其他盘符。就可以用我上面的代码。也很简单。同时要把import 的itext类注释。

不过itext 的作者不推存使用jsp去生成pdf,而是使用servlet,他说jsp有时出现问题。抱歉,我没仔细看。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: