使用itext生成pdf文件
1.使用itext生成pdf首先需要引入itext的包,由于我们的项目时maven项目,所以只需在pom.xml中配置即可:
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.0</version> </dependency> <dependency> <groupId>com.itextpdf.tool</groupId> <artifactId>xmlworker</artifactId> <version>5.5.0</version> </dependency>
2.生成pdf文件:
/** * * Description: 公共方法:生成pdf文件<br> * @return */ public File pdfInfo() throws Exception { //生成PDF源文件 File file=new File("毕结业证书.pdf"); //文档生成器--PageSize.A4默认A4打印 //A4的构造方法为new RectangleReadOnly(595, 842),参数 对调即是做横向展示 Document document=new Document(new RectangleReadOnly(842, 595)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); for(DiplomaPrintQB qb:list) { PdfContentByte cb = writer.getDirectContent(); /*BaseFont chineseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);*/ String font=getFont(zzBydypz.getXzt());//该处调用getFont方法,获取需要使用字体
//设置pdf字体 BaseFont chineseFont = BaseFont.createFont(font, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); cb.beginText(); cb.setFontAndSize(chineseFont, Integer.parseInt(zzBydypz.getXdx())); //遍历xxh数组,确定字段绝对位置 for(int i=0;i<xxh.length;i++) {
//获取需要打印的内容 String value=getContent(xxh[i],qb); //添加学生照片 if(xxh[i].equals("24")) { if(StringUtils.isBlank(value)){ HttpServletRequest request=ServletActionContext.getRequest();
//获取系统自带默认照片 String path = request.getSession().getServletContext().getRealPath("/"); value=path+"images/new/img-show.png"; } Image image=Image.getInstance(value); image.setAbsolutePosition(Integer.parseInt(hzb[i]), (450-Integer.parseInt(zzb[i]))); cb.addImage(image); }else{ cb.showTextAligned(PdfContentByte.ALIGN_LEFT, value, Integer.parseInt(hzb[i]), (580-Integer.parseInt(zzb[i])), 0); } } cb.endText(); //下一页(用于生成新的PDF页面) document.newPage(); } document.close(); return file; }
3.提供一个下载 pdf的方法:
/** * * Description: 下载PDF<br> * @return */ public void downloadDataPdf() throws Exception { InputStream is = new BufferedInputStream(new FileInputStream(pdfInfo())); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("application/pdf"); OutputStream os = ResponseUtils.renderExcel(response, "毕结业证书.pdf"); byte[] readByte = new byte[4096]; int c; while ((c = is.read(readByte)) != -1) { os.write(readByte,0,c); } os.flush(); if (os != null) { os.close(); } if (is != null) { is.close(); } }
4.至此就可以通过浏览器下载所需的pdf文件,注:该方法使用的为文字绝对定位方法,由
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, value, Integer.parseInt(hzb[i]), (580-Integer.parseInt(zzb[i])), 0);第三个和第四个参数确定文字显示位置,第三个参数决定横坐标,第四个决定纵坐标,itextpdf坐标以pdf左下角点位原点