Programing

Asp.Net MVC PDF를 생성하기 위해보기를 얻는 방법

crosscheck 2020. 10. 27. 07:51
반응형

Asp.Net MVC PDF를 생성하기 위해보기를 얻는 방법


컨트롤러에 대한 작업을 호출하고 싶습니다. 컨트롤러가 모델에서 데이터를 가져 오도록합니다. 그런 다음보기가 실행되고 PDF가 생성됩니다. 내가 찾은 유일한 예는 Lou http://whereslou.com/2009/04/12/returning-pdfs-from-an-aspnet-mvc-action 의 기사 입니다. 그의 코드는 매우 우아합니다. 보기는 ITextSharp를 사용하여 PDF를 생성합니다. 유일한 단점은 그의 예가 Spark View Engine을 사용한다는 것입니다. 표준 Microsoft 뷰 엔진으로 비슷한 작업을 수행 할 수있는 방법이 있습니까?


iTextSharp를 사용하여 MVC에서 동적 PDF를 생성합니다. PDF를 Stream 개체에 넣은 다음 ActionResult가 FileStreamResult를 반환하기 만하면됩니다. 사용자가 다운로드 할 수 있도록 콘텐츠 배치도 설정했습니다.

공용 FileStreamResult PDFGenerator ()
{
    스트림 fileStream = GeneratePDF ();

    HttpContext.Response.AddHeader ( "content-disposition", 
    "첨부 파일; 파일 이름 = form.pdf");

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

또한 템플릿 PDF를 가져 와서 텍스트와 이미지를 쓸 수있는 코드도 있습니다 (원하는 경우).

  • 참고 : 스트림 위치를 0으로 설정해야합니다.
개인 스트림 GeneratePDF ()
{
    // PDF를 만들어 스트림에 넣습니다. 아래 pdf 변수
    // PDF 파일에 내용을 쓰는 데 사용하는 클래스에서 가져옴

    MemoryStream ms = 새로운 MemoryStream ();

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

    반환 ms;
}

이 문제에 대한 최종 답변은 Rotativa 를 사용하는 것이 었습니다 .

다른 솔루션과 마찬가지로 WKhtmltopdf.exe를 래핑하지만 내가 찾은 것 중 가장 사용하기 가장 쉽습니다.

나는 가서 문제를 잘 해결하는 다른 모든 답변에 투표했지만 이것이 위의 질문에서 제기 된 문제를 해결하는 데 사용한 것입니다. 다른 답변과 다릅니다.

다음은 Rotativa 자습서 입니다.

설치 한 후에는이 모든 것이 필요합니다.

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

아주 간단합니다.


html로 레이아웃을 만들고 나중에 pdf로 인쇄하는 것이 가장 빠른 방법입니다.

HTML에서 pdf 로의 변환은 phantomjs , wkhtmltopdf 또는 jsreport에 의해 제공됩니다.

jsreport 는 asp.net mvc 뷰와의 직접 통합을 제공합니다. 여기서 컨트롤러 동작을 속성으로 표시하면 html 대신 pdf가 인쇄됩니다.

블로그 게시물 에 대한 추가 정보

면책 조항 : 저는 jsreport의 작성자입니다.


이것은 오래된 질문이지만 여전히 관련이 있으며 잘 작동하는 구현을 공유 할 것이라고 생각했습니다.

  1. Webkit 엔진을 사용하여 HTML 페이지를 PDF로 변환하는 WkHtmlToPdf 기반 Pechkin 라이브러리의 포크 인 NuGet 패키지 TuesPechkin을 설치합니다.

  2. 보기를 읽고 HTML 문자열로 변환하는 작은 도우미를 작성하십시오 (mvcContext는 this.HttpContext입니다). 교체는 물론 선택 사항입니다! :

    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() { }
    }
    

위의 노력은 여기에서 왔습니다 : http://wouterdekort.blogspot.co.uk/2012/10/rendering-aspnet-mvc-view-to-string-in.html?showComment=1414603363455#c7863520150405064571

  1. 문서를 생성하는 MVC 작업 만들기

    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");
    }
    

나는 또한이 http://www.codeproject.com/Articles/260470/PDF-reporting-using-ASP-NET-MVC3를 보았습니다 . 쉽고 빠르며 MVC와 잘 어울립니다.

그러나 지금까지 유일한 단점은 적절한 레이아웃을 원하는 것이 유연하지 않다는 것입니다. 예를 들어 html을 통해 테이블 ​​및 셀 테두리를 많이 제어 할 수 없습니다. 일종의 강제 새 페이지를 지원하지만 iTextsharp에 패치를 적용해야합니다.


방금 wkhtmltopdf를 사용하여 html로 레이아웃을 만든 다음 나중에 pdf로 변환합니다.

쉽고, 커스터마이징이 가능하고, 굉장합니다. :)


매우 늦게 회신했지만 다음 URL이 내 결과를 빠르게 얻는 데 도움이된다는 것을 알았습니다.

(Nuget 패키지를 사용하여 iTextSharp DLL을 참조해야합니다.)

https://www.aspsnippets.com/Articles/Export-Grid-Html-Table-data-from-database-to-PDF-file-using-iTextSharp-in-ASPNet-MVC.aspx

EDIT This is the code I used to make the table look a little different(This is landscape as well:

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");
            }
        }

Hope this helps someone else as well.


A small example using rotativa package in asp.net mvc

We will create a function to populate the data. We will insert data for 7 days (Feb 1 2018 - Feb 7 2018) showing the first punch and the last punch for particular day with remarks.

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
            };
        }

We will then create a function to DownloadPdf. To download the pdf we will need to create 2 function. 1. to download pdf 2. to view 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);
        }

You can view the detail explanation on this link . Visit here .

Curtesoy : thelearninguy.com

참고URL : https://stackoverflow.com/questions/779430/asp-net-mvc-how-to-get-view-to-generate-pdf

반응형