Saving a byte array to PDF file with OfficeJs
<p>Using OfficeJs I want to save a Word document as a PDF and post that file to an Api.</p>
<p><a href="http://dev.office.com/reference/add-ins/shared/document.getfileasync" rel="nofollow noreferrer">Office.context.document.getFileAsync</a> will let you get the entire document in a choice of 3 formats:</p>
<ul>
<li><strong>compressed</strong>: returns the entire document (.pptx or .docx) in Office Open XML (OOXML) format as a byte array</li>
<li><strong>pdf</strong>: returns the entire document in PDF format as a byte array</li>
<li><strong>text</strong>: returns only the text of the document as a string. (Word only)</li>
</ul>
<p>I am posting the PDF byte array to a WebApi action that looks like this:</p>
<pre><code>public async Task&lt;IHttpActionResult&gt; Upload([FromBody]byte[] bytes)
{
    File.WriteAllBytes(@&quot;C:\temp\testpdf.pdf&quot;, bytes);
    return Ok();
}
</code></pre>
<p>On inspection the byte array is the same array created by the getFileAsync from Office Js.</p>
<p>The problem is the file written in <code>File.WriteAllBytes</code> is corrupt. If I open it with notepad, it is a string of the bytes - <code>37,80,68,70,45,49,46,53,13,10,37... and so on</code>.</p>
<p>Any idea why the method WriteAllBytes does not create a PDF file from the OfficeJS pdf byte stream?</p>
<h2>UPDATE 25/5/16</h2>
<p>As hawkeye @StefanHegny pointed out, the byte array appears to be Ascii characters. Converting each byte to <code>char</code> and writing that out to PDF like this creates a blank PDF, but on inspection with NotePad, the contents do like a like a PDF document, though quite different to that when saving the same .docx as a .pdf.</p>
<pre><code>var content = &quot;&quot;;
foreach (var b in model.Bytes)
{
    content += (char) b;
}

File.WriteAllText(@&quot;C:\temp\testpdf.pdf&quot;, content);
</code></pre>
<p>Also note, this is extremely slow - about 5 minutes for 500kb PDF byte array on my dev machine.</p>