I am using iTextSharp library for HTML to PDF conversion. Could you suggest why following HTML+CSS is not converted to PDF properly? Looks like elements margins are not applied at all…Text is stuck to the left. Browser (Chrome) centers it fine.
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
}
}
Thank you. Regards
HTMLWorker? If so, then you should know thatHTMLWorkerhas been abandoned ages ago and the CSS isn't supported inHTMWorker. 2. Are you using XML Worker? If so, be aware that not all CSS values are supported, but if you provide a SSCCE, someone can take a look at it. - Bruno Lowagie