我们在项目当中经常要导出pdf文档,pdf文档还要按一定的格式导出,以下介绍导出pdf文档功能:
1)支持A4纸大小导出
2)指定文字显示的位置
3)支持表格展示数据
4)添加水印
开源下载 java导出PDF、导出漂亮PDF、导出指定格式PDF-Java文档类资源-CSDN下载
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
/**
* @param srcFile 导出文件位置
* @throws DocumentException
* @throws IOException
*/
public static void pdf6(String srcFile) throws DocumentException, IOException {
//创建文件
Document document = new Document(PageSize.A4);
//建立一个书写器
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(srcFile));
//打开文件
document.open();
//添加内容
//document.add(new Paragraph("HD content here"));
//中文字体,解决中文不能显示问题
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// 红标题字体风格
Font redTitleFont = new Font(bfChinese, 20, Font.BOLD, BaseColor.BLACK);
// 红标题抬头
Paragraph redTitle = new Paragraph("订单:6666889", redTitleFont);
redTitle.setAlignment(Element.ALIGN_LEFT); // 居中Element.ALIGN_CENTER
document.add(redTitle); // 文档中加入红标题字段
// 正文字体风格
Font contextFont = new Font(bfChinese, 10, Font.NORMAL);
// 2列的表.
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100); // 宽度100%填充
table.setSpacingBefore(10f); // 前间距
table.setSpacingAfter(10f); // 后间距
ArrayList<PdfPRow> listRow = table.getRows();
//设置列宽
float[] columnWidths = { 3f, 4f};
table.setWidths(columnWidths);
//行1
PdfPCell cells1[]= new PdfPCell[2];
PdfPRow row1 = new PdfPRow(cells1);
.......
........
.......
.......
........
.......
.......
........
.......
.......
........
.......
}