An invoice endpoint needs a PDF response, but the report generator wants somewhere to put the file. THotPDF.OutputStream is that place. A TMemoryStream owned by the application takes the document when it is assigned before BeginDoc, and EndDoc writes the complete PDF into it, with no temporary file to clean up afterwards. What happens to the bytes next is a design decision, and this article follows one invoice from its first page to an HTTP body, a database BLOB, or a file.
OutputStream as the document destination
OutputStream holds any TStream, and the application keeps ownership of it: the component writes into the stream and never frees it. The destination is chosen before BeginDoc. Once a document is open, the property setter refuses a change and raises Cannot set OutputStream value - document in progress. With a stream assigned, EndDoc writes the PDF there instead of to FileName. The switch works both ways. An assignment of nil returns the component to the file route, where EndDoc saves to FileName and raises Invalid filename. if that property is still empty. AutoLaunch needs no line here. The viewer launch belongs to SaveToFile, so a document written to a stream never opens one.
Where the bytes land is less obvious. EndDoc writes from the stream's current position and reads that position back as the byte offset of each object for the cross-reference table. ISO 32000-1 §7.5.4 defines such an offset as the number of bytes from the first byte of the file, so the cursor, which is Position on any TStream, has to be at zero when EndDoc runs. A new TMemoryStream is a valid destination as it is, with Position and Size both at zero. A stream reused for the next request needs Clear first, which puts both values back to zero. A bare rewind keeps the old length, so a shorter PDF is followed by leftover bytes of the document before it, and a copy of Bytes.Size bytes ships that leftover.
When EndDoc returns, Position is zero and Size is the length of the PDF in bytes. The function below returns the stream and hands ownership to its caller. Pdf lives inside one generation attempt. If a drawing call or EndDoc raises, the except block frees Bytes before any caller can receive a half-written document. Compression is off by default. A new component starts with cmNone, so the listing sets cmFlateDecode. The page carries the reference INV-1042, which gives the reopen in the next section something to look for. Page sizes, fonts, and coordinates are the subject of the one-page HotPDF program, and its drawing calls move into the block between BeginDoc and EndDoc here.
program InvoiceStream;
{$APPTYPE CONSOLE}
uses
System.Classes, System.SysUtils, Vcl.Graphics, HPDFDoc;
function CreateInvoicePdf: TMemoryStream;
var
Bytes: TMemoryStream;
Pdf: THotPDF;
begin
Bytes := TMemoryStream.Create;
try
Pdf := THotPDF.Create(nil);
try
Pdf.OutputStream := Bytes; // set before BeginDoc
Pdf.Compression := cmFlateDecode; // a new component starts at cmNone
Pdf.Title := 'Invoice INV-1042';
Pdf.BeginDoc;
Pdf.CurrentPage.SetFont('Arial', [fsBold], 16);
Pdf.CurrentPage.TextOut(50, 50, 0, 'Invoice INV-1042');
Pdf.EndDoc; // writes Bytes, leaves Position at 0
finally
Pdf.Free;
end;
Result := Bytes; // the caller owns the stream from here
except
Bytes.Free;
raise;
end;
end;
What does reopening the stream prove?
The first five bytes are a cheap test. ISO 32000-1 §7.5.2 makes the first line of a file %PDF- followed by a version number, and RFC 8118 lists those characters as the magic number of application/pdf. A buffer that fails this test is an error page in JSON, a text preamble, or nothing at all. A truncated buffer passes it. The check reads the start of the file and stops, whilst a viewer finds the catalog, the pages, and the page contents from the other end, where the trailer's startxref entry holds the offset of the last cross-reference section (§7.5.5). The full text of ISO 32000-1 has the wording of both sections.
The reopen answers the larger question. LoadFromStream parses the stream into a fresh THotPDF instance and returns the number of pages in the page tree it built. A value below 1 means that none was built. Bytes that are not a PDF can raise PDF parsing error: … instead, so the call belongs inside the exception handling the service already has. ExtractLoadedPageText returns the text of one page. It gives back False when the page has no readable content stream. The text is rebuilt from glyph positions. That makes a token without spaces, such as the invoice reference, the dependable thing to look for. A valid page tree that carries the wrong template or the wrong invoice is a mundane failure in a report service, and a page count alone does not reveal it. An invoice that can span several pages needs the count for that input, or a reference searched on the pages where it belongs.
procedure CheckInvoicePdf(Bytes: TStream);
var
Header: AnsiString;
Reader: THotPDF;
PageCount: Integer;
PageText: UnicodeString;
begin
if Bytes.Size < 5 then
raise Exception.CreateFmt('Could not read a PDF header from a stream of %d bytes',
[Bytes.Size]);
SetLength(Header, 5);
Bytes.Position := 0;
Bytes.ReadBuffer(Header[1], 5);
Writeln('Header: ', Header);
Reader := THotPDF.Create(nil);
try
Bytes.Position := 0;
PageCount := Reader.LoadFromStream(Bytes);
Writeln('Pages: ', PageCount);
if Reader.ExtractLoadedPageText(0, PageText) then
Writeln('Page 1 text: ', PageText)
else
Writeln('Page 1 text: none extracted');
finally
Reader.Free;
end;
end;
Expected output from CheckInvoicePdf, placed under CreateInvoicePdf in the console program, on the stream that the function returned:
Header: %PDF-
Pages: 1
Page 1 text: Invoice INV-1042
Where should the stream cursor be before a PDF copy?
At zero, and it will not be there by accident. EndDoc leaves the cursor at the start, but the check has moved it twice since: the header read advanced it by five bytes, and the reopen seeks back and forth through the stream. The reopened document keeps that stream as its source and reads page objects on demand, so nothing else should seek in it until the THotPDF instance that loaded it is freed. With Size at 2048 and Position at 5, 2043 bytes remain, and a request for 2048 makes CopyFrom raise EReadError. Zero is special. A count of zero makes CopyFrom rewind the source first and then copy everything the source holds. The Delphi RTL reference for TStream.CopyFrom gives the wording of both rules, which the table applies to the stream in this program.
| Step | Position | Size | Result of CopyFrom(Bytes, Bytes.Size) |
|---|---|---|---|
After CreateInvoicePdf | 0 bytes | PDF length in bytes | The whole file is copied |
| After the five-byte header read | 5 bytes | PDF length in bytes | EReadError, because the request runs 5 bytes past the end of the stream |
After LoadFromStream | Wherever the reopen stopped reading | PDF length in bytes | Unreliable, so the listing below rewinds first |
Here the destination is a local file for an operator who wants a copy beside an invoice record. Two open modes apply here. fmCreate replaces a file of that name, and fmExclusive creates the file only when the name is free, so the choice between them decides what happens to the previous copy. The reopen runs first. Its three lines describe the bytes that are about to be copied, and a service that rejects them can stop before any file is touched. The copy is explicit. It starts from zero and passes Bytes.Size as the count, so both the start and the length are stated in the call. The program block at the end runs the whole chain once.
procedure SaveInvoiceCopy(const OutputFile: string);
var
Bytes: TMemoryStream;
Destination: TFileStream;
begin
Bytes := CreateInvoicePdf;
try
CheckInvoicePdf(Bytes);
Destination := TFileStream.Create(OutputFile, fmCreate);
try
Bytes.Position := 0;
Destination.CopyFrom(Bytes, Bytes.Size);
finally
Destination.Free;
end;
finally
Bytes.Free;
end;
end;
begin
SaveInvoiceCopy('Invoice INV-1042.pdf');
end.
The same stream sequence in C++Builder
The listing runs the three steps with the VCL stream classes and the generated header HPDFDoc.hpp. OutputStream holds a bare pointer. It receives bytes.get() and not the smart pointer, because the property is declared as TStream *. One THotPDF is alive per step: pdf is reset before the reopen and reader before the copy. BeginDoc() needs no argument, because Initial defaults to false. TextOut is the unified name for both compilers and takes a wide literal; PrintText is still declared for C++Builder as an alias for older code. The console lines come out as in the Delphi program.
#include <vcl.h>
#include <cstdio>
#include <memory>
#pragma hdrstop
#include "HPDFDoc.hpp"
void SaveInvoiceCopy(const UnicodeString& outputFile)
{
std::unique_ptr<TMemoryStream> bytes(new TMemoryStream());
std::unique_ptr<THotPDF> pdf(new THotPDF(nullptr));
pdf->OutputStream = bytes.get(); // set before BeginDoc
pdf->Compression = cmFlateDecode;
pdf->Title = "Invoice INV-1042";
pdf->BeginDoc();
pdf->CurrentPage->SetFont("Arial", TFontStyles() << fsBold, 16);
pdf->CurrentPage->TextOut(50, 50, 0, L"Invoice INV-1042");
pdf->EndDoc(); // leaves bytes->Position at 0
pdf.reset();
char header[6] = {};
bytes->ReadBuffer(header, 5);
std::printf("Header: %s\n", header);
std::unique_ptr<THotPDF> reader(new THotPDF(nullptr));
bytes->Position = 0;
std::printf("Pages: %d\n", reader->LoadFromStream(bytes.get()));
UnicodeString pageText;
if (reader->ExtractLoadedPageText(0, pageText))
std::printf("Page 1 text: %s\n", AnsiString(pageText).c_str());
reader.reset();
std::unique_ptr<TFileStream> output(new TFileStream(outputFile, fmCreate));
bytes->Position = 0;
output->CopyFrom(bytes.get(), bytes->Size);
}
Delivery to HTTP, a database, and email as binary data
The finished stream can be an HTTP response body, a database BLOB, or a file attachment. application/pdf is the media type for every PDF version. RFC 8118 registers it with the note Encoding considerations: binary. That IETF registration of the PDF media type is the citation for a transport that insists on a text encoding. The content length is Bytes.Size. A server API that asks for an explicit length gets that number, and the bytes come from the stream as they are. ISO 32000-1 §7.5.2 asks for a comment line of at least four bytes with codes of 128 or more right after the header, so that transfer software treats the file as binary. HotPDF writes that line second. A text decode followed by a re-encode can change those bytes, the compressed streams behind them, and every offset that points into the file. Base64 is for transports that require text and nothing else.
| Destination | Handoff | What to inspect if the document arrives incomplete |
|---|---|---|
| HTTP response | The server API that accepts a stream or a binary body, with response framing left to the server when it streams the response | The first bytes and the length of the downloaded response body; a middleware error can send a readable message in place of the PDF |
| Database BLOB | A binary parameter, with the stream kept alive until the database client has uploaded it | The BLOB length and then the stored bytes loaded back into a stream; a client-side cursor still at the end can yield an empty value |
| Email attachment | The PDF bytes and a file name passed to the attachment API under its encoding contract | The decoded attachment and its prefix; a payload that still begins with JVBERi0 is Base64 text that was encoded twice |
Each framework takes the stream in its own way. Some copy the bytes during the upload call and others read the stream after the call has returned, and the description of the stream parameter is where the documentation says which. That second case needs a live stream. The consumer may keep reading until its work completes, including any queueing or retry, and a stream freed by the handler that generated the PDF produces a file that opens locally and arrives damaged. One stream has one cursor. A preview and an upload that both seek need independent copies or serialised access, and one owner per handoff keeps position and lifetime under a single control.
A memory stream suits a short invoice or a small report whose whole response is easy to hold. Image-heavy exports change the arithmetic. Each job then holds the serialised file on top of whatever the report itself needs, and several jobs at once hold that much apiece. OutputStream accepts any TStream, a TFileStream included, which is the practical choice when the size varies too much to budget or when another service reads the file later. Documents that already exist on disk are the subject of the HotPDF guide to the Direct File API for large PDFs, which covers page counts, copies, and incremental updates without loading the whole document. For a small in-memory report I would keep the boundary at EndDoc and choose the delivery adapter around the finished stream. The HotPDF Delphi Component page lists the supported Delphi and C++Builder versions.