Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 encoded String to binary file

I have a Base64 encoded String that contains PDF data. Using the EncdDecd unit I can decode the String to a Byte Array.

This is where I am having trouble: I tried saving the characters to a String but once it hits a zero value (ASCII = 0 or #0 or $00) the String no longer appends. Example:

uses
  EncdDecd;
var
  EncodedString : String;
  Report : String;
  Base64Bytes: TBytes; // contains the binary data
begin
  Base64Bytes := DecodeBase64(EncodedString);
  for I := 0 to Length(Base64Bytes) - 1 do
    begin
      Report := Report + Chr(Base64Bytes[I]);
    end;

Writing to a text file seems to work better but after renaming it to .PDF the file does not open correctly.

How can I write to a binary file in Delphi? Or even save the data to a stream? Basically I am just trying to take the encoded String and save it to a PDF/binary file, or display the PDF in Delphi.

I have looked around quite a bit and found a possible solution in Saving a Base64 string to disk as a binary using Delphi 2007 but is there another way?

like image 321
Trevor Avatar asked Aug 27 '26 02:08

Trevor


1 Answers

This should do it:

procedure DecodeBaseToFile(const FileName: string; 
  const EncodedString: AnsiString);
var
  bytes: TBytes;
  Stream: TFileStream;
begin
  bytes := DecodeBase64(EncodedString);
  Stream := TFileStream.Create(FileName, fmCreate);
  try
    if bytes<>nil then
      Stream.WriteBuffer(bytes[0], Length(bytes));
  finally
    Stream.Free;
  end;
end;

Note: I have only compiled this in my head.

like image 76
David Heffernan Avatar answered Aug 29 '26 14:08

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!