bagus prasojo
bagus prasojo

Reputation: 603

How to read and write a PDF file using TStreamWriter and TStreamReader?

Here is my code:

procedure TForm1.Button2Click(Sender: TObject);
var
  Reader: TStreamReader;
  Writer: TStreamWriter;
begin
  Reader := TStreamReader.Create('D:\Downloads\cover.pdf', TEncoding.UTF8, False);
  try
    Writer := TStreamWriter.Create('D:\Downloads\coverb.pdf', False, TEncoding.UTF8);
    try
      Writer.Write(Reader.ReadToEnd());
    finally
      Writer.Free;
      ShowMessage('Berhasil');
    end;
  finally
    Reader.Free();
  end;
end;

Using the above code, Reader.ReadToEnd(), I got no string, and coverb.pdf is empty.

I'm using Delphi XE.

Upvotes: 3

Views: 6516

Answers (4)

Roberto Novakosky
Roberto Novakosky

Reputation: 371

Do you need to write one new PDF file manually? In this case you need to know the struct of format to PDF files. Use the ISO 32000-2 to format version 2.0, so is possible to build with binary streams your PDF file, but with sure if you use some ready components will be more easy...

Here is one example how to do manually: https://blogs.embarcadero.com/how-to-create-a-pdf-file-with-delphi-and-add-an-image-to-it/ (this example is very simple, so don't use compress inside file)

But I sugest lybraries as GDPicture or Gnostice...

Upvotes: 0

IceCold
IceCold

Reputation: 21154

You can use Embarcadero's ReadAllText function. Like this:

Uses IOUtils;

TFile.ReadAllText(FileName);

It will correctly detect ANSI, Unicode and binary files.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612964

PDF files are generally compressed binary files and so cannot be read as UTF8. Doing so will lead to codec errors. Remember that not all sequences of bytes are valid UTF8 sequences.

It looks like you just need to call CopyFile instead of your complex stream based code, but perhaps this is just a cut down sample.

Upvotes: 4

Remy Lebeau
Remy Lebeau

Reputation: 596246

If the file is not empty but ReadToEnd() is returning an empty string, then the TEncoding object being used to decode the file bytes into Unicode is encountering conversion errors. The RTL does not raise an exception on string conversion errors. If all you want to do is make an exact copy of the file, use CopyFile(), or use TFileStream and the TStream.CopyFrom() method.

Upvotes: 3

Related Questions