我在尝试使用 iTextSharp (5.4.3) 生成库将 css 文件应用到我的 pdf 时遇到问题。基本上css根本没有被应用。
我的 vb.net 文件中有以下方法
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
CSS 文件只包含:
p{color:#e10000;margin-bottom:1.2em;}
(这是为了测试它是否正确渲染,所有文字都应该是红色的)
我的问题是以下命令
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, input, New FileStream(HttpContext.Current.Server.MapPath("~/assets/css/pdf.css"), FileMode.Open, FileAccess.Read))
正确生成 pdf,但不对其应用 CSS。我知道它正在读取 CSS,因为在我应用 FileAccess.Read 属性之前我有权限异常
方法
p.Parse(input, Encoding.UTF8)
不生成任何 pdf,只是“不允许元素”异常,这是因为 html(来自 radeditor 文本框 Q3 2013)是旧 html,并且解析似乎有表格问题。