版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36675996/article/details/79715491
一:用word写好模板
二:另存为pdf格式
三:用Adobe Acrobat XI Pro打开转存好的pdf
对文本域进行编辑,也就是上图框内的内容,写自己需要的名字.双击操作,可以选择字体大小,位置
四:都操作完后保存
五:在项目中的webapp下新建一个存放该pdf的文件夹,将操作完的pdf放进去
———-代码外以操作完,开始写代码
util类
package ;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
public class PdfUtil {
/**
* 获取pdf文件字节数组输出流
*
* @param templateFilePath
* 模版文件所在文件夹路径
* @param templateFileName
* 模版文件名称
* @param resultMap
* 字段Map,key值存储字段名称,value存储字段属性
* @return
* @throws IOException
* @throws DocumentException
*/
public static ByteArrayOutputStream createPdfBaosOne(String templateFilePath, String templateFileName,
Map<String, String> resultMap) {
ByteArrayOutputStream ba = new ByteArrayOutputStream();
try {
PdfReader reader = new PdfReader(templateFilePath + "\\" + templateFileName);
PdfStamper stamp = new PdfStamper(reader, ba);
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
/* 获取模版中的字段 */
AcroFields form = stamp.getAcroFields();
if (resultMap != null) {
for (Map.Entry<String, String> entry : resultMap.entrySet()) {
form.setFieldProperty(entry.getKey(), "textfont", bf, null);
form.setField(entry.getKey(), entry.getValue());
}
}
stamp.setFormFlattening(true);
stamp.close();
reader.close();
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (DocumentException documentException) {
documentException.printStackTrace();
}
return ba;
}
}
controller类
@RequestMapping(value = "xxxx")//前台请求路径映射
public void exportPdf(HttpServletResponse response, HttpServletRequest request)
throws IOException, DocumentException {
// 文件根路径
String fileRootPath = request.getSession().getServletContext().getRealPath("/templates");
Map<String, String> resultMap = new HashMap<String, String>();
String filename = "你的导出的名字.pdf";
/* 设置字段MAP */
resultMap.put("name", "张三");//在文本域编辑的名字
resultMap.put("ksbh", "66666");
ByteArrayOutputStream ba;
// 文件名称
String fileName = "zgsc.pdf";//在webapp下新建的文件夹中的pdf模板名字
ba = PdfUtil.createPdfBaosOne(fileRootPath, fileName, resultMap);
// 使用流的方式输出pdf文件
response.setContentType("application/pdf");
response.setHeader("Content-disposition",
"attachment;filename=" + new String(filename.getBytes("gb2312"), "ISO8859_1"));
OutputStream ouputStream = response.getOutputStream();
ba.writeTo(ouputStream);
ouputStream.flush();
ouputStream.close();
ba.close();
return ;
}