📜 ⬆️ ⬇️

We generate 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, according to a similar principle, it is possible to implement the solution for other platforms.

Task:

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

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:



Wkhtmltopdf has versions for different operating systems, source codes.

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

Minus ideas - an external utility is used.

Source: https://habr.com/ru/post/190658/


All Articles