介绍
这几天需要写一些PDF的模板,使用到itext,写一个Demo。
实现基本步骤:
创建一个PDF的基本步骤:
1.先创建一个Document
2.新建一个书写器和Document关联
2.1.添加水印和页眉页脚
3.打开文档
4.向文档中添加内容
5.关闭文档
依赖:
<dependencies>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>
代码:
测试类:
package xyq.text;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.lowagie.text.pdf.PdfTable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MyTest {
public static void main(String[] args) throws Exception {
Document document = new Document(PageSize.A4);
File file = new File("F:\\PDFDemo.pdf");
file.createNewFile();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
writer.setPageEvent(new Watermark("Hello IText"));
writer.setPageEvent(new MyHeaderFooter());
document.open();
document.addTitle("addTitle");
document.addAuthor("addAuthor");
document.addSubject("addSubject");
document.addKeywords("addKeyWords");
document.addCreator("addCreator");
document.addCreationDate();
new MyTest().generatePDF(document);
document.close();
}
private static Font titleFont;
private static Font headFont;
private static Font keyFont;
private static Font textFont;
private static int maxWidth = 520;
static {
try {
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titleFont = new Font(bfChinese, 16, Font.BOLD);
headFont = new Font(bfChinese, 14, Font.BOLD);
keyFont = new Font(bfChinese, 10, Font.BOLD);
textFont = new Font(bfChinese, 10, Font.NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
}
private void generatePDF(Document document) throws Exception {
Paragraph paragraph = new Paragraph("美好的一天从早起开始", titleFont);
paragraph.setAlignment(1);
paragraph.setIndentationLeft(12);
paragraph.setIndentationRight(12);
paragraph.setFirstLineIndent(24);
paragraph.setLeading(20f);
paragraph.setSpacingBefore(5f);
paragraph.setSpacingAfter(10f);
Paragraph p1 = new Paragraph();
p1.add(new Chunk(new LineSeparator()));
Paragraph p2 = new Paragraph();
p2.add(new Chunk(new DottedLineSeparator()));
Anchor anchor = new Anchor("baidu");
anchor.setReference("www.baidu.com");
Anchor gotoP = new Anchor("goto");
gotoP.setReference("#top");
Image image = Image.getInstance("F:\\sundun\\111.jpg");
image.setAlignment(Image.ALIGN_CENTER);
image.scalePercent(40);
PdfPTable table = createTable(new float[]{40, 120, 120, 120, 80, 80});
table.addCell(createCell("美好的一天开始了", headFont, Element.ALIGN_LEFT, 6, false));
table.addCell(createCell("早上9:00", keyFont, Element.ALIGN_CENTER));
table.addCell(createCell("中午11:00", keyFont, Element.ALIGN_CENTER));
table.addCell(createCell("中午13:00", keyFont, Element.ALIGN_CENTER));
table.addCell(createCell("下午15:00", keyFont, Element.ALIGN_CENTER));
table.addCell(createCell("下午17:00", keyFont, Element.ALIGN_CENTER));
table.addCell(createCell("晚上19:00", keyFont, Element.ALIGN_CENTER));
Integer totalQuantity = 0;
for (int i = 0; i < 5; i++) {
table.addCell(createCell("起床", textFont));
table.addCell(createCell("吃午饭", textFont));
table.addCell(createCell("午休", textFont));
table.addCell(createCell("下午茶", textFont));
table.addCell(createCell("回家", textFont));
table.addCell(createCell("吃晚饭", textFont));
totalQuantity++;
}
table.addCell(createCell("总计", keyFont));
table.addCell(createCell("", textFont));
table.addCell(createCell("", textFont));
table.addCell(createCell("", textFont));
table.addCell(createCell(String.valueOf(totalQuantity) + "件事", textFont));
table.addCell(createCell("", textFont));
document.add(paragraph);
document.add(anchor);
document.add(p2);
document.add(gotoP);
document.add(p1);
document.add(table);
document.add(image);
}
private PdfPCell createCell(String value, Font font) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, font));
return cell;
}
private PdfPCell createCell(String value, Font font, int align) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
return cell;
}
private PdfPCell createCell(String value, Font font, int align, int colspan) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
return cell;
}
private PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
cell.setPadding(3.0f);
if (!boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(15.0f);
cell.setPaddingBottom(8.0f);
} else {
cell.setBorder(0);
cell.setPaddingTop(0.0f);
cell.setPaddingBottom(8.0f);
}
return cell;
}
private PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
cell.setBorderWidthLeft(borderWidth[0]);
cell.setBorderWidthRight(borderWidth[1]);
cell.setBorderWidthTop(borderWidth[2]);
cell.setBorderWidthBottom(borderWidth[3]);
cell.setPaddingTop(paddingSize[0]);
cell.setPaddingBottom(paddingSize[1]);
if (flag) {
cell.setColspan(2);
}
return cell;
}
private PdfPTable createTable(int colNumber, int align) {
PdfPTable table = new PdfPTable(colNumber);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(align);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
private PdfPTable createTable(float[] widths) {
PdfPTable table = new PdfPTable(widths);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
private PdfPTable creatBlankTable() {
PdfPTable table = new PdfPTable(1);
table.getDefaultCell().setBorder(0);
table.addCell(createCell("", keyFont));
table.setSpacingAfter(20.0f);
table.setSpacingBefore(20.0f);
return table;
}
}
页脚/页眉:
package xyq.text;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import javax.print.Doc;
import java.io.IOException;
public class MyHeaderFooter extends PdfPageEventHelper {
PdfTemplate totalPage;
Font hfFont;
{
try {
hfFont = new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 8, Font.NORMAL);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onOpenDocument(PdfWriter pdfWriter, Document document) {
PdfContentByte directContent = pdfWriter.getDirectContent();
totalPage = directContent.createTemplate(30, 16);
}
public void onEndPage(PdfWriter writer, Document document) {
PdfPTable table = new PdfPTable(3);
try {
table.setTotalWidth(PageSize.A4.getWidth() - 100);
table.setWidths(new int[]{24, 24, 3});
table.setLockedWidth(true);
table.getDefaultCell().setFixedHeight(-10);
table.getDefaultCell().setBorder(Rectangle.BOTTOM);
table.addCell(new Paragraph("我是页眉/页脚", hfFont));
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(new Paragraph("第" + writer.getPageNumber() + "页", hfFont));
PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));
cell.setBorder(Rectangle.BOTTOM);
table.addCell(cell);
table.writeSelectedRows(0, -1, 50, PageSize.A4.getHeight() - 20, writer.getDirectContent());
} catch (Exception e) {
e.printStackTrace();
}
}
public void onCloseDocument(PdfWriter writer, Document document) {
String text = "总" + (writer.getPageNumber()) + "页";
ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text, hfFont), 2, 2, 0);
}
}
水印:
package xyq.text;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
public class Watermark extends PdfPageEventHelper {
Font font = new Font(Font.FontFamily.HELVETICA, 30, Font.BOLD, new GrayColor(0.95f));
private String waterCont;
public Watermark() {
}
public Watermark(String waterCont) {
this.waterCont = waterCont;
}
@Override
public void onEndPage(PdfWriter writer, Document document) {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
ColumnText.showTextAligned(
writer.getDirectContentUnder(),
Element.ALIGN_CENTER,
new Phrase(this.waterCont == null ? "HELLO HELLo" : this.waterCont, font),
(50.5f + i * 350),
(40.0f + j * 150),
writer.getCurrentPageNumber() % 2 == 1 ? 45 : -45);
}
}
}
}