首先附上iText官网地址:http://developers.itextpdf.com
点击打开链接
身为一个菜鸟,最近遇到需求——要求后台自动生成pdf,客户给的模板是这个样子的(部分):
参考了官网上给的例子过后我的步骤是:
1、首先是找到每个文本框的位置,并用红色框框标记
Rectangle[] areas = new Rectangle[] {new Rectangle(50, 750, 200, 50), new Rectangle(300, 750, 200, 50)};
// for canvas usage one should create a page
pdfDoc.addNewPage();
for (Rectangle rect : areas) {
new PdfCanvas(pdfDoc.getFirstPage()).setLineWidth(0.5f).setStrokeColor(Color.RED).rectangle(rect).stroke();
}
2、找好所有的位置后再往里面填充数据
3、去掉红色框框
Paragraph p0 = new Paragraph(map.get("custCompanyName").toString()).setFont(f);
new Canvas(new PdfCanvas(pdfDoc.getFirstPage()).stroke(), pdfDoc, areas1[0])
.add(p0.setFixedPosition(218, 593, 324));
最后给附上我的整个代码和结果
package com.bupt.common.itext; import com.bupt.common.entity.MaintenanceMaterial; import com.itextpdf.forms.PdfAcroForm; import com.itextpdf.io.image.ImageDataFactory; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.geom.Rectangle; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfReader; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.canvas.PdfCanvas; import com.itextpdf.layout.Canvas; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Image; import com.itextpdf.layout.element.Paragraph; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; import java.util.Random; public class PdfUtils{ public static String manipulatePdf(HttpServletRequest request, Map<String,Object> map) throws Exception { //String pdfDir = "E:///IdeaProjects/newWindPower/web/"; String pdfDir = request.getSession().getServletContext().getRealPath("/");
final String SRC = pdfDir+"pdfMold/维修报告模板.pdf" // id + 时间戳 + 随机数 + 原有的后缀名 保证不会被重复 String reportPdfUrl = "PdfTemp/" + System.currentTimeMillis() + "-" + new Random().nextInt(100000) +".pdf"; String DEST = pdfDir+reportPdfUrl; PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST)); PdfAcroForm form = PdfAcroForm.getAcroForm(