利用itext包生成pdf请求,代码如下:
引入itext包
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.0</version> </dependency>
//1,创建文档对象 Document document = new Document(); //2,监听输出流 ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); //3,打开文档 document.open(); //4,添加文本 document.add(new Paragraph("pdf渲染好的文本")); //5,关闭文档 document.close(); //6,设置请求返回类型 response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=onetouchExchangeAccount.pdf"); response.setContentLength(baos.size()); OutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); out.close();
如果输出pdf文档有中文,则需要加入中文字体库包
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
上面第4步代码需要加入字体设置,代码修改如下:
BaseFont bfChinese = BaseFont.createFont( "STSongStd-Light" , "UniGB-UCS2-H" , false ); Font fontChinese = new Font(bfChinese , 12, Font.NORMAL); document.add(new Paragraph("pdf渲染好的文本",fontChinese));