Fork me on GitHub

【java Itext Pdf】itext pdf隔行换色 itext5添加表格背景颜色

Itext5 pdf 行变色效果图:

新需求,隔行换色,itext in action 是个很好的说明书,照着英文读下来,很简单的进行了实现,思路如下:

 

1.先创建PdfPTable对象,生成PDF表格cell之后,添加隔行换色的事件,将此事件在PdfPTable加入Document对象之前,插入进去

2.隔行换色的事件需要自己写一个java类,里面去定义背景颜色和长宽高,实质就是在pdf表格生成之后,去读取当页page内的所有行和列,并创建一个矩形,加入背景,覆盖到cell内,达到背景有颜色的效果。

 

隔行换色的java类:要实现PdfPTableEvent这个接口,否则就没有然后了。

 

AlternatingBackground.java

/**
 * Project Name:report
 * File Name:AlternatingBackground.java
 * Package Name:com.riambsoft.report.util
 * Date:2013-5-27上午11:08:30
 * Copyright (c) 2013, riambsoft All Rights Reserved.
 *
 */
     
package com.itext.me;
     
import java.awt.Color;
import java.lang.management.ManagementFactory;
     
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
     
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPTableEvent;
     
/**
 * ClassName:AlternatingBackground <br/> Function: TODO ADD FUNCTION. <br/> Reason: TODO ADD REASON. <br/> Date: 2013-5-27 上午11:08:30 <br/>
 * 
 * @author Administrator
 * @version
 * @since JDK 1.5
 * @see
 */
public class AlternatingBackground implements PdfPTableEvent {
     
    public void tableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) {
             
        int columns;
        Rectangle rect;  
             
        //合适的颜色:(235,235,235)
        int footer = widths.length - table.getFooterRows();
        int header = table.getHeaderRows() - table.getFooterRows() + 1;
        for (int row = header; row < footer; row += 2) {
            columns = widths[row].length - 1;
            rect = new Rectangle(widths[row][0], heights[row], widths[row][columns], heights[row + 1]);
            rect.setBackgroundColor(new BaseColor(235,235,235));
            rect.setBorder(Rectangle.NO_BORDER);
            canvases[PdfPTable.BASECANVAS].rectangle(rect);
        }
    }
     
}

然后再在你的pdf生成类里面,去new 一个这个事件,加到pdftable中即可。LOOK

/**
 * Project Name:TestItext
 * File Name:TestPdf.java
 * Package Name:com.itext.me
 * Date:2013-5-28下午03:38:17
 * Copyright (c) 2013, riambsoft All Rights Reserved.
 *
 */
      
package com.itext.me;
      
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
      
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPTableEvent;
import com.itextpdf.text.pdf.PdfWriter;
      
/**
 * ClassName:TestPdf <br/> Function: TODO ADD FUNCTION. <br/> Reason: TODO ADD REASON. <br/> Date: 2013-5-28 下午03:38:17 <br/>
 * 
 * @author Administrator
 * @version
 * @since JDK 1.5
 * @see
 */
public class TestPdf {
      
    /**
     * main:(这里用一句话描述这个方法的作用). <br/>
     * 
     * @param args
     * @throws IOException 
     * @throws DocumentException 
     * @since JDK 1.5
     */
    public static void main(String[] args) throws IOException, DocumentException {
      
        String fileDesc = "";
        FileOutputStream outr = null;// 创建输出流
        // 生成随机数
        Random random = new Random();
        int x = random.nextInt();
        fileDesc = "c:\\pdftest\\" + "_" + x + ".pdf";// 路径下一定要有此文件
        BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontChinese = new Font(baseFontChinese, 12, Font.NORMAL);
        // step 1
        Document document = new Document();
        // step 2
        try {
            outr = new FileOutputStream(fileDesc);
            PdfWriter.getInstance(document, outr);
            // step 3
            document.open();
            // step 4
            PdfPTable table = new PdfPTable(3);
            // the cell object
            PdfPCell cell;
            // we add a cell with colspan3
            cell = new PdfPCell(new Phrase("Cell with colspan 3"));
            cell.setColspan(3);
            table.addCell(cell);
            // now we add a cell with rowspan2
            cell = new PdfPCell(new Phrase("Cell with rowspan 2 跨行", fontChinese));
            cell.setRowspan(2);
            // cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
            // we add the four remaining cells with addCell()
            table.addCell("row 1-1; cell 1");
            table.addCell("row 1-2; cell 2");
      
            cell = new PdfPCell(new Phrase("Cell with rowspan 2 跨行", fontChinese));
            table.addCell("row 2-1; cell 1");
            table.addCell("row 2-2; cell 2");
                  
            table.addCell("row 3-1; cell 1");
            table.addCell("row 3-2; cell 2");
            table.addCell("row 3-3; cell 3");
                  
            table.addCell("row 4-1; cell 1");
            table.addCell("row 4-2; cell 2");
            table.addCell("row 4-3; cell 3");
                  
            table.addCell("row 5-1; cell 1");
            table.addCell("row 5-2; cell 2");
            table.addCell("row 5-3; cell 3");
                  
            table.addCell("row 6-1; cell 1");
            table.addCell("row 6-2; cell 2");
            table.addCell("row 6-3; cell 3");
                  
            table.addCell("row 7-1; cell 1");
            table.addCell("row 7-2; cell 2");
            table.addCell("row 7-3; cell 3");
                  
            table.addCell("row 8-1; cell 1");
            table.addCell("row 8-2; cell 2");
            table.addCell("row 8-3; cell 3");
                  
            table.addCell("row 9-1; cell 1");
            table.addCell("row 9-2; cell 2");
            table.addCell("row 9-3; cell 3");
                  
                  
            //加入隔行换色事件
            PdfPTableEvent event = new AlternatingBackground();
            table.setTableEvent(event);
            //end
                  
                  
            document.add(table);
            document.close();
        } catch (DocumentException e1) {
            e1.printStackTrace();
        } finally {
            if (outr != null) {
                outr.close();
            }
            String cmd = "\"C:\\Program Files\\Foxit Software\\Foxit Reader\\Foxit Reader.exe\" ";// 这个是命令行打开福昕阅读器,我的福昕安装路径,你可以仿造我的写一个。
            System.out.println(cmd + "\"" + fileDesc + "\"" + " -n");
            Runtime.getRuntime().exec(cmd + "\"" + fileDesc + "\"" + " -n");
            // 打开pdf
        }
    }
      
}

结果图:

所有源码+jar包+doc文档 下载:http://download.csdn.net/detail/ae6623/5471531

落雨 csdn 本文:http://blog.csdn.net/ae6623/article/details/8987645

落雨

2013年5月29日9:19:03

qq 394263788

 

posted @ 2013-05-28 17:59  _落雨  阅读(3372)  评论(0编辑  收藏  举报