spring boot itextPdf根據模板生成pdf文件

在開發一些平臺中會遇到將數據庫中的數據渲染到PDF模板文件中的場景,用itextPdf徹底動態生成PDF文件的太過複雜,經過itextPdf/AcroFields能夠比較簡單的完成PDF數據渲染工做(PDF模板的表單域數據需定義名稱)java

  • Controller獲取HttpServletResponse 輸出流
package pdf.controller;

import com.itextpdf.text.DocumentException;
import service.PdfService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping(WebConstants.WEB_pdf + "/download")
@Api(description = "pdf下載相關", tags = "Pdf.download")
@NoAuth
public class PdfDownloadController {

    @Autowired
    private PdfService PdfService;
    
    @Value("${pdf.template.path}")
    private String templatePath ;

    @ApiOperation(value = "申請表下載")
    @RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
    @ResponseBody 
    @NoLogin
    public void download(@PathVariable("id") Long id, HttpServletResponse response) throws IOException, DocumentException {
        
        //設置響應contenType
        response.setContentType("application/pdf");
        //設置響應文件名稱
        String fileName = new String("申請表.pdf".getBytes("UTF-8"),"iso-8859-1");
        //設置文件名稱
        response.setHeader("Content-Disposition", "attachment; filename="+fileName);
        //獲取輸出流
        OutputStream out = response.getOutputStream(); 
        PdfService.download(id, templatePath ,out);
    }
}
  • Service生成pdf數據響應輸出流
1.業務service-負責實現獲取pfd模板數據,數據庫數據,實現動態賦值生成PDF

package service.impl;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
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;

@Service
public class ApplyServiceImpl implements ApplyService {

    @Override
    public DetailDTO getDetail(Long id) {
       // 獲取業務數據
       return null;
    }
    
    @Override
    public Map<String, String> getPdfMapping(DetailDTO dto) {
        // TODO Auto-generated method stub
        // 獲取pdf與數據庫的數據字段映射map
    }
    
    @Override
    public void download(Long id, String templatePath, OutputStream out) {
        // TODO Auto-generated method stub
        DetailDTO dto  =  getDetail(id);
        Map<String, String> fieldMapping = getPdfMapping(dto);
        String filePath;
        byte[] pdfTemplate;
        ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
        try {
            //獲取模板文件路徑
            filePath = ResourceUtils.getURL(templatePath).getPath();
            //獲取模板文件字節數據
            pdfTemplate = IOUtils.toByteArray(new FileInputStream(filePath));
            //獲取渲染數據後pdf字節數組數據
            byte[] pdfByteArray = generatePdfByTemplate(pdfTemplate, fieldMapping);
            pdfOutputStream.write(pdfByteArray);
            pdfOutputStream.writeTo(out);
            pdfOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                pdfOutputStream.close();
                out.flush();  
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
        }

    }

    @Override
    //itextPdf/AcroFields完成PDF數據渲染
    public byte[] generatePdfByTemplate(byte[] pdfTemplate, Map<String, String> pdfParamMapping) {
        Assert.notNull(pdfTemplate, "template is null");
        if (pdfParamMapping == null || pdfParamMapping.isEmpty()) {
            throw new IllegalArgumentException("pdfParamMapping can't be empty");
        }

        PdfReader pdfReader = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfStamper stamper = null;
        try {
            // 讀取pdf模板
            pdfReader = new PdfReader(pdfTemplate);
            stamper = new PdfStamper(pdfReader, baos);
            //獲取全部表單字段數據
            AcroFields form = stamper.getAcroFields();
            form.setGenerateAppearances(true);

            // 設置
            ArrayList<BaseFont> fontList = new ArrayList<>();
            fontList.add(getMsyhBaseFont());
            form.setSubstitutionFonts(fontList);

            // 填充form
            for (String formKey : form.getFields().keySet()) {
                form.setField(formKey, pdfParamMapping.getOrDefault(formKey, StringUtils.EMPTY));
            }
            // 若是爲false那麼生成的PDF文件還能編輯,必定要設爲true
            stamper.setFormFlattening(true);
            stamper.close();
            return baos.toByteArray();
        } catch (DocumentException | IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (stamper != null) {
                try {
                    stamper.close();
                } catch (DocumentException | IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
            if (pdfReader != null) {
                pdfReader.close();
            }

        }
        throw new SystemException("pdf generate failed");
    }

    /**
     * 默認字體
     *
     * @return
     */
    private BaseFont getDefaultBaseFont() throws IOException, DocumentException {
        return BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    }

    /**
     * 微軟宋體字體
     *
     * @return
     */
     //設定字體
    private BaseFont getMsyhBaseFont() throws IOException, DocumentException {
        try {
            return BaseFont.createFont("/msyh.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException | IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return getDefaultBaseFont();
    }
}
  • 數據庫的數據到pdf字段的映射能夠使用配置,創建數據字段映射表,經過反射
    能夠將數據庫數 據對象轉爲map,再經過定義的靜態map映射表,將數據map轉
    換爲pdf表單數據map
BeanUtils.bean2Map(bean);
    /**
     * JavaBean對象轉化成Map對象
     * @param javaBean
     * @return
     */
    public static Map bean2Map(Object javaBean) {
        Map map = new HashMap();

        try {
            // 獲取javaBean屬性
            BeanInfo beanInfo = Introspector.getBeanInfo(javaBean.getClass());

            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            if (propertyDescriptors != null && propertyDescriptors.length > 0) {
                String propertyName = null; // javaBean屬性名
                Object propertyValue = null; // javaBean屬性值
                for (PropertyDescriptor pd : propertyDescriptors) {
                    propertyName = pd.getName();
                    if (!propertyName.equals("class")) {
                        Method readMethod = pd.getReadMethod();
                        propertyValue = readMethod.invoke(javaBean, new Object[0]);
                        map.put(propertyName, propertyValue);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
    
    字段映射配置
    public class PdfMapping {

        public final static Map<String, String> BASE_INFO_MAPPING = new HashMap() {
           {
            put("name", "partyA");
            put("identity", "baseIdentity");

           }
        };
    }
相關文章
相關標籤/搜索