【问题标题】:iTextSharp Print To PDF Displays CSS and JS In The PDF [duplicate]iTextSharp打印到PDF在PDF中显示CSS和JS [重复]
【发布时间】:2018-06-14 21:38:46
【问题描述】:

我正在使用 iTextSharp.dll 将我的页面打印为 pdf。我遇到的唯一问题是 pdf 显示了我在页面上的 CSS 和 JavaScript。有没有办法可以将 iTextSharp 设置为 显示 CSS/JS?

是的,我将我的 CSS/JS 直接输入到 .aspx 页面中——因为这是一个小项目。当然,对于一个大型项目,我会将其分开。

编辑
这是我当前写入页面的语法

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
this.Page.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10);
pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4); 
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();

【问题讨论】:

  • 虽然您没有共享任何代码,但很明显您使用的是过时的HTMLWorker 类。您描述的问题(CSS 语法在 PDF 文件中可见的事实)与 here 描述的问题之一完全相同。
  • @BrunoLowagie - 我的错误,我以为我包含了我的 C# 语法。我已经更新了我的帖子以包含此类内容。令人印象深刻的是,您可以看出我正在使用该课程。
  • 这并不令人印象深刻,因为这是一个已知问题,已通过丢弃 HTMLWorker 并用更好的东西替换它来解决。

标签: c# asp.net itext


【解决方案1】:

有一个类似的打印问题并通过使用字符串删除样式解决。替换方法查看可能帮助您解决问题的代码

  Regex regSimple = new Regex(@"(?i)<img\b[^>]*?style\s*=(['""]?)(?<style>[^'""]+)\1[^>]*?>");
        if (regSimple.IsMatch(html))
        {
            html = html.Replace(Convert.ToString(regSimple.Match(html)), Convert.ToString(regSimple.Match(html)).Replace("style=\"", "").Replace("height:", "height=\"").Replace("\"width:", "width=\""));

        }

【讨论】:

  • 如何将它与我当前的语法联系起来?
  • html 是来自 url WebClient client = new WebClient(); 的 html 文本String html = client.DownloadString("url here");
  • 根据您的代码用 sw 更改 html 并将这一行放在 StringReader sr = new StringReader(sw.ToString()); 之后
猜你喜欢
  • 2011-08-31
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 2017-04-29
  • 2013-07-01
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
相关资源
最近更新 更多