Java生成PDF之iTextPDF的使用
阿新 • • 發佈:2018-09-27
tde context work tput not 使用 reat instance exp
今天做財務方面相關數據的導出功能,需要導出PDF和Excel,在項目經理那裏得知有一個叫iTextPDF的java框架導出PDF文件很好用,於是拿來玩兒玩兒。
1 package com.smart.produce.modules.finance.controller;
2
3 import com.alibaba.fastjson.JSONObject;
4 import com.itextpdf.text.Document;
5 import com.itextpdf.text.PageSize;
6 import com.itextpdf.text.Rectangle;
7 import com.itextpdf.text.pdf.PdfWriter;
8 import com.smart.produce.modules.finance.service.IExportService;
9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.stereotype.Controller;
11 import org.springframework.web.bind.annotation.RequestMapping;
12 import org.springframework.web.bind.annotation.RequestMethod;
13 import org.springframework.web.bind.annotation.ResponseBody;
14
15 import javax.servlet.http.HttpServletRequest;
16 import java.io.FileOutputStream;
17 import java.lang.reflect.Method;
18
19 @Controller
20 @RequestMapping("${admin.url.prefix}/finance/export")
21 public class ExportController {
22
23 @Autowired
24 private IExportService exportService;
25
26 private String exportPath = "/static/financeExport";
27
28 @ResponseBody
29 @RequestMapping(value="exportPDF", method={RequestMethod.GET, RequestMethod.POST})
30 public String expStatementPDF(HttpServletRequest request, String name) {
31 JSONObject result = new JSONObject();
32 result.put("code", 0);
33 result.put("msg", "success");
34 // 輸出文件路徑
35 String filePath = exportPath + "/" + name + ".pdf";
36 result.put("data", filePath);
37 String realPath = request.getServletContext().getRealPath("/");
38 try {
39 //Step 1—Create a Document.
40 Rectangle rectangle = new Rectangle(PageSize.A4);
41 Document document = new Document(rectangle);
42 document.setMargins(20, 20, 40, 40);
43 //Step 2—Get a PdfWriter instance.
44 PdfWriter.getInstance(document, new FileOutputStream(realPath + filePath));
45 //Step 3—Open the Document.
46 document.open();
47 //Step 4—Add content.
48 Method method = IExportService.class.getDeclaredMethod(name + "Print", new Class[]{Document.class, String.class});
49 method.invoke(exportService, document, realPath);
50 //Step 5—Close the Document.
51 document.close();
52 } catch(Exception e) {
53 e.printStackTrace();
54 result.put("code", -1);
55 result.put("msg", e.getMessage());
56 }
57 return result.toString();
58 }
59
60 }
Java生成PDF之iTextPDF的使用