【发布时间】:2013-04-01 08:35:16
【问题描述】:
我正在寻找一种从 Windows 2003 服务器中运行的 ASP.NET 应用程序打印 ASP.NET/Mono MVC2 视图的方法。 我根据Programmatically "hello world" default SERVER-side printer in ASP.NET MVC尝试了下面的代码
但这会输出原始的 html 字符串。如何使用免费软件将视图打印为格式化文本?
订单布局创建为 html 局部视图。如果有其他免费的方式来打印格式化的订单,我可以用其他形式而不是 html 创建布局。
我发现只有免费的解决方案需要使用 Windows Forms WebBrowser 控件,但这在也运行在 Mono 下的 MVC2 应用程序中看起来不合理。
我查看了 Rotativa (http://nuget.org/packages/Rotativa/),但它似乎不允许打印 html。
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Web.Mvc;
public class PrintController : Controller
{
string body;
public ActionResult Complete()
{
body = RenderViewToString<TestOrder>("~/Views/Checkout/Order.ascx", new TestOrder() { Number = "1" });
PrintOrder();
return View("PaymentComplete");
}
void PrintOrder()
{
// https://stackoverflow.com/questions/12229823/programmatically-hello-world-default-server-side-printer-in-asp-net-mvc
var doc = new PrintDocument();
doc.PrinterSettings.PrinterName = "HP Laserjet 1200";
doc.PrintPage += new PrintPageEventHandler(ProvideContent);
doc.Print();
}
void ProvideContent(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawString(body,
new Font("Arial", 12),
Brushes.Black,
e.MarginBounds.Left,
e.MarginBounds.Top);
}
string RenderViewToString<T>(string viewPath, T model)
{ // https://stackoverflow.com/questions/483091/render-a-view-as-a-string
ViewData.Model = model;
using (var writer = new StringWriter())
{
var view = new WebFormView(viewPath);
var vdd = new ViewDataDictionary<T>(model);
var viewCxt = new ViewContext(ControllerContext, view, vdd, new TempDataDictionary(), writer);
viewCxt.View.Render(viewCxt, writer);
return writer.ToString();
}
}
}
public class TestOrder
{
public string Number;
}
【问题讨论】:
-
谢谢。您引用的问题使用 WinForms WebBrowser 控件。这是否适用于在 IIS 服务下运行的 ASP.NET MVC2 应用程序?我真的应该将 winforms 引用添加到 MVC2 项目吗?
标签: asp.net .net asp.net-mvc asp.net-mvc-2 printing-web-page