iText详细介绍及应用

一、Itext简介

iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。

iText的安装非常方便,在http://www.lowagie.com/iText/download.html网站上下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用iText类库了。

二、生成PDF步骤

1、创建文档对象实例

Document document = new Document();

2、建立书写器(Writer)与文档对象(document)关联,通过书写器将文档写入磁盘

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));

DEST:生成PDF文件

3、打开文档

document.open();

4、向文档中添加内容

document.add(new Paragraph("PDF demo")); 

5、关闭文档

document.close();

三、具体分析

1、对象实例

public document();

public document(Rectangle pageSize);

public document(Rectangle pageSize, int marginLeft, int marginRight, int marginTop, int marginBottom);

pageSize是指文档页面大小,public document();页面大小为A4,效果等同于Document(PageSize.A4);

marginLeft、marginRight、marginTop、marginBottom分别为左、右、上、下的页边距。

通过参数pageSize可以设定页面大小、面背景色、以及页面横向/纵向等属性。iText定义了A0-A10、AL、LETTER、HALFLETTER、_11x17、LEDGER、NOTE、B0-B5、ARCH_A-ARCH_E、FLSA和FLSE等纸张类型,也可以通过Rectangle pageSize = new Rectangle(144, 720);自定义纸张。通过Rectangle方法rotate()可以将页面设置成横向。

2、书写器对象

一旦文档(document)对象建立好之后,需要建立一个或多个书写器(Writer)对象与之关联。通过书写器(Writer)对象可以将具体文档存盘成需要的格式。

PDFWriter可以将文档存成PDF文件;HtmlWriter可以将文档存成html文件

3、文档属性

在文档打开之前,可以设定文档的标题、主题、作者、关键字、装订方式、创建者、生产者、创建日期等属性,调用的方法分别是:

public boolean addTitle(String title) 
public boolean addSubject(String subject) 
public boolean addKeywords(String keywords) 
public boolean addAuthor(String author) 
public boolean addCreator(String creator) 
public boolean addProducer() 
public boolean addCreationDate() 
public boolean addHeader(String name, String content)

其中方法addHeader对于PDF文档无效,addHeader仅对html文档有效,用于添加文档的头信息。

当新的页面产生之前,可以设定页面的大小、书签、脚注(HeaderFooter)等信息,调用的方法是:

public boolean setPageSize(Rectangle pageSize) 
public boolean add(Watermark watermark) 
public void removeWatermark() 
public void setHeader(HeaderFooter header) 
public void resetHeader() 
public void setFooter(HeaderFooter footer) 
public void resetFooter() 
public void resetPageCount() 
public void setPageCount(int pageN)

如果要设定第一面的页面属性,这些方法必须在文档打开前调用。

对于PDF文档,iText还提供了文档的显示属性,通过调用书写器的 setViewerPreferences方法可以控制文档打开时Acrobat Reader的显示属性,如是否单页显示、是否全屏显示、是否隐藏状态条等属性。

另外,iText也提供了对PDF文件的安全保护,通过书写器(Writer)的setEncryption方法,可以设定文档的用户口令、只读、可打印等属性。

4、添加文档内容

所有向文档添加的内容都是以对象为单位的,如Phrase、Paragraph、Table、Graphic对象等。比较常用的是段落(Paragraph)对象,用于向文档中添加一段文字。

 

IText中用文本块(Chunk)、短语(Phrase)和段落(paragraph)处理文本。文本块(Chunk)是处理文本的最小单位,有一串带格式(包括字体、颜色、大小)的字符串组成。如以下代码就是产生一个字体为HELVETICA、大小为10、带下划线的字符串:

Chunk chunk1 = new Chunk("This text is underlined", 
               FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE)); 

短语(Phrase)由一个或多个文本块(Chunk)组成,短语(Phrase)也可以设定字体,但对于其中以设定过字体的文本块(Chunk)无效。通过短语(Phrase)成员函数add可以将一个文本块(Chunk)加到短语(Phrase)中,如:phrase6.add(chunk);

