如何获取视图生成 PDF

我想调用控制器上的操作。让控制器从模型中获取数据。然后视图运行并生成一个 PDF。我发现的唯一一个例子是在 Lou http://whereslou.com/2009/04/12/returning-pdfs-from-an-aspnet-mvc-action的一篇文章中。他的代码非常优雅。视图使用 ITextSharp 生成 PDF。唯一的缺点是他的示例使用了 Spark View Engine。是否有一种方法可以用标准的 Microsoft 视图引擎做类似的事情?

101007 次浏览

我使用 iTextSharp 在 MVC 中生成动态 PDF。所有您需要做的就是将您的 PDF 放入一个 Stream 对象,然后您的 ActionResult 返回一个 FileStreamResult。我还设置了内容配置,以便用户可以下载它。

public FileStreamResult PDFGenerator()
{
Stream fileStream = GeneratePDF();


HttpContext.Response.AddHeader("content-disposition",
"attachment; filename=form.pdf");


return new FileStreamResult(fileStream, "application/pdf");
}

我也有代码,使我能够采取一个模板 PDF,写文本和图像等(如果你想这样做)。

  • 注意: 必须将 Stream 位置设置为0。
private Stream GeneratePDF()
{
//create your pdf and put it into the stream... pdf variable below
//comes from a class I use to write content to PDF files


MemoryStream ms = new MemoryStream();


byte[] byteInfo = pdf.Output();
ms.Write(byteInfo, 0, byteInfo.Length);
ms.Position = 0;


return ms;
}

我也遇到了这个 http://www.codeproject.com/Articles/260470/PDF-reporting-using-ASP-NET-MVC3。它简单,迅速,适合与 MVC。

然而,到目前为止唯一的缺点是,它不是很灵活,你想有一个体面的布局,例如,你没有太多的控制与表格,和单元格边框通过 html。它有点支持强制新页面,但是你必须给 iTextSharp 应用一个补丁。

我只使用 wkhtmltopdf,在 html 中创建布局,然后将其转换为 pdf。

简单,可定制,酷毙了:)

在 html 中创建布局,然后打印成 pdf 是最快的方法。

HTML 到 pdf 的转换由 幻影WkhtmltopdfJsreport提供

Jsreport 提供了与 asp.net mvc 视图的直接集成, 你可以用属性标记控制器操作,它会为你打印 pdf 而不是 html。

更多关于 博客文章的信息

免责声明: 我是 jsreport 的作者

这是一个老问题,但仍然是相关的,我想我只是分享我已经实现了哪些工作得很好。

  1. 安装 NuGet 包 TuesPechkin-一个 Pechkin 库中的 fork,基于 wkhtmlTopdf,使用 Webkit 引擎将 HTML 页面转换为 PDF。

  2. Write a little helper to read a view and convert it to an HTML string (mvcContext is this.HttpContext). The replace is optional of course!:

    public static string RenderViewToString(HttpContextBase mvcContext, string area, string controllerName, string viewName, object model)
    {
    var context = System.Web.HttpContext.Current;
    var contextBase = mvcContext;
    var routeData = new RouteData();
    if (area == null) area = "";
    
    
    routeData.DataTokens.Add("area", area);
    
    
    routeData.Values.Add("controller", controllerName);
    
    
    var controllerContext = new ControllerContext(contextBase,
    routeData,
    new EmptyController());
    
    
    var razorViewEngine = new RazorViewEngine();
    var razorViewResult = razorViewEngine.FindView(controllerContext,
    viewName,
    "",
    false);
    
    
    var writer = new StringWriter();
    var viewContext = new ViewContext(controllerContext,
    razorViewResult.View,
    new ViewDataDictionary(model),
    new TempDataDictionary(),
    writer);
    razorViewResult.View.Render(viewContext, writer);
    
    
    string hostAddress = context.Request.Url.Scheme + "://" + context.Request.Url.Authority;
    
    
    return writer.ToString()
    .Replace("src=\"/", "src=\"" + hostAddress + "/")
    .Replace("<link href=\"/", "<link href=\"" + hostAddress + "/");
    }
    
    
    class EmptyController : ControllerBase
    {
    protected override void ExecuteCore() { }
    }
    

