A regular expression that swaps every 1 0 0 rg for a neutral gray in a decoded page content stream will also rewrite the string literal (1 0 0 rg) printed on a page of a PDF tutorial. If the page carries an inline image, the same eight bytes can turn up inside the raw sample data between ID and EI, where they are pixels and nothing else. The regex cannot tell any of these apart. An editor that has already tokenized the stream can: a string literal is one operand, an inline image is one opaque unit, and an operator is a word that ends an operation
Content streams look like text, which is exactly what makes text tools dangerous on them. ISO 32000-1 §7.8.2 defines a stream as a sequence of operands followed by operators, interpreted by what amounts to a stack machine; there is no document tree to walk, and the syntax is decided token by token. The rest of this article is about editing at that token level from Delphi, and about the guard rails worth keeping switched on when you do
One event per operator, one decision per event
HotPDF exposes this through THotPDF.VisitLoadedPageContentOperators. The method parses the page's content, fires one event per operation, and asks your code for a THPDFContentOperatorAction: coaKeep, coaDelete, coaReplace, coaStop or coaReject. Every operator you keep is copied back byte for byte, whitespace and comments included, and new bytes are written only where you deleted or replaced something. A pass that keeps everything therefore returns the original stream unchanged, down to the last byte
A few details decide how the walk looks from inside the callback. The event fires three kinds of phase: covpBeginStream once before the first operator, covpOperator for each operation, and covpEndStream once at the end. An inline image arrives as a single covpOperator event named BI whose byte span covers everything from BI through EI, so deleting it removes the whole image and you never see its binary payload as a run of fake operators. When a page stores /Contents as an array of streams, the parts are read back to back as one sequence, which is how §7.8.2 says a consumer should treat them
You can attach your code in two ways: assign the OnContentOperator event, or set ContentOperatorVisitor to an object implementing IHPDFContentOperatorVisitor. If both are set, the interface visitor runs first and the event sees the action and replacement it chose, so the event can refine the decision. Both run synchronously on the calling thread. Here is a read-only audit across a whole document:
uses
SysUtils, HPDFDoc, HPDFContentStream;
procedure TAuditor.HandleOperator(Sender: TObject;
var EventData: THPDFContentOperatorEventData);
var
Bytes: TBytes;
begin
if EventData.Phase <> covpOperator then
Exit;
// Count text-showing operators drawn inside marked content
if (EventData.OperatorName = 'Tj') or
(EventData.OperatorName = 'TJ') then
begin
Inc(FTextOperators);
if EventData.State.MarkedContentDepth > 0 then
Inc(FTextInsideMarkedContent);
end;
// Read an operand only when you need it; name bytes keep their leading slash
if EventData.OperatorName = 'Do' then
if EventData.View.GetOperandBytes(0, Bytes) then
NoteXObjectUse(TEncoding.ANSI.GetString(Bytes)); // your own bookkeeping
EventData.Action := coaKeep;
end;
procedure TAuditor.Run(const FileName: string);
var
Pdf: THotPDF;
Stats: THPDFContentOperatorVisitStatistics;
I, TotalOperators, MaxDepth: Integer;
begin
Pdf := THotPDF.Create(nil);
try
if Pdf.LoadFromFile(FileName) <= 0 then
Exit;
Pdf.OnContentOperator := HandleOperator;
TotalOperators := 0;
MaxDepth := 0;
for I := 0 to Pdf.LoadedPageCount - 1 do
begin
// Stats is refilled on every call, so fold each page into the totals
if not Pdf.VisitLoadedPageContentOperators(I, False, Stats) then // audit only
begin
Writeln(Format('page %d skipped: %s', [I + 1, string(Stats.Diagnostic)]));
Continue;
end;
Inc(TotalOperators, Stats.VisitedOperatorCount);
if Stats.MaximumGraphicsStateDepth > MaxDepth then
MaxDepth := Stats.MaximumGraphicsStateDepth;
end;
Writeln(Format('%d operators visited, max q/Q depth %d',
[TotalOperators, MaxDepth]));
finally
Pdf.Free;
end;
end;
The second argument, ApplyChanges, is False here. That turns the call into a dry run even when the visitor deletes or replaces operators: the statistics still report what would have changed, including Modified and OutputBytes, and the page itself is left alone. Running a rewrite visitor once with False on a sample batch before letting it loose with True costs one extra parse per page
Why does the callback get a read-only view?
The callback never receives a syntax tree it can modify. EventData.View is a THPDFContentOperatorView with three read methods, GetOperationBytes, GetOperandBytes and GetOperandNode, and every change has to go through Action and Replacement. Direct mutation would let a visitor slip past the replacement byte budget and the overlapping-edit check. Two edits that claim overlapping byte ranges produce output that is wrong in ways no parser will notice, so routing all changes through one field means each one is checked the same way
Reading on demand also keeps audits cheap. A visitor that only looks at OperatorName and OperandCount never copies operand bytes at all, which matters on pages that run into hundreds of thousands of operations
What the view returns is the source spelling, unprocessed. A name operand comes back as /Wm0 with its slash, and a name written with hex escapes comes back with the escapes intact. ISO 32000-1 §7.3.5 allows /W#6D0 as another spelling of /Wm0, and some producers do write names that way. A visitor that compares raw bytes against '/Wm0' will miss it. Decode #xx sequences before you compare names; the same goes for numbers, which arrive as text such as .5 or -0.25 and need parsing on your side
Depths always describe the original input
Each event carries a State record with GraphicsStateDepth, TextObjectDepth, MarkedContentDepth and CompatibilityDepth. Those are the q/Q, BT/ET, BMC/BDC/EMC and BX/EX nesting levels as they stood in the source immediately before the current operator. Delete a q earlier in the stream and the following events still report the depth the source had. The depth counters stop at zero, so a stray Q in a sloppy file does not drive them negative
Anchoring state to the input is deliberate. The same audit run twice over the same document produces identical numbers, and an audit that runs alongside edits does not shift its own frame of reference halfway through. If you need the depth of the output, you know exactly which operators you removed and can compute it. Going the other way, recovering stable input positions from an output that changes under you, is not something a visitor could do reliably
Deleting and replacing operators in Delphi
A replacement is raw content-stream bytes covering the whole operation, operands and operator together, and you own their syntax. Two traps show up in practice. The first is operand count: a malformed file can carry an rg with two operands, and a visitor that blindly reads three will either fail or invent a color. The second is purely Delphi. FloatToStr and FormatFloat follow the user's locale, so on a German or French Windows install a computed gray of 0.25 comes out as 0,25, and that is not a number in PDF syntax at all. Build replacement numbers with a format settings record whose decimal separator is a period:
constructor TPageCleaner.Create;
begin
inherited Create;
FPdfNumbers := TFormatSettings.Create;
FPdfNumbers.DecimalSeparator := '.'; // PDF numbers never use a comma
end;
// Your own helper: parse one numeric operand with the period separator
function TPageCleaner.ReadNumber(const EventData: THPDFContentOperatorEventData;
Index: Integer; out Value: Double): Boolean;
var
Bytes: TBytes;
begin
Result := EventData.View.GetOperandBytes(Index, Bytes) and
TryStrToFloat(TEncoding.ANSI.GetString(Bytes), Value, FPdfNumbers);
end;
procedure TPageCleaner.HandleOperator(Sender: TObject;
var EventData: THPDFContentOperatorEventData);
var
Bytes: TBytes;
R, G, B: Double;
begin
if EventData.Phase <> covpOperator then
Exit; // Action already arrives as coaKeep
if EventData.OperatorName = 'Do' then
begin
// IsWatermarkName is your own helper; decode #xx escapes before comparing
if EventData.View.GetOperandBytes(0, Bytes) and
IsWatermarkName(TEncoding.ANSI.GetString(Bytes)) then
EventData.Action := coaDelete;
end
else if EventData.OperatorName = 'rg' then
begin
if (EventData.OperandCount = 3) and ReadNumber(EventData, 0, R) and
ReadNumber(EventData, 1, G) and ReadNumber(EventData, 2, B) then
begin
EventData.Replacement := TEncoding.ANSI.GetBytes(
FormatFloat('0.####', 0.3 * R + 0.59 * G + 0.11 * B, FPdfNumbers) + ' g');
EventData.Action := coaReplace;
end
else
EventData.Action := coaReject; // something we do not understand: leave the page alone
end;
end;
The action set has two exits, and they mean different things. coaStop ends the walk and keeps every decision made so far; the operator that requested it counts as kept and the rest of the stream is copied through untouched. That fits a search that has found what it was after. coaReject throws the whole visit away and leaves the page exactly as it was, which is the right answer whenever the visitor meets input its rules were not written for. For a cleanup tool that runs unattended over files from many producers, reject is the safer reflex than a best guess
The begin and end phases have narrower rules. During covpBeginStream and covpEndStream only keep, stop and reject are accepted; asking for a delete or replace there ends the visit with a visitor error. Rejecting at the end phase is legitimate and handy: an audit can collect counts through the walk and, at covpEndStream, refuse the page if they do not reconcile with what it expected
What output validation catches, and what it cannot
THPDFContentOperatorVisitOptions.Default sets ValidateOutput to True, together with MaxReplacementBytes of 64 MiB, MaxOperators of 1,000,000, MaxSourceBytes of 256 MiB and a limit of 256 for nested arrays and dictionaries (MaxDepth). With validation on, the rewritten stream is parsed again under the same lexeme, depth and operator limits before anything is accepted. Leave it on. The cost is one extra parse of a page you have just edited, and what it buys is a guarantee that an unterminated string, an unbalanced array or a replacement that left operands without an operator never reaches the saved file
The check is syntactic, and its reach ends there. A replacement of 0.25 rg parses cleanly even though rg wants three operands, and an extra Q that unbalances the graphics state is valid syntax as well. Those are the visitor's job, which is why the example above checks OperandCount before it builds anything. On the input side the rule is just as strict: if the source stream does not parse, for example because it contains an unterminated inline image, the visit ends with covsInvalidInput before your callback sees a single operator. Refusing to edit a stream that cannot be fully tokenized is the conservative choice, and for a rewriting tool it is the correct one
Reading the statistics after a pass
The Status field of THPDFContentOperatorVisitStatistics names seven endings: covsCompleted, covsStopped, covsRejected, covsInvalidInput, covsLimitExceeded, covsInvalidOutput and covsVisitorError. The method returns True only for completed and stopped walks. covsInvalidOutput points at your replacement bytes, covsInvalidInput at the source, and a visitor that raises an exception ends up as covsVisitorError with the exception message in Diagnostic. ErrorOffset gives the byte position where the problem was found, or -1 when there is none
The counters make an audit check itself. KeptOperatorCount, DeletedOperatorCount and ReplacedOperatorCount add up to VisitedOperatorCount, the four Maximum…Depth fields show how deeply the page nests, and SourceBytes against OutputBytes gives the size effect of the edit in one subtraction
When ApplyChanges is True and the pass modified something, the page's /Contents, single stream or array, is replaced by one new stream holding the validated output, and cached renderings of that page are discarded. The new stream is written without a filter, so a document-wide rewrite can grow the file noticeably until you compress it:
var
Options: THPDFContentOperatorVisitOptions;
Stats: THPDFContentOperatorVisitStatistics;
I, Changed: Integer;
begin
Options := THPDFContentOperatorVisitOptions.Default; // ValidateOutput is already True
Options.MaxReplacementBytes := 1024 * 1024; // a gray conversion needs far less
Pdf.OnContentOperator := Cleaner.HandleOperator;
Changed := 0;
for I := 0 to Pdf.LoadedPageCount - 1 do
begin
// nil = no cancellation token
if not Pdf.VisitLoadedPageContentOperators(I, True, Options, nil, Stats) then
begin
Log(Format('page %d left unchanged: status %d at offset %d, %s', // Log is yours
[I + 1, Ord(Stats.Status), Stats.ErrorOffset, string(Stats.Diagnostic)]));
Continue;
end;
if Stats.Modified then
Inc(Changed);
end;
if Changed > 0 then
begin
Pdf.CompressLoadedDocument; // rewritten content streams are stored unfiltered
Pdf.SaveLoadedDocument('cleaned.pdf');
end;
end;
A lower MaxReplacementBytes is cheap insurance against a visitor bug that replaces every operator with a long string; the visit fails with covsLimitExceeded instead of producing a page several times its original size. If you pass a THPDFCancellationToken instead of nil, the walk checks it every 256 operations, and a cancellation surfaces as an exception you catch around the call; it never shows up in Status
Where the operator visitor fits, and where something else is better
The visitor works on the page's own content stream. A watermark drawn inside a Form XObject is reached through the Do that paints it, which is why the example deletes that invocation and leaves the form object itself alone. For several common jobs there are higher-level routes that need no visitor at all. Converting device colors across pages is what RewriteLoadedPageColors does. Removing content permanently, with the resource cleanup real redaction needs, is covered in redaction and page stitching on loaded documents, and replacing visible text is covered in search and replace in an existing PDF. Write a visitor when your rule is structural rather than textual, or when you need an audit that no existing report answers
Operator visiting, glyph extraction and the higher-level rewrites all work on the same loaded document in Delphi and C++Builder; the HotPDF Delphi PDF component page lists the rest of what you can do with a PDF once it is open