1. 程式人生 > >Java動態數據生成PDF文檔及下載

Java動態數據生成PDF文檔及下載

當前 日期 數據 obj 中文 獲取 ont logger time

查了很多 aozbbs.com Q1446595067 資料都沒有我想要的pdf,於是根據iText基礎知識(這裏是看了寶爺的筆記點擊打開鏈接)自行編輯了一個簡單的表格pdf文檔

運用MVC springCXF

需要的jar包:https://download.csdn.net/download/weixin_40989555/10487913

jar包已經解決中文的編碼問題,可以直接使用。

若編寫多行多列表格(maven依賴):
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>

<version>5.5.10</version>

    </dependency>

話不多說,下面進行編碼。

jsp頁面

xxxxx提醒
js /** * 點擊“是”進行PDF打印 */ function pdfPrint(){ var aab001 = qdw_aab001; document.getElementById("form_delayWarn").action = "./lrs/querydelay/delWarnPdfPrint.do?aab001=" + aab001; return doConfirm("下載", function() { document.getElementById("form_delayWarn").submit(); }); /* 直接新開一個頁面顯示不下載 (js2方法) var url = "./lrs/querydelay/delWarnPdfPrint.do?aab001=" + aab001; window.open(url, "xxxxxxx"); */ } Controller層 import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.itextpdf.text.Element; import com.lowagie.text.Chapter; import com.lowagie.text.Document; import com.lowagie.text.Font; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Section; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; private QueryDelayServiceq qdService; @SuppressWarnings("unchecked") @RequestMapping(value = "/delWarnPdfPrint" , method = RequestMethod.POST) @ResponseBody public String delWarnPdfPrint(String aab001, HttpServletRequest req, HttpServletResponse resp) throws Exception { log.info("xxxxPDF打印-返回數據"); //返回list集合數據 String alllist = qdService.delWarnPdfPrint(aab001); File file = null; InputStream fin = null; ServletOutputStream out = null; List list = new ArrayList(); List pdflist = new ArrayList(); try { list = (List) JacksonUtil.toList(alllist, ArrayList.class, BC90.class);//這是我自定義的String轉list集合方法,跳過 for (BC90 bc90 : list) { DWPdf dpdf = new DWPdf(); dpdf.setRownum(bc90.getRownum()); dpdf.setAac003(bc90.getAac003()); dpdf.setAac002(bc90.getAac002()); dpdf.setAbc939(bc90.getAbc939()); dpdf.setAbc913(bc90.getAbc913()); dpdf.setAbc914(bc90.getAbc914()); dpdf.setAbc909(bc90.getAbc909()); pdflist.add(dpdf); } } catch (Exception e) { e.printStackTrace(); log.error("逾期合同json轉換出錯",e); } /*******pdf文件內容生成開始*********/ Document document = new Document(PageSize.A4, 25, 25, 25, 25); //創建文件夾 String filePar = null; Date nowTime = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd.hh.mm.ss"); String time = sdf.format(nowTime);//獲取當前時間字符串形式 filePar = "C:/企業逾期合同"+time;// 文件夾路徑 File myPath = new File( filePar ); file = new File(filePar+"/"+"企業逾期合同.pdf"); if (!myPath.exists()){ myPath.mkdir(); } /* * import com.lowagie.text.pdf.PdfWriter; */ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));// throws FileNotFoundException, // DocumentException document.open(); /* * 設中文字體 */ BaseFont bfChinese = null;// FontFactory.getFont(FontFactory.COURIER, // 14, Font.BOLD, new CMYKColor(0, 255, 0, 0);//大小,粗細,顏色 try { bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); } catch (IOException e) { e.printStackTrace(); } //定義中文字體大小 Font f10 = new Font(bfChinese, 10, Font.NORMAL); Font f12 = new Font(bfChinese, 12, Font.NORMAL); Font f26 = new Font(bfChinese, 26, Font.NORMAL);//一號字體 /* * 創建標題 */ Paragraph title1 = new Paragraph("標 題", f26); title1.setAlignment(Element.ALIGN_CENTER); Chapter chapter1 = new Chapter(title1, 1); chapter1.setNumberDepth(0); Section section1 = chapter1; // 創建有7列的表格 int colNumber = 7; PdfPTable t = new PdfPTable(colNumber); t.setSpacingBefore(25);//設置段落上空白 t.setSpacingAfter(25);//設置段落上下空白 t.setHorizontalAlignment(Element.ALIGN_CENTER);// 居左 float[] cellsWidth = { 0.08f, 0.1355f, 0.2f, 0.3f, 0.2f, 0.2f , 0.145f }; // 定義表格的寬度 t.setWidths(cellsWidth);// 單元格寬度 t.setTotalWidth(500f);//表格的總寬度 t.setWidthPercentage(100);// 表格的寬度百分比 //設置表頭 PdfPCell c1 = new PdfPCell(new Paragraph("序號",f12)); t.addCell(c1); PdfPCell c2 = new PdfPCell(new Paragraph("姓名",f12)); t.addCell(c2); PdfPCell c3 = new PdfPCell(new Paragraph("×××號",f12)); t.addCell(c3); PdfPCell c4 = new PdfPCell(new Paragraph("單位名稱",f12)); t.addCell(c4); PdfPCell c5 = new PdfPCell(new Paragraph("合同開始日期",f12)); t.addCell(c5); PdfPCell c6 = new PdfPCell(new Paragraph("合同結束日期",f12)); t.addCell(c6); PdfPCell c7 = new PdfPCell(new Paragraph("合同狀態",f12)); t.addCell(c7); //向表格類動態填充list集合數據 for(int i=0;i
0) { filename = URLEncoder.encode(filename, "UTF-8"); } else { filename = new String(filename.getBytes("UTF-8"), "ISO8859-1"); } //下載使用 刪除可用(js2方法)直接在頁面顯示不下載 resp.addHeader("Content-Disposition", "attachment;filename=" + filename + ".pdf");//這裏填想要的文件格式 out = resp.getOutputStream(); byte[] buffer = new byte[512]; // 緩沖區 int bytesToRead = -1; // 通過循環將讀入的Word文件的內容輸出到瀏覽器中 while ((bytesToRead = fin.read(buffer)) != -1) { out.write(buffer, 0, bytesToRead); } } finally { if (fin != null) fin.close(); if (out != null) out.close(); if (file != null) file.delete(); // 刪除臨時文件 if (myPath != null) myPath.delete(); } return null; } Service層 public String delWarnPdfPrint(String aab001) { if(aab001 != null){ List delWrList = BC90Mapper.delWarnPdfPrint(aab001); Map pdfMap = new TreeMap(); Map allMap = new TreeMap(); allMap.put("delWrList", delWrList); return JsonUtil.toJson(delWrList);//這裏是自定義方法轉譯維json字符串返回數據 } return respErrorMsg("請重新登入系統或刷新頁面"); } mapper層 List delWarnPdfPrint(String aab001); 寫了那麽多來看看效果吧

Java動態數據生成PDF文檔及下載