Well, as this is taking too long I finally somewhat solved this way:
1. The CGI program gets the Id file (from the database, there's a relation between the filename and an Id).
2. The CGI runs (using TProcess) an external executable passing the ID as param.
3. The executable receives the ID, do an SQL query to find the filename, loads it into a TMemoryStream, saves to a new file called /tmp/<ID>.pdf and writes 'ok' to stdout.
4. The CGI reads the result of the program, if it's 'ok' then reads the file into a TMemoryStream and sends its content to the client.
Awful, but works.