使用iTextSharp进行转换后,HTML元素的边距不会应用于PDF中

时间:2016-06-09 11:20:24

标签: html css itextsharp

我正在使用iTextSharp库进行HTML到PDF的转换。 您能否建议为什么HTML + CSS没有正确转换为PDF?看起来根本没有应用元素边距...文本粘在左边。浏览器(Chrome)很好。

CSS:

  #sgh-mainC {
    width: 100px;
    margin-top: 0;
    margin-bottom: 0;
    margin-right: auto;
    margin-left: auto;
}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>PDS</title>
</head>
<body>
    <div id="sgh-mainC">
        text that should be centered
    </div>
</body>
</html>

C#:

 private void CreatePdf(string html, string css)
        {
            try
            {
                Byte[] bytes;
                using (var ms = new MemoryStream())
                {
                    using (var doc = new Document())
                    {
                        using (var writer = PdfWriter.GetInstance(doc, ms))
                        {
                            doc.Open();
                            var cssResolver = new StyleAttrCSSResolver();
                            var msCss = XMLWorkerHelper.GetCSS(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(css)));
                            cssResolver.AddCss(msCss);

                            HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                            htmlContext.AutoBookmark(false);
                            var htmlStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html));

                            PdfWriterPipeline pdfPpl = new PdfWriterPipeline(doc, writer);
                            HtmlPipeline htmlPpl = new HtmlPipeline(htmlContext, pdfPpl);
                            CssResolverPipeline cssPpl = new CssResolverPipeline(cssResolver, htmlPpl);

                            new XMLParser(new XMLWorker(cssPpl, true)).Parse(htmlStream);

                            doc.Close();
                        }
                    }
                    bytes = ms.ToArray();
                }
                if (File.Exists(FilePath))
                {
                    File.Delete(FilePath);
                }
                var file = File.Create(FilePath);
                file.Write(bytes, 0, bytes.Count());
                file.Close();
            }
            catch (Exception exc)
            {
                //TODO log errror
            }
        }

谢谢。 此致

1 个答案:

答案 0 :(得分:1)

这个问题有点陈旧,但万一其他人偶然发现这篇文章......

似乎iTextSharp实际支持的CSS集非常有限。您可以在http://demo.itextsupport.com/xmlworker/itextdoc/CSS-conformance-list.htm

找到它