0

I am trying to generate a view as pdf. For that I want to convert an action view to a string.I tried the the following code. But I didn't get a solution.

  1. I want to get .cshtml view to the string.
  2. Set this View as Pdf.

Controller

    public void UrlAsPDF(string date)
    {
        string HTMLContent = View("_LoadItemOnDate",new { date = date });
        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=" + "PDFfile.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.BinaryWrite(GetPDF(HTMLContent));
        Response.End();
    }

HTMLContent in the above code is a wrong code.

PDF Generator

public byte[] GetPDF(string pHTML)
    {
        byte[] bPDF = null;

        MemoryStream ms = new MemoryStream();
        TextReader txtReader = new StringReader(pHTML);

        // 1: create object of a itextsharp document class  
        Document doc = new Document(PageSize.A4, 25, 25, 25, 25);

        // 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file  
        PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms);

        // 3: we create a worker parse the document  
        HTMLWorker htmlWorker = new HTMLWorker(doc);

        // 4: we open document and start the worker on the document  
        doc.Open();
        htmlWorker.StartDocument();


        // 5: parse the html into the document  
        htmlWorker.Parse(txtReader);

        // 6: close the document and the worker  
        htmlWorker.EndDocument();
        htmlWorker.Close();
        doc.Close();

        bPDF = ms.ToArray();

        return bPDF;
    }

ActionResult _LoadItemOnDate

 public ActionResult _LoadItemOnDate(string date)
    {
        var dt = DateTime.ParseExact(date, "dd/MM/yyyy",
                                   System.Globalization.CultureInfo.InvariantCulture);
        bool Working = true;
        var custmenuheadList = _customermenuH.findbyDate(dt).GroupBy(x => x.CustMenu_OrderId).Select(x => x.First());
        List<CustomerViewModel> CustomerList = new List<CustomerViewModel>();

        if (dt.DayOfWeek.ToString() == "Friday" || dt.DayOfWeek.ToString() == "Saturday")
        {
            Working = false;
        }
        var address = _custaddress.FindbyId(0);
        foreach (var item in custmenuheadList)
        {
            var CustomerOrder = _custOrder.FindbyId(Convert.ToInt64(item.CustMenu_OrderId));
            if(CustomerOrder.CustOrdr_Count == 0 || CustomerOrder.CustOrdr_Count == null)
            {
                CustomerOrder.CustOrdr_Count = 1;
            }
            if(CustomerOrder.IsPaid != null)
            {
                for (int i = 0; i < CustomerOrder.CustOrdr_Count; i++)
                {
                    var customer = _customer.FindbyId(Convert.ToInt64(item.CustMenu_CustID));
                    if (Working != true)
                    {
                        address = _custaddress.FindbyId(Convert.ToInt64(CustomerOrder.DelvryAddr_Weekend));
                    }
                    else
                    {
                        address = _custaddress.FindbyId(Convert.ToInt64(CustomerOrder.DelvryAddr_Working));
                    }
                    CustomerViewModel cvmobj = new CustomerViewModel();
                    cvmobj.CustName = customer.CustName;
                    cvmobj.CustPhone = customer.CustPhone;
                    if (address != null)
                    {
                        cvmobj.CustAddr1 = address.CustAddr1;
                        cvmobj.CustAddr2 = address.CustAddr2;

                        var city = _city.FindbyId(Convert.ToInt64(address.CustAddrCityID));
                        var State = _state.FindbyId(Convert.ToInt64(address.CustAddrStateID));
                        if (city != null)
                        {
                            cvmobj.CityName = city.Name;
                        }
                        if (State != null)
                        {
                            cvmobj.StateName = State.StateName;
                        }
                    }
                    CustomerList.Add(cvmobj);
                }
            }
        }
        return View(CustomerList);
    }

Trying to get a better Solution.

Alsamil Mehboob
  • 384
  • 2
  • 6
  • 24
  • Your question is rather broad. I was tempted to close it as a duplicate of [Converting HTML to PDF using iText ](https://stackoverflow.com/questions/47895935/converting-html-to-pdf-using-itext/47896272#47896272) because the answer to that question explains what you're doing wrong in the *PDF Generator* part of your question. Maybe I'll vote to close this question as off-topic, because you're asking to recommend a tool. If you indeed want a recommendation for a better solution, you will find a better solution [here](https://stackoverflow.com/questions/47895935). – Bruno Lowagie Jan 15 '18 at 12:07
  • But the PDF generating code has no error. I want to convert my partial view as a string. – Alsamil Mehboob Jan 15 '18 at 12:18

1 Answers1

1

To convert a view to a string you can use the following method:

  private static string RenderPartialViewToString(Controller controller, string viewName, Object model)
        {
            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                controller.ViewData.Model = model; 

                ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.ToString();
            }
        }
Syl20
  • 117
  • 2
  • 18
  • private string ConvertViewToString(string viewName, object model) { ViewData.Model = model; using (StringWriter writer = new StringWriter()) { ViewEngineResult vResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName); ViewContext vContext = new ViewContext(this.ControllerContext, vResult.View, ViewData, new TempDataDictionary(), writer); vResult.View.Render(vContext, writer); return writer.ToString(); } } – Alsamil Mehboob Jan 16 '18 at 04:52
  • This one is my solution right now. Thank you. – Alsamil Mehboob Jan 16 '18 at 04:52
  • No worries, glad you found a solution! – Syl20 Jan 16 '18 at 11:13