使用ASP.net,C#,MVC在模板中生成pdf

145*_*446 3 asp.net-mvc pdf-generation entity-framework-4 asp.net-mvc-3

我是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);
}
Run Code Online (Sandbox Code Playgroud)
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");
    }
}
Run Code Online (Sandbox Code Playgroud)
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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 6

我推荐iTextSharp库.

查看本教程,了解如何使用库从c#填充pdf.使用Adobe 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(); 
Run Code Online (Sandbox Code Playgroud)