The important thing in life is to have a great aim , and the determination

常用链接

统计

IT技术链接

保险相关

友情链接

基金知识

生活相关

最新评论

iText JSP中生成PDF(入门)

iText简介

  iText是一个开放源码的Java类库,可以用来方便地生成PDF文件。大家通过访问http://sourceforge.net/project/showfiles.php?group_id=15255&release_id=167948下载最新版本的类库,下载完成之后会得到一个.jar包,把这个包加入JDK的classpath即可使用。如果生成的PDF文件中需要出现中文、日文、韩文字符,则还需要通过访问http://itext.sourceforge.net/downloads/iTextAsian.jar下载iTextAsian.jar包。

  关于iText类库的使用,http://www.lowagie.com/iText/tutorial/index.html有比较详细的教程。该教程从入门开始,比较系统地介绍了在PDF文件中放入文字、图片、表格等的方法和技巧。读完这片教程,大致就可以做一些从简单到复杂的PDF文件了。不过,试图通过教程解决在生成PDF文件过程中遇到的所有困难无疑是一种奢望。所以,阅读iText的api文档显得非常重要。读者在下载类库的同时,也可以下载类库的文档。

可参考资料 :  

http://dev.csdn.net/article/62/62119.shtm       http://myowndream.blog.com.cn/archives/2007/2089386.shtml
http://tag.csdn.net/tag/itext.xml

一  HelloWorld实例

以下是上述教程中一个最简单的例子,这个例子刻画了通过iText生成PDF文件的一般程序框架。读者只需要在document.open();和document.close();两条语句中间加入自己希望放在PDF文件中的内容即可。该例子只在PDF文件中加了“Hello World“一行文字。

Document document = new Document();

try{
    PdfWriter.getInstance(document, new FileOutputStream ("Chap0101.pdf"));

    document.open();

    document.add(new Paragraph("Hello World"));
}catch(DocumentException de){
     System.err.println(de.getMessage());
}catch(IOException ioe){
     System.err.println(ioe.getMessage());
}
 
document.close();

可以看到一个PDF文件的输出,总共只需要5个步骤
a.创建一个Document实例
  Document document = new Document();
b.将Document实例和文件输出流用PdfWriter类绑定在一起
  PdfWriter.getInstance(document,new FileOutputStream("HelloWorld.pdf"));
c.打开文档
  document.open();
d.在文档中添加文字
  document.add(new Paragraph("Hello World"));
e.关闭文档
  document.close();
这样5个步骤,就可以生成一个PDF文档了。

然而在PDF中指定文字、图画、表格的位置是一件非常麻烦的事情。除了不断地在程序中修改位置、然后运行程序、生成PDF文件、观察元素在PDF中的位置是否合理这样的过程以外,似乎还没有其它更好的方法。

二。如何使用jsp、servlet输出iText生成的pdf?
   如果每次都在服务端生成一个PDF文件给用户,不仅麻烦,而且浪费服务器资源,最好的方法就是以二进制流的形式输送到客户端。
1)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] );
 }

%>

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();
}

三。如何输出中文?
     首先需要下载iTextAsian.jar包,可以到iText的主站上下,ireport也是需要这个包的。然后定义中文字体:

    private static final Font getChineseFont() {
         Font FontChinese
= null;
        
try {
             BaseFont bfChinese
= BaseFont.createFont("STSong-Light",
                    
"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
             FontChinese
= new Font(bfChinese, 12, Font.NORMAL);
         }
catch (DocumentException de) {
             System.err.println(de.getMessage());
         }
catch (IOException ioe) {
             System.err.println(ioe.getMessage());
         }
        
return FontChinese;
     }


我将产生中文字体封装在方法内,自定义一个段落PDFParagraph继承自Paragraph,默认使用中文字体:

class PDFParagraph extends Paragraph {
        
public PDFParagraph(String content) {
            
super(content, getChineseFont());
         }
     }


使用的时候就可以简化了:

Paragraph par = new PDFParagraph("你好");


四。如何设置PDF横向显示和打印?

Rectangle rectPageSize = new Rectangle(PageSize.A4);// 定义A4页面大小
rectPageSize = rectPageSize.rotate();// 加上这句可以实现A4页面的横置
Document doc = new Document(rectPageSize,50,50,50,50);//4个参数,设置了页面的4个边距


五。如何设置跨行和跨列?

使用PdfPTable和PdfPCell 是没办法实现跨行的,只能跨列,要跨行使用com.lowagie.text.Table和com.lowagie.text.Cell类,Cell类有两个方法:setRowspan()和setColspan()。

六。如何设置单元格边界宽度?

Cell类的系列setBorderWidthXXXX()方法,比如setBorderWidthTop(),setBorderWidthRight()等

七。如何设置表头?
希望每一页都有表头,可以通过设置表头来实现。对于PdfPTable类来说,可以这样设置:

PdfPTable table = new PdfPTable(3);
table.setHeaderRows(
2); // 设置了头两行为表格头


而对于om.lowagie.text.Table类,需要在添加完所有表头的单元格后加上一句代码:

table.endHeaders();


八。如何设置列宽?

Table table = new Table(8);
float[] widths = { 0.10f, 0.15f, 0.21f, 0.22f, 0.08f, 0.08f, 0.10f,
                    
0.06f };
table.setWidths(widths);


上面的代码设置了一个有8列的表格,通过一个float数组设置列宽,这里是百分比。

九。单元格内段落文字居中和换行?
居中通过Cell类来设置,一开始我以为设置段落对齐就可以了,没想到是需要设置单元格:

cell.setHorizontalAlignment(Element.ALIGN_CENTER);



转义符\n实现。在我的这个应用中,因为数据库取出的数据是为了显示在html上的,所以有很多<br>标签,可以使用正则表达式替换成"\n"

"<br>1.测试<br>2.测试2".replaceAll("<br>|</br>","\n");


十。如何显示页码?
复杂的页码显示和水印添加,需要使用到PdfPageEventHelper、PdfTemplate等辅助类,具体的例子参见iText的文档,如果只是为了简单的显示页数,可以使用下面的代码:

             HeaderFooter footer = new HeaderFooter(new Phrase("页码:",getChineseFont()), true);
             footer.setBorder(Rectangle.NO_BORDER);
             document.setFooter(footer);
             document.open();

你可能注意到了,添加footer需要在document.open之前。

posted on 2009-08-12 09:48 鸿雁 阅读(2327) 评论(0)  编辑  收藏 所属分类: IT技术相关


只有注册用户登录后才能发表评论。


网站导航: