pdfbox&iText生成PDF文件格式及读取PDF文件内容的小示例--完美支持中文版

来源:互联网 发布:mac air 搜狗输入法 编辑:程序博客网 时间:2024/04/30 07:49
最近项目中有个需求需要将数据库中的数据导出到PDF文件中,所以在网上查找了相关的开源框架——pdfbox&itext

    于是乎写了一个简单的工具类,如有需要的可以直接拿去用,切勿跟俺客气~。

    本工具类所用到的相关jar包及版本有:

    1.pdfbox-1.5.0.jar

    2.fontbox-1.5.0.jar

    3.jempbox-1.5.0.jar

    4.iText-5.0.6.jar;

    5.SIMHEI.TTF()——黑体常规字体,可以去C:\\windows\\Fonts目录下去找,并放在工程的src目录下面~

    写小入门的帖子我喜欢开门见山,直接上代码,其中的注释已经非常清楚,main方法中有使用实例,代码结构讲太多了显得自己很啰嗦,或者觉得自己不太善于讲。没有直接上代码来得爽快!有喜欢的拿回去自己好好研究一下,运行之前记得先将之上列出的jar补齐了就OK~。

Java代码 复制代码 收藏代码
  1. package com.test.common.util;   
  2.   
  3. import java.io.File;   
  4. import java.io.FileInputStream;   
  5. import java.io.FileNotFoundException;   
  6. import java.io.FileOutputStream;   
  7. import java.io.IOException;   
  8.   
  9. import org.apache.pdfbox.pdfparser.PDFParser;   
  10. import org.apache.pdfbox.pdmodel.PDDocument;   
  11. import org.apache.pdfbox.util.PDFTextStripper;   
  12.   
  13. import com.itextpdf.text.BaseColor;   
  14. import com.itextpdf.text.Chapter;   
  15. import com.itextpdf.text.Document;   
  16. import com.itextpdf.text.DocumentException;   
  17. import com.itextpdf.text.Font;   
  18. import com.itextpdf.text.FontFactory;   
  19. import com.itextpdf.text.List;   
  20. import com.itextpdf.text.ListItem;   
  21. import com.itextpdf.text.PageSize;   
  22. import com.itextpdf.text.Paragraph;   
  23. import com.itextpdf.text.Phrase;   
  24. import com.itextpdf.text.Rectangle;   
  25. import com.itextpdf.text.Section;   
  26. import com.itextpdf.text.pdf.BaseFont;   
  27. import com.itextpdf.text.pdf.PdfWriter;   
  28.   
  29. /**  
  30.  * 功能 PDF读写类  
  31.  * @CreateTime 2011-4-14 下午02:44:11  
  32.  */  
  33. public class PDFUtil {   
  34.        
  35. //  public static final String CHARACTOR_FONT_CH_FILE = "SIMFANG.TTF";  //仿宋常规  
  36.     public static final String CHARACTOR_FONT_CH_FILE = "SIMHEI.TTF";  //黑体常规  
  37.        
  38.     public static final Rectangle PAGE_SIZE = PageSize.A4;   
  39.     public static final float MARGIN_LEFT = 50;   
  40.     public static final float MARGIN_RIGHT = 50;   
  41.     public static final float MARGIN_TOP = 50;   
  42.     public static final float MARGIN_BOTTOM = 50;   
  43.     public static final float SPACING = 20;   
  44.        
  45.        
  46.     private Document document = null;   
  47.        
  48.     /**  
  49.      * 功能:创建导出数据的目标文档  
  50.      * @param fileName 存储文件的临时路径  
  51.      * @return   
  52.      */  
  53.     public void createDocument(String fileName) {   
  54.         File file = new File(fileName);   
  55.         FileOutputStream out = null;   
  56.         document = new Document(PAGE_SIZE, MARGIN_LEFT, MARGIN_RIGHT, MARGIN_TOP, MARGIN_BOTTOM);   
  57.         try {   
  58.             out = new FileOutputStream(file);   
  59. //          PdfWriter writer =    
  60.             PdfWriter.getInstance(document, out);   
  61.         } catch (FileNotFoundException e) {   
  62.             e.printStackTrace();   
  63.         } catch (DocumentException e) {   
  64.             e.printStackTrace();   
  65.         }   
  66.         // 打开文档准备写入内容   
  67.         document.open();   
  68.     }   
  69.        
  70.     /**  
  71.      * 将章节写入到指定的PDF文档中  
  72.      * @param chapter  
  73.      * @return   
  74.      */  
  75.     public void writeChapterToDoc(Chapter chapter) {   
  76.         try {   
  77.             if(document != null) {   
  78.                 if(!document.isOpen()) document.open();   
  79.                 document.add(chapter);   
  80.             }   
  81.         } catch (DocumentException e) {   
  82.             e.printStackTrace();   
  83.         }   
  84.     }   
  85.        
  86.     /**  
  87.      * 功能  创建PDF文档中的章节  
  88.      * @param title 章节标题  
  89.      * @param chapterNum 章节序列号  
  90.      * @param alignment 0表示align=left,1表示align=center 
  91.      * @param numberDepth 章节是否带序号 设值=1 表示带序号 1.章节一;1.1小节一...,设值=0表示不带序号 
  92.      * @param font 字体格式  
  93.      * @return Chapter章节  
  94.      */  
  95.     public static Chapter createChapter(String title, int chapterNum, int alignment, int numberDepth, Font font) {   
  96.         Paragraph chapterTitle = new Paragraph(title, font);   
  97.         chapterTitle.setAlignment(alignment);   
  98.         Chapter chapter = new Chapter(chapterTitle, chapterNum);   
  99.         chapter.setNumberDepth(numberDepth);    
  100.         return chapter;   
  101.     }   
  102.        
  103.     /**  
  104.      * 功能:创建某指定章节下的小节  
  105.      * @param chapter 指定章节  
  106.      * @param title 小节标题  
  107.      * @param font 字体格式  
  108.      * @param numberDepth 小节是否带序号 设值=1 表示带序号 1.章节一;1.1小节一...,设值=0表示不带序号 
  109.      * @return section在指定章节后追加小节  
  110.      */  
  111.     public static Section createSection(Chapter chapter, String title, Font font, int numberDepth) {   
  112.         Section section = null;   
  113.         if(chapter != null) {   
  114.             Paragraph sectionTitle = new Paragraph(title, font);   
  115.             sectionTitle.setSpacingBefore(SPACING);   
  116.             section = chapter.addSection(sectionTitle);   
  117.             section.setNumberDepth(numberDepth);   
  118.         }   
  119.         return section;   
  120.     }   
  121.        
  122.     /**  
  123.      * 功能:向PDF文档中添加的内容  
  124.      * @param text 内容  
  125.      * @param font 内容对应的字体  
  126.      * @return phrase 指定字体格式的内容  
  127.      */  
  128.     public static Phrase createPhrase(String text,Font font) {   
  129.         Phrase phrase = new Paragraph(text,font);   
  130.         return phrase;   
  131.     }   
  132.        
  133.     /**  
  134.      * 功能:创建列表  
  135.      * @param numbered  设置为 true 表明想创建一个进行编号的列表  
  136.      * @param lettered 设置为true表示列表采用字母进行编号,为false则用数字进行编号 
  137.      * @param symbolIndent  
  138.      * @return list  
  139.      */  
  140.     public static List createList(boolean numbered, boolean lettered, float symbolIndent) {   
  141.         List list = new List(numbered, lettered, symbolIndent);   
  142.         return list;   
  143.     }   
  144.        
  145.     /**  
  146.      * 功能:创建列表中的项  
  147.      * @param content 列表项中的内容  
  148.      * @param font 字体格式  
  149.      * @return listItem  
  150.      */  
  151.     public static ListItem createListItem(String content, Font font) {   
  152.         ListItem listItem = new ListItem(content, font);   
  153.         return listItem;   
  154.     }   
  155.   
  156.     /**  
  157.      * 功能:创造字体格式  
  158.      * @param fontname   
  159.      * @param size 字体大小  
  160.      * @param style 字体风格  
  161.      * @param color 字体颜色  
  162.      * @return Font  
  163.      */  
  164.     public static Font createFont(String fontname, float size, int style, BaseColor color) {   
  165.         Font font =  FontFactory.getFont(fontname, size, style, color);   
  166.         return font;   
  167.     }   
  168.        
  169.     /**  
  170.      * 功能: 返回支持中文的字体---仿宋  
  171.      * @param size 字体大小  
  172.      * @param style 字体风格  
  173.      * @param color 字体 颜色  
  174.      * @return  字体格式  
  175.      */  
  176.     public static Font createCHineseFont(float size, int style, BaseColor color) {   
  177.         BaseFont bfChinese = null;   
  178.         try {   
  179.             bfChinese = BaseFont.createFont(CHARACTOR_FONT_CH_FILE,BaseFont.IDENTITY_H, BaseFont.EMBEDDED);   
  180.         } catch (DocumentException e) {   
  181.             e.printStackTrace();   
  182.         } catch (IOException e) {   
  183.             e.printStackTrace();   
  184.         }   
  185.         return new Font(bfChinese, size, style, color);   
  186.     }   
  187.        
  188.     /**  
  189.      * 最后关闭PDF文档  
  190.      */  
  191.     public void closeDocument() {   
  192.         if(document != null) {   
  193.             document.close();   
  194.         }   
  195.     }   
  196.        
  197.   
  198.     /**  
  199.      * 读PDF文件,使用了pdfbox开源项目  
  200.      * @param fileName  
  201.      */  
  202.     public void readPDF(String fileName) {   
  203.         File file = new File(fileName);   
  204.         FileInputStream in = null;   
  205.         try {   
  206.             in = new FileInputStream(fileName);   
  207.             // 新建一个PDF解析器对象   
  208.             PDFParser parser = new PDFParser(in);   
  209.             // 对PDF文件进行解析   
  210.             parser.parse();   
  211.             // 获取解析后得到的PDF文档对象   
  212.             PDDocument pdfdocument = parser.getPDDocument();   
  213.             // 新建一个PDF文本剥离器   
  214.             PDFTextStripper stripper = new PDFTextStripper();   
  215.             // 从PDF文档对象中剥离文本   
  216.             String result = stripper.getText(pdfdocument);   
  217.             System.out.println("PDF文件的文本内容如下:");   
  218.             System.out.println(result);   
  219.   
  220.         } catch (Exception e) {   
  221.             System.out.println("读取PDF文件" + file.getAbsolutePath() + "生失败!" + e);   
  222.             e.printStackTrace();   
  223.         } finally {   
  224.             if (in != null) {   
  225.                 try {   
  226.                     in.close();   
  227.                 } catch (IOException e1) {   
  228.                 }   
  229.             }   
  230.         }   
  231.     }   
  232.   
  233.     /**  
  234.      * 测试pdf文件的创建  
  235.      * @param args  
  236.      */  
  237.     public static void main(String[] args) {   
  238.   
  239.         String fileName = "E:\\tmp\\pdf\\test11.pdf";  //这里先手动把绝对路径的文件夹给补上。  
  240.         PDFUtil pdfUtil = new PDFUtil();   
  241.            
  242.         Font chapterFont = PDFUtil.createCHineseFont(20, Font.BOLD, new BaseColor(00255));//文章标题字体  
  243.         Font sectionFont = PDFUtil.createCHineseFont(16, Font.BOLD, new BaseColor(00255));//文章小节字体  
  244.         Font textFont = PDFUtil.createCHineseFont(10, Font.NORMAL, new BaseColor(000));//小节内容字体  
  245.            
  246.         pdfUtil.createDocument(fileName);   
  247.         Chapter chapter = PDFUtil.createChapter("糖尿病病例1"110, chapterFont);   
  248.         Section section1 = PDFUtil.createSection(chapter, "病例联系人信息", sectionFont,0);   
  249.         Phrase text1 = PDFUtil.createPhrase("如您手中有同类现成病例,在填写完以上基础信息后,传病例附件",textFont);   
  250.         section1.add(text1);   
  251.            
  252.         Section section2 = PDFUtil.createSection(chapter, "病例个人体会", sectionFont,0);   
  253.         Phrase text2 = PDFUtil.createPhrase("1.下载病例生成PDF文档",textFont);   
  254. //      text2.setFirstLineIndent(20);  //第一行空格距离  
  255.         section2.add(text1);   
  256.         section2.add(text2);   
  257.            
  258.         List list = PDFUtil.createList(truefalse20);   
  259.         String tmp = "还有什么能够文档。文档是 PDF 文档的所有元素的容器。 ";   
  260.         ListItem listItem1 = PDFUtil.createListItem(tmp,textFont);   
  261.         ListItem listItem2 = PDFUtil.createListItem("列表2",textFont);   
  262.         list.add(listItem1);   
  263.         list.add(listItem2);   
  264.         section2.add(list);   
  265.            
  266.         pdfUtil.writeChapterToDoc(chapter);   
  267.         pdfUtil.closeDocument();   
  268.     }   
  269. }  

 

    有了这个小工具类,您就不用担心怎样将数据库中的数据导出到PDF文件中了,另外这只是文本文件的导出,还有有关图片导出,标签建立、与lucene整合搜索等功能没有包含,有可能你要问我为什么不把这几个功能都写完整了呢?很简单,因为我也不会呀~。待我研究研究哈。

转载地址:http://www.iteye.com/topic/1006313

0 0
原创粉丝点击