简体   繁体   中英

How do I a generate PDF document using ASP.NET Core MVC c#

I am doing my final year project and the concept of C# MVC is still new to me. I want to generate PDFs directly from the application. I am using SelectPDF. In my view I have a button that is used to generate the PDF. When clicked the PDF is generated the problem is that it is blank with no content in it. Here is the code within the controller

public ActionResult GeneratePdf( string html)
        {
            html = html.Replace("StrTag","<").Replace("EndTag",">");
            HtmlToPdf oHtmlToPdf = new HtmlToPdf();
            PdfDocument oPdfDocument = oHtmlToPdf.ConvertHtmlString(html);
            byte[] pdf = oPdfDocument.Save();

            oPdfDocument.Close();
            return File(pdf,"application/pdf","Financial Report.pdf");
        }

Below is the javascript code within the view

<script type="text/javascript">
            $("#PDF").click(function () {
                var html = $("#PdfContainer").html();


                html = html.replace(/</g, "StrTag").replace(/>/g, "EndTag");
                window.open('../Account/GeneratePdf?html=' + html, '_blank');

            });
</script>

I am open to any suggestions if there any. Basically all I want is to be able to generate PDFs directly from the application.

In view page use below code

<a href="@Url.Action("Export", "ControllerName")" style="border: 1px solid #e7eaec; padding: 5px;" class="pull-right">Download PDF</a>

Install the in your project itextsharp.xmlworker

Add reference and code on your controller

using System.IO;
using System.Reflection.Metadata;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;

private static PdfPCell PhraseCell(Phrase phrase, int align)
        {
            PdfPCell cell = new PdfPCell(phrase);
            cell.BorderColor = BaseColor.WHITE;
            cell.VerticalAlignment = Element.ALIGN_TOP;
            cell.HorizontalAlignment = align;
            cell.PaddingBottom = 2f;
            cell.PaddingTop = 0f;
            return cell;
        }
        public FileResult Export()
    {
        string html = "StrTag Messgae EndTag";
        string ExportData = "This is first pdf generat";
        using (MemoryStream stream = new System.IO.MemoryStream())
        {
            StringReader reader = new StringReader(ExportData);
            Document PdfFile = new iTextSharp.text.Document(PageSize.A3);
            PdfWriter writer = PdfWriter.GetInstance(PdfFile, stream);
            PdfFile.Open();
            PdfPCell cell = null;
            PdfPTable table = null;
            Phrase phrase2 = null;
            Phrase phrase1 = null;
            phrase2 = new Phrase();
            var titleFont = FontFactory.GetFont("Arial", 16, iTextSharp.text.Font.BOLD);


            table = new PdfPTable(1);
            table.TotalWidth = 800f;
            table.LockedWidth = true;
            table.SpacingBefore = 10;
            table.SpacingAfter = 10;
            table.HorizontalAlignment = Element.ALIGN_LEFT;

            PdfFile.Add(table);
            phrase1 = new Phrase();
             html = html.Replace("StrTag", "<").Replace("EndTag", ">");
            phrase1.Add(new Chunk(html, FontFactory.GetFont("Arial", 14, Font.BOLD)));
            cell = PhraseCell(phrase1, PdfPCell.ALIGN_CENTER);
            cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
            table.AddCell(cell);
            PdfFile.Add(table);

            PdfFile.Open();
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, PdfFile, reader);
            PdfFile.Close(); return File(stream.ToArray(), "application/pdf", "Financial Report.pdf");
        }
    }

You can view, and download , a complete step-by-step Converting MVC View to PDF tutorial which shows you how to set up and work with an MVC application (the example is using IronPDF).

Full code in the tutorial, but below shows Post method which handles the download button

[HttpPost]
public ActionResult TicketView(TicketModel model)
{
  IronPdf.Installation.TempFolderPath = $@" {_host.ContentRootPath}/irontemp/";
  IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
  var html = this.RenderViewAsync("_TicketPdf", model);
  var ironPdfRender = new IronPdf.ChromePdfRenderer();
  var pdfDoc = ironPdfRender.RenderHtmlAsPdf(html.Result);
  return File(pdfDoc.Stream.ToArray(), "application/pdf");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM