简体   繁体   中英

Convert HTML with CSS to PDF using iTextSharp

I am working in asp.net with C# website. I want to convert a HTML DIV which contains various html elements like divs,label, tables and images with css styles(background color, cssClass etc) and I want its whole content to be converted into PDF using iTextSharp DLL but here I am facing a issue that css is not getting applied.Can any one help me by providing any example or code snippet.

Install 2 NuGet packages iTextSharp and itextsharp.xmlworker and use the following code:

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;


byte[] pdf; // result will be here

var cssText = File.ReadAllText(MapPath("~/css/test.css"));
var html = File.ReadAllText(MapPath("~/css/test.html"));

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();

            pdf = memoryStream.ToArray();
}

Check out Pechkin , a C# wrapper for wkhtmltopdf.

Specifically at this point in time (considering a pending pull request) I'd check out this fork that addresses a couple of bugs (particularly helpful in IIS based on my experience).

If you don't go with the fork / get other stability issues you may want to look at having some kind of "render queue" (eg in a database) and have a background process (eg Windows service) periodically run over the queue and render then store the binary content somewhere (either in database as well, or on file system). This depends entirely on your use-case though.

Alternatively the similar solution @DaveDev has comment linked to.

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