Java 填充数据到pdf模板打印

js代码:

<% String filepath = request.getRealPath("/"); %>

var filepath = $("#filepath").val();

success : function(data) {
	if (data.success) {
	/* window.location.href = "${pageContext.request.contextPath}/" + data.tempFile; //当前画面打开 */
	// 新标签页打开								
	window.open("${pageContext.request.contextPath}/" + data.tempFile);
	} else {
		toastr.error(data.message);
	} 
},
error : function() {
	toastr.error("系统异常,请联系管理员");
},

java代码:

    @ResponseBody
	@RequestMapping(value = "/printQualification", method = RequestMethod.POST)
	public Map printQualification(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 获取参数
		String label_number = String.valueOf(request.getParameter("label_number"));
		String product_model = String.valueOf(request.getParameter("product_model"));
		String model_number = String.valueOf(request.getParameter("model_number"));
		String version_number = String.valueOf(request.getParameter("version_number"));
		String qualification_number = String.valueOf(request.getParameter("qualification_number"));
		String filepath = String.valueOf(request.getParameter("filepath"));

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/json; charset=UTF-8");

		// 填充数据
		QualificationInfo qualificationInfo = new QualificationInfo();
		qualificationInfo.setLabel_number(label_number);
		qualificationInfo.setProduct_model(product_model);
		qualificationInfo.setModel_number(model_number);
		qualificationInfo.setVersion_number(version_number);
		qualificationInfo.setQualification_number(qualification_number);
		qualificationInfo.setPrint_date(new Date());

		String sourceFile = filepath + "PdfTemplate/Qualification.pdf";
		// String targetFile = "D:/tests.pdf";
		String nowTime = new SimpleDateFormat("yyyyMMddHHmmsss").format(new Date());
		// 获取服务器路径
		String targetFile = "video\\temp\\" + nowTime + ".pdf";
		String realPath = request.getSession().getServletContext().getRealPath("/");
		realPath = realPath + targetFile;
		// map赋值
		HashMap map = new HashMap<>();
		map.put("product_name", "测试");
		// 产品型号、模号、版本号相同 (map的key与pdf模板表单中一致)
		map.put("product_model", String.valueOf(product_model));
		map.put("model_number", String.valueOf(model_number));
		map.put("version_number", String.valueOf(version_number));
		// 数量
		map.put("qualification_number", String.valueOf(qualification_number));
		// 日期
		map.put("print_date", String.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(print_date)));
		map.put("label_number", "123456789");
		// 定义二维码内容
		String content = "barcode";
		// 标签模板填充
		map.put("QRCodeInfo", content);
		map.put("InnerBoxDetail", "详细信息");
		PdfHelper.fromPDFTempletToPdfValue(sourceFile, map, realPath);

		Map result = new HashMap<>();
		result.put("success", true);
		result.put("tempFile", targetFile);

		return result;
	}

PdfHelper方法代码:

public static String fromPDFTempletToPdfValue(String fileName, Map param, String path_) {

		try {
			// 获得pdf阅读器
			PdfReader reader = new PdfReader(fileName);
			// 字节数组输出流
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			PdfStamper stamp = new PdfStamper(reader, bos);

			BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			stamp.getAcroFields().addSubstitutionFont(bf);
			// 自定义表单
			AcroFields form = stamp.getAcroFields();

			for (Entry entry : param.entrySet()) {
				String key = entry.getKey();
				String val = String.valueOf(entry.getValue());
				if (!key.startsWith("QRCodeInfo")) {
					// 正常的字段赋值
					// 要输入中文就要设置域的字体;
					form.setFieldProperty(key, "textfont", bf, null);
					// 为需要赋值的域设置值;
					form.setField(key, val);
				} else {
					// 二维码
					PdfContentByte under = stamp.getOverContent(1);
					List positions = form.getFieldPositions("QRCodeInfo");
					com.itextpdf.text.Rectangle r = positions.get(0).position;
					float x = r.getLeft();
					float y = r.getBottom();
					float urx = r.getRight();
					float ury = r.getTop();

					Image image = getQRcode(val);
					image.scaleToFit(new com.itextpdf.text.Rectangle(x, y, urx, ury));
					image.setAbsolutePosition(x, y);
					under.addImage(image);
				}
			}
			stamp.setFormFlattening(true);
			stamp.close();
			// 设置为true/false在点击生成的pdf文档的填充域时有区别,
			FileOutputStream fos = new FileOutputStream(path_);
			fos.write(bos.toByteArray());
			fos.close();
			// File temp = new File(path_);
			// byte[] bs = getContent(path_);
			// temp.delete();
			return path_;
		} catch (IOException | DocumentException e) {
			e.printStackTrace();
		}
		return null;
	}

 

你可能感兴趣的:(Java,web开发,Java开发,java)