iText生成PDF

  1. package test;
  2. import com.ExtraTrading.admin.ConfPageUtil;
  3. import com.ExtraTrading.util.Common;
  4. import com.lowagie.text.*;
  5. import com.lowagie.text.Font;
  6. import com.lowagie.text.Image;
  7. import com.lowagie.text.List;
  8. import com.lowagie.text.Rectangle;
  9. import com.lowagie.text.pdf.BaseFont;
  10. import com.lowagie.text.pdf.PdfWriter;
  11. import fr.simatai.domain.FileLike;
  12. import org.apache.commons.io.FileUtils;
  13. import org.apache.commons.io.IOCase;
  14. import org.apache.commons.io.filefilter.SuffixFileFilter;
  15. import org.apache.commons.io.filefilter.TrueFileFilter;
  16. import org.apache.commons.lang.StringUtils;
  17. import org.apache.commons.logging.Log;
  18. import org.apache.commons.logging.LogFactory;
  19. import org.pdfbox.pdfparser.PDFParser;
  20. import org.pdfbox.pdmodel.PDDocument;
  21. import org.pdfbox.util.PDFTextStripper;
  22. import java.awt.*;
  23. import java.io.File;
  24. import java.io.FileInputStream;
  25. import java.io.FileOutputStream;
  26. import java.io.IOException;
  27. import java.util.ArrayList;
  28. import java.util.Collection;
  29. import java.util.Date;
  30. import java.util.Iterator;
  31. /**
  32.  * 很多应用程序要求动态生成 PDF 文档。这类应用程序包括银行生成用于电子邮件投递的客户报表,到读者购买特定图书章节并以 PDF 格式接收这些文档。例子罗列下去是很多的。在本文中,将使用 iText Java 库生成 PDF 文档,并引导您完成一个示例应用程序,以使您能够更好地理解和使用 iText。
  33.   iText 是 Lowagie.com 站点(请参阅 参考资料)免费提供的 Java 库。iText 库的功能很强大,支持 HTML、RTF 和 XML 文档的生成,此外还能够生成 PDF 文档。可以从多种字体中选择文档中所使用的字体。同时,iText 的结构允许使用相同的代码生成以上任意类型的文档。
  34.  * http://www.lowagie.com/iText/
  35.  * iText API:近距离观察
  36.   com.lowagie.text.Document 是生成 PDF 的主要的类。它是需要使用的第一个类。一旦开始创建文档,将需要一个写入器向文档中写入内容。com.lowagie.text.pdf.PdfWriter 就是一个 PDF 写入器。下面列出了通常需要使用的类:
  37.   com.lowagie.text.Paragraph —— 这个类表示一个缩进的段落。
  38.   com.lowagie.text.Chapter —— 这个类表示 PDF 文档中的章节。使用 Paragraph 作为题目并使用 int 作为章节号码来创建它。
  39.   com.lowagie.text.Font —— 这个类包含了全部的字体规范,例如字体、大小、样式和颜色。各种字体都在这个类中声明为静态常数。
  40.   com.lowagie.text.List —— 这个类表示一个列表,按顺序包含许多 ListItems。
  41.   com.lowagie.text.Table —— 这个类表示包含单元格的表,单元格有序地排列在矩阵中。
  42.  */
  43. public class JAVAtoPDF {
  44.   Log log = LogFactory.getLog(JAVAtoPDF.class);
  45.     private static final Font FONT = FontFactory.getFont(FontFactory.COURIER, 8, Font.NORMAL, Color.BLACK);
  46.  /**
  47.   * 写PDF文件,展示了PDF文档、章节、小节、字体、段落、表格、列表的使用
  48.   * 最后展示如何使用写入中文。
  49.   * @param fileName
  50.   */
  51.  public void writePDF(String fileName) {
  52.   File file = new File(fileName);
  53.   FileOutputStream out = null;
  54.   try {
  55.    //(1)实例化文档对象
  56.    //第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
  57.    Document document = new Document(PageSize.A4, 50505050);
  58.    //(2)创建写入器
  59.    //第一个参数是对文档对象的引用,第二个参数是输出的文件,将out和document连接起来
  60.    out = new FileOutputStream(file);
  61.    PdfWriter writer = PdfWriter.getInstance(document, out);
  62.    //打开文档准备写入内容
  63.       document.addTitle("TEST的PDF");
  64.       document.addSubject("这是一个关于发票的PDF");
  65.       document.addKeywords("Invoice,new Green Continent Co.,Ltd");
  66.       document.addAuthor("BOSS");
  67.       document.addCreator("BEAUTY9235");
  68.       document.addProducer();
  69.       document.addCreationDate();
  70.       document.open();
  71.       HeaderFooter header = new HeaderFooter(new Phrase("This is a header."), false);
  72.       HeaderFooter footer = new HeaderFooter(new Phrase("Copyright 2004 Little Ben, LLC. All rights reserved. /nNot to be reproduced or distributed without written consent from Little Ben, LLC./n Page", FONT), true);
  73.             java.util.List numberList = new ArrayList();
  74.             String webpath = ConfPageUtil.get("web.path");
  75.             Image[] img = new Image[100];
  76.             Collection c = FileUtils.listFiles(new File(webpath + "/customerlogo/"), new SuffixFileFilter(new String[]{"gif"}, IOCase.INSENSITIVE), TrueFileFilter.INSTANCE);
  77.             int k = 0;
  78.             for (
  79.                 Iterator it = c.iterator(); it.hasNext();) {
  80.                 File f = new File(it.next().toString());
  81.                 FileLike fileLike = new FileLike();
  82.                 fileLike.setName(f.getName());
  83.                 fileLike.setSizestr(Common.keep2DecimalFraction((f.length()) / 1024));
  84.                 fileLike.setPath(f.getPath());
  85.                 fileLike.setLastModified(f.lastModified());
  86.                 String p = StringUtils.replace(StringUtils.replace(f.getPath(), "F://data//wwwroot//", ""), "//", "/");
  87.                 log.debug(p);
  88.                 img[k++] = Image.getInstance(p);
  89.                 fileLike.setLastModifiedstr(Common.getPatternDateString("yyyy-MM-dd HH:mm:ss"new Date(f.lastModified())));
  90.                 numberList.add(fileLike);
  91.             }
  92.             int row = 7;
  93.             int col = 5;
  94.             int pageSize = 6;
  95.             int pageCount = (numberList.size() + pageSize - 1) / pageSize;
  96.             for (int j = 0; j < pageCount; j++) {
  97.                 Table table = new Table(col, row);
  98.                 table.setBorderWidth(0);
  99.                 table.setBorderColor(new Color(000));
  100.                 table.setPadding(2);
  101.                 table.setSpacing(0);
  102.                 table.setAlignment(Table.ALIGN_CENTER);
  103.                 float[] widths = {0.10f, 0.2f, 0.5f, 0.05f, 0.15f};
  104.                 table.setWidths(widths);
  105.                 // cell.setHeader(true);
  106.                 Cell c1 = new Cell(new Paragraph("name", FONT));
  107.                 c1.setHeader(true);
  108.                 table.addCell(c1);
  109.                 // table.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);
  110.                 Cell c2 = new Cell(new Paragraph("pic", FONT));
  111.                 c2.setHeader(true);
  112.                 table.addCell(c2);
  113.                 Cell c3 = new Cell(new Paragraph("path", FONT));
  114.                 c3.setHeader(true);
  115.                 table.addCell(c3);
  116.                 Cell c4 = new Cell(new Paragraph("size", FONT));
  117.                 c4.setHeader(true);
  118.                 table.addCell(c4);
  119.                 Cell c5 = new Cell(new Paragraph("modify", FONT));
  120.                 c5.setHeader(true);
  121.                 table.addCell(c5);
  122.                 table.endHeaders();
  123.                 for (int m = 0; m < 5; m++) {
  124.                     FileLike fileLike = (FileLike) numberList.get(pageCount + m);
  125.                     table.addCell(new Cell(new Paragraph(fileLike.getName(), FONT)));
  126.                     //table.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);
  127.                     table.addCell(new Cell(Image.getInstance(StringUtils.replace(StringUtils.replace(fileLike.getPath(), "F://data//wwwroot//simatai//", ""), "//", "/"))));
  128.                     table.addCell(new Cell(new Paragraph(fileLike.getPath(), FONT)));
  129.                     table.addCell(new Cell(new Paragraph(fileLike.getSizestr(), FONT)));
  130.                     table.addCell(new Cell(new Paragraph(fileLike.getLastModifiedstr(), FONT)));
  131.                 }
  132.                 table.setWidth(100);
  133.                 document.add(table);
  134.                 footer.setAlignment(HeaderFooter.ALIGN_CENTER);
  135.                 footer.setBorder(Rectangle.NO_BORDER);
  136.                 document.setFooter(footer);
  137.                 header.setAlignment(HeaderFooter.ALIGN_CENTER);
  138.                 header.setBorder(Rectangle.NO_BORDER);
  139.                 document.setHeader(header);
  140.                 document.newPage();
  141.             }
  142.             Image jpeg = Image.getInstance("WebRoot/icon/detourer-com.jpg");
  143.             // log.debug(jpeg.getUrl());
  144.             //图片居中
  145.             jpeg.setAlignment(Image.LEFT | Image.TEXTWRAP);
  146.             document.add(jpeg);
  147.    //(3)下面创建章节对象
  148.    //首先创建段落对象,作为章节的标题。FontFactory用于指定段落的字体。
  149.    Font font = FontFactory.getFont(FontFactory.HELVETICA,
  150.      18, Font.BOLDITALIC, new Color(00255));
  151.    Paragraph chapter1_title = new Paragraph("Chapter 1",font);
  152.    //创建了一个章节对象,标题为"Chapter 1"
  153.    Chapter chapter1 = new Chapter(chapter1_title, 1);
  154.    //将编号级别设为 0 就不会在页面上显示章节编号
  155.    chapter1.setNumberDepth(0);
  156.    //(4)创建小节对象
  157.    //创建小节对象的标题
  158.    font = FontFactory.getFont(FontFactory.HELVETICA, 16,
  159.      Font.BOLD, new Color(25500));
  160.    Paragraph section1_title1 = new Paragraph("Section 1 of Chapter 1", font);
  161.    //创建一个小节对象,标题为"This is Section 1 in Chapter 1",属于chapter1。
  162.    Section section1 = chapter1.addSection(section1_title1);
  163.    //(5)往小节中写文本内容
  164.    Paragraph text = new Paragraph("This is the first text in section 1 of chapter 1.");
  165.    section1.add(text);
  166.    text = new Paragraph("Following is a 5×5 table:");
  167.    section1.add(text);
  168.    //(6)往小节中写表格
  169.    //创建表格对象
  170.    Table table = new Table(55);
  171.    //设置表格边框颜色
  172.    table.setBorderColor(new Color(220255100));
  173.    //设置单元格的边距间隔等
  174.    table.setPadding(1);
  175.    table.setSpacing(1);
  176.    table.setBorderWidth(1);
  177.    //单元格对象
  178.    Cell cell = null;
  179.    //添加表头信息
  180.    for (int colNum=0; colNum<5; colNum++){
  181.     cell = new Cell("header-" + colNum);
  182.     cell.setHeader(true);
  183.     table.addCell(cell);
  184.    }
  185.    table.endHeaders();
  186.    //添加表的内容
  187.    for (int rowNum=1; rowNum<5; rowNum++){
  188.     for (int colNum=0; colNum<5; colNum++){
  189.      cell= new Cell("value-" + rowNum + "-" + colNum);
  190.      table.addCell(cell);
  191.     }
  192.    }
  193.    //将表格对象添加到小节对象中
  194.    section1.add(table);
  195.    //(7)添加列表
  196.    // 列表包含一定数量的 ListItem。可以对列表进行编号,也可以不编号。
  197.    // 将第一个参数设置为 true 表明想创建一个进行编号的列表;
  198.    // 第二个参数设置为true表示列表采用字母进行编号,为false则用数字进行编号;
  199.    // 第三个参数为列表内容与编号之间的距离。
  200.    List list = new List(truefalse20);
  201.    ListItem item = new ListItem("First item of list;");
  202.    list.add(item);
  203.    item = new ListItem("Second item of list;");
  204.    list.add(item);
  205.    item = new ListItem("Third item of list.");
  206.    list.add(item);
  207.    //将列表对象添加到小节对象中
  208.    section1.add(list);
  209.    //(8)添加中文
  210.    //允许在PDF中写入中文,将字体文件放在classPath中。
  211.    //simfang.ttf是仿宋的字体文件
  212.    BaseFont bfChinese = BaseFont.createFont("simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
  213.    //中文大小为20,加粗
  214.    font = new Font(bfChinese, 20, Font.BOLD);
  215.    text = new Paragraph("PDF中文测试", font);
  216.    section1.add(text);
  217.    //(9)将章节对象加入到文档中
  218.    document.add(chapter1);
  219.    //(10)关闭文档
  220.    document.close();
  221.    System.out.println("PDF文件生成成功,PDF文件名:" + file.getAbsolutePath());
  222.   } catch (DocumentException e) {
  223.    System.out.println("PDF文件"+ file.getAbsolutePath() + "生成失败!" + e);
  224.    e.printStackTrace();
  225.   } catch (IOException ee) {
  226.    System.out.println("PDF文件"+ file.getAbsolutePath() + "生成失败!" + ee);
  227.    ee.printStackTrace();
  228.   } finally {
  229.    if (out != null){
  230.     try {
  231.      //关闭输出文件流
  232.      out.close();
  233.     } catch (IOException e1) {
  234.     }
  235.    }
  236.   }
  237.  }
  238.  /**
  239.   * 读PDF文件,使用了pdfbox开源项目,新的版本已经支持中文了。
  240.   * 上www.pdfbox.org下载读PDF的jar包
  241.   * @param fileName
  242.   */
  243.  public void readPDF(String fileName) {
  244.   File file = new File(fileName);
  245.   FileInputStream in = null;
  246.   try {
  247.    in = new FileInputStream(fileName);
  248.    //新建一个PDF解析器对象
  249.    PDFParser parser = new PDFParser(in);
  250.    //对PDF文件进行解析
  251.    parser.parse();
  252.    //获取解析后得到的PDF文档对象
  253.    PDDocument pdfdocument = parser.getPDDocument();
  254.    //新建一个PDF文本剥离器
  255.    PDFTextStripper stripper = new PDFTextStripper();
  256.    //从PDF文档对象中剥离文本
  257.    String result = stripper.getText(pdfdocument);
  258.    System.out.println("PDF文件" + file.getAbsolutePath() + "的文本内容如下:");
  259.    System.out.println(result);
  260.   } catch (Exception e) {
  261.    System.out.println("读取PDF文件"+ file.getAbsolutePath() + "生失败!" + e);
  262.    e.printStackTrace();
  263.   } finally {
  264.    if (in != null){
  265.     try {
  266.      in.close();
  267.     } catch (IOException e1) {
  268.     }
  269.    }
  270.   }
  271.  }
  272.  public static void main(String[] args) {
  273.   JAVAtoPDF pdf = new JAVAtoPDF();
  274.   String fileName = "f:/temp/tempPDF.pdf";
  275.   pdf.writePDF(fileName);
  276.   pdf.readPDF(fileName);
  277.  }
  278. }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值