【发布时间】:2012-01-16 00:33:59
【问题描述】:
我是 MVC 的初学者,需要在提供的模板上生成 PDF 发票。在进行了一些谷歌搜索之后,现在我能够生成 pdf 但不能在模板中生成。任何机构都可以帮助我解决这个问题。我在下面写我的代码:
public ActionResult pdfStatement(string InvoiceNumber)
{
InvoiceNumber = InvoiceNumber.Trim();
ObjectParameter[] parameters = new ObjectParameter[1];
parameters[0] = new ObjectParameter("InvoiceNumber", InvoiceNumber);
var statementResult = _db.ExecuteFunction<Models.Statement>("uspInvoiceStatement", parameters);
Models.Statement statement = statementResult.SingleOrDefault();
return ViewPdf("Invoice", "pdfStatement", statement);
}
public class PdfViewController : Controller
{
private readonly HtmlViewRenderer htmlViewRenderer;
private readonly StandardPdfRenderer standardPdfRenderer;
public PdfViewController()
{
this.htmlViewRenderer = new HtmlViewRenderer();
this.standardPdfRenderer = new StandardPdfRenderer();
}
protected ActionResult ViewPdf(string pageTitle, string viewName, object model)
{
// Render the view html to a string.
string htmlText = this.htmlViewRenderer.RenderViewToString(this, viewName, model);
// Let the html be rendered into a PDF document through iTextSharp.
byte[] buffer = standardPdfRenderer.Render(htmlText, pageTitle);
// Return the PDF as a binary stream to the client.
return new BinaryContentResult(buffer, "application/pdf");
}
}
public class BinaryContentResult : ActionResult
{
private readonly string contentType;
private readonly byte[] contentBytes;
public BinaryContentResult(byte[] contentBytes, string contentType)
{
this.contentBytes = contentBytes;
this.contentType = contentType;
}
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.Clear();
response.Cache.SetCacheability(HttpCacheability.Public);
response.ContentType = this.contentType;
using (var stream = new MemoryStream(this.contentBytes))
{
stream.WriteTo(response.OutputStream);
stream.Flush();
}
}
}
【问题讨论】:
-
如前所述,iText 可能是要考虑的库。您可能希望查看一个地理工具来定义现有 PDF 的边界,您可以在其中编写以后的动态数据:github.com/applicius/dhek。
标签: asp.net-mvc asp.net-mvc-3 entity-framework-4 pdf-generation