一、IText概述
IText是著名的开放项目,是用于生成PDF文档的一个java类库。通过IText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。
引入jar包
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
案例
@Action("report_exportPdf")
public String exportPdf() throws IOException, DocumentException {
// 查询出 满足当前条件 结果数据
List<WayBill> wayBills = wayBillService.findWayBills(model);
// 下载导出
// 设置头信息
ServletActionContext.getResponse().setContentType("application/pdf");
String filename = "运单数据.pdf";
String agent = ServletActionContext.getRequest()
.getHeader("user-agent");
filename = FileUtils.encodeDownloadFilename(filename, agent);
ServletActionContext.getResponse().setHeader("Content-Disposition",
"attachment;filename=" + filename);
// 生成PDF文件
Document document = new Document();
PdfWriter.getInstance(document, ServletActionContext.getResponse()
.getOutputStream());
document.open();
// 写PDF数据
// 向document 生成pdf表格
Table table = new Table(7);
table.setWidth(80); // 宽度
table.setBorder(1); // 边框
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // 水平对齐方式
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP); // 垂直对齐方式
// 设置表格字体 --- 显示中文
BaseFont cn = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",
false);
Font font = new Font(cn, 10, Font.NORMAL, Color.BLUE);
// 写表头
table.addCell(buildCell("运单号", font));
table.addCell(buildCell("寄件人", font));
table.addCell(buildCell("寄件人电话", font));
table.addCell(buildCell("寄件人地址", font));
table.addCell(buildCell("收件人", font));
table.addCell(buildCell("收件人电话", font));
table.addCell(buildCell("收件人地址", font));
// 写数据
for (WayBill wayBill : wayBills) {
table.addCell(buildCell(wayBill.getWayBillNum(), font));
table.addCell(buildCell(wayBill.getSendName(), font));
table.addCell(buildCell(wayBill.getSendMobile(), font));
table.addCell(buildCell(wayBill.getSendAddress(), font));
table.addCell(buildCell(wayBill.getRecName(), font));
table.addCell(buildCell(wayBill.getRecMobile(), font));
table.addCell(buildCell(wayBill.getRecAddress(), font));
}
// 将表格加入文档
document.add(table);
document.close();
return NONE;
}
private Cell buildCell(String content, Font font)
throws BadElementException {
Phrase phrase = new Phrase(content, font);
return new Cell(phrase);
}
二、入门案例
1、生成一个PDF
-
- Document document = new Document();
-
- PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "createSamplePDF.pdf"));
-
- document.open();
-
- document.add(new Paragraph("Hello World"));
-
- document.close();
2、页面大小,页面背景色,页边空白,Title,Author,Subject,Keywords
-
- Rectangle rect = new Rectangle(PageSize.B5.rotate());
-
- rect.setBackgroundColor(BaseColor.ORANGE);
-
- Document doc = new Document(rect);
-
- PdfWriter writer = PdfWriter.getInstance(doc, out);
-
-
- writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
-
-
- doc.addTitle("Title@sample");
- doc.addAuthor("Author@rensanning");
- doc.addSubject("Subject@iText sample");
- doc.addKeywords("Keywords@iText");
- doc.addCreator("Creator@iText");
-
-
- doc.setMargins(10, 20, 30, 40);
-
- doc.open();
- doc.add(new Paragraph("Hello World"));
3、设置密码
- PdfWriter writer = PdfWriter.getInstance(doc, out);
-
-
- writer.setEncryption("Hello".getBytes(), "World".getBytes(),
- PdfWriter.ALLOW_SCREENREADERS,
- PdfWriter.STANDARD_ENCRYPTION_128);
-
- doc.open();
- doc.add(new Paragraph("Hello World"));
4、添加Page
- document.open();
- document.add(new Paragraph("First page"));
- document.add(new Paragraph(Document.getVersion()));
-
- document.newPage();
- writer.setPageEmpty(false);
-
- document.newPage();
- document.add(new Paragraph("New page"));
5、添加水印(背景图)
-
- PdfReader reader = new PdfReader(FILE_DIR + "setWatermark.pdf");
- PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR
- + "setWatermark2.pdf"));
-
- Image img = Image.getInstance("resource/watermark.jpg");
- img.setAbsolutePosition(200, 400);
- PdfContentByte under = stamp.getUnderContent(1);
- under.addImage(img);
-
-
- PdfContentByte over = stamp.getOverContent(2);
- over.beginText();
- BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
- BaseFont.EMBEDDED);
- over.setFontAndSize(bf, 18);
- over.setTextMatrix(30, 30);
- over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
- over.endText();
-
-
- Image img2 = Image.getInstance("resource/test.jpg");
- img2.setAbsolutePosition(0, 0);
- PdfContentByte under2 = stamp.getUnderContent(3);
- under2.addImage(img2);
-
- stamp.close();
- reader.close();
6、插入Chunk, Phrase, Paragraph, List
-
- document.add(new Chunk("China"));
- document.add(new Chunk(" "));
- Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
- Chunk id = new Chunk("chinese", font);
- id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
- id.setTextRise(6);
- document.add(id);
- document.add(Chunk.NEWLINE);
-
- document.add(new Chunk("Japan"));
- document.add(new Chunk(" "));
- Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
- Chunk id2 = new Chunk("japanese", font2);
- id2.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
- id2.setTextRise(6);
- id2.setUnderline(0.2f, -2f);
- document.add(id2);
- document.add(Chunk.NEWLINE);
-
-
- document.newPage();
- document.add(new Phrase("Phrase page"));
-
- Phrase director = new Phrase();
- Chunk name = new Chunk("China");
- name.setUnderline(0.2f, -2f);
- director.add(name);
- director.add(new Chunk(","));
- director.add(new Chunk(" "));
- director.add(new Chunk("chinese"));
- director.setLeading(24);
- document.add(director);
-
- Phrase director2 = new Phrase();
- Chunk name2 = new Chunk("Japan");
- name2.setUnderline(0.2f, -2f);
- director2.add(name2);
- director2.add(new Chunk(","));
- director2.add(new Chunk(" "));
- director2.add(new Chunk("japanese"));
- director2.setLeading(24);
- document.add(director2);
-
-
- document.newPage();
- document.add(new Paragraph("Paragraph page"));
-
- Paragraph info = new Paragraph();
- info.add(new Chunk("China "));
- info.add(new Chunk("chinese"));
- info.add(Chunk.NEWLINE);
- info.add(new Phrase("Japan "));
- info.add(new Phrase("japanese"));
- document.add(info);
-
-
- document.newPage();
- List list = new List(List.ORDERED);
- for (int i = 0; i < 10; i++) {
- ListItem item = new ListItem(String.format("%s: %d movies",
- "country" + (i + 1), (i + 1) * 100), new Font(
- Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE));
- List movielist = new List(List.ORDERED, List.ALPHABETICAL);
- movielist.setLowercase(List.LOWERCASE);
- for (int j = 0; j < 5; j++) {
- ListItem movieitem = new ListItem("Title" + (j + 1));
- List directorlist = new List(List.UNORDERED);
- for (int k = 0; k < 3; k++) {
- directorlist.add(String.format("%s, %s", "Name1" + (k + 1),
- "Name2" + (k + 1)));
- }
- movieitem.add(directorlist);
- movielist.add(movieitem);
- }
- item.add(movielist);
- list.add(item);
- }
- document.add(list);
7、插入Anchor, Image, Chapter, Section
-
- Paragraph country = new Paragraph();
- Anchor dest = new Anchor("china", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
- dest.setName("CN");
- dest.setReference("http://www.china.com");//external
- country.add(dest);
- country.add(String.format(": %d sites", 10000));
- document.add(country);
-
- document.newPage();
- Anchor toUS = new Anchor("Go to first page.", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
- toUS.setReference("#CN");
- document.add(toUS);
-
-
- document.newPage();
- Image img = Image.getInstance("resource/test.jpg");
- img.setAlignment(Image.LEFT | Image.TEXTWRAP);
- img.setBorder(Image.BOX);
- img.setBorderWidth(10);
- img.setBorderColor(BaseColor.WHITE);
- img.scaleToFit(1000, 72);
- img.setRotationDegrees(-30);
- document.add(img);
-