0

I'm calling a json-rpc api that returns a UCHAR array that represents a PDF file (so the result property on return contains a string representation of a UCHAR array). I need to convert this result string into a Byte array so I can handle it as a PDF file, i.e., save it and/or forward it as a file in a POST to another api.

I have tried the following (the result variable is the returned UCHAR string):

char[] pdfChar = result.ToCharArray();
byte[] pdfByte = new byte[pdfChar.Length];
for (int i = 0; i < pdfChar.Length; i++)
{
    pdfByte[i] = Convert.ToByte(pdfChar[i]);
}
File.WriteAllBytes(basePath + "test.pdf", pdfByte);

I have also tried:

byte[] pdfByte = Encoding.ASCII.GetBytes(pdfObj.result);
File.WriteAllBytes(basePath + "test.pdf", pdfByte);

With both of these, when I try to open the resulting test.pdf file, it will not open, presumably because it was not converted properly.

Ely Bascoy
  • 11
  • 5

2 Answers2

0

Do you know the file encoding format? Try to use this

return System.Text.Encoding.UTF8.GetString(pdfObj.result)

EDIT:

The solution you found is also reported here

var base64EncodedBytes = System.Convert.FromBase64String(pdfObj.result);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes)
ElettroAle
  • 119
  • 1
  • 8
  • I did not try this, because I was able to find the solution before I saw this reply. Thank you anyway for the incredibly fast reply and the suggestion of an absolutely viable troubleshooting step! – Ely Bascoy Aug 16 '19 at 16:48
0

Turns out that, although the output of the API function is UCHAR, when it comes in as part of the JSON string, it is a base64 string, so this works for me:

byte[] pdfBytes = Convert.FromBase64String(pdfObj.result);

I'm pretty sure the API is making that conversion "under the hood", i.e., while the function being called returns UCHAR, the api is using a framework to create the JSON-RPC responses, and it is likely performing the conversion before sending it out. If it is .NET that makes this conversion from UCHAR to base64, then please feel free to chime in and confirm this.

Ely Bascoy
  • 11
  • 5