itext生成pdf (详细注释 附带工具类)

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.CMYKColor;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class ITextTest {

    public static void main(String[] args) throws DocumentException, MalformedURLException, IOException {
        //Step 1: 实例化文档对象,设置文档背景,大小等
        Rectangle rectPageSize = new Rectangle(PageSize.A4);// A4纸张 
        rectPageSize.setBackgroundColor(BaseColor.BLUE);//文档的背景色
        //创建一个文档对象,设置初始化大小和页边距
        Document document = new Document(rectPageSize, 40, 40, 40, 40);// 上、下、左、右间距  
        //Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        //Step 2: 创建 PdfWriter 对象:第一个参数是文档对象的引用,第二个参数是输出将写入的文件的绝对名称
        PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("./ITextTest.pdf"));
        //Step 3: 打开文档对象
        document.open();
        //Step 4: 向文档中添加内容
        //iText中用文本块(Chunk)、短语(Phrase)和段落(paragraph)处理文本。
        //1. 创建文本块对象
        //文本块(Chunk)是处理文本的最小单位,有一串带格式(包括字体、颜色、大小)的字符串组成。
        Chunk chunk1 = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE));
        document.add(chunk1);
        //2. 创建短语对象
        //短语(Phrase)由一个或多个文本块(Chunk)组成,短语(Phrase)也可以设定字体,但对于其中已设定过字体的文本块(Chunk)无效。
        //通过短语(Phrase)成员函数add可以将一个文本块(Chunk)加到短语(Phrase)中,如:phrase.add(chunk);
        Phrase phrase1 = new Phrase("The first Phrase");
        document.add(phrase1);
        Phrase phrase2 = new Phrase();
        phrase2.add(chunk1);
        document.add(phrase2);
        //3. 创建段落对象
        //段落(paragraph)由一个或多个文本块(Chunk)或短语(Phrase)组成,相当于WORD文档中的段落概念,
        //同样可以设定段落的字体大小、颜色等属性。另外也可以设定段落的首行缩进、对齐方式(左对齐、右对齐、居中对齐)。
        //通过函数setAlignment可以设定段落的对齐方式,setAlignment的参数1为居中对齐、2为右对齐、3为左对齐,默认为左对齐。
        Anchor anchorTarget = new Anchor("First page of the document.");//创建定位符(链接)
        anchorTarget.setName("BackToTop");//当单击 backToTop 链接时,它会将您带到文档的第一页
        Paragraph paragraph1 = new Paragraph();//创建一段段落
        paragraph1.setSpacingBefore(50);//设置上边距
        paragraph1.add(anchorTarget);//将定位符添加到段落中
        document.add(paragraph1);//将段落添加到文档中
        //使用文本以及字体、颜色、字号等默认设置创建一个默认段落
        document.add(new Paragraph("Some more text on the first page with different color and font type.",
                FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD,new CMYKColor(0, 255, 0, 0))));
        //4. 创建章对象
        //章是一种特殊的节,它从一个新页开始且默认会显示一个编号。
        Paragraph title1 = new Paragraph("Chapter 1", FontFactory.getFont(
                FontFactory.HELVETICA, 18, Font.BOLDITALIC, new CMYKColor(0,255, 255, 17)));
        Chapter chapter1 = new Chapter(title1, 1);//创建章(内容,编号)
        chapter1.setNumberDepth(0);//将编号深度设置为 0,这样就不会在页面上显示章编号
        //5. 创建节对象.节是章的子元素
        Paragraph title11 = new Paragraph("This is Section 1 in Chapter 1",
                FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD,new CMYKColor(0, 255, 255, 17)));
        Section section1 = chapter1.addSection(title11);//创建节
        Paragraph someSectionText = new Paragraph("This text comes as part of section 1 of chapter 1.");
        section1.add(someSectionText);//在节下添加一些文本
        someSectionText = new Paragraph("Following is a 3 X 2 table.");
        section1.add(someSectionText);
        //6. 创建表格对象Table (int columns)、Table(int columns, int rows)
        //创建表格时必须指定表格的列数,而对于行数可以不用指定
        PdfPTable t = new PdfPTable(3);//创建一个3列表格对象
        t.setSpacingBefore(25);//设置上边距
        t.setSpacingAfter(25);//设置下边距
        PdfPCell c1 = new PdfPCell(new Phrase("Header1"));
        t.addCell(c1);
        PdfPCell c2 = new PdfPCell(new Phrase("Header2"));
        t.addCell(c2);
        PdfPCell c3 = new PdfPCell(new Phrase("Header3"));
        t.addCell(c3);
        t.addCell("1.1");
        t.addCell("1.2");
        t.addCell("1.3");
        section1.add(t);
        //7. 创建列表对象
        //列表包含多个 ListItem。一个列表可带有编号,也可不带编号。
        //将第一个参数作为 true 传送,表明您希望创建带编号的列表。
        List l = new List(true, false, 10);
        l.add(new ListItem("First item of list"));
        l.add(new ListItem("Second item of list"));
        section1.add(l);
        //8. 将 Image 添加到主 Document 中
        //目前iText支持的图像格式有:GIF, Jpeg, PNG, wmf等格式,对于不同的图像格式,iText用同样的构造函数自动识别图像格式。
        //图像的位置主要是指图像在文档中的对齐方式、图像和文本的位置关系。
        //IText中通过函数public void setAlignment(int alignment)进行处理,
        //参数alignment为Image.RIGHT、Image.MIDDLE、Image.LEFT分别指右对齐、居中、左对齐;
        //当参数alignment为Image.TEXTWRAP、Image.UNDERLYING分别指文字绕图形显示、图形作为文字的背景显示。
        //这两种参数可以结合以达到预期的效果,如setAlignment(Image.RIGHT|Image.TEXTWRAP)显示的效果为图像右对齐,文字围绕图像显示。
        //Image 方法缩放图像:scaleAbsolute()、scaleAbsoluteWidth()、scaleAbsoluteHeight()、scalePercentage()、scaleToFit()等
        //函数public void scaleAbsolute(int newWidth, int newHeight)直接设定显示尺寸;
        //函数public void scalePercent(int percent)设定显示比例,如scalePercent(50)表示显示的大小为原尺寸的50%;
        //而函数scalePercent(int percentX, int percentY)则设定图像高宽的显示比例。
        //如果图像需要旋转一定角度之后在文档中显示,可以通过函数public void setRotation(double r)设定,
        //参数r为弧度,如果旋转角度为30度,则参数r= Math.PI / 6。
        Image image2 = Image.getInstance("IBMLogo.bmp");
        image2.scaleAbsolute(120f, 120f);
        section1.add(image2);
        //9. 将定位符添加到主文档中
        Paragraph title2 = new Paragraph("Using Anchor", FontFactory.getFont(
             FontFactory.HELVETICA, 16, Font.BOLD, new CMYKColor(0, 255, 0,0)));
        section1.add(title2);
        title2.setSpacingBefore(5000);
        Anchor anchor2 = new Anchor("Back To Top");
        anchor2.setReference("#BackToTop");//设置引用
        section1.add(anchor2);
        //10. 将一章添加到主文档中
        document.add(chapter1);
        //11. 中文处理
        //默认的iText字体设置不支持中文字体,需要下载远东字体包iTextAsian.jar,否则不能往PDF文档中输出中文字体。
        //BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        //没有字体包的话,可以调用系统自身的字体来使用
        //simsun.ttc:简体中文,msyhl.ttc:微软雅黑
        //注意:在.ttc后一定要加,1
        BaseFont bfChinese = BaseFont.createFont("c://windows//fonts//msyhl.ttc,1",
                BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        Font fontChinese = new Font(bfChinese, 12,Font.NORMAL);
        String content="默认的iText字体设置不支持中文字体,需要下载远东字体包iTextAsian.jar,"
                + "否则不能往PDF文档中输出中文字体。\n iText的安装非常方便,"
                + "在http://www.lowagie.com/iText/download.html - download 网站上下载iText.jar文件后,"
                + "只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用iText类库了。"
                + "\n 本地化测试包括繁体\n本地化測試包括繁體";              
        Paragraph pragraph=new Paragraph(content, fontChinese);
        document.add(pragraph);
        //Step 4:关闭文档对象
        document.close();
    }
}


 

