itext入门案例

介绍
这几天需要写一些PDF的模板,使用到itext,写一个Demo。
实现基本步骤:
创建一个PDF的基本步骤:
	1.先创建一个Document
	2.新建一个书写器和Document关联
		2.1.添加水印和页眉页脚
	3.打开文档
	4.向文档中添加内容
	5.关闭文档
依赖:
<dependencies>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
    </dependencies>
代码:
测试类:
package xyq.text;

import com.itextpdf.text.*;
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 com.itextpdf.text.pdf.draw.DottedLineSeparator;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.lowagie.text.pdf.PdfTable;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MyTest {
   public static void main(String[] args) throws Exception {

       // 1.新建Document对象
       Document document = new Document(PageSize.A4);

       // 2.新建一个书写器和document关联
       File file = new File("F:\\PDFDemo.pdf");
       file.createNewFile();
       PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

       // 水印
       writer.setPageEvent(new Watermark("Hello IText"));

       // 页脚
       writer.setPageEvent(new MyHeaderFooter());

       // 3.打开文档
       document.open();
       // 标题
       document.addTitle("addTitle");
       // 作者
       document.addAuthor("addAuthor");
       // 主题
       document.addSubject("addSubject");
       // 关键字
       document.addKeywords("addKeyWords");
       // 创建者
       document.addCreator("addCreator");
       // 创建时间
       document.addCreationDate();


       // 4.向文档中添加内容
       new MyTest().generatePDF(document);

       // 5.关闭文档
       document.close();
   }

   // 定义全局的字体静态变量
   private static Font titleFont;
   private static Font headFont;
   private static Font keyFont;
   private static Font textFont;
   // 最大宽度
   private static int maxWidth = 520;

   // 静态代码块
   static {
       try {
           // 不同字体,(这里定义为同一种字体,包含不同字号,不同style)
           BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
           titleFont = new Font(bfChinese, 16, Font.BOLD);
           headFont = new Font(bfChinese, 14, Font.BOLD);
           keyFont = new Font(bfChinese, 10, Font.BOLD);
           textFont = new Font(bfChinese, 10, Font.NORMAL);
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

   // 生成pdf文件
   private void generatePDF(Document document) throws Exception {
       // 段落
       Paragraph paragraph = new Paragraph("美好的一天从早起开始", titleFont);
       // 设置文字居中,0靠左,1居中,2靠右
       paragraph.setAlignment(1);
       // 设置左缩进
       paragraph.setIndentationLeft(12);
       // 设置右缩进
       paragraph.setIndentationRight(12);
       // 设置首行缩进
       paragraph.setFirstLineIndent(24);
       // 行间距
       paragraph.setLeading(20f);
       // 设置段落上空白
       paragraph.setSpacingBefore(5f);
       // 设置段落下空白
       paragraph.setSpacingAfter(10f);

       // 直线
       Paragraph p1 = new Paragraph();
       p1.add(new Chunk(new LineSeparator()));

       // 点线
       Paragraph p2 = new Paragraph();
       p2.add(new Chunk(new DottedLineSeparator()));

       // 超链接
       Anchor anchor = new Anchor("baidu");
       anchor.setReference("www.baidu.com");

       // 定位
       Anchor gotoP = new Anchor("goto");
       gotoP.setReference("#top");

       // 添加图片
       Image image = Image.getInstance("F:\\sundun\\111.jpg");
       image.setAlignment(Image.ALIGN_CENTER);
       // 按照比例进行缩放
       image.scalePercent(40);

       // 表格
       PdfPTable table = createTable(new float[]{40, 120, 120, 120, 80, 80});
       table.addCell(createCell("美好的一天开始了", headFont, Element.ALIGN_LEFT, 6, false));
       table.addCell(createCell("早上9:00", keyFont, Element.ALIGN_CENTER));
       table.addCell(createCell("中午11:00", keyFont, Element.ALIGN_CENTER));
       table.addCell(createCell("中午13:00", keyFont, Element.ALIGN_CENTER));
       table.addCell(createCell("下午15:00", keyFont, Element.ALIGN_CENTER));
       table.addCell(createCell("下午17:00", keyFont, Element.ALIGN_CENTER));
       table.addCell(createCell("晚上19:00", keyFont, Element.ALIGN_CENTER));
       Integer totalQuantity = 0;
       for (int i = 0; i < 5; i++) {
           table.addCell(createCell("起床", textFont));
           table.addCell(createCell("吃午饭", textFont));
           table.addCell(createCell("午休", textFont));
           table.addCell(createCell("下午茶", textFont));
           table.addCell(createCell("回家", textFont));
           table.addCell(createCell("吃晚饭", textFont));
           totalQuantity++;
       }
       table.addCell(createCell("总计", keyFont));
       table.addCell(createCell("", textFont));
       table.addCell(createCell("", textFont));
       table.addCell(createCell("", textFont));
       table.addCell(createCell(String.valueOf(totalQuantity) + "件事", textFont));
       table.addCell(createCell("", textFont));

       document.add(paragraph);
       document.add(anchor);
       document.add(p2);
       document.add(gotoP);
       document.add(p1);
       document.add(table);
       document.add(image);
   }

   /**
    * ---------------------------创建表格单元格的方法start------------------------
    */
   /**
    * 创建单元格,指定字体
    *
    * @param value
    * @param font
    * @return
    */
   private PdfPCell createCell(String value, Font font) {
       PdfPCell cell = new PdfPCell();
       cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
       cell.setHorizontalAlignment(Element.ALIGN_CENTER);
       cell.setPhrase(new Phrase(value, font));
       return cell;
   }

   /**
    * 创建单元格,指定字体,水平
    *
    * @param value
    * @param font
    * @return
    */
   private PdfPCell createCell(String value, Font font, int align) {
       PdfPCell cell = new PdfPCell();
       cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
       cell.setHorizontalAlignment(align);
       cell.setPhrase(new Phrase(value, font));
       return cell;
   }

   /**
    * 创建单元格,指定字体,水平,单元格跨x列合并
    *
    * @param value
    * @param font
    * @return
    */
   private PdfPCell createCell(String value, Font font, int align, int colspan) {
       PdfPCell cell = new PdfPCell();
       cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
       cell.setHorizontalAlignment(align);
       cell.setColspan(colspan);
       cell.setPhrase(new Phrase(value, font));
       return cell;
   }

   /**
    * 创建单元格,指定字体,水平,单元格跨x列合并,设置单元格内边距
    *
    * @param value
    * @param font
    * @return
    */
   private PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
       PdfPCell cell = new PdfPCell();
       cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
       cell.setHorizontalAlignment(align);
       cell.setColspan(colspan);
       cell.setPhrase(new Phrase(value, font));
       cell.setPadding(3.0f);
       if (!boderFlag) {
           cell.setBorder(0);
           cell.setPaddingTop(15.0f);
           cell.setPaddingBottom(8.0f);
       } else {
           cell.setBorder(0);
           cell.setPaddingTop(0.0f);
           cell.setPaddingBottom(8.0f);
       }
       return cell;
   }

   /**
    * 创建单元格,指定字体,水平,边框宽度,0表示无边框
    *
    * @param value
    * @param font
    * @return
    */
   private PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
       PdfPCell cell = new PdfPCell();
       cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
       cell.setHorizontalAlignment(align);
       cell.setPhrase(new Phrase(value, font));
       cell.setBorderWidthLeft(borderWidth[0]);
       cell.setBorderWidthRight(borderWidth[1]);
       cell.setBorderWidthTop(borderWidth[2]);
       cell.setBorderWidthBottom(borderWidth[3]);
       cell.setPaddingTop(paddingSize[0]);
       cell.setPaddingBottom(paddingSize[1]);
       if (flag) {
           cell.setColspan(2);
       }
       return cell;
   }
   /**
    * ---------------------------创建表格单元格的方法end------------------------
    */
   /**
    * ---------------------------创建表格的方法start------------------------
    */
   /**
    * 创建默认列宽,指定列长,水平的表格
    *
    * @param
    * @return
    */
   private PdfPTable createTable(int colNumber, int align) {
       PdfPTable table = new PdfPTable(colNumber);
       try {
           table.setTotalWidth(maxWidth);
           table.setLockedWidth(true);
           table.setHorizontalAlignment(align);
           table.getDefaultCell().setBorder(1);
       } catch (Exception e) {
           e.printStackTrace();
       }
       return table;
   }

   /**
    * 创建指定列宽,列数的表格
    *
    * @param widths
    * @return
    */
   private PdfPTable createTable(float[] widths) {
       PdfPTable table = new PdfPTable(widths);
       try {
           table.setTotalWidth(maxWidth);
           table.setLockedWidth(true);
           table.setHorizontalAlignment(Element.ALIGN_CENTER);
           table.getDefaultCell().setBorder(1);
       } catch (Exception e) {
           e.printStackTrace();
       }
       return table;
   }

   /**
    * 创建空白的表格
    *
    * @return
    */
   private PdfPTable creatBlankTable() {
       PdfPTable table = new PdfPTable(1);
       table.getDefaultCell().setBorder(0);
       table.addCell(createCell("", keyFont));
       table.setSpacingAfter(20.0f);
       table.setSpacingBefore(20.0f);
       return table;
   }

   /**
    * ---------------------------创建表格单元格的方法end------------------------
    */
}


