I have a problem trying to apply a css file to my pdf using the iTextSharp (5.4.3) generation library. basically the css is not being applied at all.
I have the following method in my vb.net file
Protected Sub btnPreview_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPreview.Click
Dim bytes As Byte()
bytes = System.Text.Encoding.UTF8.GetBytes(letterRadEdit.Content)
Dim tagProcessor As tool.xml.html.DefaultTagProcessorFactory()
Using input As New MemoryStream(bytes, False)
Dim ms As New MemoryStream()
Dim document As New iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 36, 36, 36, 36)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, ms)
writer.CloseStream = False
document.Open()
Dim htmlContext As HtmlPipelineContext = New HtmlPipelineContext(Nothing)
htmlContext.SetAcceptUnknown(True)
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory())
Dim cssResolver As ICSSResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(False)
cssResolver.AddCssFile(HttpContext.Current.Server.MapPath("/assets/css/pdf.css"), True)
Dim pipeline As New CssResolverPipeline(cssResolver, New HtmlPipeline(htmlContext, New PdfWriterPipeline(document, writer)))
Dim pdfworker As New XMLWorker(pipeline, True)
Dim p As New XMLParser(True, pdfworker, New System.Text.UTF8Encoding)
Try
'p.AddListener(pdfworker)
'p.Parse(input, Encoding.UTF8)
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, input, New FileStream(HttpContext.Current.Server.MapPath("~/assets/css/pdf.css"), FileMode.Open, FileAccess.Read))
Catch
Finally
pdfworker.Close()
End Try
document.Close()
ms.Position = 0
Response.Buffer = True
Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment; filename=preview.pdf")
Response.BinaryWrite(ms.GetBuffer())
Response.Flush()
End Using
End Sub
the CSS file simply contains :
p{color:#e10000;margin-bottom:1.2em;}
(This is to test whether it's rendering correctly, all text should be red)
My problem is that the following command
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, input, New FileStream(HttpContext.Current.Server.MapPath("~/assets/css/pdf.css"), FileMode.Open, FileAccess.Read))
correctly produces the pdf, but doesn't apply the CSS to it. I know it's reading the CSS because I had a permissions exception until I applied the FileAccess.Read property
the method
p.Parse(input, Encoding.UTF8)
doesn't produce any pdf, just an 'Element not allowed' exception, this is because the html (coming from a radeditor text box Q3 2013) is old html and the parse seems to have a problem with tables.
iTextSharp is very poor with designs using css, images etc. Instead wkhtmltopdf is the best.
Well it would appear that the CSS was correctly being applied as I tested a
to the pdf, and all the cells got bordered in red, so it would appear that the pdf overrides certain styles. Not sure why.