段落(paragraph)由一个或多个文本块(Chunk)或短语(Phrase)组成,相当于WORD文档中的段落概念,同样可以设定段落的字体大小、颜色等属性。另外也可以设定段落的首行缩进、对齐方式(左对齐、右对齐、居中对齐)。通过函数setAlignment可以设定段落的对齐方式,setAlignment的参数1为居中对齐、2为右对齐、3为左对齐,默认为左对齐。

 

Itext中处理表格在有PDFTable,Table。对于简单在表格处理可以用Table,但如果要处理复杂的表格就需要PDFTable进行处理。

创建表格时,必须要指定列,行则不是必须的。

建立表格之后,可以设定表格的属性,如:边框宽度、边框颜色、衬距(padding space 即单元格之间的间距)大小等属性。

 

IText中处理图像的类为Image,目前iText支持的图像格式有:GIF, Jpeg, PNG, wmf等格式,对于不同的图像格式,iText用同样的构造函数自动识别图像格式。通过下面的代码分别获得gif、jpg、png图像的实例。

Image gif = Image.getInstance("vonnegut.gif"); 
Image jpeg = Image.getInstance("myKids.jpg"); 
Image png = Image.getInstance("hitchcock.png");

图像的位置 
图像的位置主要是指图像在文档中的对齐方式、图像和文本的位置关系。IText中通过函数public void setAlignment(int alignment)进行处理,参数alignment为Image.RIGHT、Image.MIDDLE、Image.LEFT分别指右对齐、居中、左对齐;当参数alignment为Image.TEXTWRAP、Image.UNDERLYING分别指文字绕图形显示、图形作为文字的背景显示。这两种参数可以结合以达到预期的效果,如setAlignment(Image.RIGHT|Image.TEXTWRAP)显示的效果为图像右对齐,文字围绕图像显示。

图像的尺寸和旋转 
如果图像在文档中不按原尺寸显示,可以通过下面的函数进行设定:

public void scaleAbsolute(int newWidth, int newHeight) 

public void scalePercent(int percent) 

public void scalePercent(int percentX, int percentY)

函数public void scaleAbsolute(int newWidth, int newHeight)直接设定显示尺寸;

函数public voidscalePercent(int percent)设定显示比例,如scalePercent(50)表示显示的大小为原尺寸的50%;

而函数scalePercent(int percentX, int percentY)则图像高宽的显示比例。 

如果图像需要旋转一定角度之后在文档中显示,可以通过函数public void setRotation(double r)设定,参数r为弧度,如果旋转角度为30度,则参数r= Math.PI/6。

 四、中文处理

默认的iText字体设置不支持中文字体,需要下载远东字体包iTextAsian.jar,否则不能往PDF文档中输出中文字体。通过下面的代码就可以在文档中使用中文了:

BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

或者

