Document的几U构造函敎ͼ public Document(); public Document(Rectangle pageSize); public Document(Rectangle pageSize, int marginLeft, int marginRight, int marginTop, int marginBottom); 下面两种比较有用Q如果是你想定义U张大小和边~的时候。对于MarginQiText上提到“You can also change the margins while you are adding content. Note that the changes will only be noticed on the NEXT page. If you want the margins mirrored (odd and even pages), you can do this with this method: setMarginMirroring(true). ”不q,对于tablegq不好。tableq不会了理会你设定的marginQ如果想改变它的maginq是需要去改变它的宽度QsetWidthQ?br /> 2 pdf表单
使用PdfStamper是可以填充pdf表单的,q样qZ一U很好的报表生成思\?br />word制作报表样式-->acrobat转pdf-->itext填充数据-->输出pdf q做非常单,因ؓ可以比较Ҏ的控制pdf的样式。我对于Java的报表工具了解的q不多,不过在jasperreportsQ即使用GUI工具做一个样式比较复杂的报表也不是怎么Ҏ。比如有那种斜线的表_比较花哨的嵌套表根{这L情况q是比较多见的,客户不会关系你实现v来是否困难。不q想要用这U方式也有不的地方。首先是acrobat把word转化成pdf的时候,格式L保持不好Q特别的是字体。然后是文g的体U这L成的pdf会比直接用iText生成的pdf文g大很多,acrobat在pdf里加入了太多无用的信息。初ơ用iText填充Adobe Designer生成的pdf表单时会有点麻烦。在Designer中设计了一个name的text文本框的l定名ؓname。照着iText中例子用用PdfStamper的setFieldҎ去这样写form.setField("name", "XXXX");q不会成功。原因是Adobe Designer生成的表单名都是h层次的,它可能是q个样子form1[0].#subform[0].name[0]。不q我们可以用一个方法把它们列出来,只要做一ơ就知道l构了,可以使用cM下面的代码: PdfReader reader = new PdfReader("form.pdf"); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream("registered_flat.pdf")); AcroFields form = stamp.getAcroFields(); for (Iterator it = form.getFields().keySet().iterator(); it .hasNext();) { System.out.println(it.next()); } 如果直接用iText~程生成的表单就不会有这L问题Q设定的什么名字就是什么名字?br /> 3 表单元素
pdfq不像html那样h良好清晰的结构,而是一个有层次的文类型。在它的maillist里,作者说明了iText虽然可以操作现存的pdf文g但是没办法去q原它的l构的。没办法像html一P能从一个pdf文g获得一个清晰的“源文g”的。关于层ơ,可以从iText上得到详l的讲述Q获取去看看pdf规范。表单和普通文本是不在一个层上的。没办法适用对待文本表各一h它们单的addqDocument对象。获取一个cb直接ȝl对定位的方法可以加入表单元素,不过很多的时候因为排版ƈ不能那么单的d。就是在html中布局一样可以用表格定位。想把一个表单元素加入cellQ要借助cell的setCellEventҎ。以一个checkboxZ。新Z个类CheckBoxFormQ实现PdfPCellEvent接口。需要实C个cellLayout的方法?br /> public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) position可以好好利用Q它包含当前cell的位|信息,你可以用它来定自己checkbox的位|?br />position.top()-position.bottom()p得到高position.right()-position.left()可以得到长,如果需要这两个值得花可以如此计。下面的代码是定义一个宽度ؓa的checkbox的rectangle 。它在cell中水q_中,垂直也居中?br /> float bo = (position.top()-position.bottom()-a)/2; float ao = (position.right()-position.left()-a)/2; Rectangle rectangle = new Rectangle(position.left() + ao, position .bottom() + bo, position.left() +ao+ a, position.bottom()+ bo + a); 然后把它加入Document RadioCheckField tf = new RadioCheckField(writer, rectangle, fieldname, "f"); tf.setCheckType(RadioCheckField.TYPE_SQUARE); tf.setBorderWidth(1); tf.setBorderColor(Color.black); tf.setBackgroundColor(Color.white); try { PdfFormField field = tf.getCheckField(); writer.addAnnotation(field); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } 其它的元素与此类伹{?br /> 4 PdfPTable和Table