需求说明:
把每个人某月的工资数据生成为单个的pdf,并把一个部门的pdf打包成rar共用户查询下载,就算只有一个人也要打包成rar下载
整体的pdf可以分为两部分组成,第一部分为一对一,相当于一个表格只有一条数据,此部分使用 adboe 模板制作,利用pdf表单域,给每个表单域复制,从而生成pdf,第二部分为表单数据,因为会有多条数据产生,所以在第一部分的基础上,在后面追加pdf
- 前面为获取tomcat根目录方法,后面则在此目录后面新建一个目录
String tomcatPath = System.getProperty("catalina.home")+"/juejin/"
- 判断上面目录是否存在,如果不存在就新建一个目录,目的为在tomcat根目录下面建一个目录,为临时文件夹
File myPath = new File(tomcatPath);
if(!myPath.exists()){
myPath.mkdir();
logger.info("存放文件目录为"+tomcatPath)
}
3.获取存放模板的路径:此文件放在 webapps/template/juejin.pdf
String path = request.getSession().getServletContext().getRealPath("template/juejin.pdf");
调用:File tozipFile = jueJinService.PDFTemplet(file,juejin,path);
- 根据模板生成pdf,内容为一对一生成数据,例如奖状
/**
* 生成pdf
* @param file 新建立的pdf的名字
* @param jueJin 单独每个实体类,用于放在模板中的字段
* @param path 模板路径
* @throws Exception
*/
public File PDFTemplet(File file, JueJin jueJin, String path) throws Exception{
//本地模板路径
String templatePdfPath = path;
Document document = new Document();
//生产pdfreader
PdfReader reader = new PdfReader(templatePdfPath);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
/* 读取*/
PdfStamper pdfStamper= new PdfStamper(reader,bos);
/*设置字体格式*/
//BaseFont baseFont = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
ArrayList<BaseFont> fontList=new ArrayList<>();
fontList.add(bf);
AcroFields s=pdfStamper.getAcroFields();//获取form域
s.setSubstitutionFonts(fontList);
/*Field , 这个是自己在pdf上定义的变量名称*/
//这里设置number = 1 是因为模板只能对应一条记录
s.setField("number","1");
s.setField("name",jueJin.getName());
// 如果为false那么生成的PDF文件还能编辑,一定要设为true
pdfStamper.setFormFlattening(true);
pdfStamper.close();
FileOutputStream fileSteam =new FileOutputStream(file);
fileSteam.write(bos.toByteArray());
//fileSteam.close();
bos.close();
reader.close();
return file;
}
调用:File finalFile =jueJinService.generatePDF(file,fileTable,List);
- 利用
itextpdf生成 表单数据
// 定义全局的字体静态变量
private static Font titlefont;
private static Font headfont;
private static Font keyfont;
private static Font textfont;
// 最大宽度
private static int maxWidth = 150;
// 静态代码块
static {
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 8, Font.BOLD);
headfont = new Font(bfChinese, 8, Font.BOLD);
keyfont = new Font(bfChinese, 8, Font.BOLD);
textfont = new Font(bfChinese, 8, Font.NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param file 导入文件,为使用表单域之后的文件
* @param fileTable 返回的文件为,加入表格之后的文件
* list 生成表格的多条数据
* @return
* @throws Exception
*/
public File generatePDF(File file,File fileTable,List<JueJin> list) throws Exception {
// 段落
File finalFile = fileTable;
FileOutputStream outputStream = new FileOutputStream(finalFile);
PdfReader reader = new PdfReader(file.getPath());// 读取pdf模板
Rectangle pageSize = reader.getPageSize(1);
Document document = new Document(pageSize);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cbUnder = writer.getDirectContentUnder();
PdfImportedPage pageTemplate = writer.getImportedPage(reader, 1);
cbUnder.addTemplate(pageTemplate, 0, 0);
document.newPage();
// 表格
PdfPTable table = createTable(new float[] { 50,100});
table.addCell(createCell("表头", textfont, Element.ALIGN_LEFT, 2, false));
table.addCell(createCell("序号", textfont, Element.ALIGN_CENTER)); // 1
table.addCell(createCell("名字", textfont, Element.ALIGN_CENTER)); // 2
Integer totalQuantity = 1;
for(JueJin juejin :list){
table.addCell(createCell(totalQuantity.toString(), textfont, Element.ALIGN_CENTER));
table.addCell(createCell(juejin.getName(), textfont, Element.ALIGN_CENTER));
totalQuantity ++;
}
if(list.size()==0){
table.addCell(createCell("1", textfont));
table.addCell(createCell("无数据", textfont, Element.ALIGN_CENTER));
}
document.add(table);
document.close();
reader.close();
return finalFile;
}
/**
* 创建单元格(指定字体)
* @param value
* @param font
* @return
*/
public 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;
}
/**
* 创建单元格(指定字体、水平..)
* @param value
* @param font
* @param align
* @return
*/
public 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;
}
/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并)
* @param value
* @param font
* @param align
* @param colspan
* @return
*/
public 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;
}
/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并、设置单元格内边距)
* @param value
* @param font
* @param align
* @param colspan
* @param boderFlag
* @return
*/
public 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 if (boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(0.0f);
cell.setPaddingBottom(15.0f);
}
return cell;
}
/**
* 创建单元格(指定字体、水平..、边框宽度:0表示无边框、内边距)
* @param value
* @param font
* @param align
* @param borderWidth
* @param paddingSize
* @param flag
* @return
*/
public 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;
}
/**------------------------创建表格单元格的方法end----------------------------*/
/**--------------------------创建表格的方法start------------------- ---------*/
/**
* 创建默认列宽,指定列数、水平(居中、右、左)的表格
* @param colNumber
* @param align
* @return
*/
public 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;
}
/**
* 创建指定列宽、列数的表格
* @param widths
* @return
*/
public 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;
}
/**
* 创建空白的表格
* @return
*/
public PdfPTable createBlankTable() {
PdfPTable table = new PdfPTable(1);
table.getDefaultCell().setBorder(0);
table.addCell(createCell("", keyfont));
table.setSpacingAfter(20.0f);
table.setSpacingBefore(20.0f);
return table;
}
- 压缩
/**
* 把文件集合打成zip压缩包
* @param srcFiles 压缩文件集合
* @param zipFile zip文件名
* @throws RuntimeException 异常
*/
public String toZip(List<File> srcFiles, File zipFile) throws RuntimeException{
String returnZipPath = "";
long start = System.currentTimeMillis();
if(zipFile == null){
logger.error("压缩包文件名为空!");
return "压缩包文件名为空";
}
if(!zipFile.getName().endsWith(".rar")){
logger.error("压缩包文件名异常,zipFile={}", zipFile.getPath());
return "压缩包文件名异常";
}
ZipOutputStream zos = null;
try {
FileOutputStream out = new FileOutputStream(zipFile);
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.setComment("我是注释");
zos.closeEntry();
in.close();
//out.close();
}
long end = System.currentTimeMillis();
logger.info("压缩完成,耗时:" + (end - start) + " ms");
returnZipPath = zipFile.getName();
} catch (Exception e) {
e.printStackTrace();
logger.error("ZipUtil toZip exception, ", e);
throw new RuntimeException("zipFile error from ZipUtils", e);
}finally {
try{
zos.close();
}catch (IOException io){
io.printStackTrace();
}
}
return returnZipPath;
}
7.调用浏览器方法,使用户保存在本地
String Zippath = tomcatPath+juejinService.toZip(toZips,zipFiles);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + new String((zipFile+".rar").getBytes(), "UTF-8"));
//读取文件
InputStream in = new FileInputStream(Zippath);
ServletOutputStream outputStream = response.getOutputStream();
//写文件
int b;
while((b=in.read())!= -1){
outputStream.write(b);
}
in.close();
outputStream.close();
- 删除服务器tomcat临时文件
/**
* 迭代删除文件夹
* @param dirPath 文件夹路径
*/
public void deleteDir(String dirPath){
File file = new File(dirPath);// 读取
if(file.isFile()){ // 判断是否是文件夹
file.delete();// 删除
}else{
File[] files = file.listFiles(); // 获取文件
if(files == null){
file.delete();// 删除
}else{
for (int i = 0; i < files.length; i++){// 循环
deleteDir(files[i].getAbsolutePath());
}
file.delete();// 删除
}
}
}
当初写这个是在网上边学边写的,可以说是把网上的资料拼了一下,具体的网址已经忘记了,如果作者看到某一部分是自己,可以联系我。