【问题标题】:Generate JPEG from Html Content In Asp.Net MVC在 Asp.Net MVC 中从 Html 内容生成 JPEG
【发布时间】:2013-05-08 07:14:07
【问题描述】:

我想在 Asp.Net MVC 中使用 C# 从 Textarea 或其他输入控件(不是整个网页)中输入的 HTML 代码生成图像 (JPEG)。MVC 不支持网络浏览器控件。

此 HTML 包含数据和图像

HTML

<b>Convert Html To Image<b> 
<br/>
<img src="C:\Logo.jpg" alt="Smiley face" width="42" height="42"> 

我将html代码传递给了位图图像创建函数的控制器

private Bitmap CreateBitmapImage(string html)
{
   Bitmap objBmpImage = new Bitmap(1, 1);

   int intWidth = 0;
   int intHeight = 0;

   // Create the Font object for the image text drawing.
   Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold,  System.Drawing.GraphicsUnit.Pixel);

   // Create a graphics object to measure the text's width and height.
   Graphics objGraphics = Graphics.FromImage(objBmpImage);

   // This is where the bitmap size is determined.
   intWidth = (int)objGraphics.MeasureString(html, objFont).Width;
   intHeight = (int)objGraphics.MeasureString(html, objFont).Height;

   // Create the bmpImage again with the correct size for the text and font.
   objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));

   // Add the colors to the new bitmap.
   objGraphics = Graphics.FromImage(objBmpImage);

   // Set Background color
   objGraphics.Clear(Color.White);
   objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
   objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
   objGraphics.DrawString(html, objFont, new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);
   objGraphics.Flush();
   return (objBmpImage);
}

但它会像这样返回输出

但需要输出

有没有办法生成这个(从 html 生成图像的步骤)或任何可用的第三方开源组件,如 HtmlToImageConverter ?

【问题讨论】:

  • @I4V 感谢您的回复我不想使用第三方 .net 组件并且 IECapt 不支持所有浏览器
  • @Prabu 只需要支持一个“浏览器”,对吧?还是要生成多个 JPEG,每个浏览器模拟器一个?
  • @Prabu:我很好奇你认为 DrawString 方法实际上做了什么?方法名称本身表示它绘制了一个字符串。没有哪里暗示它将字符串解析为 html,下载 html 中的任何图像,然后像网页一样呈现出来。
  • 另一种选择可能是使用 itextsharp 转换为 pdf

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

可以将 HTML 渲染为图像 HtmlRendererdll。 你可以在 HtmlRenderer.WinForms NuGet 包中获取它(它也会安装 HtmlRenderer.Core)

有一个关于它的issues 列表,但它有效。 你可以做类似的事情

public static Image RenderToImage<T>(String fullViewName, T model)
{
    String html = RenderViewToString(fullViewName, model);
    var image = HtmlRender.RenderToImage(html);
    return image;
}

public static String RenderViewToString<T>(String fullViewName, T model)
{
    String viewText = File.ReadAllText(fullViewName);
    String renderedText = Razor.Parse(viewText, model); // RazorEngine here. I don't have MVC
    return renderedText;
}

【讨论】:

    【解决方案2】:

    webSupergoo 从 html 生成 jpg。它不是开源的,但可以免费下载如果它可以解决您的问题,您也可以将 html 转换为 pdf 使用 itextsharp

    【讨论】:

    • 感谢您的回复,但它没有解决我的 pbm 我需要它用于我们的名片设计网站..(用户根据要求自定义布局然后他们保存它(保存的图像 URL 存储在数据库中) )
    猜你喜欢
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    相关资源
    最近更新 更多