我正在使用Winnovative HTML to PDF with MVC 4.基本示例工作正常(下面是代码)但我需要用户点击“打印按钮”,代码必须生成PDF,我也需要打开自动生成PDF并打开打印机对话框(用户希望按最少的点击次数来打印文档):
在我的View Index.cshtml中,我有:
@using (Html.BeginForm("ImpresionSeccionVistaActual", "Home", FormMethod.Post))
{
}
在我的HomeController我有:
using Winnovative;
[HttpPost]
public ActionResult ImpresionSeccionVistaActual(FormCollection collection)
{
object model = null;
ViewDataDictionary viewData = new ViewDataDictionary(model);
// transmit the posted data to view
viewData.Add("nombre", collection["nombre"]);
// The string writer where to render the HTML code of the view
StringWriter stringWriter = new StringWriter();
// Render the Index view in a HTML string
ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, "Seccion", null);
ViewContext viewContext = new ViewContext(
ControllerContext,
viewResult.View,
viewData,
new TempDataDictionary(),
stringWriter
);
viewResult.View.Render(viewContext, stringWriter);
// Get the view HTML string
string htmlToConvert = stringWriter.ToString();
// Get the base URL
String currentPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
String baseUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Home/Seccion".Length);
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
//htmlToPdfConverter.OpenAction.Action = New PdfActionJavaScript("print()")
htmlToPdfConverter.JavaScriptEnabled = true;
// Set license key received after purchase to use the converter in licensed mode
// Leave it not set to use the converter in demo mode
htmlToPdfConverter.LicenseKey = key;
// Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed
// Set this property to 0 if you don't need to wait for such asynchcronous operations to finish
htmlToPdfConverter.ConversionDelay = 2;
// Convert the HTML string to a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlToConvert, baseUrl);
// Send the PDF file to browser
FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
fileResult.FileDownloadName = "ImpresionSeccionVistaActual.pdf";
return fileResult;
}
View Seccion.cshtml只有:
@{
ViewBag.Title = "Seccion ejemplo";
var nombre = ViewBag.Nombre;
}
我今天所做的就是点击,显示在浏览器底部下载的PDF,如附图 .
有帮助吗?