HTML and Razor print with Xamarin for iOS

Posted · Add Comment


I recently had to add a print functionality on an iPad app, developed with Xamarin.

iOS provides a very nice feature, called UIMarkupTextPrintFormatter, which allows printing HTML formatted content, you can easily format the document you have to print.  That’s pretty cool!

The other amazing thing, Xamarin supports the Preprocessed Razor Template! We can also generate dynamic HTML with a data model. To do that, you have to:

In Xamarin Studio or Visual Studio:

Create a new Data Model / Entity: ExpenseReport.cs

public class ExpenseReport
public string Item { get; set; }
public double Price { get; set; }
public DateTime Date { get; set; }

Add a new item: Preprocessed Razor Template, ExpenseReport.cshtml

  • Modifiy the cshtml file
  • Add the @model
  • Create your html
  • Add dynamic content
  • Save, cs files are going to be generated

@model IEnumerable<ExpenseReport>
@foreach (var item in Model)
<span style="font-weight:bold">@item.Item</span>
<span>$ @item.Price</span>
<span>@item.Date.ToString("MM-dd-YYYY HH:mm")</span>


Add Print Code

var printInfo = UIPrintInfo.PrintInfo;
printInfo.OutputType = UIPrintInfoOutputType.General;
printInfo.JobName = "Expense report";
var template = new ExpenseReport() { Model = myDataModel };
var page = template.GenerateString ();
var textFormatter = new UIMarkupTextPrintFormatter (page);
textFormatter.StartPage = 0;
var printer = UIPrintInteractionController.SharedPrintController;
printer.PrintInfo = printInfo;
printer.PrintFormatter = textFormatter;
printer.ShowsPageRange = true;
printer.Present (true, (handler, completed, err) => {
if (!completed && err != null) {
Console.WriteLine ("error");

With that 2 features, we can very easily print dynamic HTML content. That great!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>