加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

iText—java导出PDF工具类

(2011-10-20 00:54:46)
标签:

it

import java.awt.Color;
import java.awt.Point;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.lowagie.text.Anchor;
import com.lowagie.text.Annotation;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Chapter;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.ListItem;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Section;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;


public class PdfUtil {

private static final Log log = LogFactory.getLog(PdfUtil.class);// 日志


public static void exportPdf(String content, String pdfPath) {
   Document document = null;
   OutputStream out = null;
   try {
    // 1.建立com.lowagie.text.Document对象的实例
    document = new Document();
    // 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
    out = new FileOutputStream(pdfPath);
    PdfWriter.getInstance(document, out);
    // 3.打开文档
    document.open();
    // 4.向文档中添加内容
    document.add(new Paragraph(content)); // 会中文乱码
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (DocumentException e) {
    e.printStackTrace();
   } finally {
    document.close();// 5.关闭文档
    try {
     out.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
}


public static void exportPdf(Paragraph para, String pdfPath,
    boolean vertical) {
   Document doc = null;
   OutputStream out = null;
   try {
    // 1.建立com.lowagie.text.Document对象的实例
    doc = buildDoc(vertical);
    // 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
    out = new FileOutputStream(pdfPath);
    PdfWriter.getInstance(doc, out);
    // 3.打开文档
    doc.open();
    // 4.向文档中添加内容
    doc.add(para);

   } catch (Exception e) {
    e.printStackTrace();
    log.debug("生成pdf出错");
   } finally {
    close(doc, out);// 5.关闭
   }
}


public static void exportPdf(Document doc, Element element, String pdfPath) {
   OutputStream out = null;
   try {
    // 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
    out = new FileOutputStream(pdfPath);
    PdfWriter.getInstance(doc, out);
    // 3.打开文档
    doc.open();
    // 4.向文档中添加内容
    doc.add(element);
   } catch (Exception e) {
    e.printStackTrace();
    log.debug("生成pdf出错");
   } finally {
    close(doc, out);// 5.关闭
   }
}


public static void exprotPdf(Document doc, PdfBean pdfBean) {
   OutputStream out = null;
   try {
    // 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
    out = new FileOutputStream(pdfBean.getFileName());
    PdfWriter writer = gerPdfWriter(doc, out);
    doc = setPdfProperty(doc, pdfBean); // 设置属性

    // 加密处理
    if (pdfBean.isEncryptFlag()) {
     List permissionList = pdfBean.getPermissionList();
     if (permissionList != null && permissionList.size() > 0) {
      int allPermission = 0;
      for (Iterator it = permissionList.iterator(); it.hasNext();) {
       int permission = (Integer) it.next();
       allPermission = allPermission | permission; // 有或运算来累加权限
      }
      writer = encrypt(writer, pdfBean.getUserPsw(), pdfBean
        .getOwnerPsw(), allPermission);
     }
    }
    // 3.打开文档
    doc.open();

    // 4.向文档中添加内容
    List elementList = pdfBean.getElementList();
    if(elementList != null && !elementList.isEmpty()){
     for(Iterator it = elementList.iterator(); it.hasNext();){
      Element element = (Element) it.next();
      doc.add(element);
     }
    }
   } catch (Exception e) {
    e.printStackTrace();
    log.debug("生成pdf出错");
   } finally {
    close(doc, out);// 5.关闭
   }
}



public static void exprotPdfToUrl(Document doc, PdfBean pdfBean, HttpServletResponse response) {
   ByteArrayOutputStream bao = null;
   ServletOutputStream out = null;
   try {
    // 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
    bao = new ByteArrayOutputStream();
    PdfWriter writer = gerPdfWriter(doc, bao);
    doc = setPdfProperty(doc, pdfBean); // 设置属性
    // 加密处理
    if (pdfBean.isEncryptFlag()) {
     List permissionList = pdfBean.getPermissionList();
     if (permissionList != null && permissionList.size() > 0) {
      int allPermission = 0;
      for (Iterator it = permissionList.iterator(); it.hasNext();) {
       int permission = (Integer) it.next();
       allPermission = allPermission | permission; // 有或运算来累加权限
      }
      writer = encrypt(writer, pdfBean.getUserPsw(), pdfBean
        .getOwnerPsw(), allPermission);
     }
    }
    // 3.打开文档
    doc.open();
    // 4.向文档中添加内容
    List elementList = pdfBean.getElementList();
    if(elementList != null && !elementList.isEmpty()){
     for(Iterator it = elementList.iterator(); it.hasNext();){
      Element element = (Element) it.next();
      doc.add(element);
     }
    }
    doc.close(); //关闭document
   
    //response设置
    response.setContentType("application/pdf");
   
   
//    response.setHeader("Content-Disposition", "attachment;filename=\"temp.pdf\"");   
//    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");   
//    response.setHeader("Pragma", "public");   
//    response.setDateHeader("Expires", (System.currentTimeMillis() + 1000)); 
   
    response.setContentLength(bao.size());
    out = response.getOutputStream();
    bao.writeTo(out);
    out.flush();   
   } catch (Exception e) {
    e.printStackTrace();
    log.debug("页面输出pdf出错");
   } finally {
    try {
     bao.close();
     out.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   
   }
}


public static Chunk getChunk(String content, Font font){
   Chunk chunk = new Chunk(content, font);
   return chunk;
}


public static Phrase getPhrase(String content, Font font){
   Phrase phrase = new Phrase(content, font);
   return phrase;
}


public static Paragraph getPara(String content, Font font) {
   Paragraph para = new Paragraph(content, font);
   return para;
}


public static Anchor getAnchor(String content, Font font, String url){
   Anchor anchor = new Anchor(content, font);
   anchor.setReference(url);
   return anchor;
}


public static com.lowagie.text.List getPdfList(List list, boolean numbered, float symbolIndent, Font font){
   com.lowagie.text.List pdfList = new com.lowagie.text.List(numbered, symbolIndent);
   ListItem li = null;
   if(list != null && !list.isEmpty()){
    for(Iterator it = list.iterator(); it.hasNext(); ){
     li = new ListItem(it.next().toString(), font);
     pdfList.add(li);
    }
   }
   return pdfList;
}


public static Annotation getAnnotation(String title, String text, float x, float y){
   Annotation anno = new Annotation(title, text, x, 0f, 0f, y);
   return anno;
}


public static Annotation getAnnotationUrl(float llx, float lly, float urx, float ury, String url){
   Annotation anno = new Annotation(llx, lly, urx, ury, url);
   return anno;
}


public static Chapter getChapter(String content , Font font, int numberDepth){
   Paragraph p = getPara(content, font);
   Chapter chapter = new Chapter(p, numberDepth);
   return chapter;
}




public static Section getSection(Chapter chapter, String content, Font font, int numberDepth){
   Paragraph p = getPara(content, font);
   Section s = chapter.addSection(p, numberDepth);
   return s;
}


public static Section getSection(Section section, String content, Font font, int numberDepth){
   Paragraph p = getPara(content, font);
   Section s = section.addSection(p, numberDepth);
   return s;
}


public static Image getImage(String imgPath, int alignMent,
    float absoluteX, float absoluteY) {
   Image img = null;
   try {
    img = Image.getInstance(imgPath);// 取得图片对象
    // 设置与文字对齐方式
    img.setAlignment(alignMent);// Image.RIGHT, MIDDLE, LEFT
           // ,TEXTWRAP(环绕), UNDERLYING(背景)
    if (absoluteX != -1 && absoluteY != -1) {// 戓x, y均不等于-1
     img.setAbsolutePosition(absoluteX, absoluteY);// 设置绝对位置
    }
   } catch (Exception e) {
    log.debug("创建图片对象错误");
    e.printStackTrace();
   }
   return img;
}

public static Table getTable() {
   Table table = null;
   try {
    table = new Table(4, 3);
    table.setAutoFillEmptyCells(true);// 没数据的cell为空
    table.addCell("a1", new Point(2, 2));
    table.addCell("b1", new Point(4, 3));

   } catch (BadElementException e) {
    e.printStackTrace();
   }
   return table;
}

public static Table getTable(TableBean tableBean, Font thFont, Font bodyFont) {
   Table table = null;
   try {
    table = new Table(tableBean.getColumns()); // 生成table对象
    table.setWidth(tableBean.getWidth()); // 宽度
    table.setBorderWidth(tableBean.getBorderWidth()); // 边框宽度
    table.setBorderColor(tableBean.getBorderColor()); // 边框color
    table.setPadding(tableBean.getCellPadding()); // 单元格内边距
    table.setSpacing(tableBean.getCellSpacing()); // 单元格外边距
    table.setAlignment(tableBean.getAlignMent()); // table对齐方式
    // 增加表头
    table = getTableTh(table, tableBean.getThList(), thFont);
    // 增加表数据
    table = getTableBody(table, tableBean.getBodyList(), bodyFont);
    table.setLastHeaderRow(2);//设置跨页时,表头还在
   } catch (Exception e) {
    log.debug("生成table错误");
    e.printStackTrace();
   }
   return table;
}


public static Table getTableTh(Table table, List<String> thList,
    Font cnBoldFont) {
   Cell cell = null;
   try {
    if (thList != null && !thList.isEmpty()) {
     for (Iterator it = thList.iterator(); it.hasNext();) {
      String thName = (String) it.next();
      Chunk thChunk = getChunk(thName, cnBoldFont);
      cell = new Cell(thChunk);
      cell.setHeader(true); // 设为头部
      cell.setHorizontalAlignment(Cell.ALIGN_CENTER);// 横向距中
      cell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
      cell.setBackgroundColor(new Color(239, 219, 150)); // 背景#EFDB96 土黄色
      table.addCell(cell);
     }
    }
   } catch (Exception e) {
    log.debug("生成表头出错");
    e.printStackTrace();
   }
   return table;
}

public static Table getTableBody(Table table, List<List> bodyList,
    Font cnFont) {
   Cell cell = null;
   try {
    if (bodyList != null && !bodyList.isEmpty()) {
     int i = 1;
     for (Iterator it = bodyList.iterator(); it.hasNext(); i++) {
      List rowList = (List) it.next();
      if (rowList != null && !rowList.isEmpty()) {
       for (Iterator it2 = rowList.iterator(); it2.hasNext();) {
        String cellContent = (String) it2.next();
        Paragraph tdPara = new Paragraph(cellContent,
          cnFont);
        cell = new Cell(tdPara);
        cell.setHorizontalAlignment(Cell.ALIGN_CENTER);// 横向距中
//        cell.setVerticalAlignment(Cell.ALIGN_TOP);
        if (i % 2 == 0) {
         cell.setBackgroundColor(new Color(240, 240, 240)); // 背景 #F0F0F0
        }
        table.addCell(cell);
       }
      }
     }
    }
   } catch (Exception e) {
    log.debug("生成表头出错");
    e.printStackTrace();
   }
   return table;
}


public static Document buildDoc(boolean vertical) {
   Document doc = null;
   if (vertical) {// 竖的,默认
    doc = new Document();
   } else {// 横向
    doc = new Document(PageSize.A4.rotate());
   }
   return doc;
}


public static Document setPdfProperty(Document doc, PdfBean pdfBean) {
   if (pdfBean.getTitle() != null) {
    doc.addTitle(pdfBean.getTitle()); // 标题
   }
   if (pdfBean.getSubject() != null) {
    doc.addSubject(pdfBean.getSubject());// 主题
   }
   if (pdfBean.getAuthor() != null) {
    doc.addAuthor(pdfBean.getAuthor()); // 作者
   }
   if (pdfBean.getKeywords() != null) {
    doc.addKeywords(pdfBean.getKeywords()); // 关键词
   }
   if (pdfBean.getCreator() != null) {
    doc.addCreator(pdfBean.getCreator()); // 创建人
   }
   if (pdfBean.getTitle() != null) {
    doc.addTitle(pdfBean.getTitle()); // 标题
   }
   Map headerMap = pdfBean.getHeaderMap();
   if (headerMap != null) {
    for (Iterator it = headerMap.entrySet().iterator(); it.hasNext();) {
     Object key = it.next();
     Object val = headerMap.get(key);
     doc.addHeader(key.toString(), val.toString());
    }
   }
   if (pdfBean.getHeader() != null) {// 报头
    Font font = ITextFontUtil.getCnBoldFont(20, Color.BLACK); // 设置字体
    HeaderFooter header = new HeaderFooter(new Phrase(pdfBean
      .getHeader(), font), false); //false表示,没有含有数字(页码)
    header.setAlignment(Element.ALIGN_CENTER);// 居中
    // header.setBorder(Rectangle.NO_BORDER);//设置边界宽度,默认是1
    doc.setHeader(header);
   }
   if (pdfBean.getFooter() != null) {// 报尾
    HeaderFooter footer = new HeaderFooter(new Phrase(pdfBean
      .getFooter()), true); //true表示,含有数字(页码)
    footer.setAlignment(Element.ALIGN_RIGHT);
    doc.setFooter(footer);
   }
   return doc;
}


public static PdfWriter gerPdfWriter(Document doc, OutputStream out) {
   PdfWriter writer = null;
   try {
    writer = PdfWriter.getInstance(doc, out);
   } catch (DocumentException e) {
    log.debug("创建PdfWriter失败");
    e.printStackTrace();
   }
   return writer;
}


public static PdfWriter encrypt(PdfWriter writer, String userPsw,
    String ownerPsw, int permissions) {
   try {
    writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, userPsw,
      ownerPsw, permissions);
   } catch (DocumentException e) {
    log.debug("pdf加密错误");
    e.printStackTrace();
   }
   return writer;
}


public static void close(Document doc, OutputStream out) {
   try {
    doc.close();// 关闭文档
    out.close();
   } catch (IOException e) {
    log.debug("关闭document或输出流错误");
    e.printStackTrace();
   }
}

0

阅读 收藏 喜欢 打印举报/Report
前一篇:jxl导出excel
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有