使用asp.net将div捕获为图像 - c#

时间:2016-08-19 08:23:45

标签: c# asp.net

在我的c#windows应用程序中,我使用下面的代码成功捕获了panel1作为图像(bmp,jpg,png)

int x1 = SystemInformation.WorkingArea.X;
int y1 = SystemInformation.WorkingArea.Y;
int width1 = panel1.Width;
int height1 = panel1.Height;
Rectangle bounds1 = new Rectangle(x1, y1, width1, height1);
Bitmap img1 = new Bitmap(width1, height1);
panel1.DrawToBitmap(img1, bounds1);

我在asp网站上使用此代码将asp面板捕获为图像。但SystemInformationDrawToBitmap无法在网络项目中使用。任何人都可以告诉我如何捕获具有实际宽度和高度的asp面板。

我的完整Windows应用按钮代码如下所示

private void savetypebtn_Click(object sender, EventArgs e)
    {
        try
        {
            int x1 = SystemInformation.WorkingArea.X;
            int y1 = SystemInformation.WorkingArea.Y;
            int width1 = panel1.Width;
            int height1 = panel1.Height;
            Rectangle bounds1 = new Rectangle(x1, y1, width1, height1);
            Bitmap img1 = new Bitmap(width1, height1);
            panel1.DrawToBitmap(img1, bounds1);

            string saved_file = "";
            savedialog.InitialDirectory = "D:";
            savedialog.Title = "Save Quotation";
            savedialog.FileName = "";
            savedialog.Filter = "Jpg image|*.jpg|Bitmap image|*.bmp|png image|*.png";

            if (savedialog.ShowDialog() != DialogResult.Cancel)
            {
                saved_file = savedialog.FileName;
                img1.Save(saved_file, System.Drawing.Imaging.ImageFormat.Bmp);
            }
        }
        catch (Exception ex)
        {
            errorlbl.Visible=True;
            errorlbl.Text = ex.Message;
        }

1 个答案:

答案 0 :(得分:0)

这是我找到的解决方案。首先获取控件的渲染html输出,如How do I get the HTML output of a UserControl in .NET (C#)?

所示
StringBuilder myStringBuilder = new StringBuilder();
TextWriter myTextWriter = new StringWriter(myStringBuilder);
HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);
Panel1.RenderControl(myWriter);
string html = myTextWriter.ToString();   

然后如图所示Convert HTML string to image将html转换为图像

 public void ConvertHtmlToImage()
{

  System.Drawing.Image img = HtmlRender.RenderToImage(html, new Size(400, 200), Color.Linen);//html is the varialbe obtained above
   img.Save(Server.MapPath("/Images/save.jpg"), ImageFormat.Jpeg);
}

您必须将HTMLrenderer库添加到项目中才能使其正常工作