Generating a PDF from an HTML template with conditions using wkhtmltopdf and RazorEngine

Published on August 20, 2013

Generating a PDF from an HTML template with conditions using wkhtmltopdf and RazorEngine

    Despite the fact that the post offers a blank, a recipe for ASP.NET, it is quite possible to implement the solution for other platforms by the same principle.

    Task:
    • generate DOC or PDF from file template, with substitution of values
    • need the ability to include minimal logic in the template to write less code, if necessary, only external files need to be edited
    • update . the result of the work must be saved in a file for the possibility of further manipulation

    Under the cut is a very simple and short solution, C # code examples. Despite this, that the post offers a recipe for ASP.NET, it is quite possible to implement the solution for other platforms according to similar principles.

    Decision:

    1. We generate a temporary HTML file. The file will be generated by the RazorEngine engine (can be installed via NuGet ). The code will look something like this:

      string template = File.ReadAllText("template1.cshtml");
      string result = Razor.Parse(template, new { Name = "Пользователь", ShowBlock1 = false, ShowBlock2 = true });
      File.WriteAllText("C:/tests/input.html", result);
      

      Content template1.cshtml

      <!DOCTYPE html>
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
      </head>
      <body>
      <h1>Просто текст.</h1>
      <p>имя тебе - @Model.Name</p>
      <p style="display:@( Model.ShowBlock1 ? "block" : "none")">Блок 1</p>
      <p style="display:@( Model.ShowBlock2 ? "block" : "none")">Блок 2</p>
          <table style="border:1px solid black" border="1" style="width:100%" width="100%">
              <tr>
                  <td>111</td>
                  <td><img src="C:/tests/1.png"/></td>
                  <td>333</td>
              </tr>
          </table>
      </body>
      </html>
      

    2. Now we generate the file by calling an external utility - wkhtmltopdf , you can download it here .

      var process = new Process
      {
          StartInfo =
              {
                  FileName = "C:/Program Files (x86)/wkhtmltopdf/wkhtmltopdf.exe",
                  Arguments = "C:/tests/input.html C:/tests/output.pdf"
              }
      };
      process.Start();
      

    3. At the end of the temporary file can be deleted.
      File.Delete("C:/tests/input.html");
      


    The resulting PDF:



    At wkhtmltopdf have versions for different operating systems, there is a source.

    The template engine, of course, can be used differently.

    Minus ideas - an external utility is used.