将MvcHtmlString转换并保存为图像或PDF

时间:2014-05-04 08:02:41

标签: asp.net-mvc-4 dom

我目前正致力于一个基本上通过动态地将HtmlTemplate与一些数据进行映射来构建MvcHtmlString的应用程序。

我希望能够将此MvcHtmlString转换并保存为图像/ PDF到我的本地磁盘。

这是我在映射后生成MvcHtmlString的函数:

public static MvcHtmlString Map(this IDictionary<string, object> row, string htmlTemplate)
    {
        var htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(htmlTemplate);

        foreach (var key in row.Keys)
        {
            var elements = htmlDoc.DocumentNode.SelectSingleNode("//body")
                                  .Descendants()
                                  .Where(d => d.Attributes
                                               .Any(a => a.Name == "class" && a.Value == key));
            if (elements != null && elements.Count() > 0)
            {
                foreach (var element in elements)
                {
                    object attributeValue = null;
                    row.TryGetValue(key, out attributeValue);

                    if (element.HasChildNodes)
                    {
                        // We only get the first img element within the element 
                        // as we dont expect there to be more than one <img> tag
                        // within a parent element
                        var imgChildNode = element.Descendants("img").FirstOrDefault();
                        if (imgChildNode != null)
                        {
                            imgChildNode.SetAttributeValue("src", attributeValue.ToString());
                        }
                        else
                        {
                            element.InnerHtml = string.Empty;
                            element.InnerHtml = attributeValue.ToString();
                        }
                    }
                    else
                    {
                        element.InnerHtml = string.Empty;
                        element.InnerHtml = attributeValue.ToString();
                    }
                }
            }
        }

        var sw = new StringWriter();
        htmlDoc.Save(new StringWriter(sw.GetStringBuilder()));
        var htmlString = MvcHtmlString.Create(sw.ToString());
        return htmlString;
    }

然后我使用此功能保存图像(但这只是渲染黑块)

private void SaveImageFromHtml(MvcHtmlString html)
    {
        var decodedHtml = html.ToHtmlString();
        Bitmap m_Bitmap = new Bitmap(600, 800);
        PointF point = new PointF(0, 0);
        SizeF maxSize = new System.Drawing.SizeF(600, 800);
        HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap), decodedHtml,
                                                point, maxSize);

        m_Bitmap.Save(@"D:\Test.png", ImageFormat.Png);
    }

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

找到原因。我使用的HtmlRenderer库没有支持&#34; float&#34;在css标记中,因此输出图像搞砸了