3
votes

I have a 64 base encoded string that contains PDF file data.

Using the EncdDecd namespace 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 null value(ascii = 0) the string no longer appends..

Example
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;
end;

Writing to a text file seems to work better but after renaming it to a pdf it 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 file, or display the pdf in delphi.

Thanks

p.s.

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

1
Duplicate of Saving a Base64 string to disk as a binary using Delphi 2007. I don't see what new information you're requesting here. If you just want additional options, they belong as answers to the original question, not this duplicate. - Rob Kennedy
what have you tried? what was the problem? How do you "append" the string? please post your code using "EncdDecd namespace". Also, how do you change a text file to a pdf? again post your code. There are many ways in Delphi to transform a string and save it in binary. The link you posted is quite a compact code to do it. - PA.

1 Answers

9
votes

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.