項目需要根據一個已知的模板文檔,取數據然后填充空格。
先制作word版模板,然后另存為pdf格式,轉換后使用Adobe Acrobat Pro添加域,生成PDF模板。
利用itext讀取模板,填充數據,下載導出。
參考大神鏈接:https://blog.csdn.net/tyc_054600/article/details/104060362
具體步驟:
1、pom引用
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.11</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
2、創建PdfUtil類
package com.ruoyi.common.utils.itext;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.ruoyi.common.config.RuoYiConfig;
import java.net.URLEncoder;
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
import java.util.List;
/**
* @Description
* @auther Tian
* @Date 2020/4/11 13:28
**/
public class PdfUtil {
/**
* 利用模板生成pdf保存到某路徑下
*/
public static String pdfOut(String modalFilename,String newFilename,Map<String, Object> inputMap) {
// 生成的新文件路徑
String path0 = RuoYiConfig.getReportPath();
File f = new File(path0);
if (!f.exists()) {
f.mkdirs();
}
// 模板路徑
String templatePath = RuoYiConfig.getReportPath() + modalFilename;
// 創建文件夾
String newPdfPath = RuoYiConfig.getDownloadPath() + newFilename;
File file = new File(templatePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
File file1 = new File(newPdfPath);
if (!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
PdfReader reader;
FileOutputStream out;
ByteArrayOutputStream bos;
PdfStamper stamper;
try {
String path = "C:/WINDOWS/Fonts/simsun.ttc,0";//windows里的字體資源路徑
BaseFont bf = BaseFont.createFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 輸出流
out = new FileOutputStream(newPdfPath);
// 讀取pdf模板
reader = new PdfReader(templatePath);
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
//文字類的內容處理
Map<String, String> datemap = (Map<String, String>) inputMap.get("dateMap");
form.addSubstitutionFont(bf);
for (String key : datemap.keySet()) {
String value = datemap.get(key);
form.setField(key, value);
}
// 表格類
Map<String, List<List<String>>> listMap = (Map<String, List<List<String>>>) inputMap.get("list");
for (String key : listMap.keySet()) {
List<List<String>> lists = listMap.get(key);
int pageNo = form.getFieldPositions(key).get(0).page;
PdfContentByte pcb = stamper.getOverContent(pageNo);
Rectangle signRect = form.getFieldPositions(key).get(0).position;
//表格位置
int column = lists.get(0).size();
PdfPTable table = new PdfPTable(column);
float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
int size = lists.get(0).size();
float width[] = new float[size];
for (int i = 0; i < size; i++) {
if (i == 0) {
width[i] = 60f;
} else {
width[i] = (tatalWidth - 60) / (size - 1);
}
}
table.setTotalWidth(width);
table.setLockedWidth(true);
table.setKeepTogether(true);
table.setSplitLate(false);
table.setSplitRows(true);
Font FontProve = new Font(bf, 12, 0);
//表格數據填寫
int rowFirstPage=21;//第一頁最大行數
int row = lists.size()>=rowFirstPage?rowFirstPage:lists.size();
for (int i = 0; i < lists.size(); i++) {
List<String> list = lists.get(i);
for (int j = 0; j < column; j++) {
Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve);
PdfPCell cell = new PdfPCell(paragraph);
cell.setBorderWidth(0.5f);
cell.setVerticalAlignment(Element.ALIGN_CENTER);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setLeading(0, (float) 1.4);
table.addCell(cell);
}
}
table.writeSelectedRows(0, row, signRect.getLeft(), signRect.getTop(), pcb);//從指定位置寫入表格
//表格內容超出一頁
if(lists.size()>rowFirstPage){
int rowOtherPage=25;//新增頁表格行數
int pageAddNum=(lists.size()-rowFirstPage)/rowOtherPage;//待增加頁數
if((lists.size()-rowFirstPage)%rowOtherPage>0){
pageAddNum++;
}
for(int i=0;i<pageAddNum;i++){
int rowNowStart=i*rowOtherPage+rowFirstPage;
int rowNowEnd=rowNowStart+rowOtherPage;
if(rowNowEnd>lists.size()){
rowNowEnd=lists.size();
}
stamper.insertPage(reader.getNumberOfPages() + 1, reader.getPageSizeWithRotation(1));//新增空白頁
PdfContentByte under = stamper.getOverContent(reader.getNumberOfPages());//捕獲新增的空白頁
table.writeSelectedRows(rowNowStart, rowNowEnd, signRect.getLeft(), 750, under);
}
}
}
stamper.setFormFlattening(true);// 如果為false,生成的PDF文件可以編輯,如果為true,生成的PDF文件不可以編輯
stamper.close();
Document doc = new Document(PageSize.LETTER.rotate());//pdf橫向打開
doc.setPageSize(PageSize.A4);
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
int pages = stamper.getReader().getNumberOfPages();
for (int i = 1; i <= pages; i++) {
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
copy.addPage(importPage);
}
doc.close();
out.close();
reader.close();
return newFilename;
} catch (IOException | DocumentException e) {
System.out.println(e);
}
return "";
}
/**
* 利用模板生成pdf導出
*/
public static void pdfExport(String modalFilename,String newFilename, HttpServletResponse response,Map<String, Object> inputMap) {
// 生成的新文件路徑
String path0 = RuoYiConfig.getReportPath();
File f = new File(path0);
if (!f.exists()) {
f.mkdirs();
}
// 模板路徑
String templatePath = RuoYiConfig.getReportPath()+modalFilename;
File file = new File(templatePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
PdfReader reader;
ByteArrayOutputStream bos;
PdfStamper stamper;
OutputStream out = null;
try {
Map<String, String> datemap = (Map<String, String>) inputMap.get("dateMap");
String path = "C:/WINDOWS/Fonts/simsun.ttc,0";//windows里的字體資源路徑
BaseFont bf = BaseFont.createFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 輸出流
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(newFilename, "UTF-8"));
out = new BufferedOutputStream(response.getOutputStream());
// 讀取pdf模板
reader = new PdfReader(templatePath);
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
//文字類的內容處理
form.addSubstitutionFont(bf);
for (String key : datemap.keySet()) {
String value = datemap.get(key);
form.setField(key, value);
}
stamper.setFormFlattening(false);
stamper.close();
Document doc = new Document(PageSize.LETTER.rotate());//pdf橫向打開
doc.setPageSize(PageSize.A4);
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
copy.addPage(importPage);
doc.close();
out.close();
reader.close();
} catch (IOException | DocumentException e) {
System.out.println(e);
} finally {
try {
assert out != null;
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 讀取本地pdf,這里設置的是預覽
*/
public static void readPdf(String filename,HttpServletResponse response) {
response.reset();
response.setContentType("application/pdf");
try {
File file = new File(RuoYiConfig.getReportPath()+filename);
FileInputStream fileInputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream();
IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
response.setHeader("Content-Disposition", "inline; filename= "+filename);
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、創建Controller
//導出PDF報表
@GetMapping("/downReport/{id}")
public AjaxResult downloadPDF(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) throws Exception {
String modalFilename="taskreport.pdf";
String newFilename="記錄單.pdf";
Map<String, Object> dataMap=taskService.getModalData(id);//獲取導出模板中需要填充的數據
//生成文件放入download文件夾,返回生成文件名稱
return AjaxResult.success(PdfUtil.pdfOut(modalFilename, newFilename,dataMap));
}
4、獲取導出模板中需要填充的數據
//查找導出數據
@Override
public Map<String, Object> getModalData(Long id) {
Map<String, Object> dataMap=new HashMap<>();
Map<String, String> dataMap1 = new HashMap<>();
Task task = taskMapper.selectTaskById(id);
dataMap1.put("id", id.toString());
dataMap1.put("taskType", changeTaskType(task.getTaskType()));
dataMap1.put("createBy", task.getCreateBy());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(task.getCreateTime());
dataMap1.put("createTime", dateString);
dataMap.put("dateMap",dataMap1);//獲取填充PDF的數據
//設備列表
TaskItem taskItem =new TaskItem();
taskItem.setTaskId(id);
List<TaskItem> taskItems=taskMapper.selectTaskItemList(taskItem);
List<List<String>> List = new ArrayList<List<String>>();
List<String> listHead = new ArrayList<String>();
listHead.add("序號");
listHead.add("編號");
listHead.add("類型");
List.add(listHead);
int i=1;
for (TaskItem item:taskItems) {//一行一個list
List<String> list = new ArrayList<String>();
list.add(i+"");
list.add(item.getSenu());
list.add(item.getTypeModel());
List.add(list);
i++;
}
Map<String, List<List<String>>> listMap = new HashMap<String, List<List<String>>>();
listMap.put("deviceLists", List);
dataMap.put("list", listMap);
return dataMap;
}
5、頁面添加下載按鈕,如果沒有form可JS添加
function downPdf(){
var url = '/system/reportexport/downPdf/';
var form = $("<form>");//定義一個form表單
form.attr("style", "display:none");
form.attr("target", "");
form.attr("method", "get"); //請求類型
form.attr("action", url); //請求地址
$("body").append(form);//將表單放置在web中
form.submit();//表單提交
}
6、制作模板
在指定位置添加pdf模板,先用word編輯好要到處的模板,另存為可以存為PDF格式。
轉換為PDF后使用Adobe Acrobat Pro(網上有破解版,下載時注意不要附加其他的軟件下載),打開要使用的PDF,
表單->添加或編輯域->修改域名(域名即為待填充的字段名稱)
此時會默認添加很多域,可以手動增加或刪除域,雙擊域可修改域的名稱、可讀屬性、字體大小和樣式。
7、字體問題
中文問題:
String path = "C:/WINDOWS/Fonts/simsun.ttc,0";//windows里的字體資源路徑
BaseFont bf = BaseFont.createFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
有些中文顯示不全 企業名稱顯示企名稱,但是預覽點擊時顯示企業名稱,預覽和打印顯示企名稱
考慮是字體包的問題,替換字體包 為仿宋 String path = "C:/WINDOWS/Fonts/simsun.ttc,0";//windows里的字體資源路徑,正常顯示
本地查看電腦所帶字體:C:/WINDOWS/Fonts,這個文件夾下的字體,右鍵打開屬性,會看到文件名。個人建議使用宋體,使用windows自帶字體,這樣兼容性會高很多。
參考大神鏈接:
1、https://www.cnblogs.com/whalesea/p/11752086.html
2、https://www.cnblogs.com/whalesea/p/11714681.html
3、https://blog.csdn.net/yangdonghhm/article/details/84239196
8、下載后使用AdobeReader打開會報錯,缺少字體包
可以使用右擊,選擇瀏覽器打開
或者是AdobeReader字體包的原因
使用Adobe Acrobat Pro域編輯時,選擇域屬性,選擇字體為生成文件選用的字體,windows系統自帶字體包含宋體,使用宋體可以
9、下載后不可編輯
域屬性選擇只讀,否則下載的文件就可以編輯,在AdobeReader中打開這些位置還會顯示藍色。
10、增加權限
https://www.cnblogs.com/matrix-zhu/p/6305944.html
