前端发送数据到后台servlet打印pdf与word文档

前端需要使用表单提交数据,后端便可以直接通过读写流写入pdf与word模板。完成文件的下载,jquery ajax发送的数据经后端接收后不能调用保存方法,无法下载。使用表单提交代码如下:
前台js:
//封装提交数据的方法
//生成表单;url为访问的后台接口,filevalue为需要传入的数据;
function downloadFileByForm(filevalue,url) {

  var form = $("<form></form>").attr("action", url).attr("method", "post");
    form.append($("<input></input>").attr("type", "hidden").attr("name", "fileName").attr("value", filevalue));
 //提交表单。
    form.appendTo('body').submit().remove();
}

后台servlet:
1、需要准备一个pdf/word模板放到项目的lib文件中,需要插件库itext-1.3.jar,(支持word)itext-asian-5.2.0.jar,itextpdf-5.5.11.jar(支持pdf)
2、在Dopost中利用request.getParmart(“fileName”),获取前台发送的数据并解析出来,传入一个封装方法中,用于布局pdf:

public void pdflife(String path,String fontpath,JSONObject jsonObject) {
Document document = new Document();
try {
//文件路径
PdfWriter.getInstance(document, new FileOutputStream(path));
document.open();
// 使用iTextAsian.jar中的字体
BaseFont FontChinese = BaseFont.createFont(fontpath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//系统默认字体
// String fontPath = “C:/Windows/Fonts/msyh.ttf”;
// BaseFont baseFont1 = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(FontChinese);
Font f20 = new Font(FontChinese, 20, Font.NORMAL);//一号字体
//添加logo图片
String headPicture = “C:/Users/ffgg/Pictures/8.jpg”;
try {
Image image = Image.getInstance(headPicture);
image.scaleAbsolute(30, 30);//调整图片大小
document.add(image);
} catch (Exception ex) {
}
//第3步,向文档添加文字. 文档由段组成
Paragraph title1 = new Paragraph(“报错收集器”, f20);
title1.setSpacingAfter(10);//–段落后距离
title1.setAlignment(Element.ALIGN_CENTER);//居中
Chapter chapter1 = new Chapter(title1, 1);
chapter1.setNumberDepth(1);
Section section1 = chapter1;
document.add(title1);
//加横线
//1.线宽度
//2.直线长度,是个百分百,0-100之间
//3.直线颜色
//4.直线位置
//5.上下移动位置
LineSeparator line = new LineSeparator(0.5f,100,BaseColor.BLACK,Element.ALIGN_CENTER,-15f);
document.add(line);
PdfPTable table = new PdfPTable(4);//创建一个含有4列的表格
//实例化表格
// table.setSpacingBefore(35);//设置段落上空白标题与内容间距离
float[] cellsWidth = { 0.3f, 0.4f, 0.3f, 0.4f};
table.setWidths(cellsWidth);// 单元格宽度
table.setTotalWidth(500f);//表格总宽度
table.setWidthPercentage(100);//表格宽度百分比
table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
//格子(用来装表头的数据)
PdfPCell[] cells=new PdfPCell[4];
//用来装userid
PdfPCell cell1;
//用来装name
PdfPCell cell2;
//用来装info
PdfPCell cell3;
PdfPCell cell4;
Paragraph title2 = new Paragraph(“基础信息”, f20);
title2.setSpacingAfter(10);//–段落后距离
title2.setSpacingBefore(10);//–段落前距离
title2.setAlignment(Element.ALIGN_CENTER);//居中
//首行合并列
document.add(title2);
cell1=new PdfPCell(new Phrase(“1234”,font));
cell2=new PdfPCell(new Phrase(“1234”,font));
cell3=new PdfPCell(new Phrase(“1234”,font));
cell4=new PdfPCell(new Phrase(“1234”,font));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);
Paragraph title3 = new Paragraph(“工况信息”, f20);
title3.setSpacingAfter(10);//–段落后距离
title3.setSpacingBefore(10);//–段落前距离
title3.setAlignment(Element.ALIGN_CENTER);//居中
//首行合并列

                 document.add(title3);
                 LineSeparator line2 = new LineSeparator(0.5f,100,BaseColor.BLACK,Element.ALIGN_CENTER,5f);
                   document.add(line2);
        //组成一行
        table.completeRow();
 //开启文档分页
        table.setSplitLate(false);
        table.setSplitRows(true);
        //把表格添加进文档
        document.add(table);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        document.close();
    }
}

3、封装一个调用模 板pdf数据的方法save():
public void save(HttpServletRequest request,HttpServletResponse response,String path,String name) throws IOException {

FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;

try {
//获取下载文件所在路径
// String path = request.getServletContext().getRealPath("/WEB-INF/data/"+name);
File file = new File(path);
//判断文件是否存在
if(file.exists()){
//且仅当此对象抽象路径名表示的文件或目录存在时,返回true
response.setContentType(“application/”+name);
//控制下载文件的名字
response.addHeader(“Content-Disposition”, “attachment;filename=”+name);
byte buf[] = new byte[1024];
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
os = response.getOutputStream();
int i = bis.read(buf);
while(i!=-1){
os.write(buf,0,i);
i = bis.read(buf);

}
}else{
System.out.println(“您下载的资源已经不存在了”);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
os.close();
bis.close();
fis.close();
}
}
4、最后在dopost中调用这两个方法:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(“text/html;charset=utf-8”);
String fileName = request.getParameter(“fileName”);
System.out.print(fileName);
JSONObject jsonObject = JSONObject.fromObject(fileName);

    //String name="报告.docx";
      String name="baogao.pdf";
      //读取模板路径
	  String path = request.getServletContext().getRealPath("/WEB-INF/data/"+name);			  
	  String fontpath=request.getServletContext().getRealPath("/WEB-INF/data/msyh.ttf");
	  pdflife(path,fontpath,jsonObject);//必须先写入数据到模板,再执行save,否则下载文件  的数据无更新
	  save(request,response,path,name);
	  }
	  最后前台点击下载,发送数据后,后台调用save()方法,直接在前端浏览器生成pdf文件,pdf效果如下:

在这里插入图片描述
最后:第一次写博客,本文不详细叙述过程,只粗略介绍实现方法。关于pdf设置布局,字体文件等没有叙述。如需要详细了解可以联系我qq1310675056

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值