BaseFont bfChinese = BaseFont.createFont("C:/Windows/Fonts/simhei.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);、

注意:此处大小写敏感!例如宋体的英文名称是SimSun(注意不是simsun!,首字母都是大写的)

      错误写法:font-family:宋体 或者  font-family:simsun

      正确写法:font-family:SimSun 或者 font-family:SimHei

  确保上述所有字体均通过addFont加入,字体名称错误或者字体不存在会抛出异常,很方便,但是没导入的字体不会有任何提示。

五、例子

 1、IText转PDF

//取数据
        WaybillVO waybillVO = waybillManageService.getWaybillInfo(user, waybillId);

        //A4横向
        Document document = new Document(PageSize.A4.rotate());
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));
        // 设置中文字体
        BaseFont bfChinese =
                BaseFont.createFont("C:/Windows/Fonts/simhei.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        //字体
        Font titleChinese = new Font(bfChinese, 20, Font.BOLD);
        Font secondtitleChinese = new Font(bfChinese, 12, Font.BOLD);
        Font fontChinese = new Font(bfChinese, 8, Font.NORMAL);

        document.open();
        Paragraph title = new Paragraph("上海飞粟供应链管理有限公司",titleChinese);
        //设置标题格式对齐方式
        title.setAlignment(Element.ALIGN_CENTER);
        document.add(title);

        Paragraph secondTitle = new Paragraph();
        Phrase nbsp = new Phrase("                                         ");
        secondTitle.add(nbsp);
        Phrase shd = new Phrase("送   货   单",secondtitleChinese);
        secondTitle.add(shd);

        secondTitle.add(nbsp);
        Phrase fax = new Phrase("本送货单传真有效",fontChinese);
        secondTitle.add(fax);
        secondTitle.setAlignment(Element.ALIGN_CENTER);
        secondTitle.setSpacingBefore(20f);
        document.add(secondTitle);

        // 设置表格的列宽和列数
        float[] widths = {25f, 30f, 35f, 25f, 25f, 25f, 30f, 30f, 25f, 25f, 25f };
        // 建立一个pdf表格
        PdfPTable table = new PdfPTable(widths);

        table.setSpacingBefore(20f);
        // 设置表格宽度为100%
        table.setWidthPercentage(100);

        PdfPCell cell = null;
        //第一行
        cell = new PdfPCell(new Paragraph("系统单号",fontChinese));
        cell.setMinimumHeight(MINI_CELL_HEIGHT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getWaybill().getId().toString(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setColspan(2);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("发货单号",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getWaybill().getCustomerOrderNumber() == null ? "" : waybillVO.getWaybill().getCustomerOrderNumber(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setColspan(3);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("委托方",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getShipperCompany().getCompanyName(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setColspan(2);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("等待通知卸货",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);

        //第二行
        cell = new PdfPCell(new Paragraph("收货方",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setMinimumHeight(MINI_CELL_HEIGHT);
        cell.setColspan(3);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("收货联系电话",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getWaybill().getConsigneePhone(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setColspan(3);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("要求到货时间",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(new SimpleDateFormat("yyyy-MM-dd").format(waybillVO.getWaybill().getExpectedDeliveryTime()),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setColspan(2);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getWaybill().getWaitUnloading() == 2 ? "是" : "否",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);

        //第三行
        cell = new PdfPCell(new Paragraph("收货联系人",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setMinimumHeight(MINI_CELL_HEIGHT);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getWaybill().getConsigneeName(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setColspan(2);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("收货地址",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getWaybill().getToDetail(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setColspan(7);
        table.addCell(cell);

        //第四行
        cell = new PdfPCell(new Paragraph("货品名称",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setMinimumHeight(MINI_CELL_HEIGHT);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("件数",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("规格型号(公斤/件)",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("重量(吨)",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("包装方式",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("提货时间",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("提货地",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("提货仓库",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("提货联系人",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("提货联系电话",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("备注",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);

        //第五行
        cell = new PdfPCell(new Paragraph(waybillVO.getVarietyMap().get("thirdName").toString(),fontChinese));
        cell.setMinimumHeight(MINI_CELL_HEIGHT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getCargo().getAmount().toString(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getCargo().getSpecifications(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);

        String weight = "";
        if (waybillVO.getCargo().getWeight() != null) {
            weight = waybillVO.getCargo().getWeight().toString();
        } else if (waybillVO.getCargo().getVolume() != null) {
            weight = waybillVO.getCargo().getVolume().toString();
        }
        cell = new PdfPCell(new Paragraph(weight,fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);

        String packingManner = "";
        if ("tray".equals(waybillVO.getCargo().getPackingManner())) {
            packingManner = "托盘";
        } else if ("cargo".equals(waybillVO.getCargo().getPackingManner())) {
            packingManner = "散货";
        } else if ("other".equals(waybillVO.getCargo().getPackingManner())) {
            packingManner = "其他";
        }
        cell = new PdfPCell(new Paragraph(packingManner,fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(new SimpleDateFormat("yyyy-MM-dd").format(waybillVO.getWaybill().getExpectedPickupTime()),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getWaybill().getFromDetail(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getWaybill().getFromCompany(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getWaybill().getConsignerName(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getWaybill().getConsignerPhone(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getWaybill().getRemark() == null ? "" : waybillVO.getWaybill().getRemark(),fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);

        //第六行

        PdfPTable inerTable = new PdfPTable(widths);
        inerTable.setWidthPercentage(100);

        PdfPCell inerCell = null;
        inerCell = new PdfPCell(new Paragraph("合计",fontChinese));
        inerCell.setMinimumHeight(MINI_CELL_HEIGHT);
        inerCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        inerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        inerCell.setBorder(0);
        inerTable.addCell(inerCell);

        inerCell = new PdfPCell(new Paragraph(waybillVO.getCargo().getAmount() + "件",fontChinese));
        inerCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        inerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        inerCell.setColspan(3);
        inerCell.setBorderWidth(0);
        inerTable.addCell(inerCell);

        inerCell = new PdfPCell(new Paragraph(weight + "吨",fontChinese));
        inerCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        inerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        inerCell.setBorderWidth(0);
        inerTable.addCell(inerCell);

        inerCell = new PdfPCell(new Paragraph("",fontChinese));
        inerCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        inerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        inerCell.setColspan(6);
        inerCell.setBorder(0);
        inerTable.addCell(inerCell);

        cell.addElement(inerTable);
        cell.setColspan(11);
        table.addCell(cell);

        //第七行
        cell = new PdfPCell(new Paragraph("代收物项",fontChinese));
        cell.setMinimumHeight(MINI_CELL_HEIGHT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setColspan(3);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("代收金额",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("",fontChinese));
        cell.setColspan(6);
        table.addCell(cell);

        //第八行
        cell = new PdfPCell(new Paragraph("委托方\n(签字并盖章)",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setMinimumHeight(MINI_CELL_HEIGHT * 3);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("",fontChinese));
        cell.setColspan(3);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("操作备注",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(waybillVO.getWaybill().getRemark(),fontChinese));
        cell.setColspan(6);
        table.addCell(cell);

        //第九行
        int colspanLength = 2;
        if (waybillVO.getVehicleVOList() != null) {
            colspanLength += waybillVO.getVehicleVOList().size();
        }
        cell = new PdfPCell(new Paragraph("运输公司\n(签字并盖章)",fontChinese));
        cell.setMinimumHeight(MINI_CELL_HEIGHT * colspanLength);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setRowspan(colspanLength);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("",fontChinese));
        cell.setColspan(3);
        cell.setRowspan(colspanLength);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph("车号",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setMinimumHeight(MINI_CELL_HEIGHT);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("车型",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("司机",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("手机号",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("身份证号",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setColspan(3);
        table.addCell(cell);

        java.util.List<VehicleVO> vehicleVOList = waybillVO.getVehicleVOList();
        if (vehicleVOList != null) {
            for (int i = 0; i < vehicleVOList.size(); i++) {
                VehicleVO vehicleVO = vehicleVOList.get(i);
                cell = new PdfPCell(new Paragraph(vehicleVO.getVehicle().getPlateNumber(),fontChinese));
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setMinimumHeight(MINI_CELL_HEIGHT);
                table.addCell(cell);

                String model = "";
                if (VehicleModel.high_sided.equals(vehicleVO.getVehicle().getModel())) {
                    model = "高栏";
                } else if (VehicleModel.flatbed.equals(vehicleVO.getVehicle().getModel())) {
                    model = "平板";
                } else if (VehicleModel.van.equals(vehicleVO.getVehicle().getModel())) {
                    model = "厢式";
                } else if (VehicleModel.other.equals(vehicleVO.getVehicle().getModel())) {
                    model = "集装箱";
                }
                cell = new PdfPCell(new Paragraph(model,fontChinese));
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(vehicleVO.getDriver().getRealName(),fontChinese));
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph(vehicleVO.getDriver().getPhone(),fontChinese));
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell);
                cell = new PdfPCell(new Paragraph("",fontChinese));
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setColspan(3);
                table.addCell(cell);
            }
        }

        cell = new PdfPCell(new Paragraph("车队备注",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setMinimumHeight(MINI_CELL_HEIGHT);
        cell.setColspan(7);
        table.addCell(cell);

        //第十行
        cell = new PdfPCell(new Paragraph("收货方\n(签字并盖章)",fontChinese));
        cell.setMinimumHeight(MINI_CELL_HEIGHT * 3);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("",fontChinese));
        cell.setColspan(3);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("收货情况",fontChinese));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("",fontChinese));
        cell.setColspan(6);
        table.addCell(cell);

        document.add(table);

        Paragraph bottomString = new Paragraph();
        Phrase phone = new Phrase("客服电话:4009205366",fontChinese);
        bottomString.add(phone);
        Phrase nbspBottom = new Phrase("                                                                   ");
        bottomString.add(nbspBottom);
        Phrase zd = new Phrase("制单:" + waybillVO.getStaffAccount().getRealName(),fontChinese);
        bottomString.add(zd);
        Phrase nbspBottom2 = new Phrase("               ");
        bottomString.add(nbspBottom2);
        Phrase printTime = new Phrase("打印时间:" + new SimpleDateFormat("yyyy-MM-dd HH:MM:ss").format(waybillVO.getPrintTime()),fontChinese);
        bottomString.add(printTime);
        bottomString.setIndentationLeft(70);
        document.add(bottomString);

        document.close();

 2、IText转Word

com.lowagie.text.Document document = new com.lowagie.text.Document(com.lowagie.text.PageSize.A4.rotate());
        //建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
        RtfWriter2.getInstance(document, new FileOutputStream(DEST_WORD_PATH));
        //设置中文字体
        com.lowagie.text.pdf.BaseFont bfChinese =
                com.lowagie.text.pdf.BaseFont.createFont("C:/Windows/Fonts/simhei.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        document.open();
        com.lowagie.text.Font titleFont = new com.lowagie.text.Font(Font.NORMAL,16, Font.BOLD);

        //第一级标题样式
        RtfParagraphStyle rtfGsBt1 = RtfParagraphStyle.STYLE_HEADING_1;
        rtfGsBt1.setAlignment(Element.ALIGN_LEFT);
        rtfGsBt1.setStyle(Font.BOLD);
        rtfGsBt1.setSize(15);

        //第二级标题样式
        RtfParagraphStyle rtfGsBt2 = RtfParagraphStyle.STYLE_HEADING_2;
        rtfGsBt2.setAlignment(Element.ALIGN_LEFT);
        rtfGsBt2.setStyle(Font.BOLD);
        rtfGsBt2.setSize(13);

        //正文
        com.lowagie.text.Paragraph title = new com.lowagie.text.Paragraph("利用IText书写Word例子");
        // 设置标题格式对齐方式
        title.setAlignment(Element.ALIGN_CENTER);
        title.setFont(new com.lowagie.text.Font(bfChinese, 17, Font.BOLD));
        document.add(title);

        com.lowagie.text.Paragraph title1 = new com.lowagie.text.Paragraph("一、基本内容");
        title1.setFont(rtfGsBt1);
        document.add(title1);

        com.lowagie.text.Paragraph title11 = new com.lowagie.text.Paragraph("1.1 第一小节内容");
        title11.setFont(rtfGsBt2);
        document.add(title11);

        // 正文字体风格
        com.lowagie.text.Font contextFont = new com.lowagie.text.Font(bfChinese, 12,  com.lowagie.text.Font.NORMAL);
        com.lowagie.text.Paragraph context = new com.lowagie.text.Paragraph("iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。" +
                "通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。 iText的安装非常方便," +
                "下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用iText类库了。");
        //设置行距
        context.setLeading(3f);
        context.setFont(contextFont);
        // 离上一段落(标题)空的行数
        context.setSpacingBefore(1);
        // 设置第一行空的列数
        context.setFirstLineIndent(20);
        document.add(context);

        com.lowagie.text.Paragraph title12 = new com.lowagie.text.Paragraph("1.2 第二小节内容");
        // 设置标题格式对齐方式
        title.setFont(rtfGsBt2);
        document.add(title);

        context = new com.lowagie.text.Paragraph("一般情况下,iText使用在有以下一个要求的项目中:\n\n" +
                " 内容无法提前利用:取决于用户的输入或实时的数据库信息。\n\n" +
                " 由于内容,页面过多,PDF文档不能手动生成。\n\n" +
                " 文档需在无人参与,批处理模式下自动创建。\n\n" +
                " 内容被定制或个性化;例如,终端客户的名字需要标记在大量的页面上。\n");
        //设置行距
        context.setLeading(3f);
        context.setFont(contextFont);
        // 离上一段落(标题)空的行数
        context.setSpacingBefore(1);
        // 设置第一行空的列数
        context.setFirstLineIndent(20);
        document.add(context);

        com.lowagie.text.Paragraph title2 = new com.lowagie.text.Paragraph("二、插入图片");
        title2.setFont(rtfGsBt1);
        document.add(title2);

        //添加图片
        com.lowagie.text.Image img = com.lowagie.text.Image.getInstance("http://sports.nen.com.cn/imagelist/11/24/w26o1rh8621m.jpg");
        if(img==null)
            return;
        img.setAbsolutePosition(0, 0);
        img.setAlignment(Element.ALIGN_CENTER);
        img.scaleAbsolute(400, 400);
        img.scaleAbsolute(1000, 1000);
        img.scalePercent(50);
        img.scalePercent(50, 50);
        img.setRotation(0);
        document.add(img);

        com.lowagie.text.Paragraph title3 = new com.lowagie.text.Paragraph("二、插入简单表格");
        title3.setFont(rtfGsBt1);
        document.add(title3);

        //为了解决在插入段落与表之间产生多余的空格
        document.add(new com.lowagie.text.Phrase(""));

        new com.lowagie.text.Paragraph();

        Table table=new Table(4);//列数必须设置,而行数则可以按照个人要求来决定是否需要设置
        table.setAlignment(Element.ALIGN_CENTER);// 居中显示
        table.setAlignment(Element.ALIGN_MIDDLE);// 纵向居中显示
        table.setAutoFillEmptyCells(true);// 自动填满
        table.setBorderColor(new Color(0, 125, 255));// 边框颜色
        table.setBorderWidth(1);// 边框宽度
        table.setSpacing(2);// 衬距,
        table.setPadding(2);// 即单元格之间的间距
        table.setBorder(20);// 边框
        for (int i = 0; i < 3*3; i++) {
            table.addCell(new Cell(""+i));
        }
        document.add(table);

        com.lowagie.text.Paragraph title4 = new com.lowagie.text.Paragraph("二、插入较复杂表格");
        title4.setFont(rtfGsBt1);
        document.add(title4);

        document.add(new com.lowagie.text.Paragraph("22"));

        document.add(insertBGColor());

        document.add(insertBGColor());

        document.close();

3、IText添加书签

Document document = new Document(PageSize.A4);

        BaseFont bfCN =
                BaseFont.createFont("C:/Windows/Fonts/simhei.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        // 章的字体
        Font chFont = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLUE);
        // 节的字体
        Font secFont = new Font(bfCN, 12, Font.NORMAL, new BaseColor(0, 204,
                255));
        // 正文的字体
        Font textFont = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLACK);

        PdfWriter.getInstance(document, new FileOutputStream(DEST));
        document.open();

        int chNum = 1;
        Chapter chapter = new Chapter(new Paragraph("Michael介绍", chFont),
                chNum++);

        Section section = chapter.addSection(new Paragraph("基本信息", secFont));
        section.setIndentation(10);
        section.setIndentationLeft(10);
        section.setBookmarkOpen(true);
        section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
        section.add(new Paragraph("苦逼的码农一枚。。。", textFont));

        Section section2 = chapter.addSection(new Paragraph("SNS", secFont));
        section2.setIndentation(10);
        section2.setIndentationLeft(10);
        section2.setBookmarkOpen(false);
        section2.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
        section2.add(new Paragraph("SNS地址分类:", textFont));

        section = section2.addSection(new Paragraph(new Chunk("我的博客", secFont)
                .setUnderline(0.2f, -2f).setAnchor("http://www.cnblogs.com/xiaoSY-learning")));
        section.setBookmarkOpen(false);
        section.setIndentation(10);
        section.setIndentationLeft(10);
        section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
        section.add(new Paragraph(new Chunk("我的blog地址:http://www.cnblogs.com/xiaoSY-learning/",
                textFont).setUnderline(0.2f, -2f).setAnchor(
                "http://www.cnblogs.com/xiaoSY-learning/")));
        section.add(new Paragraph("分享自己的技术心得。", textFont));

        section = section2.addSection(new Paragraph(new Chunk("我的weibo",
                secFont).setUnderline(0.2f, -2f).setAnchor(
                "http://weibo.com/u/2772113512")));
        section.setIndentation(10);
        section.setIndentationLeft(10);
        section.setBookmarkOpen(false);
        section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
        section.add(new Paragraph(new Chunk("我的weibo:http://weibo.com/u/2772113512",
                textFont).setUnderline(0.2f, -2f).setAnchor(
                "http://weibo.com/u/2772113512")));
        section.add(new Paragraph("发表下心情,分享下技术,转转乱七八糟的新闻。", textFont));

        section = section2.addSection(new Paragraph(new Chunk("twitter",
                secFont)));
        section.setIndentation(10);
        section.setIndentationLeft(10);
        section.setBookmarkOpen(false);
        section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
        section.add(new Paragraph(new Chunk("twitter:@suncto", textFont)
                .setUnderline(0.2f, -2f).setAnchor("twitter:twitter:twitter:")));
        section.add(new Paragraph("一个常常被墙的地方", textFont));

        LineSeparator line = new LineSeparator(1, 100, new BaseColor(204, 204,
                204), Element.ALIGN_CENTER, -2);

        Paragraph p_line = new Paragraph("分割线");
        p_line.add(line);
        chapter.add(p_line);
        document.add(chapter);

        chapter = new Chapter(new Paragraph("Miu的介绍", chFont), chNum++);
        section = chapter.addSection(new Paragraph("基本信息", secFont));
        section.setIndentation(10);
        section.setIndentationLeft(10);
        section.setBookmarkOpen(false);
        section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
        section.add(new Paragraph("90后一枚,喜欢美食和旅游。。。", textFont));

        document.add(chapter);

        document.close();

 4、添加水印

public void addWaterMark(String srcFile, String destFile, String text,int textWidth,
                             int textHeight, String imgFile,int imgWidth, int imgHeight) throws IOException, DocumentException {

        // 待加水印的文件
        PdfReader reader = new PdfReader(srcFile);
        // 加完水印的文件
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));

        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;

        BaseFont font =
                BaseFont.createFont("C:/Windows/Fonts/simhei.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        // BaseFont base2 = BaseFont.createFont(BaseFont.HELVETICA,
        // BaseFont.WINANSI, BaseFont.EMBEDDED);
        // 水印文字
        String waterText = text;
        Image image = null;
        if (!StringUtils.isBlank(imgFile)) {
            image = Image.getInstance(imgFile);
            image.setAbsolutePosition(imgWidth, imgHeight);
            // 设置图片的显示大小
            image.scaleToFit(100, 125);
        }
        int j = waterText.length(); // 文字长度
        char c = 0;
        int high = 0;// 高度
        // 循环对每页插入水印
        for (int i = 1; i < total; i++) {
            // 水印的起始
            high = 50;
            // 水印在之前文本之上
            content = stamper.getOverContent(i);
            if (image != null) {
                content.addImage(image);
            }

            if (!StringUtils.isBlank(text)) {
                // 开始
                content.beginText();
                // 设置颜色 默认为蓝色
                content.setColorFill(BaseColor.BLUE);
                // 设置字体及字号
                content.setFontAndSize(font, 38);
                // 设置起始位置
                content.setTextMatrix(textWidth, textHeight);
                // 开始写入水印
                content.showTextAligned(Element.ALIGN_LEFT, text, textWidth, textHeight, 45);
                content.endText();
            }
        }
        stamper.close();
    }

猜你喜欢

转载自blog.csdn.net/xu906722/article/details/80157253