工具类

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CreatePDF {

    private Document document = null;  

    /** 
     * 功能:创建导出数据的目标文档 
     * @param fileName 存储文件的临时路径  
     */  
    public void createDocument(String fileName) {  
        File file = new File(fileName);  
        FileOutputStream out = null;  
        document = new Document(PageSize.A4,50,50,50,50);  
        try {  
            out = new FileOutputStream(file);  
            PdfWriter.getInstance(document, out);  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (DocumentException e) {  
            e.printStackTrace();  
        }  
        // 打开文档准备写入内容  
        document.open();  
    }  

    /** 
     * 功能:创造字体格式 
     * @param fontname  
     * @param size 字体大小 
     * @param style 字体风格 
     * @param color 字体颜色 
     * @return Font 
     */  
    public static Font createFont(String fontname, float size, int style, BaseColor color) {  
        Font font =  FontFactory.getFont(fontname, size, style, color);  
        return font;  
    }  

    /**
     * 功能: 返回支持中文的字体
     * @param fontStr 指定字体所在位置
     * @param size 字体大小 
     * @param style 字体风格 
     * @param color 字体 颜色 
     * @return  字体格式 
     */
    public static Font createChineseFont(String fontStr,float size,int style,BaseColor color){
        BaseFont bfChinese = null;  
        try {  
            bfChinese = BaseFont.createFont(fontStr+",1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);  
        } catch (DocumentException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return new Font(bfChinese, size, style, color);  
    }

    /** 
     * 功能: 返回支持中文的字体---微软雅黑
     * @param size 字体大小 
     * @param style 字体风格 
     * @param color 字体 颜色 
     * @return  字体格式 
     */  
    public static Font createChineseFont(float size, int style, BaseColor color) {   
        return createChineseFont("c://windows//fonts//msyhl.ttc", size, style, color);  
    }  

    /** 
     * 功能:向PDF文档中添加短语
     * @param text 内容 
     * @param font 内容对应的字体 
     * @return phrase 指定字体格式的内容 
     */  
    public static Phrase createPhrase(String text,Font font) {  
        Phrase phrase = new Phrase(text,font);  
        return phrase;  
    }  

    /** 
     * 功能:向PDF文档中添加段落 
     * @param text 内容 
     * @param font 内容对应的字体 
     * @return Paraggraph 指定字体格式的内容 
     */  
    public static Paragraph createParagraph(String text,Font font) {  
        Paragraph paragraph = new Paragraph(text,font);  
        return paragraph;  
    }  

    /**
     * 创建链接
     * @param text 内容
     * @param target 链接的名称
     * @return 链接
     */
    public static Anchor setAnchor(String text,String target){
        Anchor anchorTarget = new Anchor(text);//创建定位符(链接)
        anchorTarget.setName(target);//当单击 target 链接时,它会将您带到文档的第一页
        return anchorTarget;
    }

    /** 
     * 功能  创建PDF文档中的章节 
     * @param title 章节标题 
     * @param chapterNum 章节序列号 
     * @param alignment 0表示align=left,1表示align=center 
     * @param numberDepth 章节是否带序号 设值=1 表示带序号 1.章节一;1.1小节一...,设值=0表示不带序号 
     * @param font 字体格式 
     * @return Chapter章节 
     */  
    public static Chapter createChapter(String title, int chapterNum, int alignment, int numberDepth, Font font) {  
        Paragraph chapterTitle = new Paragraph(title, font);  
        chapterTitle.setAlignment(alignment);  
        Chapter chapter = new Chapter(chapterTitle, chapterNum);  
        chapter.setNumberDepth(numberDepth);   
        return chapter;  
    }

    /** 
     * 功能:创建某指定章节下的小节 
     * @param chapter 指定章节 
     * @param title 小节标题 
     * @param font 字体格式 
     * @param numberDepth 小节是否带序号 设值=1 表示带序号 1.章节一;1.1小节一...,设值=0表示不带序号 
     * @return section在指定章节后追加小节 
     */  
    public static Section createSection(Chapter chapter, String title, Font font, int numberDepth) {  
        Section section = null;  
        if(chapter != null) {  
            Paragraph sectionTitle = new Paragraph(title, font);  
            sectionTitle.setSpacingBefore(20);  
            section = chapter.addSection(sectionTitle);  
            section.setNumberDepth(numberDepth);  
        }  
        return section;  
    }  

    /**
     * 创建表格
     * @param colnum 列数
     * @return 列数为colnum的表格
     */
    public static PdfPTable createPdfPTable(int colnum){
        PdfPTable table=new PdfPTable(colnum);
        return table;
    }

    /**
     * 创建表格的单元格
     * @param p 短语
     * @return 单元格
     */
    public static PdfPCell createPdfPCell(Phrase p){
        PdfPCell c = new PdfPCell(p);
        return c;
    }

    /** 
     * 功能:创建列表 
     * @param numbered  设置为true表明想创建一个进行编号的列表 
     * @param lettered 设置为true表示列表采用字母进行编号,为false则用数字进行编号 
     * @param symbolIndent listItem的缩进量
     * @return list 
     */  
    public static List createList(boolean numbered, boolean lettered, float symbolIndent) {  
        List list = new List(numbered, lettered, symbolIndent);  
        return list;  
    }  

    /** 
     * 功能:创建列表中的项 
     * @param content 列表项中的内容 
     * @param font 字体格式 
     * @return listItem 
     */  
    public static ListItem createListItem(String content, Font font) {  
        ListItem listItem = new ListItem(content, font);  
        return listItem;  
    }  

    /**
     * 创建图像
     * @param image 图像文件
     * @return 图像对象
     */
    public static Image createImage(String image){
        Image im=null;
        try {
            im = Image.getInstance(image);
        } catch (BadElementException ex) {
            Logger.getLogger(CreatePDF.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(CreatePDF.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CreatePDF.class.getName()).log(Level.SEVERE, null, ex);
        }
        return im;
    }

    /**
     * 引用链接
     * @param text 内容
     * @param tar 连接到定位符
     * @return 链接
     */
    public static Anchor getAnchor(String text,String tar){
        Anchor anchor = new Anchor(text);
        anchor.setReference("#"+tar);//设置引用
        return anchor;
    }

    /** 
     * 将章节写入到指定的PDF文档中 
     * @param chapter 
     */  
    public void writeChapterToDoc(Chapter chapter) {  
        try {  
            if(document != null) {  
                if(!document.isOpen()) document.open();  
                document.add(chapter);  
            }  
        } catch (DocumentException e) {  
            e.printStackTrace();  
        }  
    } 

    /** 
     * 最后关闭PDF文档 
     */  
    public void closeDocument() {  
        if(document != null) {  
            document.close();  
        }  
    }  

    public static void main(String args[]){
        String fileName="createPDF.pdf";
        CreatePDF pdf=new CreatePDF();

        Font chapterFont = createChineseFont(20, Font.BOLD, new BaseColor(0, 0, 255));//文章标题字体  
        Font sectionFont = createChineseFont(16, Font.BOLD, new BaseColor(0, 0, 255));//文章小节字体  
        Font textFont = createChineseFont(10, Font.NORMAL, new BaseColor(0, 0, 0));//小节内容字体  

        pdf.createDocument(fileName);//打开文档

        //创建章节
        Chapter chapter = createChapter("章1", 1, 1, 0, chapterFont);  
        Section section1 = createSection(chapter, "节1.1", sectionFont,0);  
        Phrase text1 = createPhrase("Hello,欢迎使用iText",textFont);  
        section1.add(text1); 
        //创建定位符
        Anchor anchor1=setAnchor("This is an anchor","Back to Top");
        Paragraph paragraph1=createParagraph("这是一段段落",sectionFont); 
        paragraph1.add(anchor1);
        section1.add(paragraph1);

        Section section2 = createSection(chapter, "节1.2", sectionFont,0);  
        Phrase text2 = createPhrase("列表:",textFont);  
        text2.setLeading(20); //上边距  
        section2.add(text2);  

        //创建列表
        List list = createList(true, false, 20);  
        String tmp = "文档是 PDF 文档的所有元素的容器";  
        ListItem listItem1 = createListItem(tmp,textFont);  
        ListItem listItem2 = createListItem("列表2",textFont);  
        list.add(listItem1);  
        list.add(listItem2); 
        //创建图像
        Image i=createImage("./IBMLogo.bmp");
        list.add(i);
        section2.add(list);  

        Section section3 = createSection(chapter, "节1.3", sectionFont,0);  
        Phrase text3 = createPhrase("表格:",textFont);  
        section3.add(text3);  

        //创建表格
        PdfPTable table=createPdfPTable(3);
        table.addCell(i);
        table.addCell(text3);
        table.addCell("列3");
        table.addCell(text2);

        Section section4 = createSection(chapter, "节1.4", sectionFont,0);  
        Phrase text4 = createPhrase("定位符:",textFont);   
        section4.add(text4); 
        //引用定位符
        Anchor anchor2=getAnchor("Back to Top","Back to Top");
        section4.add(anchor2);

        //写入一整章内容
        pdf.writeChapterToDoc(chapter); 

        //关闭文档
        pdf.closeDocument();
    }
}

参考: 
http://www.ibm.com/developerworks/cn/opensource/os-javapdf/ 

http://www.yesky.com/397/1707397_2.shtml 

http://www.cnblogs.com/LifelongLearning/archive/2010/12/28/1919138.html

--------------------- 
作者:Fighting_No1 
来源:CSDN 
原文:https://blog.csdn.net/fighting_no1/article/details/50930410 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/zxgmdzz/article/details/87937261
今日推荐