java spring maven pdf 匯出
阿新 • • 發佈:2018-12-07
pdf表單模板
js : 渲染出動態的html ,其實就是一個a標籤
Visitor.operateFormatter = function(value, row, index) { //編輯 var editButton = '<button type="button" class="btn btn-success btn-xs" onclick="Visitor.openUpdateVisitor(\'' + row.id + '\')" '; if($("#visitor_update").val() == undefined){ editButton += 'disabled="disabled"'; } editButton += '><i class="fa fa-edit"></i> 編輯</button>'; //刪除 var deleteButton = '<button type="button" class="btn btn-danger btn-xs button-margin" onclick="Visitor.delete(\'' + row.id + '\')" '; if($("#visitor_delete").val() == undefined){ deleteButton += 'disabled="disabled"'; } deleteButton += '><i class="fa fa-remove"></i> 刪除</button>'; //pdf下載 var pdfButton = '<a href="visitor/exportPDF/' + row.id + '" '; pdfButton += '> PDF</a>'; return [ editButton,deleteButton,pdfButton,].join(''); }
controller
/** * pdf匯出 **/ @RequestMapping(value ="/exportPDF/{visitorId}") public ModelAndView exportPDF(@PathVariable Integer visitorId,HttpServletRequest request, HttpServletResponse response) { Visitor visitor = visitorService.selectById(visitorId); String title ="訪客資訊"; try { PdfReader reader = new PdfReader("C:\\Users\\donald\\Desktop\\visitor.pdf"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PdfStamper ps = new PdfStamper(reader, bos); /** * 使用中文字型 使用 AcroFields填充值的不需要在程式中設定字型,在模板檔案中設定字型為中文字型 Adobe 宋體 std L */ AcroFields s = ps.getAcroFields(); //設定key-value值 //通過s.setFieldProperty("欄位名", "textfont", BaseFont , null); 設定欄位的格式或者在模板中修改樣式 s.setField("parkId",visitor.getParkId().toString()); s.setField("visitorName",visitor.getVisitorName()); s.setField("visitorMobile",visitor.getVisitorMobile()); SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); s.setField("appointTime",simpledateformat.format(visitor.getAppointTime())); s.setField("inviter",visitor.getInviter()); // 設為true ps.setFormFlattening(true); ps.close(); // excel 表文件名 String fileName = title + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".pdf"; String fileName11 = URLEncoder.encode(fileName,"UTF-8"); String headStr = "attachment; filename=\"" + fileName11 + "\""; response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", headStr); //通過response物件獲取OutputStream流 OutputStream out = response.getOutputStream(); out.write(bos.toByteArray()); out.close(); } catch (IOException | DocumentException e) { e.printStackTrace(); } return null; }
maven 載入的jar包
<!--pdf 匯出需要的jar包 --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.6</version> </dependency> <dependency> <groupId>com.itextpdf.tool</groupId> <artifactId>xmlworker</artifactId> <version>5.5.6</version> </dependency>
參考網址:https://blog.csdn.net/u011391773/article/details/53084231
pdf檔案匯出進階版
1. pdf檔案網頁預覽
2.pdf檔案合併
3.刪除專案路徑的pdf
引入pdfjs
js:
WorkOrder.printReceipt = function () {
if (this.check()) {
window.open('/static/js/plugins/pdfjs/web/viewer.html?file=' + encodeURIComponent(Feng.ctxPath + "/workOrder/print_receipt/"+ this.ids,"pdf"));
}
};
//ids 是check 方法裡面把多個id 用都用隔開儲存的一個js屬性
controller:
/**
* @Author Donald
*/
@Permission
@RequestMapping(value = "/print_receipt/{ids}")
@ResponseBody
public void printReceipt(@PathVariable String ids){
try {
String workOrderIds[] = ids.split(","); //運單id陣列
List<File> fileList = new ArrayList<>(); // 每頁pdf檔案一個file集合
String path = Class.class.getClass().getResource("/").getPath();
path = path.replace("/target/classes/","/src/main/webapp/static/file/"); //讀取模板的資料夾路徑
int workOrderId;
//遍歷運單
for(int i = 0 ;i < workOrderIds.length; i++) {
workOrderId = Integer.parseInt(workOrderIds[i]);
WorkOrder workOrder = workOrderService.selectById(workOrderId);
//獲取商品明細行
List<Map<String, Object>> result = workOrderLineService.selectOrderLineListByWorkOrderId(String.valueOf(workOrderId) ,null ,true);
int x = result.size(); //運單的商品行總數,每行商品錄入後減一
int y = x/7 ; //獲得整除數, 每頁簽收單最多7行資料
int z = result.size(); //獲得餘數,
int itemNo = 1;
//遍歷,滿7行的一頁,不夠7行當一頁
for( int a = y ; a >= 0 ; a = a - 1){
PdfReader reader = new PdfReader(path+"ReceipTemplate.pdf");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PdfStamper ps = new PdfStamper(reader, bos);
AcroFields s = ps.getAcroFields();
//設定中文字型
BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
s.addSubstitutionFont(bfChinese);
//設定key-value值
//通過s.setFieldProperty("欄位名", "textfont", BaseFont , null); 設定欄位的格式或者在模板中修改樣式
s.setField("itemNo" ,String.valueOf(itemNo) ); // 簽收單序號
Consigner consigner = consignerService.selectById(workOrder.getOriginConsignerId());
s.setField("ConsignerName",consigner.getConsignerName()); // 貨主名字
s.setField("toAddress",workOrder.getToAddress()); // 地址
s.setField("toReceiver",workOrder.getToReceiver()); //聯絡人
if(workOrder.getToMobile().length() > 0){
s.setField("toMobile",workOrder.getToMobile()); //聯絡方式
}else {
s.setField("toMobile",workOrder.getToPhone()); //聯絡方式
}
// 獲取運單歷史,根據接收者型別,分別在公司表或者是司機表裡面獲取其名字
WorkOrderHistory workOrderHistory = workOrderHistoryService.selectByWorkOrderIdAndFromUser(workOrderId,workOrder.getOriginLogisticsCompanyId(),0);
int receiverType = workOrderHistory.getReceiverType();
int receiverId = workOrderHistory.getReceiverId();
String receiverName ;
if(receiverType==0){
LogisticsCompany logisticsCompany = logisticsCompanyService.selectById(receiverId);
receiverName = logisticsCompany.getLogisticsCompanyName();
}else{
CarrierInfo carrierInfo = carrierInfoService.selectById(receiverId);
receiverName = carrierInfo.getUserName();
}
s.setField("receiverName",receiverName); // 承運商
String planShippedDateStr = (new java.text.SimpleDateFormat("yyyy-MM-dd ")).format(workOrder.getPlanShipDate());
s.setField("shippedDate",planShippedDateStr); // 發貨日期
// a > 0 滿7行一頁
if(a > 0){
for(int b = 1 ;b <= 7 ; b++ ){
Map<String, Object> workOrderLine = result.get(result.size() - x);
s.setField("workNo" + b ,workOrderLine.get("work_no").toString()); // 發貨單號
s.setField("description" + b ,workOrderLine.get("description").toString()); // 型號
s.setField("quantity" + b ,workOrderLine.get("quantity").toString()); //數量
s.setField("partNo" + b ,workOrderLine.get("part_no").toString()); //物料編號
if(workOrderLine.get("customer_po_no") !=null){
s.setField("customerPoNo" + b ,workOrderLine.get("customer_po_no").toString()); //訂單號
}
if(workOrderLine.get("customer_note") !=null){
s.setField("noteText" + b ,workOrderLine.get("customer_note").toString()); // 備註
}
x = x - 1;
}
}else if( (a == 0) && (x > 0)){
for(int c = 1 ;c <= x ; c++ ){
Map<String, Object> workOrderLine = result.get(result.size() - x - c + 1);
s.setField("workNo" + c ,workOrderLine.get("work_no").toString()); // 發貨單號
s.setField("description" + c ,workOrderLine.get("description").toString()); // 型號
s.setField("quantity" + c ,workOrderLine.get("quantity").toString()); //數量
s.setField("partNo" + c ,workOrderLine.get("part_no").toString()); //物料編號
if(workOrderLine.get("customer_po_no") !=null){
s.setField("customerPoNo" + c ,workOrderLine.get("customer_po_no").toString()); //訂單號
}
if(workOrderLine.get("customer_note") !=null){
s.setField("noteText" + c ,workOrderLine.get("customer_note").toString()); // 備註
}
}
}
// 設為true
ps.setFormFlattening(true);
ps.close();
// 生成單個pdf檔案存入temp裡面,並新增到fileList
File file = new File(path+"temp/"+ String.valueOf(System.currentTimeMillis()).substring(4, 13)+".pdf");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bos.toByteArray());
fileOutputStream.flush();
fileOutputStream.close();
fileList.add(file);
bos.flush();
bos.close();
reader.close();
}
}
// 把個fileList的多個file 合成一個多頁的file2 pdf檔案
File file2 = new File(path+"temp/" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".pdf");
PdfReader reader2 = new PdfReader(fileList.get(0).getPath());
Document document = new Document(reader2.getPageSize(1));
if (!file2.exists()) {
file2.createNewFile();
}
PdfCopy copy = new PdfCopy(document, new FileOutputStream(file2.getPath()));
document.open();
for (int i = 0; i < fileList.size(); i++)
{
PdfReader reader = new PdfReader(fileList.get(i).getPath());
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++)
{
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
reader.close();
}
reader2.close();
document.close();
copy.close();
//輸出pdf檔案到html頁面
FileInputStream fileInputStream = new FileInputStream(file2);
HttpServletResponse response = getHttpServletResponse();
response.setHeader("Content-Disposition", "attachment;fileName="+ new String("成品簽收單.pdf".getBytes("utf-8"),"ISO8859-1"));
response.setContentType( "multipart/form-data");
OutputStream outputStream = response.getOutputStream();
IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
fileInputStream.close();
outputStream.flush();
outputStream.close();
//刪除fileList檔案
for( File file3 : fileList){
if(file3.exists()){
file3.delete();
}
}
//刪除file2
if(file2.exists()){
file2.delete();
}
} catch (IOException e){
e.printStackTrace();
} catch (DocumentException e){
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}finally {
}
}
maven:
<!-- pdf檔案html頁面瀏覽需要的io -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!--pdf 匯出需要的jar包 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.6</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.6</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>