title: Generating PDF from Base64 Byte Array in VBA
body: <p>I have the following JSON response from a webservice method which will return byte[] in PDF format:</p>
  
  <pre><code>JVBERi0xLjQKJeLjz9MKMSAwI......nVq2P63zkirBH1z9aW3pDxn6F7q9TFV==
  </code></pre>
  
  <p>The return value is a byte() array. I been trying for a few days trying to use the function available in one of the questions posted in "<a href="https://stackoverflow.com/questions/48351495/generating-pdf-from-base64-string-in-vba/51149030#51149030">Generating PDF from Base64 string in VBA</a>" to generate PDF from the above Base64 Byte array, but I couldn't. </p>
  
  <p>What I have done is that based on the return byte array from the webservice method, I save it as a byte array variable name <strong>b64testByte</strong>. Subsequently, I then proceed to call 2 methods in my program, namely encodeBase64 first, and followed by DecodeBase64. The PDF file is generated. However, when I try to open the file, there is an error which reads "Error: the document is damaged and cannot be repaired. Adobe Reader could not open because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded)." </p>
  
  <pre><code>Dim b64testByte() As Byte
  b64testByte = xmlhttp.responseText 
  
  Dim B64String As String
  B64String = encodeBase64(b64testByte)
  
  
      Dim FilePath As String
      FilePath = "D:\label.pdf"
      Open FilePath For Binary Access Write As #1
      Put #1, 1, DecodeBase64(B64String)
      Close #1
  
  
  Private Function DecodeBase64(ByVal strData As String) As Byte()
      Dim objXML As Object 'MSXML2.DOMDocument
      Dim objNode As Object 'MSXML2.IXMLDOMElement
      'get dom document
      Set objXML = CreateObject("MSXML2.DOMDocument")
      'create node with type of base 64 and decode
      Set objNode = objXML.createElement("b64")
      objNode.DataType = "bin.base64"
      objNode.Text = strData
      DecodeBase64 = objNode.nodeTypedValue
      'clean up
      Set objNode = Nothing
      Set objXML = Nothing
  End Function
  
  Private Function encodeBase64(ByRef arrData() As Byte) As String
      Dim objXML As Object 'MSXML2.DOMDocument
      Dim objNode As Object 'MSXML2.IXMLDOMElement
      'get dom document
      Set objXML = CreateObject("MSXML2.DOMDocument")
  
      Set objNode = objXML.createElement("b64")
      objNode.DataType = "bin.base64"
      objNode.nodeTypedValue = arrData
      encodeBase64 = objNode.Text
  
      Set objNode = Nothing
      Set objXML = Nothing
  End Function**
  </code></pre>