title: Save a PDF as ByteArray to HttpResponse using PDFDocument.Save
body: <p>I am trying to send a <strong><code>Byte Array</code></strong> of Conversion - HTML to PDF using <code>SelectPDF</code> in C#. The Sample code I given below. I'm having a WebAPI, in that I'm doing this. I need to send the PDF document as an byte array and need to display in the client UI. The following code is not performing.</p>
  
  <p>Refer documentation of SelectPDF <a href="https://selectpdf.com/docs/M_SelectPdf_PdfDocument_Save_3.htm" rel="nofollow noreferrer">https://selectpdf.com/docs/M_SelectPdf_PdfDocument_Save_3.htm</a></p>
  
  <pre><code>string html = "&lt;html&gt;&lt;body&gt;hello world&lt;/body&gt;&lt;/html&gt;";
  PdfDocument doc = converter.ConvertHtmlString(html, "");
  doc.Save(HttpContext.Current.Response, true, "C:\MyProject\Pdf\Sample.pdf");
  </code></pre>
  
  <p>If I make the API return type as <code>HttpResponseMessage</code>, then its working, instead of returning the HttpContext.Current.Response (Return type is HttpResponse), its not working.</p>
  
  <p>Working code </p>
  
  <p>Saving the pdf to local using the following code <code>doc.Save(URL)</code> and then need to read the file (<a href="https://stackoverflow.com/questions/2451864/c-sharp-4-0-convert-pdf-to-byte-and-vice-versa">C# 4.0: Convert pdf to byte[] and vice versa</a>)</p>
  
  <p>Kindly assist me how to return the Response using <code>doc.Save(HttpContext.Current.Response, true, "C:\MyProject\Pdf\Sample.pdf");</code></p>
  
  <blockquote>
    <p>Note: Kindly provide the solution without saving the file in local
    (i.e., Server Local)</p>
  </blockquote>
  
  <p>Working C# Code:</p>
  
  <pre><code>public HttpResponseMessage GetSamplePDF() {
      string html = "&lt;html&gt;&lt;body&gt;hello world&lt;/body&gt;&lt;/html&gt;";
      PdfDocument doc = converter.ConvertHtmlString(html, "");
      doc.Save("C:\MyProject\Pdf\Sample.pdf");
  
      pdfData = System.IO.File.ReadAllBytes("C:\MyProject\Pdf\Sample.pdf");
  
      var result = new HttpResponseMessage(HttpStatusCode.OK) {
                  Content = new ByteArrayContent(reportdata)
              };
      result.Content.Headers.ContentDisposition =
                  new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") {
                      FileName = "SamplePDF"
                  };
      result.Content.Headers.ContentType =
                  new MediaTypeHeaderValue("application/octet-stream");
  
     return result;
  }
  </code></pre>
  
  <p>Moreover the UI code is <a href="https://stackoverflow.com/questions/38031229/embed-a-blob-using-pdfobject">Embed a Blob using PDFObject</a></p>