iText产生PDF

通过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);//文章的小标题1
			section0.add(textPhrase);
			
			Section section = chapter1.addSection("xiao biao ti er",2);//文章的小标题2
			section.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();


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章