`

Itext

    博客分类:
  • web
阅读更多
引用


package com.zhaipuhong.j2se.pdf;  
 
import java.io.IOException;  
import java.util.Date;  
 
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
 
import com.lowagie.text.Document;  
import com.lowagie.text.DocumentException;  
import com.lowagie.text.Paragraph;  
import com.lowagie.text.pdf.PdfWriter;  
import com.lowagie.text.pdf.BaseFont;  
import com.lowagie.text.pdf.PdfPTable;  
import com.lowagie.text.pdf.PdfPCell;  
import java.awt.Color;  
 
public class PdfServlet extends HttpServlet {  
 
    private static final long serialVersionUID = -6033026500372479591L;  
 
    public void doGet (HttpServletRequest request, HttpServletResponse response)  
    throws IOException, ServletException {  
 
        // step 1  建立文档对象  
        Document document = new Document();  
        try {  
                //设置文档相应类型  
                response.setContentType("application/pdf");  
                PdfWriter.getInstance(document, response.getOutputStream());  
 
 
                // step 3  打开文档  
                document.open();  
                //支持中文  
                BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
                com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL);  
                Paragraph pragraph=new Paragraph("你好", FontChinese);  
 
 
                // step 4  向文档中添加内容  
                document.add(pragraph);  
                document.add(new Paragraph(" Hello World !"));  
                document.add(new Paragraph("Date 时间"+new Date().toString()));  
                document.add(new Paragraph(new Date().toString()));  
                document.add(new Paragraph(new Date().toString()));  
 
 
 
                PdfPTable table = new PdfPTable(3);  
                        PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3"));  
                        cell.setColspan(3);  
                        table.addCell(cell);  
                        table.addCell("1.1");  
                        table.addCell("2.1");  
                        table.addCell("3.1");  
                        table.addCell("1.2");  
                        table.addCell("2.2");  
                        table.addCell("3.2");  
                        cell = new PdfPCell(new Paragraph("cell test1"));  
                        cell.setBorderColor(new Color(255, 0, 0));  
                        table.addCell(cell);  
                        cell = new PdfPCell(new Paragraph("cell test2"));  
                        cell.setColspan(2);  
                        cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));  
                        table.addCell(cell);  
                        document.add(table);  
 
        }catch(DocumentException de) {  
            de.printStackTrace();  
            System.err.println("document: " + de.getMessage());  
        }  
 
        // step 5: 关闭文档对象  
        document.close();  
    }  
 
    //支持中文  
    public Paragraph getChineseString(String chineseString){  
      Paragraph pragraph=null;  
      BaseFont bfChinese = null;  
      try {  
        bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",  
                                        BaseFont.NOT_EMBEDDED);  
        com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese,  
            12, com.lowagie.text.Font.NORMAL);  
         pragraph = new Paragraph(chineseString, FontChinese);  
      }  
      catch (Exception ex) {  
        ex.printStackTrace();  
      }  
      return pragraph;  
    }  




引用


iText经验总结

admin 发表于: 2008-6-05 14:45 来源: pdf之家
因为前些日子在一个项目中用到了iText,稍有收获,便总结于此,以供他人所需。

iText是一个比较底层的pdf库,很多项目的pdf操作都是以它为基础的。像spring,以及另一个比较有名的报表工具jasperreports。简单的pdf报表输出用它比较合适,比较复杂的话使用起来就比较困难了,你要手工编写太多的代码。

比较好的是iText网站上提供相当多的示例代码,比较容易入门。我这里只说一些在它的文档里并没有直接讲到的东西。

1 关于Document

Document的几种构造函数:
public Document();
public Document(Rectangle pageSize);
public Document(Rectangle pageSize,
int marginLeft,
int marginRight,
int marginTop,
int marginBottom);
下面两种比较有用,如果是你想定义纸张大小和边缘的时候。对于Margin,iText上提到“You can also change the margins while you are adding content. Note that the changes will only be noticed on the NEXT page. If you want the margins mirrored (odd and even pages), you can do this with this method: setMarginMirroring(true). ”不过,对于table似乎并不好使。table并不会了理会你设定的margin,如果想改变它的magin还是需要去改变它的宽度(setWidth)。

2 pdf表单

使用PdfStamper是可以填充pdf表单的,这样就给出了一种很好的报表生成思路。
word制作报表样式-->acrobat转pdf-->itext填充数据-->输出pdf
这做非常简单,因为可以比较容易的控制pdf的样式。我对于Java的报表工具了解的并不多,不过在jasperreports,即使用GUI工具做一个样式比较复杂的报表也不是怎么容易。比如有那种斜线的表头,比较花哨的嵌套表格。这样的情况还是比较多见的,客户不会关系你实现起来是否困难。不过想要使用这种方式也有不足的地方。首先是acrobat把word转化成pdf的时候,格式总是保持不好,特别的是字体。然后是文件的体积这样生成的pdf会比直接用iText生成的pdf文件大很多,acrobat在pdf里加入了太多无用的信息。初次使用iText填充Adobe Designer生成的pdf表单时会有点小麻烦。在Designer中设计了一个name的text文本框的绑定名为name。照着iText中例子使用使用PdfStamper的setField方法去这样写form.setField("name", "XXXX");并不会成功。原因是Adobe Designer生成的表单名都是具有层次的,它可能是这个样子form1[0].#subform[0].name[0]。不过我们可以用一个方法把它们列出来,只要做一次就知道结构了,可以使用类似下面的代码:
PdfReader reader = new PdfReader("form.pdf");
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream("registered_flat.pdf"));
AcroFields form = stamp.getAcroFields();
for (Iterator it = form.getFields().keySet().iterator(); it
.hasNext();) {
System.out.println(it.next());
}
如果直接用iText编程生成的表单就不会有这样的问题,设定的什么名字就是什么名字。

3 表单元素

pdf并不像html那样具有良好清晰的结构,而是一个有层次的文档类型。在它的maillist里,作者说明了iText虽然可以操作现存的pdf文件但是没办法去还原它的结构的。没办法像html一样,能从一个pdf文件获得一个清晰的“源文件”的。关于层次,可以从iText上得到详细的讲述,获取去看看pdf规范。表单和普通文本是不在一个层上的。没办法适用对待文本表各一样把它们简单的add进Document对象。获取一个cb直接去用绝对定位的方法可以加入表单元素,不过很多的时候因为排版并不能那么简单的去做。就是在html中布局一样可以使用表格定位。想把一个表单元素加入cell,要借助cell的setCellEvent方法。以一个checkbox为例。新建一个类CheckBoxForm,实现PdfPCellEvent接口。需要实现一个cellLayout的方法。
  public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
position可以好好利用,它包含当前cell的位置信息,你可以用它来确定自己checkbox的位置。
position.top()-position.bottom()就能得到高position.right()-position.left()可以得到长,如果需要这两个值得花可以如此计算。下面的代码就是定义一个宽度为a的checkbox的rectangle 。它在cell中水平居中,垂直也居中。
    float bo = (position.top()-position.bottom()-a)/2;
    float ao = (position.right()-position.left()-a)/2;    
    Rectangle rectangle = new Rectangle(position.left() + ao, position
          .bottom() + bo, position.left() +ao+ a, position.bottom()+ bo + a);
然后把它加入Document
    RadioCheckField tf = new RadioCheckField(writer, rectangle, fieldname,
          "f");
    tf.setCheckType(RadioCheckField.TYPE_SQUARE);
    tf.setBorderWidth(1);
    tf.setBorderColor(Color.black);
    tf.setBackgroundColor(Color.white);      
    try {
        PdfFormField field = tf.getCheckField();        
        writer.addAnnotation(field);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
其它的元素与此类似。

4 PdfPTable和Table

说不上哪种更好用,有时候不能不使用PdfPTable。可惜它只有setColspan方法,没有setRowspan。嵌套的时候也有区别,PdfPTable是用addcell()加入嵌套表的,table则有一个更明了的方法insertTable()。PdfPTable想进行设置border之类的操作要先获得一个默认cell,
pdfPTableName.getDefaultCell().setBorder(Rectangle.NO_BORDER);//设置无框的表
另外在PdfPTable中,一些修饰属性会因为设置的时机不正确而没有效果。如,适用cell的构造函数加入了文本,在cell的setVerticalAlignment()fangfa去设定垂直对齐方式就不会有效。还有一个有意思的不同是table默认外边框是加粗的,而PdfPTable则一样粗细。

5 字体

iText的例子有很多足够用,给出一些pdf的字体名称和编码,如果想使用内嵌字体的话。
语言 PDF 字体名
简体中文 STSong-Light
繁体中文 MHei-Medium
MSung-Light
日语 HeiseiKakuGo-W5
HeiseiMin-W3
韩语 HYGoThic-Medium
HYSMyeongJo-Medium

字符集 编码
简体中文 UniGB-UCS2-H
UniGB-UCS2-V
繁体中文 UniCNS-UCS2-H
UniCNS-UCS2-V
日语 UniJIS-UCS2-H
UniJIS-UCS2-V
UniJIS-UCS2-HW-H
UniJIS-UCS2-HW-V
韩语 UniKS-UCS2-H
UniKS-UCS2-H
必须要有Asian的包才可以用,也可以使用TrueType字体。
分享到:
评论
1 楼 zhl0475 2010-11-09  
呵呵~ 是个比较老的贴了!感谢楼主

相关推荐

    itext-2.1.7-API文档-中文版.zip

    赠送jar包:itext-2.1.7.jar; 赠送原API文档:itext-2.1.7-javadoc.jar; 赠送源代码:itext-2.1.7-sources.jar; 赠送Maven依赖信息文件:itext-2.1.7.pom; 包含翻译后的API文档:itext-2.1.7-javadoc-API文档-...

    itext-asian2.7.1+itext-asiancmaps2.7.1jar文件以及字体maven项目

    最近在做项目用到jasperreports6.5.0,该库依赖itext2.7.1版本比较旧,又不能升级itext为5.0以上。照成中文无法显示,因此打了两个字体库兼容itext2.7.1。项目完美显示中文字体。 使用方法: 1、将字体jar文件拷贝...

    itext-2.1.7-API文档-中英对照版.zip

    赠送jar包:itext-2.1.7.jar; 赠送原API文档:itext-2.1.7-javadoc.jar; 赠送源代码:itext-2.1.7-sources.jar; 赠送Maven依赖信息文件:itext-2.1.7.pom; 包含翻译后的API文档:itext-2.1.7-javadoc-API文档-...

    iText使用简单介绍.pdf

    iText 简单介绍 iText 是一款功能强大的开源 Java 组件,用于生成 PDF 文档。通过 iText,可以生成 PDF 或 RTF 文档,并可以将 XML、HTML 文件转化为 PDF 文件。iText 的安装非常方便,只需要下载 iText.jar 文件并...

    Itext7-7.1.2完整开发包

    通过iText,你可以对PDF文件进行组装、扩展、提取、切割等等多方面交互性的操作。它能够是符合大多数ISO PDF标准以及数字签名标准(PAdES)与 安全发票(ZUGFeRD)。 省时间 iText能够帮你自动完成一些繁琐事项,...

    itext-2.0.4/itext-2.1.5/itext-2.1.7

    多个版本的itext-jar包, itext-2.0.4/itext-2.1.5/itext-2.1.7

    itext官网上的最新版本 itext-5.2.1.zip (itext.jar)

    iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。 iText的安装非常方便,下载iText.jar文件后,...

    iText生成pdf解决中文不显示

    iText生成pdf解决中文不显示字库,pdf凉字不显示,由于生成iText插件生成pdf的时候中文会显示不出来,遇到过的是"凉"字,查到是字体库的原因,网上下载字体库msyh.ttc,生成的时候指定字体库,就可以解决了,小bug一...

    iText中文帮助文档_itext中文帮助文档_itext_iTextpdf_itext中文文档_

    itext 生成pdf的中文帮助文档,具体有:图片、块(下划线/删除线、上标/下标)、短句、段落等。

    itext-rtf-2.1.7.jar,iTextAsian.jar,iText-5.0.6.jar,itext-2.1.7.jar

    itext-rtf-2.1.7.jar,iTextAsian.jar,iText-5.0.6.jar,itext-2.1.7.jar

    itext itextasian 中文

    itext中文: public static void main(String[] args) { try { Document document = new Document(); OutputStream os = new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\test.pdf")); ...

    itext 生成pdf 目录

    itext 生成pdf 目录,itext 生成pdf 目录,itext 生成pdf 目录

    IText7jar集合

    IText7jar集合

    java通过itext生成word文件代码附itext-2.0.7.jar,iTextAsian.jar包

    共享一下个人用java编写的生成word文件程序,通过itext生成word文件代码附itext-2.0.7.jar,iTextAsian.jar包

    iText 7 Community版

    The iText 7 Core/Community release contains: kernel-x.y.z.jar: low-level functionality io-x.y.z.jar: low-level functionality layout-x.y.z.jar: high-level functionality forms-x.y.z.jar: AcroForms pdfa-...

    poi创建word、生成html、itext将html转换成pdf。pd4ml将jsp转成pdf

    导入的时候读取采用poi /生成的时候采用的是itext 2.通过读取数据库更改原始的.doc文件、读取数据库生成pdf。 -然后更改webRoot下面的.doc文件。然后调用ReadWriteAndDownloadDocAction生成一 个新的word...

    IText 和 iTextAsian

    IText 和 ITextAsian 的开发包

    itext-5.5.8+itext-asian+pdf jar包

    java的PDF生成jar包,包含 iText-5.5.8.jar, iTextAsian.jar, itextpdf-5.5.8, itextpdf-5.5.8-javadoc, itext-xtra-5.5.8, xmlworker-5.5.8。 已打包中文字体

    iText-5.0.6.jar(已加入iTextAsian)

    iText.jar,生成pdf所需,已经加入iTextAsian.jar中的字体类,可以不用再单独下载iTextAsian,直接将iText加入项目即可,不用配置环境变量啥的

    基于iText和flying saucer结合freemark生成pdf 范例

    基于iText和flying saucer结合freemark生成pdf 范例 1. 使用maven构建,不含jar包,可以自行使用maven下载依赖包, 2. 使用前需要将C:/Windows/Fonts/ARIALUNI.TTF 复制到doc-render/src/test/resources/config/fonts...

Global site tag (gtag.js) - Google Analytics