I\'m creating an application using C# with Winforms and now I need to print the receipt of sale on a thermal printer. To do this I\'m creating a text file and reading it to
If I want to create a report myself, instead of trying to create a text file, I'll use HTML for rendering.
Also to make rendering logic and mixing html tags and data simpler, I'd use T4 Run-time Text Templates. Then I can pass data to the html template and render the report simply. Then it's enough to assign the output string to a DocumentText
property of a WebBrowser and call its Print method.
Download
You can clone or download a working example from r-aghaei/HtmlUsingRuntimeT4.
Why HTML?
Because of simple and flexible formatting. You can use all power of html tags and css styles to format the text. It's really better than using DrawString
.
Why Run-time Text Templates?
Because it makes mixing data and html really easy and you can use C# language to perform some tasks like calculating sum, iterate over model records and so on. It uses T4
templating engine and lets you to use the template at run-time and feed data to the template.
Example
1- Add a model to project:
using System;
using System.Collections.Generic;
namespace Sample
{
public class ReportModel
{
public string CustomerName { get; set; }
public DateTime Date { get; set; }
public List OrderItems { get; set; }
}
public class OrderItem
{
public string Name { get; set; }
public int Price { get; set; }
public int Count { get; set; }
}
}
2- Add a Run-time Text Template (also known as Preprocessed Text Template) to the project and name it ReportTemplate.tt
. Open it and add such code:
<#@ template language="C#"#>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ parameter name="Model" type="Sample.ReportModel"#>
Order
Customer: <#=Model.CustomerName#>
Order Date: <#=Model.Date#>
Index Name Price Count Sum
<#
int index =1;
foreach(var item in Model.OrderItems)
{
#>
<#=index#>
<#=item.Name#>
<#=item.Price#>
<#=item.Count#>
<#=item.Count * item.Price#>
<#
index++;
}
var total= Model.OrderItems.Sum(x=>x.Count * x.Price);
#>
Total: <#=total#>
3- Put a WebBrowser
control on the form and write such code where you want to generate the report:
var rpt = new ReportTemplate();
rpt.Session = new Dictionary();
rpt.Session["Model"] = new Sample.ReportModel
{
CustomerName = "Reza",
Date = DateTime.Now,
OrderItems = new List()
{
new Sample.OrderItem(){Name="Product 1", Price =100, Count=2 },
new Sample.OrderItem(){Name="Product 2", Price =200, Count=3 },
new Sample.OrderItem(){Name="Product 3", Price =50, Count=1 },
}
};
rpt.Initialize();
this.webBrowser1.DocumentText= rpt.TransformText();
4- If you want to print the report, you can call:
this.webBrowser1.Print();
You should call Print
after the document completed. So if you want to print directly without showing output to the user, you can handle DocumentCompleted
event and call Print
there.
Here is the result: