Save webpage as PDF in ASP.net MVC 1.0

391 views
Skip to first unread message

Rajendra Prasad

unread,
Jan 11, 2011, 12:06:06 AM1/11/11
to c4...@googlegroups.com
Hi friends,

i need a sample code to save webpage as pdf in asp.net mvc 1.0 .

Could any one guide how can i do this.

thanks in advance

regards,
RajendraPrasad.

Matthew Hinze

unread,
Jan 11, 2011, 7:34:56 AM1/11/11
to c4...@googlegroups.com
There are a few options, but here's one from Mahendra Mavani

I've used two HTML to PDF converters.  Prince, the tool Mahendra uses, is very nice but it's expensive (server license is US$3800)  and a free alternative that uses webkit.    


--
You received this message because you are subscribed to the "Community for ASP.NET MVC" group.
 
To post to this group, send email to c4...@googlegroups.com
 
To unsubscribe from this group, send email to
c4mvc+un...@googlegroups.com
For more options, visit this group at
http://CommunityForMvc.Net

Dan Cary

unread,
Jan 11, 2011, 10:44:06 AM1/11/11
to c4...@googlegroups.com
We use ABC.PDF. It is only a couple hundred dollars and works fine. There are ways of getting it free. 

Dan

Ely Lucas

unread,
Jan 11, 2011, 12:10:16 AM1/11/11
to c4...@googlegroups.com
You will need a 3rd party tool to do this, as there is not any functionality to do so built into the .net framework.  One library I've used that is fairly simple is ExpertPDF (http://www.html-to-pdf.net).  I have seen an open source project as well, but don't recall the name of it off hand.  The ExpertPDF download has a fully functional trial and plenty of code samples.

--

Stephen Bohlen

unread,
Jan 11, 2011, 5:24:17 PM1/11/11
to c4mvc
If you absolutely *must* have free, iTextSharp is a .NET port of the OSS iText library in Java and works pretty well (though its somewhat rough (read: low-level) as an API).

Steve Bohlen
sbo...@gmail.com
http://blog.unhandled-exceptions.com
http://twitter.com/sbohlen

Darrell Mozingo

unread,
Jan 11, 2011, 10:49:16 AM1/11/11
to c4...@googlegroups.com
+1 for ABC PDF. xcopy deployment and easy to work with too.

Darrell

Donn Felker

unread,
Jan 11, 2011, 5:42:50 PM1/11/11
to c4...@googlegroups.com
You can also use the Spark View Engine and use the PdfResult() and you'll get the page back as a PDF.

It uses iTextSharp under the hood. https://github.com/loudej/spark/tree/master/src/Spark.Web.Mvc.Pdf


Donn Felker
Author of Android App Dev for Dummies & Intro to Android Development (tekpub.com)
Microsoft ASPInsider, MCTS, MCP, CSM, ITIL
http://blog.donnfelker.com
http://twitter.com/donnfelker

Stephen Bohlen

unread,
Jan 11, 2011, 5:59:13 PM1/11/11
to c4mvc
Fascinating; too bad that wasn't a thing 10 years ago when I had to write my own for a client!

Rajendra Prasad

unread,
Jan 12, 2011, 6:58:10 AM1/12/11
to c4...@googlegroups.com
Hi,

in my viewPage i coded like this:
<%=Html.ActionLink("View this page as PDF", "Print", new { format = "pdf" })%>

in controller

  public ActionResult Print(string format)
        {
            if (format == "pdf")
                return new PdfViewResult();

            return View();
        }      

and added          PdfViewResult given by do...@donnfelker.com


overall controller view is


namespace INCES.Controllers
{
    public class MemberController : Controller
    {
 


        public ActionResult Print(string format)
        {
            if (format == "pdf")
                return new PdfViewResult();

            return View();
        }               

    }//close of member controller

    public class PdfViewResult : ViewResult
    {
        protected override ViewEngineResult FindView(ControllerContext context)
        {
            var result = base.FindView(context);
            if (result.View == null)
                return result;

            var pdfView = new PdfView(result);
            return new ViewEngineResult(pdfView, pdfView);
        }

