java实现根据pdf文件模板生成pdf文件

一、如何制作pdf模板

1.首先创建template.doc

2.根据doc文件制作pdf模板

java实现根据pdf文件模板生成pdf文件_第1张图片

3.将doc文件输出为pdf

  文件->输出为pdf

4.输出的pdf文件

5.使用Adobe Acrobat DC打开template.pdf

java实现根据pdf文件模板生成pdf文件_第2张图片

6.填充文字及创作表单

      创作表单->添加“文本”域

   创作表单->编辑“表格”

*填充的字段名(比如对象Table的属性为name,这里名称后面一列的单元格填充name)

java实现根据pdf文件模板生成pdf文件_第3张图片

java实现根据pdf文件模板生成pdf文件_第4张图片

7.模板制作完毕

 

二、java生成pdf文件

1.java代码

PdfFileBlh.java:

@SuppressWarnings("unchecked")
public void exportPdfFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//1.获取数据 
//		String jsonString = getRequestJsonString(request);
		String jsonString = request.getParameter("jsonString");
		/*String jsonString = "{\r\n" + 
				"  \"hospitalId\":\"14064\",\r\n" + 
				"  \"hospitalName\":\"揭阳市人民医院\",\r\n" + 
				"  \"name\":\"周虎\",\r\n" + 
				"  \"gender\":\"男\",\r\n" + 
				"  \"age\":\"26岁\",\r\n" + 
				"  \"patNo\":\"0001278568\",\r\n" + 
				"  \"clinic\":\"全科医学科简易门诊\",\r\n" + 
				"  \"bedNo\":\"16床\",\r\n" + 
				"  \"specimen\":\"咽拭子\",\r\n" + 
				"  \"repNo\":\"110254767\",\r\n" + 
				"  \"serialNo\":\"0\",\r\n" + 
				"  \"doctor\":\"核酸检测号\",\r\n" + 
				"  \"applicationTime\":\"2021-02-18 15:17\",\r\n" + 
				"  \"advName\":\"新型冠状病毒核酸RNA检测(自费)\",\r\n" + 
				"  \"idType\":\"身份证\",\r\n" + 
				"  \"idNo\":\"EC3263698\",\r\n" + 
				"  \"dateOfCollection\":\"2021-02-18 15:30\",\r\n" + 
				"  \"dateOfReceipt\":\"2021-02-19 11:13\",\r\n" + 
				"  \"specimenCollector\":\"黄敏华\",\r\n" + 
				"  \"specimenReceiver\":\"钟乔华\",\r\n" + 
				"  \"dateOfInspection\":\"2021-02-19 11:15\",\r\n" + 
				"  \"dateOfReport\":\"2021-02-19 11:15\",\r\n" + 
				"  \"reportedBy\":\"陈舒兰\",\r\n" + 
				"  \"inspectedBy\":\"钟乔华\",\r\n" + 
				"  \"resultList\":[\r\n" + 
				"	{\r\n" + 
				"		\"testItems\":\"2019新型冠状病毒核酸检测\",\r\n" + 
				"		\"result\":\"阴性(-)\",\r\n" + 
				"		\"refRange\":\"阴性(-)\",\r\n" + 
				"		\"method\":\"RT-PCR\"\r\n" + 
				"	},\r\n" + 
				"	{\r\n" + 
				"		\"testItems\":\"Nucleic Acid Test For SARA-Cov-2\",\r\n" + 
				"		\"result\":\"Negative(-)\",\r\n" + 
				"		\"refRange\":\"Negative(-)\",\r\n" + 
				"		\"method\":\"RT-PCR\"\r\n" + 
				"	},\r\n" + 
				"	{\r\n" + 
				"		\"testItems\":\"2019-nCov ORFlab基因\",\r\n" + 
				"		\"result\":\"阴性Negative(-)\",\r\n" + 
				"		\"refRange\":\"阴性Negative(-)\",\r\n" + 
				"		\"method\":\"RT-PCR\"\r\n" + 
				"	},\r\n" + 
				"	{\r\n" + 
				"		\"testItems\":\"2019-nCov N基因\",\r\n" + 
				"		\"result\":\"阴性Negative(-)\",\r\n" + 
				"		\"refRange\":\"阴性Negative(-)\",\r\n" + 
				"		\"method\":\"RT-PCR\"\r\n" + 
				"	}\r\n" + 
				"  ]\r\n" + 
				"}";*/
		System.out.println("======jsonString======"+jsonString);
		if(StringUtils.isNotBlank(jsonString)) {
			//2.处理数据
			Map data = JsonUtils.toObject(jsonString, Map.class);
			//3.根据医院Id获取pdf模板文件
			String hospitalId = (String) data.get("hospitalId");
			String hospitalName = (String) data.get("hospitalName");
			String templatePath = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/template/template_" + hospitalId + ".pdf");
			String fontPath = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/template/simsun.ttc");
			System.out.println("======templatePath======"+templatePath);
			
			//4.设置响应头信息
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition","attachment;fileName="+new String((hospitalName + "检验报告单_").getBytes("GBK"), "ISO-8859-1") + DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + ".pdf");

			//5.指定解析器
			ServletOutputStream os = null;
			PdfStamper ps = null;
			PdfReader reader = null;
			Document doc = null;
			try {
				os = response.getOutputStream();
				// 6.读入pdf表单
				reader = new PdfReader(templatePath);
				// 7.根据表单生成一个新的pdf
				ps = new PdfStamper(reader, os);
				doc = new Document();
				// 8.获取pdf表单
				AcroFields form = ps.getAcroFields();
				// 9.给表单添加中文字体 。不设置的话,中文可能无法显示
				BaseFont bf = BaseFont.createFont(fontPath+",1", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
				form.addSubstitutionFont(bf);
				// 10.获取到明细
				List> resultList = (List>) data.get("resultList");
				data.remove("resultList");
				// 11.遍历data 给pdf表单表格赋值
				for (String key : data.keySet()) {
					String value = (String) data.get(key);
					form.setField(key, value);
				}
				
				// 12.处理检验明细
				if(resultList!=null && resultList.size()>0) {
					String testItems="\r\n";
					String result="\r\n";
					String refRange="\r\n";
					String method="\r\n";
					for(Map resultMap:resultList) {
						testItems+=resultMap.get("testItems")+"\r\n\r\n";
						result+=resultMap.get("result")+"\r\n\r\n";
						refRange+=resultMap.get("refRange")+"\r\n\r\n";
						method+=resultMap.get("method")+"\r\n\r\n";
					}
					form.setField("testItems", testItems);
					form.setField("result", result);
					form.setField("refRange", refRange);
					form.setField("method", method);
				}
				
				ps.setFormFlattening(true);
				ps.close();
				doc.open();
				doc.close();
				System.out.println("===============PDF导出成功=============");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					os.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static String getRequestJsonString(HttpServletRequest request)
            throws IOException {
        String submitMehtod = request.getMethod();
        // GET
        if (submitMehtod.equals("GET")) {
          return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
            // POST
        } else {
            return getRequestPostStr(request);
        }
    }
	
	public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if(contentLength<0){
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength;) 
        {
            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }
	
	public static String getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }

PdfFileController.java:

@Controller
@RequestMapping("/pdfFile")
public class PdfFileController {
	
	@Resource
	private PdfFileBlh blh;
	
	@RequestMapping(params="BLHMI=exportPdfFile")
    public void exportNoEndFormList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        blh.exportPdfFile(request,response);
    }
}

2.html代码:
 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>



	
		
		生成PDF文件
		
		
		
	
	
	
		
	

 

你可能感兴趣的:(java,生成pdf,adobe,pdf下载)