2016-02-10 47 views
9

Voglio creare un report in pdf in un'applicazione mvc di primavera. Voglio usare themeleaf per progettare la pagina di report html e quindi convertire in file pdf. Non voglio usare xlst per lo styling del pdf. È possibile farlo in questo modo?Come generare report in formato pdf utilizzando thymeleaf come motore di template?

Nota: è un requisito del cliente.

+4

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

risposta

1

Avrete bisogno di usare qualcosa come dischi volanti-pdf, creare un componente un po 'come:

@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*/ } 
      } 
     } 
    } 
} 

Poi semplicemente @Autowire questa componente per componente del controller/servizio e fare qualcosa di simile:

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

dove "greeting" è il nome del modello

Vedere http://www.oodlestechnologies.com/blogs/How-To-Create-PDF-through-HTML-Template-In-Spring-Boot per i dettagli