itext 生成pdf文档 小结(自己备忘)

1、引入maven

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.9</version>
</dependency>

<dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>5.5.9</version>
</dependency>

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>

2、大致流程

//创建一条文本对象(A4纸张大小)
Document document = new Document(PageSize.A4.rotate());

//创建一个DOC文档(根据指定的路径)
PdfWriter.getInstance(document, new FileOutputStream("E:/3.pdf"));

//打开文本对象
document.open();

//添加一个简单的段落
document.add(new Paragraph("Hello World!"));

//结束编写
document.close();

3、字体

BaseFont baseFont = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",false);

//设置字体 -- 大小、颜色
Font titleFont = new Font(baseFont, 24.0F, Font.BOLD);
Font contextFont = new Font(baseFont, 14.0F, 0);

4、表格

PdfPTable table1 = new PdfPTable(4);//创建表格

int width[] = {18,32,18,32};//设置每列宽度比例

table1.setWidths(width);//设置每列宽度比例

//第一行 第一个
PdfPCell cell11 = new PdfPCell(new Paragraph("11",contextFont));
cell11.setVerticalAlignment(Element.ALIGN_TOP);      //垂直 居上
cell11.setHorizontalAlignment(Element.ALIGN_RIGHT);  //水平 居右
cell11.setBorder(0);

//第一行 第二个
PdfPCell cell12 = new PdfPCell(new Paragraph("12",contextFont));
cell12.setVerticalAlignment(Element.ALIGN_BOTTOM);  //垂直 居下
cell12.setHorizontalAlignment(Element.ALIGN_LEFT);  //水平 居左
cell12.setBorder(0);


//第一行 第三个
PdfPCell cell13 = new PdfPCell(new Paragraph("13",contextFont));
cell13.setVerticalAlignment(Element.ALIGN_MIDDLE);  //垂直 居中
cell13.setHorizontalAlignment(Element.ALIGN_RIGHT); //水平 居右
cell13.setBorder(0);

//第一行 第四个
PdfPCell cell14 = new PdfPCell(new Paragraph("14",contextFont));
cell14.setVerticalAlignment(Element.ALIGN_MIDDLE);  //垂直 居中
cell14.setHorizontalAlignment(Element.ALIGN_LEFT);  //水平 居左
cell14.setBorder(0);

table1.addCell(cell11);
table1.addCell(cell12);
table1.addCell(cell13);
table1.addCell(cell14);

document.add(table1);

5、插入图片

//图片路径
String URL = "http://www.baidu.com/img/bd_logo1.png";
//创建图片
Image img = null;
try {
    img = Image.getInstance(URL);
    img.scalePercent(10);
} catch (BadElementException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
//内容
Paragraph context = new Paragraph();
context.setAlignment(1);
context.setFont(contextFont);
if(img == null){
    context.add("没有图片");
}else{
    context.add(img);
}
document.add(context);

 

posted @ 2017-03-14 18:00  灰灰小菜鸟  阅读(857)  评论(0编辑  收藏  举报