2016-02-10 21 views
9

Yay mvc uygulamasında pdf raporu oluşturmak istiyorum. Html rapor sayfasını tasarlamak için bunları kullanmak istiyorum ve daha sonra pdf dosyasına dönüştürmek istiyorum. Pdf'yi biçimlendirmek için xlst kullanmak istemiyorum. Bu şekilde yapmak mümkün mü?Şablon motoru olarak thymeleaf kullanarak pdf raporu nasıl oluşturulur?

Not: Bu bir istemci gereksinimidir.

+4

Bkz: http://stackoverflow.com/questions/23173485/flying-saucer-thymeleaf-and-spring – ccheneson

cevap

1
Sen, uçan daire-pdf gibi bir şey kullanmak bir bileşenini gibi biraz oluşturmanız gerekir

: gibi bir şey Denetleyiciniz/hizmet bileşenine içinde

@Component 
public class PdfGenaratorUtil { 
    @Autowired 
    private TemplateEngine templateEngine; 
    public void createPdf(String templateName, Map<String, Object> map) throws Exception { 
     Context ctx = new Context(); 
     Iterator itMap = map.entrySet().iterator(); 
     while (itMap.hasNext()) { 
      Map.Entry pair = (Map.Entry) itMap.next(); 
      ctx.setVariable(pair.getKey().toString(), pair.getValue()); 
     } 

     String processedHtml = templateEngine.process(templateName, ctx); 
     FileOutputStream os = null; 
     String fileName = UUID.randomUUID().toString(); 
     try { 
      final File outputFile = File.createTempFile(fileName, ".pdf"); 
      os = new FileOutputStream(outputFile); 

      ITextRenderer renderer = new ITextRenderer(); 
      renderer.setDocumentFromString(processedHtml); 
      renderer.layout(); 
      renderer.createPDF(os, false); 
      renderer.finishPDF(); 

     } 
     finally { 
      if (os != null) { 
       try { 
        os.close(); 
       } catch (IOException e) { /*ignore*/ } 
      } 
     } 
    } 
} 
Sonra

basitçe @Autowire bu bileşen ve yapın:

"greeting" şablonunuza

ismi detaylariçin http://www.oodlestechnologies.com/blogs/How-To-Create-PDF-through-HTML-Template-In-Spring-Boot gör

Map<String,String> data = new HashMap<String,String>(); 
    data.put("name","James"); 
    pdfGenaratorUtil.createPdf("greeting",data); 
İlgili konular