最近公司业务需要打印快递单,事先使用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";
}