Java自动生成PDF并进行邮件群发

这段时间,公司承办一个互联网峰会,需要对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);   
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值