1、导入jar包:iTextpdf.jar
2、代码部分
private void saveAsPdfFile(String pdf_save_address){
// 创建文档实例
Document document =new Document();
FileOutputStream fos =null;
PdfWriter writer;
try {
fos =new FileOutputStream(pdf_save_address);
// 获取PdfWriter实例
writer = PdfWriter.getInstance(document, fos);
// 设置每行的间距
writer.setInitialLeading(30);
// 打开文档
document.open();
// 添加标题内容
document.add(setParagraph(14, Font.BOLD, BaseColor.BLUE, "标题"));
// 添加表格,3列 注意:必须设置列数!!!
PdfPTable table =new PdfPTable(6);
// 设置table的宽度占父容器宽度的100%
table.setWidthPercentage(100);
// 设置表格上面空白宽度
table.setSpacingBefore(20f);
// 表格只可以设置水平对齐
table.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
table.addCell(setPdfCell(Font.BOLD, BaseColor.BLUE, "编号"));
table.addCell(setPdfCell(Font.BOLD, BaseColor.BLUE, "时间"));
table.addCell(setPdfCell(Font.BOLD, BaseColor.BLUE, "地点"));
for (int aw =0; aw <500; aw++) {
Log.d("wpei", "i = " + aw);
table.addCell(setPdfCell(Font.NORMAL, BaseColor.BLACK, "123456"));
}
// 如果某一个单元格没有内容,也必须创建并添加单元格。
// 如果某一行的所有列并没有填充完成,该表格的最后一行会不显示。
// 因为这种流式添加数据,所以有某个单元格没有被添加,最后肯定表现在最后一行上。
// 所以如果某一个单元格没有内容,也必须创建并添加单元格!使用completeRow()方法填充,需要注意compleRow方法只针对于当前行,并不是所有行。
table.completeRow();
document.add(table);
}catch (Exception e){
e.printStackTrace();
}finally {
// 操作完成后必须执行文档关闭操作
if(document !=null){
document.close();
}
// 关闭文件输出流
if(fos !=null){
try {
fos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}