2014-05-04 1 views
1

Je travaille actuellement sur une application qui construit fondamentalement un MvcHtmlString en mappant un HtmlTemplate avec certaines données dynamiquement.Convertir et enregistrer MvcHtmlString en Image ou PDF

Ce que je veux être en mesure de faire est de convertir et enregistrer ce MvcHtmlString en tant qu'image/PDF sur mon disque local.

Voici ma fonction qui produit le MvcHtmlString après la cartographie:

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; 
    } 

Et puis j'utilise cette fonction pour enregistrer une image (Mais ce juste rend un bloc noir)

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); 
    } 

Tous l'aide sera appréciée!

Répondre

1

J'ai trouvé la raison. La bibliothèque HtmlRenderer que j'utilisais ne supportait pas "float" dans le balisage css et donc l'image de sortie était foirée

Questions connexes