页脚/页眉:

package xyq.text;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import javax.print.Doc;
import java.io.IOException;

public class MyHeaderFooter extends PdfPageEventHelper {
   // 总页数
   PdfTemplate totalPage;
   Font hfFont;

   {
       try {
           hfFont = new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 8, Font.NORMAL);
       } catch (DocumentException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

   // 打开一个模板时,创建一个总页数的模板
   public void onOpenDocument(PdfWriter pdfWriter, Document document) {
       PdfContentByte directContent = pdfWriter.getDirectContent();
       totalPage = directContent.createTemplate(30, 16);
   }

   // 一页加载完成时触发,写入页眉和页脚
   public void onEndPage(PdfWriter writer, Document document) {
       PdfPTable table = new PdfPTable(3);
       try {
           table.setTotalWidth(PageSize.A4.getWidth() - 100);
           table.setWidths(new int[]{24, 24, 3});
           table.setLockedWidth(true);
           table.getDefaultCell().setFixedHeight(-10);
           table.getDefaultCell().setBorder(Rectangle.BOTTOM);

           table.addCell(new Paragraph("我是页眉/页脚", hfFont));
           table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
           table.addCell(new Paragraph("第" + writer.getPageNumber() + "页", hfFont));

           // 总页数
           PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));
           cell.setBorder(Rectangle.BOTTOM);
           table.addCell(cell);

           // 将页眉写到documen中
           table.writeSelectedRows(0, -1, 50, PageSize.A4.getHeight() - 20, writer.getDirectContent());
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

   // 全部加载完后,将总页数的pdf模板写到指定位置
   public void onCloseDocument(PdfWriter writer, Document document) {
       String text = "总" + (writer.getPageNumber()) + "页";
       ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text, hfFont), 2, 2, 0);
   }

}


水印:


package xyq.text;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

public class Watermark extends PdfPageEventHelper {
   Font font = new Font(Font.FontFamily.HELVETICA, 30, Font.BOLD, new GrayColor(0.95f));

   // 水印内容
   private String waterCont;

   public Watermark() {
   }

   public Watermark(String waterCont) {
       this.waterCont = waterCont;
   }

   @Override
   public void onEndPage(PdfWriter writer, Document document) {
       for (int i = 0; i < 5; i++) {
           for (int j = 0; j < 5; j++) {
               ColumnText.showTextAligned(
                       writer.getDirectContentUnder(),
                       Element.ALIGN_CENTER,
                       new Phrase(this.waterCont == null ? "HELLO HELLo" : this.waterCont, font),
                       (50.5f + i * 350),
                       (40.0f + j * 150),
                       writer.getCurrentPageNumber() % 2 == 1 ? 45 : -45);
           }
       }
   }
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值