0

I have received a Byte Array as response from a POST request to an API. The Byte Array is of a pdf document. I have been searching around but couldn't find where to start. If I have a byte array how would I go about saving it back as a PDF?

Apologies I have no code as I'm not sure where to start, could anyone provide with at least some links or guidance so I can look up how to do this?

JohnM
  • 2,422
  • 2
  • 8
  • 20
Drawleeh
  • 297
  • 1
  • 10
  • This [SO answer](https://stackoverflow.com/a/14259180/11318818) talks about creating a PDF file from a byte array but in C# ... the principle it uses is just to simply write the bytes to a file (I guess like this [SO answer](https://stackoverflow.com/a/14366273/11318818)) and add .pdf extension to the file ... as I don't have the relevant byte array then I can't test this 'theory' but would be interested to learn if it would work for you ... – JohnM Aug 10 '23 at 13:40

1 Answers1

1

Please, use the next Sub:

Sub SaveByteArray(bArr() As Byte, fileName As String, Optional overWriteFile As Boolean)
  
  With CreateObject("ADODB.Stream")
    .Open
    .Type = 1
    .Write bArr
    .SaveToFile fileName, IIf(overWriteFile, 2, 1)
    .Close
  End With
  
End Sub

And use it as:

Sub TestSaveByteArray()
  Dim fileName As String: fileName = ThisWorkbook.Path & "\myFile.pdf"
  Dim fileToRead As String: fileToRead = "C:\your path\TestFile.pdf" 'place the path of an existing pdf file!
   Dim arr() As Byte
  'load the array (somehow...), only to have a checkable byte array:
  arr = ReadBytes(fileToRead) 'you must use your existing array instead!
  
  SaveByteArray arr, fileName, True
End Sub

Private Function ReadBytes(strFile As String) As Byte() 'only to supply a (testing) byte array...
 Dim byteArr() As Byte
 Dim frFile As Integer: frFile = FreeFile
 Open strFile For Binary Access Read As #frFile
    ReDim byteArr(0 To LOF(frFile) - 1)
    Get #frFile, , byteArr
 Close #frFile
 ReadBytes = byteArr
End Function
FaneDuru
  • 38,298
  • 4
  • 19
  • 27
  • @Drawleeh Didn't you find some time to test the above solution? If tested, didn't it do what you need? I updated the answer and also placed a function able to supply (such a) byte array, to make testing more eloquent... If it does not work with the **received byte array**, this only means that the respective array is wrong. Anyhow, some feedback did not kill anybody, from what I know... – FaneDuru Aug 11 '23 at 07:27
  • 1
    Apologies, I wasn't able to get a test of the above but yesterday I hadn't figured that a simple write to file would work. Just tested, the above works perfectly okay. Thank you Fane – Drawleeh Aug 11 '23 at 08:33