The hard work of the above were from here: http://wouterdekort.blogspot.co.uk/2012/10/rendering-aspnet-mvc-view-to-string-in.html?showComment=1414603363455#c7863520150405064571

  1. Create an MVC Action to generate the document

    public ActionResult DownloadPDF(long CentreID)
    {
    var model = GetModel()
    
    
    IPechkin converter = Factory.Create();
    byte[] result = converter.Convert(Helpers.PDF.RenderViewToString(this.HttpContext, "area", "controller", "action", model);
    MemoryStream outputStream = new MemoryStream();
    outputStream.Write(result, 0, result.Length);
    outputStream.Position = 0;
    
    
    return File(outputStream, "application/pdf", "filename.pdf");
    }
    

我们对这个问题的最终答案是使用 旋转

它像其他一些解决方案一样包装了 WKhtmltopdf.exe,但是它是目前为止我发现的最容易使用的解决方案

我去投票表决所有其他的答案,也解决了这个问题,但这是我们用来解决问题中提出的问题。这和其他的答案不同。

这是 循环教程

在您安装之后,这就是您所需要的全部内容

public ActionResult PrintInvoice(int invoiceId)
{
return new ActionAsPdf(
"Invoice",
new { invoiceId= invoiceId })
{ FileName = "Invoice.pdf" };
}

很简单。

非常晚的回复,但是我发现下面的网址帮助我快速得到我的结果:

(确保您通过使用 Nuget 软件包来引用 iTextSharp DLL)

Https://www.aspsnippets.com/articles/export-grid-html-table-data-from-database-to-pdf-file-using-itextsharp-in-aspnet-mvc.aspx

剪辑 这是我用来使表看起来有点不同的代码(这也是横向的:

public string GetCssForPdf()
{
string css = "";


css = "th, td" +
"{" +
"font-family:Arial; font-size:10px" +
"}";


return css;
}


[HttpPost]
[ValidateInput(false)]
public FileResult Export(string GridHtml)
{
string webgridstyle = GetCssForPdf();


string exportData = String.Format("<html><body>{0}{1}</body></html>", "<style>" + webgridstyle + "</style>", GridHtml);
var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);


using (var input = new MemoryStream(bytes))
{
var output = new MemoryStream();
var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
var writer = PdfWriter.GetInstance(document, output);


document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
Font headerFont = FontFactory.GetFont("Verdana", 10);
Font rowfont = FontFactory.GetFont("Verdana", 10);


writer.CloseStream = false;
document.Open();


var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
document.Close();
output.Position = 0;


return File(output, "application/pdf", "Pipeline_Report.pdf");


//return new FileStreamResult(output, "application/pdf");
}
}

希望这也能帮到其他人。

在 asp.net mvc 中使用 rotativa 包的一个小例子

我们将创建一个函数来填充数据。我们将插入为期7天(2018年2月1日至2018年2月7日)的数据,显示特定日期的第一次冲击和最后一次冲击,并附上备注。

public ReportViewModel PopulateData()
{
var attendances = new List<Attendance>
{
new Attendance{ClassName = "present",Day = new DateTime(2018, 02, 01).ToString("ddd"),Date = new DateTime(2018, 02, 01).ToString("d"),FirstPunch = "09:01:00",LastPunch = "06:00:01",Remarks = ""},
new Attendance{ClassName = "absent",Day = new DateTime(2018, 02, 02).ToString("ddd"),Date = new DateTime(2018, 02, 02).ToString("d"),FirstPunch = "",LastPunch = "",Remarks = "Absent"},
new Attendance{ClassName = "holiday",Day = new DateTime(2018, 02, 03).ToString("ddd"),Date = new DateTime(2018, 02, 03).ToString("d"),FirstPunch = "",LastPunch = "",Remarks = "Democracy Day"},
new Attendance{ClassName = "present",Day = new DateTime(2018, 02, 04).ToString("ddd"),Date = new DateTime(2018, 02, 04).ToString("d"),FirstPunch = "09:05:00",LastPunch = "06:30:01",Remarks = ""},
new Attendance{ClassName = "present",Day = new DateTime(2018, 02, 05).ToString("ddd"),Date = new DateTime(2018, 02, 05).ToString("d"),FirstPunch = "09:01:00",LastPunch = "06:00:01",Remarks = ""},
new Attendance{ClassName = "leave",Day = new DateTime(2018, 02, 06).ToString("ddd"),Date = new DateTime(2018, 02, 06).ToString("d"),FirstPunch = "",LastPunch = "",Remarks = "Sick Leave"},
new Attendance{ClassName = "present",Day = new DateTime(2018, 02, 07).ToString("ddd"),Date = new DateTime(2018, 02, 07).ToString("d"),FirstPunch = "08:35:00",LastPunch = "06:15:01",Remarks = ""}
};




return new ReportViewModel
{
UserInformation = new UserInformation
{
FullName = "Ritesh Man Chitrakar",
Department = "Information Science"
},
StartDate = new DateTime(2018, 02, 01),
EndDate = new DateTime(2018, 02, 07),
AttendanceData = attendances
};
}

然后我们将创建一个下载 pdf 的函数。要下载 pdf,我们将需要创建2个函数。 1. 下载 pdf 2. 浏览 pdf

public ActionResult DownloadPdf()
{
var filename = "attendance.pdf";


/*get the current login cookie*/
var cookies = Request.Cookies.AllKeys.ToDictionary(k => k, k => Request.Cookies[k]?.Value);


return new ActionAsPdf("PdfView", new
{
startDate = Convert.ToDateTime(Request["StartDate"]),
endDate = Convert.ToDateTime(Request["EndDate"])
})
{
FileName = filename,
/*pass the retrieved cookie inside the cookie option*/
RotativaOptions = {Cookies = cookies}
};
}


public ActionResult PdfView()
{
var reportAttendanceData = PopulateData();


return View(reportAttendanceData);
}

您可以在此链接上查看详细说明。 访问 给你

屈膝礼: Thelearninguy.com