相信很多朋友在项目中或多或少会遇到报表打印的需求,然而精确套打的实现更是一份苦差呀。近日在网上找到一份chm文档,虽然这是某家公司产品开发文档(大家不要误会,我可不是想在这做广告哦
,这个产品要是免费就更好了,呵呵),但是对PDF模板制作有很详细的讲解,而且里面还有视频。。。相信大家一看就会了!
通过iText可以调用PDF模板,对模板中的字段动态赋值,从而实现套打(也就是说,我们可以不依赖这份文档中提到的产品),当我们报表的样式或位置需要调整时,我们之需修改模板即可。下一篇Blog我会给大家一个示例,等不急的话大家可以到网上找找,这方面的资料还是蛮多的。
好了,不多说了,大家快行动吧。
下面这个servlet代码填充模板(见附件中testEx.pdf文件)中的字段,代码如下:
java 代码
- import javax.servlet.*;
- import javax.servlet.http.*;
- import java.io.*;
-
- import com.lowagie.text.*;
- import com.lowagie.text.pdf.*;
-
- public class GenPdfServlet extends HttpServlet {
-
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws ServletException,
- java.io.IOException {
- response.reset();
- ByteArrayOutputStream ba = new ByteArrayOutputStream();
- try {
-
- String TemplatePDF = getServletContext().getRealPath(".")
- + "testEx.pdf";
- PdfReader reader = new PdfReader(TemplatePDF);
-
-
- PdfStamper stamp = new PdfStamper(reader, ba);
-
- PdfContentByte under = stamp.getUnderContent(1);
-
-
- BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
- BaseFont.NOT_EMBEDDED);
- Font FontChinese = new Font(bf, 12, Font.NORMAL);
-
-
- AcroFields form = stamp.getAcroFields();
-
-
- form.setField("name", "lixy");
- form.setField("age", "26");
-
- stamp.setFormFlattening(true);
-
- stamp.close();
- } catch (DocumentException de) {
- de.printStackTrace();
- System.err.println("A Document error:" + de.getMessage());
- }
- response.setContentType("application/pdf");
-
-
-
- response.setContentLength(ba.size());
- try {
- ServletOutputStream out = response.getOutputStream();
- ba.writeTo(out);
- out.flush();
- out.close();
- ba.close();
- } catch (IOException e) {
- e.printStackTrace();
- System.err.println("A Document error:" + e.getMessage());
- }
- }
- }