title: ASP.NET MVC: How can I render a Control to a Stream?
body: <p>So I'm rendering a partial view in memory in order to direct the XSL-FO data in the view to a PDF renderer.</p>
  
  <p>The PDF renderer can take a string, XmlDocument or Stream as input.</p>
  
  <p>Here is what I'd like to do: (<strong>Edited for clarity</strong>)</p>
  
  <p>Solution taken from: <a href="http://thriftybliss.spaces.live.com/blog/cns!58DA805F37F31F20!170.entry?wa=wsignin1.0&amp;sa=362921628" rel="nofollow noreferrer">http://thriftybliss.spaces.live.com/blog/cns!58DA805F37F31F20!170.entry?wa=wsignin1.0&amp;sa=362921628</a>  </p>
  
  <pre><code>var viewPage = new ViewPage();
  var viewData = new ViewDataDictionary(model);
  viewPage.ViewData = viewData;
  
  var control = viewPage.LoadControl(viewName);
  viewPage.Controls.Add(control);
  
  using (var inStream = new MemoryStream())
  {
      using (var sw = new StreamWriter(inStream))
      {
          using (var tw = new HtmlTextWriter(sw))
          {
              viewPage.RenderControl(tw);
          }
          using (var outStream = new MemoryStream())
          {
              driver.Render(inStream, outStream);
              return outStream.ToArray();
          }
      }
  }
  </code></pre>
  
  <p>Here's what works, but what I'd rather not do:</p>
  
  <pre><code>var sb = new StringBuilder();
  
  using (var sw = new StringWriter(sb))
  {
      using (var tw = new HtmlTextWriter(sw))
      {
          vp.RenderControl(tw);
      }
  }
  
  var xml = new XmlDocument();
  xml.LoadXml(sb.ToString());
  
  using (var ms = new MemoryStream())
  {
      driver.Render(xml, ms);
      return ms.ToArray();
  }
  </code></pre>
  
  <p>Unfortunately the HtmlTextWriter doesn't seem to want to write to the StreamWriter, or perhaps I just messed something else up.</p>
  
  <p>If I replace StreamWriter with StringWriter it works fine, but I can't use StringWriter because when I call .ToString() I get all kinds of escape characters that mess up the XSL-FO and the renderer throws an "Illegal Characters" exception.</p>
  
  <p>I got around this by creating an XmlDocument and loading the string into that, but it seems like a very roundabout way of doing things. I'd really just like to just capture the output from the HtmlTextWriter and feed it directly into the Renderer. Is there any way to do this?</p>
  
  <p>Thanks!</p>