iText产生PDF

来源:互联网 发布:软件周期模型 编辑:程序博客网 时间:2024/05/16 06:12

通过iText可以动态创建PDF文件,并对创建的文件进行各种设置。在itext中的文本内容基本可以分为Chunk、Phrase、Anchor、Paragraph、Chapter、Section等几种类型。

Chunk:一段字符串,好比文本的原子;

Phrase:Phrase 是chunk集合;

Chapter:好比文章的大标题;

Paragraph:好比一个文本快,就是一个段落;

Section:创建文章的小标题。


一.创建一个带有目录的PDF:

Document document = new Document();//创建一个文档对象try {//文档对象输出流PdfWriter.getInstance(document, new FileOutputStream("01.pdf"));document.open();//打开文档Chunk chunk = new Chunk("xu yan");//文章的序言Phrase chunkPhrase = new Phrase(chunk);String content = "yi yi yi yi yi";Phrase textPhrase = new Phrase(content);Phrase text = new Phrase("er er er er er");Font font = new Font(Font.HELVETICA,14,Font.BOLD);Chapter chapter1 = new Chapter(new Paragraph("da biao ti",font),1);//文章的大标题Paragraph paragraph = new Paragraph();paragraph.add(chunkPhrase);chapter1.add(paragraph);Section section0 = chapter1.addSection("xiao biao ti yi",2);//文章的小标题1section0.add(textPhrase);Section section = chapter1.addSection("xiao biao ti er",2);//文章的小标题2section.add(text);document.add(chapter1);} catch (FileNotFoundException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();}document.close();//关闭文档
效果图:

 

二.向PDF中插入静态图片:

Document document = new Document();try {PdfWriter.getInstance(document, new FileOutputStream("02.pdf"));document.open();//参数:目标图片、X方向的偏移量、Y方向的偏移量Chunk chunk = new Chunk(Image.getInstance("src/123.jpg"),0,-750);Paragraph paragraph = new Paragraph();paragraph.add(chunk);paragraph.setAlignment(Element.ALIGN_RIGHT);document.add(paragraph);} catch (Exception e) {e.printStackTrace();}document.close();


三.PDF中创建表格:

Document document = new Document();//创建一个文档对象try {PdfWriter.getInstance(document, new FileOutputStream("03.pdf"));document.open();//创建一个三列的表格PdfPTable table = new PdfPTable(3);//设置各列的宽度float[] widths = {1.3f,2.5f,1.0f};table.setWidths(widths);PdfPCell cell = new PdfPCell(new Paragraph("yiyi"));cell.setColspan(3);//设置一个单元格跨的列数table.addCell(cell);table.addCell("1.1");table.addCell("1.2");table.addCell("1.3");//设置单元格背景颜色cell = new PdfPCell(new Paragraph("is red"));cell.setColspan(3);cell.setBackgroundColor(Color.red);table.addCell(cell);//设置单元格边框颜色cell = new PdfPCell(new Paragraph("border is blue"));cell.setColspan(3);cell.setBorderColor(Color.BLUE);table.addCell(cell);//cell.setHorizontalAlignment(Element.ALIGN_RIGHT);//设置单元格内容对齐方式document.add(table);} catch (Exception e) {e.printStackTrace();}document.close();


0 0
原创粉丝点击