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?

1
  • This SO answer 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) 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 ... Commented Aug 10, 2023 at 13:40

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

@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...
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.