Convert HTML with CSS to PDF using iTextSharp

自作多情 提交于 2021-02-07 19:34:10

问题


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.


回答1:


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



回答2:


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" (e.g. in a database) and have a background process (e.g. 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.



来源:https://stackoverflow.com/questions/19661018/convert-html-with-css-to-pdf-using-itextsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!