gpt4 book ai didi

asp.net-mvc - 使用 ASP.net、C#、MVC 在模板中生成 pdf

转载 作者:行者123 更新时间:2023-12-03 23:57:23 26 4
gpt4 key购买 nike

我是 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();
}
}
}

最佳答案

我会推荐 iTextSharp图书馆。

看看这个 tutorial on how to populate a pdf 来自 c# 使用该库。在 Adob​​e Acrobat 中创建包含字段的 pdf,然后使用代码填充字段。

// Open the template pdf
PdfReader pdfReader = new PdfReader(Request.MapPath("~/assets/form.pdf"));
PdfStamper pdfStamper = new PdfStamper(pdfReader, Response.OutputStream);
pdfStamper.FormFlattening = true; // generate a flat PDF

// Populate the fields
AcroFields pdfForm = pdfStamper.AcroFields;
pdfForm.SetField("InvoiceRef", "00000");
pdfForm.SetField("DeliveryAddress", "Oxford Street, London");
pdfForm.SetField("Email", "anon@anywhere.com");
pdfStamper.Close();

关于asp.net-mvc - 使用 ASP.net、C#、MVC 在模板中生成 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8433261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com