Spring MVC PDF视图

最近公司业务需要打印快递单,事先使用adobe Acrobat 制作了申通、顺丰等快递模板,然后要把数据填充到PDF 模板,在页面展示,并可以打印。项目使用的Spring MVC 框架。

spring-servlet.xml

	<!-- 按照BeanName解析视图 -->
	<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
		<property name="order" value="1" />
	</bean>
	  
	<!-- 定义Pdf模版视图 -->
	<bean id="CNSTPDF" class="com.mxj.print.PdfStamperView">
		<property name="url" value="/WEB-INF/template/CNST.pdf" />
	</bean>


PdfStamperView.java

这里需要itext.jar,不同于iText.jar

public class PdfStamperView extends AbstractPdfStamperView {

	@Override
	protected void mergePdfDocument(Map<String, Object> model,
			PdfStamper stamper, HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("application/pdf");<span style="white-space:pre">	</span>//设置content-type,PDF 视图
//		response.setHeader("Content-Disposition", "attachment;filename="+ new String(model.get(FILENAME).toString().getBytes(), "ISO8859-1"));<span style="white-space:pre">	</span>//文件下载
		AcroFields fields = stamper.getAcroFields();
		fillData(fields, model.get("databean"));
		stamper.setFormFlattening(true);
	}

	private void fillData(AcroFields fields, Object object) throws IOException, DocumentException {
		
		DataBean databean = null;
		if(object instanceof DataBean){
			databean = (DataBean) object;
		}
		fields.setField("To_Province", databean.getProvince());
		fields.setField("To_Tel", databean.getMobile());
		fields.setField("To_District", databean.getDistric());
		fields.setField("To_City", databean.getCity());
		fields.setField("To_Name", databean.getUsername());
		fields.setField("To_Address", databean.getDetailAddress());
	    List<ProductShortname> products = databean.getProducts();
	    if(products != null && products.size() > 0){
	    	ProductShortname entity = null;
	    	for (int i = 1; i < products.size() + 1; i++) {
	    		entity = products.get(i-1);
	    		fields.setField("Product["+i+"]", entity.getShortname());
	    		fields.setField("Num["+i+"]", String.valueOf(entity.getNumber()));
			}
	    }
	}

}

Controller

	@RequestMapping("/CNST/")
	public String exportPersonalCreaditLoanContract(String orderId, String productIdStr, Model model) {
		
		if(StringUtils.isEmpty(orderId) || StringUtils.isBlank(productIdStr)){
			return "CNSTPDF";
		}
		Order order = orderService.selectBaseInfoByPrimaryKey(orderId);
		List<ProductShortname> products = productShortnameService.getAllDataByOrderIdAndProductIds(orderId, productIdStr);
		DataBean bean = new DataBean(order);
		bean.setProducts(products);
		model.addAttribute("databean", bean);
		return "CNSTPDF";
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值