简体   繁体   中英

Parse HTML to PDF with iTextSharp and MVC 4

I'm trying to convert simple (for now) view with "li" and "image" tags. In the controller first I'm getting the view as string

            ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, "Print");
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                stringView = sw.GetStringBuilder().ToString();
            }

After that I'm trying to parse the string according this documentation

            Document document = new Document();
        document.SetPageSize(iTextSharp.text.PageSize.A4);
        document.Open();


        PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);

        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
        htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
        htmlContext.SetImageProvider(new ImageProvider(Server.MapPath(Config.UploadDirectory), Request.Url.ToString()));

        //StyleAttrCSSResolver cssRevolver = new StyleAttrCSSResolver();
        var cssRevolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);

        cssRevolver.AddCssFile(Server.MapPath("~/Content/Site.css"), false);

        IPipeline pipeline = new CssResolverPipeline(cssRevolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
        XMLWorker worker = new XMLWorker(pipeline, true);
        XMLParser parser = new XMLParser(worker);

        var memViewStream = new MemoryStream(Encoding.UTF8.GetBytes(stringView));
        memViewStream.Position = 0;

        parser.Parse(memViewStream); //this line throw the exception

        document.Close();
        writer.Close();

        Response.ContentType = "application/pdf";
        return null;

But I'm getting this error and can't figure out whats wrong

Object reference not set to an instance of an object.

Stack

 at iTextSharp.text.pdf.PdfOutline.InitOutline(PdfOutline parent, String title, Boolean open)
   at iTextSharp.text.pdf.PdfOutline..ctor(PdfOutline parent, PdfDestination destination, Paragraph title, Boolean open)
   at iTextSharp.text.pdf.PdfOutline..ctor(PdfOutline parent, PdfDestination destination, Paragraph title)
   at iTextSharp.tool.xml.html.Header.WriteH.Write(PdfWriter writer, Document doc)
   at iTextSharp.text.pdf.PdfDocument.Add(IElement element)
   at iTextSharp.text.Phrase.Process(IElementListener listener)
   at iTextSharp.text.pdf.PdfDocument.Add(IElement element)
   at iTextSharp.text.List.Process(IElementListener listener)
   at iTextSharp.text.pdf.PdfDocument.Add(IElement element)
   at iTextSharp.text.Document.Add(IElement element)
   at iTextSharp.tool.xml.pipeline.end.PdfWriterPipeline.Write(IWorkerContext context, ProcessObject po)
   at iTextSharp.tool.xml.pipeline.end.PdfWriterPipeline.Close(IWorkerContext context, Tag t, ProcessObject po)
   at iTextSharp.tool.xml.XMLWorker.EndElement(String tag, String ns)
   at iTextSharp.tool.xml.parser.XMLParser.EndElement()

I have not idea why InitOutline is throwing exception.Any ideas ? Thanks

IF you want to print pdf from view then just pass a sting format of view(HTML)

in this function you will get pdf

String htmlText = html.ToString();   <== Html is a view page html string 
Document document = new Document();
string filePath = HostingEnvironment.MapPath("~/Content/Pdf/");
PdfWriter.GetInstance(document, new FileStream(filePath + "\\pdf-"+Name+".pdf", FileMode.Create));
document.Open();

iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
FontFactory.Register(Path.Combine(_webHelper.MapPath("~/App_Data/Pdf/arial.ttf")),  "Garamond");   // just give a path of arial.ttf 
StyleSheet css = new StyleSheet();
css.LoadTagStyle("body", "face", "Garamond");
css.LoadTagStyle("body", "encoding", "Identity-H");
css.LoadTagStyle("body", "size", "12pt");
hw.SetStyleSheet(css);

hw.Parse(new StringReader(htmlText));

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