关于c#:从Asp.Net MVC中的HTML内容生成JPEG

Generate JPEG from Html Content In Asp.Net MVC

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

该HTML包含数据和图像

的HTML

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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);
}

但是它像这样返回输出

enter image description here

但需要输出

enter image description here

有什么方法可以生成此代码(从html生成图像的步骤)或任何可用的第三方开源组件,例如HtmlToImageConverter?


可以将HTML渲染为图像
HtmlRenderer dll。
你可以得到它
HtmlRenderer.WinForms NuGet软件包(还将安装
HtmlRenderer.Core)

有一个有关它的问题列表,但是可以。
你可以做类似的事情

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}

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


我不称这种转换-您可以从HTML文件生成JPEG。

我不知道您在这里期望什么样的答案。 如果有一个简单的方法:

1
myHtmlDocument.GenerateJpeg();

那里没有任何第三方库。

如果您打算编写自己的库,我希望有更多详细的问题。