注意:本例子是从向模板定义的变量赋值,而不是从无到有的来生成pdf
直接就能用
maven依赖:
com.lowagie
itext
4.2.1
工具类:
package com.upincar.pdfdemo2.demo;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
public class PDFTemplet {
public void PDFTemplet (File file)throws Exception{
//本地模板路径
String templatePdfPath = PDFTemplet.class.getResource("/pdf/" + "/notice_template.pdf").toString();
//生产pdfreader
PdfReader reader = new PdfReader(templatePdfPath);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
/* 读取*/
PdfStamper pdfStamper= new PdfStamper(reader,bos);
/*设置字体格式*/
BaseFont baseFont = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
ArrayList
fontList.add(baseFont);
AcroFields s=pdfStamper.getAcroFields();
s.setSubstitutionFonts(fontList);
/*Field , 这个是自己在pdf上定义的变量名称*/
s.setField("sign_year","2019");
s.setField("sign_month","06");
s.setField("sign_day","27");
pdfStamper.setFormFlattening(true);
pdfStamper.close();
FileOutputStream fileSteam =new FileOutputStream(file);
fileSteam.write(bos.toByteArray());
fileSteam.close();
}
}
测试类
package com.upincar.pdfdemo2.demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
@RestController
public class TestController{
@RequestMapping(value ="downloadJavaPdf", method = RequestMethod.GET)
public String downloadJavaPdf(HttpServletRequest request) throws Exception {
PDFTemplet pdfTT = new PDFTemplet();
File file = new File("D:/测试用.pdf");
file.createNewFile();
pdfTT.PDFTemplet(file);
return "生成成功";
}
}
项目结构
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)