iTextSharp: Convert HTML string with CSS to PDF and save in Folder (Directory) using C#

Snooker
 
on Sep 12, 2022 08:07 AM
714 Views

This is the code I have used below which I got from this websites forum, I have added the first line which produces a pdf called Test.pdf in the Images folder of the server.

Currently the code will convert an html string to pdf and download it and the Test.pdf saved is empty.

I would like the html string to be converted to pdf but for that pdf not to be downloaded but contents saved in the Test.pdf in the Images folder on the server.

I would be very grateful if you could please help

I am nearly there, thanks

using (FileStream stream = new FileStream(Server.MapPath("~/Pdf/Test.pdf"), FileMode.OpenOrCreate))
{
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    StringReader sr = new StringReader(html);
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    PdfWriter PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
    htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
    ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
    cssResolver.AddCssFile(Server.MapPath("~/StyleSheet.css"), true);
    IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, PdfWriter)));
    var worker = new XMLWorker(pipeline, true);
    var xmlParse = new XMLParser(true, worker);
    pdfDoc.Open();
    xmlParse.Parse(sr);
    pdfDoc.Close();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.End();
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
Snooker
 
on Sep 12, 2022 11:14 AM
on Sep 13, 2022 03:54 AM

After spending the last few days trying to find code online have just managed to find some code which works at last

By using iTextSharp (V5.0 Ended With V5.5.13.3)

The following code will convert an html string with css parameters to a pdf file saved on the server where you choose the path and filename.

If using css you need to have a ccs file in this example called StyleSheet.css in the root directory, you can then either call a class from an html tag to the main css file, or use inline styles without calling the ccs file, but will have to be like this as an example:-

var html = "<table class='table'>" +  // Call to .table style on ccs file //
           "<tr ....... >" +
           "</table>";

or 

var html =  "<table style='width: 400px'>" +  // In line style no call to css file //
            "<tr ....... >" +
            "</table>";

You need to at least set up a blank ccs file for it to work even if you are just using in line styles or are not going to even use any css to keep the code happy, also notice I am using single quotes above around table class='table'  & table style='width: 400px'

// Using statements C# //
using System;
using System.IO;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml; 
 
// Actual code C# //   
var html = // Your html string & including any css parameters //            
byte[] pdf;
var cssText = File.ReadAllText(MapPath("~/StyleSheet.css"));
using (var memoryStream = new MemoryStream())
{                
   var document = new Document(PageSize.A4, 50, 50, 60, 60);
   var writer = PdfWriter.GetInstance(document, memoryStream);
   document.Open();
   using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
   {
       using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
       {
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, cssMemoryStream);
       }

       document.Close();
       var Path = "~/Pdf/";
       var FileName = "Test.pdf";
       System.IO.FileStream file = System.IO.File.Create(HttpContext.Current.Server.MapPath(Path + FileName));
       pdf = memoryStream.ToArray();
       file.Write(pdf, 0, pdf.Length);
       file.Close();
  }
}