這幾天已在做處理導出pdf文件的功能,摸索了幾天總算可以了。記錄下這幾天遇到的問題。
1.網上基本都是基於Itext5和Itext7來處理的。我最終是在Itext5上成功了,itext7應該是模板出問題了,在寫的test方法里面測試時候,總是 找不到 pdf文檔里面的form表單內容。因為需要使用adobe acrobat reader dc 來制作模板,而我沒有這個。一直導致失敗。
2.最終成功是參考這個文檔:
https://blog.csdn.net/yi2419808933/article/details/52469241
https://blog.csdn.net/yi2419808933/article/details/52469241
3.貼上最終代碼
/**
* 導出對賬單
* @return
*/
@RequestMapping("/exportSupplierFeeData")
@ResponseBody
@MasterSlaveConfigs(configs={
@MasterSlaveConfig(databaseTag="mdbcarmanage-DataSource",mode= DynamicRoutingDataSource.DataSourceMode.SLAVE)
} )
public AjaxResponse exportSupplierFeeData(HttpServletRequest request, HttpServletResponse response,
ServletOutputStream outputStream,
Integer cityId, Integer supplierId,
Integer status, Integer amountStatus, String settleStartDate,
String settleEndDate, String paymentStartTime, String paymentEndTime, String feeOrderNo){
logger.info(MessageFormat.format("查詢司機線上化入參:cityId:%s,supplierId:%s,status:%s," +
"amountStatus:%s,settleStartDate:%s,settleEndDate:%s,paymentStartTime:%s,paymentEndTime:%s",cityId,supplierId,status,amountStatus,settleStartDate,settleEndDate,paymentStartTime,paymentEndTime));
response.setContentType("application/pdf;charset=ISO8859-1");
response.setHeader("Content-disposition", "attachment; filename="+"supplierFeePDF-1.pdf");
SupplierFeeManageDto feeManageDto = new SupplierFeeManageDto();
feeManageDto.setCityId(cityId);
feeManageDto.setSettleStartDate(settleStartDate);
feeManageDto.setSettleEndDate(settleEndDate);
feeManageDto.setAmountStatus(amountStatus);
feeManageDto.setStatus(status);
SupplierFeeManage manage = supplierFeeService.queryByOrderNo(feeOrderNo);
String[] titles = { "供應商名稱1", "列名t2", "列名3", "列名4", "t5", "t6","t7"};
try {
ByteArrayOutputStream ba = new ByteArrayOutputStream();
Document document = new Document(PageSize.A3); // Step 1—Create a Document.
PdfWriter writer;
writer = PdfWriter.getInstance(document, ba);
document.open();
document.setMargins(5, 5, 5, 5);
//H 代表文字版式是橫版,相應的 V 代表豎版
BaseFont bfChinese = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);//STSongStd-Light 是字體,在jar 中以property為后綴
//參數一:新建好的字體;參數二:字體大小,參數三:字體樣式,多個樣式用“|”分隔
Font topfont = new Font(bfChinese,14,Font.BOLD);
//BaseFont bf = BaseFont.createFont("" + "fonts/simsun.ttc,0", BaseFont.IDENTITY_H,
// BaseFont.EMBEDDED);
Paragraph blankRow1 = new Paragraph(18f, " ");
blankRow1.setAlignment(Element.ALIGN_CENTER);
PdfPTable table1 = new PdfPTable(titles.length); //創建一個表格,參數為一行有幾欄
int width1[] = {100,150,150,100,50,50,55};//每欄的寬度
table1.setWidths(width1); //設置寬度
//首行
for(int i=0;i<titles.length;i++){
PdfPCell cell1 = new PdfPCell(new Paragraph(titles[i],topfont));
table1.addCell(cell1);
}
//每欄的值
//PdfPCell cell1 = new PdfPCell(new Paragraph(manage.getSupplierId()));
/* PdfPTable celltable = new PdfPTable(2);
cell1 = new PdfPCell(celltable);
cell1.setRowspan(2);
cell1.setPadding(10);
table1.addCell(cell1);*/
PdfPCell cell1 = new PdfPCell(new Paragraph("5555",topfont));
table1.addCell(cell1);
PdfPCell cell2= new PdfPCell(new Paragraph(manage.getFlowAmount(),topfont));
table1.addCell(cell2);
PdfPCell cell3= new PdfPCell(new Paragraph(manage.getSettleStartDate().toString(),topfont));
table1.addCell(cell3);
PdfPCell cell4= new PdfPCell(new Paragraph(manage.getPaymentTime().toString(),topfont));
table1.addCell(cell4);
PdfPCell cell5= new PdfPCell(new Paragraph(manage.getFeeOrderNo(),topfont));
table1.addCell(cell5);
PdfPCell cell6= new PdfPCell(new Paragraph(manage.getSupplierId().toString(),topfont));
table1.addCell(cell6);
PdfPCell cell7= new PdfPCell(new Paragraph(manage.getSupplierName().toString(),topfont));
table1.addCell(cell7);
document.add(table1);//將表格加入到document中
// document.add(table2);
document.add(blankRow1);
document.close();
ba.writeTo(outputStream);
outputStream.flush();
outputStream.close();
ba.close(); // 導出pdf注解
} catch (Exception e) {
e.printStackTrace();
}
// 模板路徑
String templatePath = "/Users/fan/workspace/mp-manage/src/main/webapp/upload/supplierFeePDF-1.pdf";
// 生成的新文件路徑
String newPDFPath = "/Users/fan/workspace/mp-manage/src/main/webapp/upload/supplierFeePDF-2.pdf";
/* PdfReader reader;
FileOutputStream out;
ByteArrayOutputStream bos;
PdfStamper stamper;
try {
out = new FileOutputStream(newPDFPath);// 輸出流
reader = new PdfReader(templatePath);// 讀取pdf模板
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
*//*String[] str = {manage.getSupplierName(), DateUtils.formatDate(manage.getSettleStartDate()),DateUtils.formatDate(manage.getSettleEndDate()),
manage.getFlowAmount()};*//*
String[] str = { "123456789", "TOP__ONE", "男", "1991-01-01", "130222111133338888", "河北省保定市" };
java.util.Iterator<String> it = form.getFields().keySet().iterator();
*//*for(int i = 0;i<feeManageList.size();i++){
SupplierFeeManage feeManage = feeManageList.get(i);
form.setField(null,feeManage.getSupplierName());
}*//*
int i = 0;
while (it.hasNext()) {
String name = it.next().toString();
System.out.println(name);
form.setField(name, str[i++]);
}
stamper.setFormFlattening(true);// 如果為false那么生成的PDF文件還能編輯,一定要設為true
stamper.close();
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
copy.addPage(importPage);
doc.close();
} catch (IOException e) {
System.out.println(1);
} catch (DocumentException e) {
System.out.println(2);
}
*/
return null;
}
