Javaの-春ブーツ2:GET HTML出力コントローラ

私は心配だ春の入門チュートリアル、およびその他のパスに、このような同じコントローラの結果へのアクセスなど、いくつかの比較的単純な事を、行う方法の損失。

 

私がやろうとしている次のとおりです。

この- >埋めThymeleafのテンプレートは、ブラウザ<をHTMLとして返される
箱のうち
、同じページのPDFファイルに戻ります>

GreetingController:

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.thymeleaf.TemplateEngine;

@Controller
@RequestMapping(path = "/")
public class GreetingController {

    @Autowired private TemplateEngine templateEngine;

    @RequestMapping(value = "/index", method = RequestMethod.GET, produces = "application/html")
    public String html(Model model) {
        model.addAttribute("some_data", some_data.getIt());
        return "some_template";
    }

    @RequestMapping(value = "/pdf", method = RequestMethod.GET, produces = "application/pdf")
    public String pdf() {
        // Option 1: get HTML output from html path
        // Option 2: put the same data in some_template via the template engine and get the resulting HTML
        // write HTML to a file using FileWriter
        // then print the temporary file with HTML to PDF via wkhtml2pdf
        return "generated_pdf";
    }

}`

たぶん私はすべてのこれらのエラーを解決するためだ、とHTMLでいっぱいにする簡単な方法があります、私に知らせてください。

エディタ:

Gradleの依存関係に似た操作を実行しようとする者:

 

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    compile("org.springframework.boot:spring-boot-devtools")
    testCompile("org.springframework.boot:spring-boot-starter-test")
}

ベストの答え

あなたが生成されたHTMLを得ることに興味を持っている場合は、最も簡単な解決策は、あなたがそれを行っているだけのように、TemplateEngine Thymeleafを使用するようになります。

 

 

Context context = new Context(Locale.getDefault());
context.setVariable("some_data", someData.getIt());
String html = templateEngine.process("some_template", context);

。その後、あなたが使用している場合、例えば、それを処理するために、PDFライブラリに任意のHTMLを使用することができフライングソーサーを、あなたが書くことができます。

 

try (ServletOutputStream stream = response.getOutputStream()) {
    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocumentFromString(html);
    renderer.layout();
    renderer.createPDF(stream);
    renderer.finishPDF();
} catch (IOException | DocumentException ex) {
    // Error handling
}

ITextRendererはあなたがOutputStreamに直接書き込むことができますので、あなたがこれを行うために)(HttpServletResponse.getOutputStreamを使用することができますので。

 

@GetMapping("/pdf")
public void pdf(HttpServletResponse response) {
    // Generate HTML + PDF
}
公開された540元の記事 ウォンの賞賛0 ビュー1977

おすすめ

転載: blog.csdn.net/weixin_44109689/article/details/103920855