본문 바로가기

.Net

HTML로 문서를 작성 > HTML 읽어서, 이미지로 다운로드

페이지 HTML 읽기

public static class ControllerExtensions
    {
        public static string RenderView(this Controller controller, string viewName, object model)
        {
            return RenderView(controller, viewName, new ViewDataDictionary(model));
        }

        public static string RenderView(this Controller controller, string viewName, ViewDataDictionary viewData)
        {
            var controllerContext = controller.ControllerContext;

            var viewResult = ViewEngines.Engines.FindView(controllerContext, viewName, null);

            StringWriter stringWriter;

            using (stringWriter = new StringWriter())
            {
                var viewContext = new ViewContext(
                    controllerContext,
                    viewResult.View,
                    viewData,
                    controllerContext.Controller.TempData,
                    stringWriter);

                viewResult.View.Render(viewContext, stringWriter);
                viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
            }

            return stringWriter.ToString();
        }
    }

 

HTML 읽어서 이미지로 다운로드

[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] // will disable caching for Index only
public ActionResult htmlView(string strInput)
{
  ViewData["strInput"] = strInput;
  return View(model);
}

[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] // will disable caching for Index only
public ActionResult img(String strInput)
{
  html = Extension.ControllerExtensions.RenderView(this, "htmlView", strInput);
  return ImgDownload(html, strInput);
}

[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] // will disable caching for Index only
public FileResult ImgDownload(String html, String strInput, string title)
{
  System.Drawing.Bitmap img = GetImageByHTMLRenderer(html);
  Byte[] result;

  using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
  {
    img.Save(ms, ImageFormat.Jpeg);
    result = ms.ToArray();
  }
  return File(result, "image/jpg", title + "_" + strInput + ".jpg");
}

[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] // will disable caching for Index only
protected Bitmap GetImageByHTMLRenderer(String html)
{
  String content = html;
            
  Int32 intX = 1030;
  Int32 intY = 1430;
  Bitmap m_Bitmap = new Bitmap(intX, intY);
  using (Graphics gfx = Graphics.FromImage(m_Bitmap))
  using (SolidBrush brush = new SolidBrush(Color.White))
  {
    gfx.FillRectangle(brush, 0, 0, intX, intY);
  }
  PointF point = new PointF(0, 0);
  SizeF maxSize = new System.Drawing.SizeF(intX, intY);
  //HtmlRenderer.WinForms (nuget)
  TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.Render(Graphics.FromImage(m_Bitmap), content, point, maxSize);

  return m_Bitmap;
}