PDF文件的生成

    技术2025-03-17  16

    iText是一个开发源代码的项目,你可以使用iText方便的实现PDF的输出。 一、iText的下载:

        你可以在 http://www.lowagie.com/iText/查看关于iText的相关信息,包括源代码,文档..

        1. itext-src-2.0.1.zip(源代码)    2. itext-2.0.1.jar(可以直接导入的jar文件)

          现在最新的Itext版本为Itext 5.0

        3. 亚洲语言包:iTextAsian.jar

            http://sourceforge.net/project/showfiles.php?group_id=15255

     

    二、示例程序

    public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello World");

        // 创建一个Document对象    Document document = new Document();    try     {

          // 生成名为 HelloWorld.pdf 的文档      PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));

          // 添加PDF文档的一些信息      document.addTitle("Hello World example");      document.addAuthor("Bruno Lowagie");      document.addSubject("This example explains how to add metadata.");      document.addKeywords("iText, Hello World, step 3, metadata");      document.addCreator("My program using iText");

          // 打开文档,将要写入内容      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();}}

    编译运行以后,我们可以在运行的目录发现生成的HelloWorld.pdf

     

    三、中文问题:

      由于iText不支持东亚语言,我们下载了iTextAsian.jar 以后,就可以在PDF里面写中文

    public class AsianTest{

    public static void main(String[] args) {

        // 创建一个Document对象    Document document = new Document();    try     {

          // 生成名为 AsianTest.pdf 的文档      PdfWriter.getInstance(document, new FileOutputStream("AsianTest.pdf"));

         /** 新建一个字体,iText的方法       * STSongStd-Light 是字体,在iTextAsian.jar 中以property为后缀        * UniGB-UCS2-H   是编码,在iTextAsian.jar 中以cmap为后缀       * H 代表文字版式是 横版, 相应的 V 代表 竖版       */      BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);        Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, Color.GREEN);

          // 打开文档,将要写入内容      document.open();

          // 插入一个段落      Paragraph par = new Paragraph("我们",fontChinese);      document.add(par);    }     catch (DocumentException de)     {      System.err.println(de.getMessage());    }    catch (IOException ioe)     {      System.err.println(ioe.getMessage());    }

        // 关闭打开的文档    document.close();}}

    就可以显示中文了。

    四、其他问题:(应导入相应的包)

    1. 换页:

    document.newPage();

           2. 表格:

     

         说明:制表格也可用 PdfPTable类 例子如下(

      ------------例子开始------------

    private void printTable(List<?> list){  String[] header = tableHeader; try {  if (header == null || header.length < 1) {        printLog.error("传入的数据不符合要求,打印失败");   return;  }

      /*Table table = new Table(header.length,1);  table.setWidth(100); // 占页面宽度 90%   table.setAlignment(Element.ALIGN_MIDDLE);//  for (String value: header){   Cell cell=new Cell(value);   table.addCell(cell);  }  document.add(table);*/

      BaseFont bfChinese = BaseFont.createFont("STSongStd-Light",    "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  Font fontChinese = new Font(bfChinese, 10, Font.NORMAL);  // 获得表头数据,并形成表头  PdfPTable pdfpTable = new PdfPTable(header.length);  float[] totalWidth = colTotalWidth;  if (totalWidth != null && totalWidth.length > 0){   pdfpTable.setTotalWidth(totalWidth);  }      pdfpTable.setWidthPercentage(105f);  pdfpTable.setHorizontalAlignment(Element.ALIGN_CENTER);  pdfpTable.setSpacingBefore(25f);  pdfpTable.setSpacingAfter(5f);  PdfPCell pdfCell = new PdfPCell();//表体单元格  pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);  pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE);  pdfCell.setBorder(Rectangle.BOX);  pdfCell.setBorderWidth(1f);  pdfCell.setMinimumHeight(15f);    pdfCell.setBackgroundColor(new Color(255, 255, 255));    PdfPCell tempPdfPCell;//表头  for (String keyName: header){   tempPdfPCell = new PdfPCell();   tempPdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);   tempPdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE);   tempPdfPCell.setBorder(Rectangle.BOX);   tempPdfPCell.setPadding(0f);   tempPdfPCell.setBorderWidth(1f);   tempPdfPCell.setMinimumHeight(22f);   tempPdfPCell.setBackgroundColor(new Color(255, 255, 255));   tempPdfPCell.setPhrase(new Phrase(keyName, fontChinese));   pdfpTable.addCell(tempPdfPCell);  }  pdfpTable.setHeaderRows(1);  //表体          for (int i = 0; i < list.size(); i++){   Object obj = list.get(i);     for(int j = 0; j < this.exportFieldValue.length; j++){   pdfCell.setPhrase(new Phrase(String.valueOf(this.methodInvokeGetter(obj,                    this.exportFieldValue[j])),fontChinese));      pdfpTable.addCell(pdfCell);    }  }      document.add(pdfpTable);       } catch (Exception e) {  printLog.error("制作表格的时候出错!具体原因可能为:", e); }}

          ----------例子结束----------

                 )

    // 设置 TableTable aTable = new Table(3);int width[] = {25,25,50};aTable.setWidths(width);aTable.setWidth(80); // 占页面宽度 80%

    aTable.setDefaultHorizontalAlignment(Element.ALIGN_LEFT);aTable.setDefaultVerticalAlignment(Element.ALIGN_MIDDLE);aTable.setAutoFillEmptyCells(true); //自动填满aTable.setPadding(1);aTable.setSpacing(1);aTable.setDefaultCellBorder(0);aTable.setBorder(0);

    Cell cell = new Cell(new Phrase("这是一个测试的 3*3 Table 数据", fontChinese ));cell.setVerticalAlignment(Element.ALIGN_TOP);cell.setRowspan(3);aTable.addCell(cell);

    aTable.addCell(new Cell("#1"));aTable.addCell(new Cell("#2"));aTable.addCell(new Cell("#3"));

    aTable.addCell(new Cell("#4"));aTable.addCell(new Cell("#5"));aTable.addCell(new Cell("#6"));

    document.add(aTable);

           3. 图片:

    // 可以是绝对路径,也可以是URLImage img = Image.getInstance("logo.gif");

    // Image image = Image.getInstance(new URL(http://xxx.com/logo.jpg));img.setAbsolutePosition(0, 0);document.add(img);

     

    iTexthttp://www.lowagie.com/iText/

    iText API: http://itext.sourceforge.net/docs/ http://www.sentom.net/list.asp?id=42

    最新回复(0)