我正在寻找一种从Windows 2003服务器上运行的ASP.NET应用程序打印ASP.NET / Mono MVC2视图的方法。 我根据Programmatically "hello world" default SERVER-side printer in ASP.NET MVC
尝试了以下代码但是这会输出原始的html字符串。如何使用免费软件将视图打印为格式化文本?
订单布局创建为html局部视图。如果有其他免费方式打印出格式化的订单,我可以用其他形式而不是html创建布局。
只有我发现的免费解决方案需要使用Windows窗体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;
}
答案 0 :(得分:-1)
有一篇关于使用iTextSharp将HTML转换为PDF的文章:http://www.dotnetspider.com/resources/43589-How-convert-HTML-PDF-ASP-NET.aspx