2016-02-10 35 views
9

私はspring mvcアプリケーションでpdfレポートを作成したいと思います。私は、HTMLレポートページを設計するためにthemeleafを使用してpdfファイルに変換したいと考えています。私はPDFをスタイリングするためにxlstを使いたくない。そのようにすることは可能ですか?テンプレートエンジンとしてthymeleafを使ってpdfレポートを生成するには?

注:これはクライアントの要件です。

+4

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

答えて

1
あなたは、フライングソーサー - PDFファイルのようなものを使用してコンポーネントに少し似て作成する必要があります

:のようなものをお使いのコントローラ/サービス・コンポーネントの中で

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

単に@Autowireこのコンポーネントをして実行します。

"greeting"は詳細用テンプレート

参照http://www.oodlestechnologies.com/blogs/How-To-Create-PDF-through-HTML-Template-In-Spring-Bootの名前です

Map<String,String> data = new HashMap<String,String>(); 
    data.put("name","James"); 
    pdfGenaratorUtil.createPdf("greeting",data); 
関連する問題