A Delphi report can look right on page one and still deliver a stretched logo, a misplaced page number, or an empty download. Each one has a small cause. PDFlibPas loads the logo once, places it with page coordinates on each page, and serialises the completed PDF into a stream that the caller owns.
How can one logo appear on many PDF pages?
Register the logo once with TPDFlib.AddImageFromFile and carry the returned image identifier through the page loop. The identifier belongs to the selected document. Register the logo after loading an existing PDF, and register it again when processing a different PDF. In PDF terms, an image XObject is a stream that stores the image samples and attributes, and a page refers to it by name and invokes it with Do from its content stream. Page two needs no second copy. Placing the image there only adds drawing instructions that point at the image the document already holds, and the first identifier serves again at whatever size the layout needs. ISO 32000-1, section 8.8 on external objects defines XObjects and the Do operator that paints them.
A logo carries two measurements that do not depend on each other: its size in pixels and the rectangle it occupies on the page. Only the ratio links them. The arithmetic is simple: a 600 by 200 pixel logo has a three-to-one aspect ratio, so a 30 mm logo in the page design comes out 10 mm high. ImageWidth and ImageHeight supply the sample counts for that calculation, and DrawImage receives the rectangle you want on the page. The sample count stays put. Enlarging the rectangle to 45 mm only spreads those samples over a larger area, because ISO 32000-1 section 8.9.4 always maps the whole image onto the unit square of user space, whatever its pixel size. If the brand mark looks squeezed, the rectangle ratio is the first thing to check, before compression settings or new artwork.
The finished file shows whether the reuse worked. In a PDF object inspector, open /Resources and then /XObject on two stamped pages: each entry pairs a resource name with an indirect reference, and both references should lead to one image stream object. Compare the references rather than the names, because a resource name is local to its page and two pages can give one image different names. Counting every object with /Subtype /Image can overshoot: the file may also hold a transparency mask, or images that came in with the source document. Print work adds a second number, effective resolution. At 30 mm wide, a 600-pixel logo works out to 508 pixels per inch. At 45 mm it has about 339. To meet a print specification, calculate the resolution from the drawn width and the horizontal pixel count.
Header placement in page coordinates
The header below uses SetOrigin(1) and SetMeasurementUnits(1), so the left and top offsets read like measurements on a printed page. In this setup a logo at (18, 9) starts 18 mm from the left and 9 mm down from the top of an ordinary, zero-offset page. DrawImage takes the top edge of the image rectangle. DrawText uses a text baseline for its vertical position, and the typeset label extends above it. That difference explains why passing the same Y value to both calls can look crooked. One call ignores the units. SetTextSize always takes points, so the label below is set at 9 points, not 9 millimetres. The example uses a 16 mm baseline. The page number sits at the right margin, and its left coordinate comes from the width of the label at the active font and size.
The routines below need SysUtils, Classes, and PDFlibrary in the uses clause of the unit that holds them. Paste them in the order shown. Each one calls the routine printed before it, so RequirePDFSuccess comes first and CreateBrandedPDFStream comes last. The calls wrapped below return 1 on success and 0 on failure. RequirePDFSuccess turns a 0 into an exception that names the call, and it leaves LastErrorCode out of the message because calls like these usually report a failure only through the return value. SelectImage and BeginOutputToStream, for example, return 0 without setting an error code, so the property would read 0 or a value left over from an earlier call.
PaintPageHeaders works on a blank document. It also works on a source PDF that opens without a password and carries no signature, provided its pages are plain. Plain means four things here. The page is unrotated. Its media box starts at (0, 0). Its /UserUnit is the default of 1. And its crop box matches the media box. Each page also needs a free strip of 22 mm at the top for the header. The loop checks only the first and the third. A media box that does not start at (0, 0), or a crop box other than the media box, passes both checks. Confirm those two boxes in the source file yourself: pdfinfo -box prints both for the first page, and adding -f 1 -l N repeats that for pages 1 to N. PageWidth and PageHeight always read the media box and ignore the crop box, which is why a print crop moves the visible edge without moving the header. ISO 32000-1 section 8.3.2.3 ties the visible area to the CropBox, the orientation to the Rotate entry, and the unit length to /UserUnit.
procedure RequirePDFSuccess(Status: Integer; const Operation: string);
begin
if Status <> 1 then
raise Exception.CreateFmt('%s failed', [Operation]);
end;
procedure PaintPageHeaders(PDF: TPDFlib; const LogoPath: WideString);
const
Margin = 18.0;
LogoWidth = 30.0;
LogoTop = 9.0;
LabelBaseline = 16.0;
var
ImageID, FontID, PageNo, PageTotal: Integer;
LogoHeight, LabelLeft: Double;
LabelText: WideString;
begin
PDF.SetOrigin(1);
PDF.SetMeasurementUnits(1);
ImageID := PDF.AddImageFromFile(LogoPath, 0);
if ImageID = 0 then
raise Exception.Create('Cannot load the logo image');
RequirePDFSuccess(PDF.SelectImage(ImageID), 'Select logo');
if (PDF.ImageWidth <= 0) or (PDF.ImageHeight <= 0) then
raise Exception.Create('The logo needs positive pixel dimensions');
LogoHeight := LogoWidth * PDF.ImageHeight / PDF.ImageWidth;
FontID := PDF.AddStandardFont(4); // Helvetica
if FontID = 0 then
raise Exception.Create('Cannot add Helvetica');
PageTotal := PDF.PageCount;
for PageNo := 1 to PageTotal do
begin
RequirePDFSuccess(PDF.SelectPage(PageNo), 'Select page');
if PDF.PageRotation <> 0 then
raise Exception.CreateFmt('Cannot place the header: page %d is rotated',
[PageNo]);
if PDF.GetPageUserUnit <> 1.0 then
raise Exception.CreateFmt(
'Cannot place the header: page %d uses a non-default unit', [PageNo]);
RequirePDFSuccess(PDF.SelectFont(FontID), 'Select font');
RequirePDFSuccess(PDF.SetTextSize(9), 'Set text size');
PDF.SetTextAlign(0);
PDF.SetTextColor(0.15, 0.15, 0.15);
LabelText := WideString(Format('Page %d of %d', [PageNo, PageTotal]));
LabelLeft := PDF.PageWidth - Margin - PDF.GetTextWidth(LabelText);
if (LabelLeft < Margin + LogoWidth + 4) or
(LogoTop + LogoHeight > 22) then
raise Exception.CreateFmt('The header does not fit page %d', [PageNo]);
RequirePDFSuccess(PDF.SelectImage(ImageID), 'Select logo');
RequirePDFSuccess(PDF.DrawImage(Margin, LogoTop, LogoWidth,
LogoHeight), 'Draw logo');
RequirePDFSuccess(PDF.DrawText(LabelLeft, LabelBaseline,
LabelText), 'Draw page number');
end;
end;
As a first input, any 600 by 200 pixel PNG will do, together with an A4 source whose first 22 mm are empty on every page. The expected logo is 30 by 10 mm. It runs from y = 9 to y = 19 mm. LabelLeft is recalculated after each page is selected and the font is set. A wider sheet therefore shifts the label to the right, and a longer label, such as the one on page 10, grows to the left. The placement check rejects a logo taller than the available strip and keeps the label four millimetres clear of the image. A photo loads just as well, but a square one comes out 30 mm high, LogoTop + LogoHeight reaches 39, and the placement check raises before that page is drawn. If the layout needs anchors, opacity, and page ranges, see the guide to composite watermark templates.
Which call writes the PDF bytes?
TPDFlib.BeginOutputToStream binds the target and TPDFlib.EndOutputStream writes the finished PDF. Nothing reaches the stream before that second call. The draw calls build page content whilst the destination is pending, and a newly bound TMemoryStream still holds zero bytes until EndOutputStream runs. Keep the stream alive whilst the binding is pending and whilst the end call writes. EndOutputStream clears the binding before it starts the save. If saving fails, discard the incomplete output and bind a fresh destination for a retry. The caller owns the stream throughout. A render job that already has its completed document in hand can use SaveToStream directly. The paired calls earn their place when the job has a begin/end structure and there is a clear point at which to hand the result to the delivery code. The API reference documents stream ownership and when the binding is cleared.
procedure WriteBrandedPDF(const SourcePDF, LogoPath: WideString;
Destination: TStream);
var
PDF: TPDFlib;
begin
PDF := TPDFlib.Create;
try
if SourcePDF = '' then
begin
RequirePDFSuccess(PDF.SetPageSize('A4'), 'Set page size');
if PDF.NewPage = 0 then
raise Exception.Create('Cannot add the second page');
end
else
RequirePDFSuccess(PDF.LoadFromFile(SourcePDF, ''), 'Load source');
RequirePDFSuccess(PDF.BeginOutputToStream(Destination),
'Bind output stream');
try
PaintPageHeaders(PDF, LogoPath);
RequirePDFSuccess(PDF.EndOutputStream, 'Write PDF');
finally
if PDF.OutputStreamActive = 1 then
PDF.CancelOutputStream;
end;
finally
PDF.Free;
end;
end;
Call WriteBrandedPDF with an empty source path to create two A4 pages, or pass the path of your own unsigned PDF to draw on its existing pages. TPDFlib.Create starts with one blank page. The empty-path branch adds just one more, and PaintPageHeaders then draws on both. The empty password suits a source that opens without one. Supply a new, empty destination at position zero for each output, so that the serialised bytes start at the beginning of the resulting PDF. Do not open the input PDF itself as the destination. LoadFromFile keeps a read handle open on the source until the loaded document is freed, because the document reads object bytes from that file on demand. Opening the file for output can then truncate it under that reader. If the job involves valid signatures or preserving earlier revisions, decide what changes are permitted before using any full rewrite. The incremental PDF save guide explains the byte ranges involved.
Returning the stream after the entire PDF is written
Return a TMemoryStream only after the PDF has been written successfully, and reset its position to zero for whatever reads it next. The function below owns the stream whilst the document is being assembled. If loading, drawing, or writing raises an exception, the function frees that stream and the caller receives the exception. A successful return hands the stream to the caller. Ownership moves with it. The caller can then pass the stream to an HTTP response or use its bytes elsewhere. Match the response framework's ownership rules so that only one component frees it.
function CreateBrandedPDFStream(const SourcePDF,
LogoPath: WideString): TMemoryStream;
var
Buffer: TMemoryStream;
begin
Buffer := TMemoryStream.Create;
try
WriteBrandedPDF(SourcePDF, LogoPath, Buffer);
Buffer.Position := 0;
except
Buffer.Free;
raise;
end;
Result := Buffer;
end;
A memory stream fits short reports. It gives the code that answers the HTTP request a completed PDF and its precise length before it sends an application/pdf response. For large reports, pass WriteBrandedPDF a TFileStream opened on a staging path instead, free it after the call returns, and publish the file from that path. I would not write a PDF straight to an already open connection. The receiver may see the early bytes whilst the rest is still being generated, and staging leaves the server free to report a write error before it publishes a result.
When the logo does not load, PaintPageHeaders raises before any page is drawn. The finally block in WriteBrandedPDF then cancels the output binding, and no byte reaches the destination. For an endpoint that sometimes sends a zero-byte attachment, look at three values in this order: the result of EndOutputStream, the Size of the stream, and its Position. A size of zero right after binding is expected. A positive size and a position at the end of the memory stream after saving are consistent with a successful write. Code that reads from the current position gets an empty payload until the position is reset. Code that always reads from offset zero hides the problem during development, which is how one generator can work with a download handler that seeks to the start and fail with another that does not. The published payload should be as long as the finished stream, and the downloaded PDF should open in a viewer with every page in place.
This page loop leaves room for hooks such as a different label on the cover or a wider margin for the appendix. The drawing and stream methods are available through losLab PDF Library for Delphi.