这段时间,公司承办一个互联网峰会,需要对4000多位客户发送邀请函,其中包括一个pdf文件和一封手写信,PDF中将从公司数据库中读取所有客户姓名,自动生成到相应位置,前期尝试Java自动生成pdf文件,并且和信纸图片一起打包到文件夹中,文件夹以客户姓名命名:
项目使用的spring+SpringMVC+mybatis
首先需要导入几个jar包,(网上查资料,有人说主要是两个,但尝试了多遍,总是报错,后来看了一篇帖子,提供了多个,就没出现问题了)
关于Java 利用itext填写pdf模板并导出,
可以参考:http://blog.csdn.net/chenxingcxcy/article/details/52404516
第一部分主要是创建PDF文件
@RequestMapping("/main")
public void main() {
List<Customer> custs = CustomerService.listSendEmail(new Customer());
for(int i = 0;i<custs.size();i++){
//为每一位客户生成PDF
generatePdf(custs.get(i));
//发送邮件给每一位客户
sendPdf(custs.get(i));
}
}
private void sendPdf(Customer customer) {
JavaMailWithAttachment se = new JavaMailWithAttachment(true);
//避免不规则姓名,姓名不符合规则,则使用客户提供的昵称
String cusName = customer.getName().trim().replaceAll("\\d+","");
if(cusName==null || cusName.length()==0){
cusName = customer.getNickName();
}
File pdf = new File("D:\\"+cusName+"\\邀请函.pdf");
File xin = new File("D:\\"+cusName+"\\感恩信.jpg");
se.doSendHtmlEmail("标题", "发件内容", customer.getEmail(), pdf,xin);
}
public void generatePdf(Customer custom){
//设置页面大小
Rectangle rect = new Rectangle(PageSize.B5.rotate());
Document doc = new Document(rect);
PdfWriter writer = null;
BaseFont bfChinese = null;
Font fontChinese = null;
//创建目录路径
String cusName = custom.getName().trim().replaceAll("\\d+","");
String pdfPath = "D:\\"+cusName +"\\邀请函.pdf";
File file = new File(pdfPath);
File fileParent = file.getParentFile();
if(!fileParent.exists()){
fileParent.mkdirs();
}
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
//向文件夹中插入信
File srcFile = new File("E:\\xin.jpg");
String xinPath = "D:\\"+cusName +"\\感恩信.jpg";
File targetFile = new File(xinPath);
File fileParent2 = file.getParentFile();
if(!fileParent2.exists()){
fileParent2.mkdirs();
}
try {
targetFile.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
InputStream in = new FileInputStream(srcFile);
OutputStream out = new FileOutputStream(targetFile);
byte[] bytes = new byte[1024];
int len = -1;
while((len=in.read(bytes))!=-1)
{
out.write(bytes, 0, len);