        class PdfView : IView, IViewEngine
        {
            private readonly ViewEngineResult _result;

            public PdfView(ViewEngineResult result)
            {
                _result = result;
            }

            public void Render(ViewContext viewContext, TextWriter writer)
            {
                // generate view in memory
                var spoolWriter = new SpoolWriter();
                _result.View.Render(viewContext, spoolWriter);

                // detect itext (or html) format of response
                XmlParser parser;
                using (var reader = GetXmlReader(spoolWriter))
                {
                    //while (reader.Read() && reader.NodeType != XmlNodeType.Element)
                    //{
                    //    // no-op
                    //}

                    if (reader.NodeType == XmlNodeType.Element && reader.Name == "itext")
                        parser = new XmlParser();
                    else
                        parser = new HtmlParser();
                }

                // Create a document processing context
                var document = new Document();
                document.Open();

                // associate output with response stream
                var pdfWriter = PdfWriter.GetInstance(document, viewContext.HttpContext.Response.OutputStream);
                pdfWriter.CloseStream = false;

                // this is as close as we can get to being "success" before writing output
                // so set the content type now
                viewContext.HttpContext.Response.ContentType = "application/pdf";

                // parse memory through document into output
                using (var reader = GetXmlReader(spoolWriter))
                {
                    parser.Go(document, reader);
                }

                pdfWriter.Close();
            }

            private static XmlTextReader GetXmlReader(IEnumerable<string> source)
            {
                return new XmlTextReader(new SpoolReader(source));
            }

            public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
            {
                throw new System.NotImplementedException();
            }

            public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
            {
                throw new System.NotImplementedException();
            }

            public void ReleaseView(ControllerContext controllerContext, IView view)
            {
                _result.ViewEngine.ReleaseView(controllerContext, _result.View);
            }
        }
    }//pdfclass
}//namespace



//while (reader.Read() && reader.NodeType != XmlNodeType.Element)
                    //{
                    //    // no-op
                    //}


if do like this i am getting empty page.



help me plz wasted 3 days on this.

thanks and regards,

Rajendra Prasad K

Rajendra Prasad

unread,
Jan 12, 2011, 6:40:02 AM1/12/11
to c4...@googlegroups.com
hi,
thanks for the help.

can i have a sample example to use this exactly.

because i am getting this error.


Root element is missing.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Xml.XmlException: Root element is missing.

Source Error:

Line 939:                using (var reader = GetXmlReader(spoolWriter))
Line 940: {
Line 941: while (reader.Read() && reader.NodeType != XmlNodeType.Element)
Line 942: {
Line 943: // no-op

Source File: D:\INCECS\INCECS\INCECS\Controllers\MemberController.cs    Line: 941

Stack Trace:

[XmlException: Root element is missing.]
System.Xml.XmlTextReaderImpl.Throw(Exception e) +76
System.Xml.XmlTextReaderImpl.ThrowWithoutLineInfo(String res) +61
System.Xml.XmlTextReaderImpl.ParseDocumentContent() +3979352
System.Xml.XmlTextReaderImpl.Read() +151
System.Xml.XmlTextReader.Read() +15
INCES.Controllers.PdfView.Render(ViewContext viewContext, TextWriter writer) in D:\INCECS\INCECS\INCECS\Controllers\MemberController.cs:941
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +280
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +10
System.Web.Mvc.<>c__DisplayClass14.<InvokeActionResultWithFilters>b__11() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +251
System.Web.Mvc.<>c__DisplayClass16.<InvokeActionResultWithFilters>b__13() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +178
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +314
System.Web.Mvc.Controller.ExecuteCore() +105
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +39
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +34
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +59
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +44
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8674318
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155


Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053




On Wed, Jan 12, 2011 at 4:12 AM, Donn Felker <do...@donnfelker.com> wrote:
Reply all
Reply to author
Forward
0 new messages