1
我目前正在開發基本上通過動態地將HtmlTemplate與一些數據進行映射來構建MvcHtmlString的應用程序。將MvcHtmlString轉換並保存爲圖像或PDF
我想要做的就是將此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);
}
任何幫助將不勝感激!