Java利用itext实现生成导出PDF文件(在网上找的数据过于杂乱,自己稍微整理了一下)
导入
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
一、文档操作主要步骤
1.新建document对象
Document document =new Document(PageSize.A4,50,50,30,20); //页面大小-左边距-右边距-上边距-下边距。
2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
PdfWriter writer =PdfWriter.getInstance(document,new FileOutputStream(filePath));
3.文档操作
document.open(); //写入数据之前要打开文档
document.add(); // 向文档中添加内容
document.close(); // 关闭文档
PS:也可以这样设置页面属性
FileOutputStream out = new FileOutputStream(pdfFile);
Rectangle tRectangle = new Rectangle(PageSize.A4); // 页面大小
tRectangle.setBackgroundColor(BaseColor.WHITE); // 页面背景色
tRectangle.setBorder(1220);// 边框
tRectangle.setBorderColor(BaseColor.BLACK);// 边框颜色
tRectangle.setBorderWidth(244.2f);// 边框宽度
Document doc = new Document(tRectangle);// 定义文档
doc = new Document(tRectangle.rotate());// 横向打印
PdfWriter writer = PdfWriter.getInstance(doc, out);// 书写器
writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);//版本(默认1.4)
二、字体
BaseFont simpChinese;
// itext jar包自带
simpChinese=BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
//系统字体
simpChinese = BaseFont.createFont("C:/Windows/Fonts/SIMHEI.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
// 宋体后面要加,0 或者,1
simpChinese = BaseFont.createFont("c://windows/fonts/SIMSUN.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
字体设置
参数一:新建好的字体;参数二:字体大小,参数三:字体样式,多个样式用“|”分隔
Font topfont =new Font(bfChinese,14,Font.BOLD);
Font textfont =new Font(bfChinese,10,,Font.BOLD|Font.UNDERLINE);
/**
* 支持中文 设置字体,字体颜色、大小等
* @param fonts 字体路径
* @param size 大小
* @param style 字体样式(比如加粗/斜体等)
* @param color 字体颜色
* @return
*/
public static Font getChineseFont(String fonts,float size, int style, BaseColor color) {
BaseFont simpChinese;
Font ChineseFont = null;
try {
simpChinese = BaseFont.createFont(fonts, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
ChineseFont = new Font(simpChinese, size,style, color);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ChineseFont;
}
三、添加文本的对象:块、短句和段落
Chunk:块(Chunk)是能被添加到文档的文本的最小单位。
Phrase:短句(Phrase)是一系列以特定间距(两行之间的距离)作为参数的块。
Paragraph :段落是一系列块和(或)短句。同短句一样,段落有确定的间距。
段落 Paragraph
添加到文档中的每一个段落将自动另起一行。
Paragraph pt=new Paragraph(name,headfont);
//设置字体样式pt.setAlignment(1);//设置文字居中 0靠左 1,居中 2,靠右
pt.setIndentationLeft(12);// 左缩进
pt.setIndentationRight(12);// 右缩进
pt.setFirstLineIndent(24);// 首行缩进
pt.setLeading(20f);// 行间距
pt.setSpacingBefore(5f);// 设置上空白
pt.setSpacingAfter(10f);// 设置段落下空白
document.add(pt);
doc.add( new Phrase("\n") ); // 文档添加空行
/**
* 设置段落样式
* @param paragraph 段落
* @param alignment 对齐方式
* @param indentationLeft 左缩进
* @param indentationRight 右缩进
* @param firstLineIndent 首行缩进
* @param fixedLeading 行间距
* @param spacingBefore 段落上空白
* @param spacingAfter 段落下空白
*/
public static void setParagraphStyle(Paragraph paragraph,
int alignment,
float indentationLeft,
float indentationRight,
float firstLineIndent,
float fixedLeading,
float spacingBefore,
float spacingAfter
) {
paragraph.setAlignment(alignment);// 对齐方式
paragraph.setIndentationLeft(indentationLeft);// 左缩进
paragraph.setIndentationRight(indentationRight);// 右缩进
paragraph.setFirstLineIndent(firstLineIndent);// 首行缩进
paragraph.setLeading(fixedLeading);// 行间距
paragraph.setSpacingBefore(spacingBefore);// 设置上空白
paragraph.setSpacingAfter(spacingAfter);// 设置段落下空白
}
四、在文档打开之前
以下项只可在文档关闭状态执行 ,包括水印、页眉、页脚
水印
writer.setPageEvent(new PdfWidget().new Watermark());
页眉
Phrase phrase=new Phrase(new Chunk("pdf页眉 ",topfont));
phrase.add(new Chunk("页眉",textfont));
HeaderFooter header =new HeaderFooter(phrase,false);//false不显示页码。
header.setBorder(Rectangle.BOTTOM);//设置是否有边框,边框在下
document.setHeader(header);//写进文档
页脚
HeaderFooter footer =new HeaderFooter(new Phrase("--"),new Phrase("--"));
footer.setAlignment(1);
footer.setBorder(Rectangle.NO_BORDER);//Rectangle.NO_BORDER没有边框
document.setFooter(footer);
五、设置文档属性 (与文档是否打开没有关联)
document.addTitle("Title@sample");// 标题
document.addAuthor("Author@nicaisheng");// 作者
document.addSubject("Subject@iText sample");// 主题
document.addKeywords("Keywords@iText");// 关键字
document.addCreator("Creator@iText");// 创建者
六、表格table
// 这是lowagie,itext版本可用
Table table =new Table(3);//括号参数表示列
int width[] = {10,45,45};//设置每列宽度比例
table.setWidths(width);
table.setWidth(95);//占页面宽度比例
table.setAlignment(Element.ALIGN_CENTER);//居中
table.setAutoFillEmptyCells(true);//自动填满
table.setBorderWidth((float)0.1);//表格边框线条宽度
table.setPadding(1);//边距:单元格的边线与单元格内容的边距
table.setSpacing(0);//间距:单元格与单元格之间的距离
table.addCell(new Paragraph("name"),textfont));//添加单元格内容
table.endHeaders();//每页都会显示表头
单元格内容样式cell
Cell cell=new Cell(new Paragraph("序号",keyfont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
table.addCell(cell);
表格嵌套
最外层表格
PdfPTable table =new PdfPTable(3);
table.setTotalWidth(300);
table.setLockedWidth(true);
PdfPCell cell;
cell =new PdfPCell(new Phrase("Table 5"));
cell.setColspan(3);
cell.setBorderWidth(0);//设置表格的边框宽度为0
table.addCell(cell);
嵌套表格
PdfPTable celltable =new PdfPTable(2);
cell =new PdfPCell(celltable);
cell.setRowspan(2);
cell.setBorderWidth(1);//设置表格的边框宽度为1
cell.setPadding(10);//设置表格与上一个表格的填充为10
table.addCell(cell);
七、文档其他内容
直线
Paragraph p1 =new Paragraph();
p1.add(new Chunk(new LineSeparator()));
doc.add(p1);
点线
Paragraph p2 =new Paragraph();
p2.add(new Chunk(new DottedLineSeparator()));
超链接
Anchor anchor =new Anchor("this is anchor");
定位
点击后,跳到topline的位置
Anchor gotop =new Anchor("go top");
gotop.setReference("#us");
图片
Image img =Image.getInstance(imgPath);
img.setAlignment(Image.MIDDLE); //设置图片居中
img.setBorder(Image.BOX);
img.setBorderWidth(10);
img.setBorderColor(BaseColor.WHITE);
img.scaleToFit(900, 350);// 设置图片大小
img.scalePercent(40);//依照比例缩放
合并PDF并插入页码https://blog.csdn.net/z446981439/article/details/103821421
参考链接:https://www.csdn.net/tags/MtzaggzsOTY4MDctYmxvZwO0O0OO0O0O.html