使用iText可以很方便地生成PDF文件,但是如果包含中文的话要先下载语言包。
生成pdf文件第一步新建文件:
Document doc = new Document(PageSize.A4);
PdfWriter.getInstance(doc, new FileOutputStream("F:/test.pdf"));
doc.open();
然后新建中文字体样式:
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
Font font = new Font(bf, 9, Font.NORMAL);
可以插入Logo:
Image image1 = Image.getInstance("Logo.png");
image1.setAlignment(Image.ALIGN_RIGHT);
doc.add(image1);
插入段落:
doc.add(newParagraph("测试/n/n", font, Paragraph.ALIGN_RIGHT));
插入表格:
PdfPTable tmpTable= new PdfPTable(1);
tmpTable.setWidthPercentage(100);
tmpTable.addCell(newCell("Test", font, PdfPCell.ALIGN_LEFT, 1, 1));
doc.add(tmpTable);
doc.close();
生成Cell的方法:
public PdfPCell newCell(String cellStr,Font font,int alignment,int colspan,int rowspan) { PdfPCell cell=new PdfPCell(); cell.setPhrase(new Paragraph(cellStr,font)); cell.setHorizontalAlignment(alignment); cell.setColspan(colspan); cell.setRowspan(rowspan); return cell; }