Building a PDF Creation Library in MQL5 (Part 3): The Byte-Exact Writer
Contents
- Introduction
- Where we are
- The one idea
- CPdfBuffer: bytes, and the current position
- CPdfWriter: objects, and where they landed
- The demo, and what it proves
- The take-away tool
- When it goes wrong
- The cheat card
- Project structure
- Conclusion
Introduction
You can build a PDF by hand, but once a file grows past a few objects every edit becomes a minefield: insert one character and /Length, the xref offsets and startxref are suddenly wrong. The format validates none of those numbers, so a single change can produce a file that one viewer silently repairs, another displays as blank, and a third refuses to open. Part 1 typed such a file by hand, and Part 2 showed how far the damage from two extra characters reaches, finishing with a validator that reports it. What we still need is a way to generate a PDF from MQL5 in one pass, so that a change in the text, the page count or the size of a stream never forces manual byte arithmetic and never leaves a forgotten literal behind in the source.
This part removes the problem rather than detecting it. The idea is small enough to state in one line, and the rest of the article is the consequences of it:
Never calculate a byte offset. Ask the buffer where it is.
A program that appends bytes to an array already knows how many bytes it has written. That number is the current byte position. If an object records it at the instant the object begins, the offset is never a guess: it cannot go stale when something above it changes, and it cannot be forgotten when the text is edited.
Two classes result from it. CPdfBuffer is a growable array of bytes and the only class in the library that stores them. CPdfWriter allocates object numbers, records where each object landed, and writes the cross-reference table based on what it observed. Together they are about 300 lines, and they are the foundation on which every later part is built.
The take-away is a tool you can use today: a script that turns any ASCII text — a log, a settings dump, a list of symbols and spreads — into a paginated PDF.

Figure 1. An account summary printed to PDF by this part's second demo.
Nothing in Figure 1 was positioned by counting bytes. The document is longer than Part 1's file by two orders of magnitude, and the difference in effort is one method call.
Where we are
Part 1 produced hello.pdf by hand. Part 2 added PdfValidate.mqh, which checks the four things a viewer checks. That file carries over unchanged and is used here to test our own output, which is what it was written for.
The one ideaHere is Part 1's code next to Part 3's, for the same three numbers.

Figure 2. The same three numbers, counted by a person and read from a buffer.
Look at the left panel of Figure 2. 43 is the length of a stream someone counted. 0000000247 is a position someone counted. 409 is another. All three are literals in the source, and all three are wrong the moment anything above them changes size.
Now the right panel. m_out.Length() is not a guess about where we are; it is the definition of where we are. content.Length() is not a claim about how big the stream is; it is the size of the stream. There is nothing to keep in sync because there is only one copy of each fact.
This is worth stating as a design rule, because it is what the whole library is organized around: a number that describes the file must be derived from the file, never maintained alongside it. Every later part obeys it. When Part 9 compresses a stream, the compressed length is read from the compressed bytes. When Part 23 writes a bookmark that points at a page, the page's object number comes from the object that was allocated for it.
CPdfBuffer: bytes, and the current position
The buffer does three things: it grows, it appends, and it answers Length().
Everything starts with PdfDefines.mqh, which holds the values more than one file needs:
//+------------------------------------------------------------------+ //| PdfDefines.mqh | //+------------------------------------------------------------------+ #ifndef PDF5_DEFINES_MQH #define PDF5_DEFINES_MQH //--- The version written into the header. 1.4 is old enough that every //--- viewer accepts it and new enough for everything this series does //--- before compressed cross-reference streams appear much later. #define PDF_VERSION "1.4" //--- Line ending. One byte, everywhere, in every file the library //--- writes. The format permits CR, LF or CRLF, but every byte offset //--- we compute depends on knowing which one is in use, so the choice //--- is made once here and never made again. #define PDF_NL "\n" //--- Page sizes in points, where one point is 1/72 inch. A4 is //--- 210 x 297 millimeters, which is 595.276 x 841.890 points. Part 4 //--- introduces fractional sizes and a millimeter helper; Part 3 keeps //--- the rounded values Part 1 typed by hand. #define PDF_A4_WIDTH 595 #define PDF_A4_HEIGHT 842 #define PDF_LETTER_WIDTH 612 #define PDF_LETTER_HEIGHT 792 //--- How many bytes the buffer asks for when it first needs memory, and //--- the smallest amount it grows by afterwards. Both are guesses tuned //--- to a one-page document; a long report reaches the doubling path //--- within a few writes either way. #define PDF_BUFFER_INITIAL 8192 #define PDF_BUFFER_MIN_GROWTH 8192 //--- The generation number written for every object. A file produced in //--- one pass never reuses an object number, so this is always zero. #define PDF_GENERATION 0 //--- The writer stops before this number, so the largest object id it //--- hands out is PDF_MAX_OBJECTS - 1. A long report uses a few thousand; //--- the limit exists so that a runaway loop fails with a message instead //--- of exhausting memory. #define PDF_MAX_OBJECTS 65536 #endif // PDF5_DEFINES_MQH //+-------------------------------------------------------------------+
PDF_NL warrants a brief explanation. Part 1 chose a bare line feed and explained why: the format allows CR, LF or CRLF, and mixing them makes offsets impossible to reason about. Putting the choice in one macro means no file in the library has to make it again. If someone later needs CRLF output, the macro is the only place to change — with one proviso: an xref entry has to stay exactly twenty bytes, and its line ending is one of them, so a CRLF build must also drop the padding space the entry writer puts before it.
Now the class itself:
//+------------------------------------------------------------------+ //| PdfBuffer.mqh | //+------------------------------------------------------------------+ #ifndef PDF5_BUFFER_MQH #define PDF5_BUFFER_MQH #include "PdfDefines.mqh" //+-------------------------------------------------------------------+ //| CPdfBuffer | //+-------------------------------------------------------------------+ class CPdfBuffer { private: uchar m_data[]; int m_length; int m_capacity; bool m_failed; bool Grow(const int needed); public: CPdfBuffer(void) { m_capacity = 0; Clear(); } void Clear(void) { m_length = 0; m_failed = false; } bool Reserve(const int bytes) { return(Grow(bytes - m_length)); } int Length(void) const { return(m_length); } bool Failed(void) const { return(m_failed); } uchar ByteAt(const int index) const; bool PutByte(const uchar value); bool PutText(const string text); bool PutLine(const string text); bool PutInt(const long value); bool PutReal(const double value, const int digits = 3); bool PutPadded(const long value, const int width); bool PutBuffer(CPdfBuffer *other); bool PutArray(const uchar &source[], const int count); bool SaveToFile(const string filename) const; bool CopyTo(uchar &target[]) const; };
Two fields carry the state that matters. m_length is how many bytes are in use; m_capacity is how many the array can hold. They are different numbers on purpose, and the difference is the subject of the next section.
Clear() sets the length to zero and leaves the capacity alone. That looks like an oversight and is the opposite: it makes a buffer cheap to reuse. The text-to-PDF demo below builds forty content streams in the same buffer, and after the first page none of them allocates anything.
Growing
//+------------------------------------------------------------------+ //| Makes room for at least `needed` more bytes. | //+------------------------------------------------------------------+ bool CPdfBuffer::Grow(const int needed) { if(needed <= 0) return(true); if(m_length + needed <= m_capacity) return(true); int wanted = m_capacity * 2; if(wanted < PDF_BUFFER_INITIAL) wanted = PDF_BUFFER_INITIAL; if(wanted < m_length + needed) wanted = m_length + needed + PDF_BUFFER_MIN_GROWTH; //--- The third argument is a reserve: MQL5 keeps that much spare room //--- past the requested size, so the next appends do not resize at all. if(ArrayResize(m_data, wanted, PDF_BUFFER_MIN_GROWTH) != wanted) { Print("CPdfBuffer: out of memory at ", wanted, " bytes"); m_failed = true; return(false); } m_capacity = wanted; return(true); }
The first two lines are the ones that run almost every time: if the bytes already fit, do nothing. The interesting part is what happens when they do not.

Figure 3. Two growth strategies, and the number of reallocations each costs.
Compare the two panels in Figure 3. On the left, the array is resized to exactly what was asked for, every time. Each resize may copy the entire array. With 200,000 small appends, that can mean about 200,000 copies, and the total work grows with the square of the document size. A 40-page report takes minutes.
On the right, capacity doubles. Writing the same document needs about 18 reallocations, because each one buys twice as much room as the last. The total copying is proportional to the final size rather than its square. This is the same reason vectors in standard libraries often double, and it is worth knowing that it is not an optimization but a change of complexity class.
The third argument to ArrayResize has a separate effect. MQL5 keeps that many spare elements past the size you asked for, so a resize to 8192 with a reserve of 8192 actually claims 16384 and the next several thousand appends touch no allocator at all. Passing it costs nothing and removes a whole class of small resizes.
Appending
//+-------------------------------------------------------------------+ //| ByteAt - function | //+-------------------------------------------------------------------+ uchar CPdfBuffer::ByteAt(const int index) const { if(index < 0 || index >= m_length) return(0); return(m_data[index]); } //+-------------------------------------------------------------------+ //| PutByte - function | //+-------------------------------------------------------------------+ bool CPdfBuffer::PutByte(const uchar value) { if(!Grow(1)) return(false); m_data[m_length++] = value; return(true); }
This is the smallest method in the library. It is not a gate that every append passes through — PutText and PutArray write into the array directly, in one pass, for the reasons given below — but all three advance the length the same way. m_length++ after the assignment is the entire bookkeeping: the position advances by exactly what was written.
//+-------------------------------------------------------------------+ //| Appends text, one byte per character. | //+-------------------------------------------------------------------+ bool CPdfBuffer::PutText(const string text) { int n = StringLen(text); if(n == 0) return(true); if(!Grow(n)) return(false); for(int i = 0; i < n; i++) m_data[m_length + i] = (uchar)(StringGetCharacter(text, i) & 0xFF); m_length += n; return(true); }
An MQL5 string is UTF-16 internally, so a character is two bytes in memory and we want one byte in the file. The mask takes the low byte of each character. Everything the library writes as syntax — keywords, names, numbers, operators — is ASCII, so the conversion is exact. For a character above 255 the mask is not an encoding but a truncation, which is why user text in this part has to stay inside ASCII. Part 5 adds the escaping and the encoding that turn arbitrary text into bytes a PDF string may legally contain.
Note that Grow(n) is called once for the whole string rather than once per character. That matters more than it looks: PutText is called for nearly every token in the document, and a per-character bounds check would run tens of millions of times in a long report.
//+-------------------------------------------------------------------+ //| PutLine - function | //+-------------------------------------------------------------------+ bool CPdfBuffer::PutLine(const string text) { return(PutText(text) && PutText(PDF_NL)); } //+-------------------------------------------------------------------+ //| PutInt - function | //+-------------------------------------------------------------------+ bool CPdfBuffer::PutInt(const long value) { return(PutText(IntegerToString(value))); }
Two lines each, and they are why the rest of the library reads the way it does. A PDF is mostly short lines of ASCII, and PutLine is the shape of nearly every statement in CPdfWriter.
Numbers
//+------------------------------------------------------------------+ //| Appends a number with trailing zeros removed. | //+------------------------------------------------------------------+ bool CPdfBuffer::PutReal(const double value, const int digits) { double v = value; if(MathAbs(v) < 0.5 * MathPow(10.0, -digits)) v = 0.0; string s = DoubleToString(v, digits); if(StringFind(s, ".") >= 0) { int last = StringLen(s) - 1; while(last > 0 && StringGetCharacter(s, last) == '0') last--; if(StringGetCharacter(s, last) == '.') last--; s = StringSubstr(s, 0, last + 1); } if(s == "-0") s = "0"; return(PutText(s)); }
This method exists because PDF's number syntax is narrower than MQL5's output. Three separate hazards are handled here, and skipping any of them produces a file that some viewers reject.
PDF has no exponent notation.1e-05 is not a number in this format, it is a syntax error. Any value small enough for DoubleToString to render that way is far below the resolution of a printed page, so it is clamped to zero rather than written. The threshold follows digits, which the library's own callers always pass as a small positive count.
Trailing zeros are wasted bytes.12.000 and 12 place the pen in the same spot, and the second is four bytes shorter. A content stream for a page of graphics contains tens of thousands of numbers, so trimming them is worth several percent of the file before any compression is applied.
Negative zero is legal and pointless.-0 appears whenever a coordinate rounds down from a very small negative value. It is valid, and it makes a reader looking at the stream wonder what it means.
//+-------------------------------------------------------------------+ //| Appends an integer padded with leading zeros. | //+-------------------------------------------------------------------+ bool CPdfBuffer::PutPadded(const long value, const int width) { string s = IntegerToString(value); for(int i = StringLen(s); i < width; i++) if(!PutByte('0')) return(false); return(PutText(s)); }
One caller, and it is the reason Part 2 exists. An xref entry is ten digits of offset, a space, five digits of generation, a space, a flag and a line ending — twenty bytes, always, because a viewer indexes the table rather than reading it. PutPadded is what produces the leading zeros that make the width fixed. The field holds ten digits, while offsets, lengths and capacities are int throughout this part, so a document is capped at two gigabytes long before that width could overflow; widening the type is a change a later part can make without touching the format.
Moving bytes about
//+-------------------------------------------------------------------+ //| Appends the contents of another buffer. | //+-------------------------------------------------------------------+ bool CPdfBuffer::PutBuffer(CPdfBuffer *other) { if(CheckPointer(other) == POINTER_INVALID) return(false); int n = other.Length(); if(n <= 0) return(true); if(!Grow(n)) return(false); for(int i = 0; i < n; i++) m_data[m_length + i] = other.ByteAt(i); m_length += n; return(true); }
This is how a content stream that was built separately gets poured into the document. The parameter is a pointer rather than a reference because MQL5 will be handed the result of GetPointer(), and because the null check then costs one line and catches a caller that forgot to build anything.
//+-------------------------------------------------------------------+ //| PutArray - function | //+-------------------------------------------------------------------+ bool CPdfBuffer::PutArray(const uchar &source[], const int count) { int n = MathMin(count, ArraySize(source)); if(n <= 0) return(true); if(!Grow(n)) return(false); ArrayCopy(m_data, source, m_length, 0, n); m_length += n; return(true); } //+-------------------------------------------------------------------+ //| CopyTo - function | //+-------------------------------------------------------------------+ bool CPdfBuffer::CopyTo(uchar &target[]) const { if(ArrayResize(target, m_length) != m_length) return(false); if(m_length > 0) ArrayCopy(target, m_data, 0, 0, m_length); return(true); }
PutArray takes bytes that already exist as an array — ArrayCopy moves them in one call. Nothing in this part uses it. It is here because the alternative is changing this class later, once other files depend on its interface, and the method that will call it is the one that embeds image pixels.
Writing the file
//+-------------------------------------------------------------------+ //| Writes the used bytes to MQL5\Files. | //| | //| FileWriteArray is given an explicit count because the array is | //| larger than the document: the doubling in Grow() leaves unused | //| capacity that would otherwise be appended after %%EOF. | //+-------------------------------------------------------------------+ bool CPdfBuffer::SaveToFile(const string filename) const { int cut = StringLen(filename) - 1; while(cut >= 0) { ushort ch = StringGetCharacter(filename, cut); if(ch == "\\" || ch == "/") break; cut--; } if(cut > 0) { FolderCreate(StringSubstr(filename, 0, cut), 0); ResetLastError(); } int handle = FileOpen(filename, FILE_WRITE | FILE_BIN); if(handle == INVALID_HANDLE) { PrintFormat("CPdfBuffer: cannot write %s, error %d", filename, GetLastError()); return(false); } uint written = FileWriteArray(handle, m_data, 0, m_length); FileClose(handle); if(written != (uint)m_length) { PrintFormat("CPdfBuffer: wrote %u of %d bytes to %s", written, m_length, filename); return(false); } return(true); } #endif // PDF5_BUFFER_MQH
Three things here are load-bearing.
FileWriteArray is given an explicit count. This is not defensive style — it is required. The array is larger than the document, because Grow() left unused capacity at the end, and writing the whole array would append several kilobytes of zeros after %%EOF. Part 2's validator would not complain, because the structure is fine; the file would simply be wrong in a way nobody notices until a strict consumer rejects it.
FILE_BIN without FILE_ANSI is correct here, unlike in Part 1. Part 1 wrote a string and needed FILE_ANSI to stop MQL5 turning it into UTF-16. We are writing a uchar array, which has no encoding to get wrong.
The folder handling at the top is small but changes how the library is used. Passing "Part03\\text.pdf" puts the output in a subfolder of MQL5\Files instead of adding to the pile at the top level, and FolderCreate makes the folder if it is missing.
CPdfWriter: objects, and where they landed
The writer holds a buffer, a table of offsets, and three pieces of state:
//+-------------------------------------------------------------------+ //| CPdfWriter | //+-------------------------------------------------------------------+ class CPdfWriter { private: CPdfBuffer m_out; int m_offset[]; int m_count; int m_open; bool m_failed; bool m_finished; void Fail(const string reason); public: CPdfWriter(void) { Reset(); } void Reset(void); bool Begin(void); bool Finish(const int root_id, const int info_id = -1); bool Save(const string filename); int NewObjectId(void); int ObjectCount(void) const { return(m_count - 1); } int OffsetOf(const int id) const; bool BeginObject(const int id); bool EndObject(void); bool WriteDictionary(const int id, const string dictionary); bool WriteStream(const int id, CPdfBuffer *content, const string extra_keys = ""); bool WriteRawStream(const int id, const uchar &bytes[], const int count, const string extra_keys = ""); bool Failed(void) const { return(m_failed); } int Length(void) const { return(m_out.Length()); } };
m_offset is indexed by object number, which is why the next method starts counting at one.
//+-------------------------------------------------------------------+ //| Reset - function | //+-------------------------------------------------------------------+ void CPdfWriter::Reset(void) { m_out.Clear(); ArrayResize(m_offset, 1); //--- Object numbering starts at 1. Slot 0 is never a real object; it //--- stands for the free-list head that every xref table begins with. m_offset[0] = 0; m_count = 1; m_open = -1; m_failed = false; m_finished = false; }
Reserving slot 0 for something that is not an object looks wasteful and saves trouble everywhere else. Part 2 explained that entry zero of every xref table is 0000000000 65535 f, the head of the list of deleted objects. Keeping the array aligned with object numbers means m_offset[5] is object 5, with no arithmetic in between and no chance of an off-by-one in the loop that writes the table.
Failing once
//+-------------------------------------------------------------------+ //| Records the first failure; later calls are ignored. | //+-------------------------------------------------------------------+ void CPdfWriter::Fail(const string reason) { if(m_failed) return; m_failed = true; Print("CPdfWriter: ", reason); }
Every append in this class could fail if memory runs out. Testing each one would treble the size of the code for a case that essentially never happens, and the result would be harder to read and therefore more likely to contain a real bug.
The alternative used here is to remember the first failure, keep going, and refuse at the end. The buffer does the same for its own appends: Grow() sets a flag that Finish() reads, so an append that ran out of memory cannot slip past Save() unnoticed. A caller using CPdfBuffer on its own has to ask Failed() itself, because SaveToFile writes whatever is in the array. It also gives better diagnostics: the first message is the cause, and the twenty that would follow it are consequences. Printing only the first is more useful than printing all of them.
Starting the file
//+-------------------------------------------------------------------+ //| Begin - function | //+-------------------------------------------------------------------+ bool CPdfWriter::Begin(void) { Reset(); m_out.PutLine("%PDF-" + PDF_VERSION); //--- A comment line of four bytes above 127. It has no meaning to a //--- reader, and its only job is to make file transfer tools treat the //--- document as binary rather than text, which stops them from //--- rewriting line endings and destroying every offset in the file. m_out.PutByte('%'); m_out.PutByte(0xE2); m_out.PutByte(0xE3); m_out.PutByte(0xCF); m_out.PutByte(0xD3); m_out.PutText(PDF_NL); return(!m_failed); }
The second line is new, and Part 1's hand-written file did not have it. It is a PDF comment — anything after % to the end of the line is ignored — whose contents are four bytes with the high bit set.
The reason is historical and still relevant. Some file-transfer tools have a text mode that converts line endings. A program that guesses the mode from the first few hundred bytes may see only ASCII in a PDF header and choose incorrectly. Converting \n to \r\n adds one byte per line, which makes every offset in the file too small, and produces exactly the damage Part 2 spent an article on. Four high bytes near the top make every such tool classify the file as binary and leave it alone.
The specification recommends this. Almost every generator does it. It also means our output will differ from Part 1's file by six bytes, which turns out to be a useful thing to be able to see.
Numbers before objects
//+-------------------------------------------------------------------+ //| Reserves the next object number. | //+-------------------------------------------------------------------+ int CPdfWriter::NewObjectId(void) { if(m_count >= PDF_MAX_OBJECTS) { Fail("too many objects"); return(-1); } if(ArrayResize(m_offset, m_count + 1) != m_count + 1) { Fail("cannot grow the offset table"); return(-1); } m_offset[m_count] = -1; // allocated, not yet written return(m_count++); }

Figure 4. Object numbers are handed out before any object is written.
Read Figure 4 in two rows. The top row reserves five numbers; nothing has been written. The bottom row writes the objects, and object 1 refers to object 2 before object 2 exists.
That is not a trick, it is the reason PDF references objects by number at all. If a page contained its content stream, the file would have to be built inside-out — deepest object first — and a document with cross-references in both directions could not be built at all. Because references are numbers, the file can be assembled in whatever order is convenient, and the only thing that has to be true at the end is that every promised number was written.
The sentinel value is what enforces that. -1 means "allocated but not written", and Finish() checks for it.
The line the class exists for
//+-------------------------------------------------------------------+ //| Opens an object and records where it starts. | //+-------------------------------------------------------------------+ bool CPdfWriter::BeginObject(const int id) { if(id < 1 || id >= m_count) { Fail(StringFormat("object id %d was never allocated", id)); return(false); } if(m_offset[id] >= 0) { Fail(StringFormat("object %d is being written twice", id)); return(false); } if(m_open >= 0) { Fail(StringFormat("object %d was not closed before %d opened", m_open, id)); return(false); } m_offset[id] = m_out.Length(); m_open = id; m_out.PutInt(id); m_out.PutText(" "); m_out.PutInt(PDF_GENERATION); m_out.PutLine(" obj"); return(true); }
Three guards and then the line this entire article is about:
m_offset[id] = m_out.Length();
The position is never predicted by a caller and never maintained by hand. Length() is itself a running count of the bytes written, so the offset is derived from the state of the buffer at the instant the object begins rather than from anybody's arithmetic. Insert a paragraph, change a font, compress a stream — everything below moves, and this line records where things actually went rather than where somebody expected them to go.
The three guards catch the three ways a caller can misuse the class, and each one names the object involved. object 4 is being written twice is a five-second fix; discovering the same mistake from a corrupted xref table is an afternoon.
//+-------------------------------------------------------------------+ //| EndObject - function | //+-------------------------------------------------------------------+ bool CPdfWriter::EndObject(void) { if(m_open < 0) { Fail("EndObject without BeginObject"); return(false); } m_out.PutLine("endobj"); m_open = -1; return(true); }
m_open exists only so that these two methods can be checked against each other. Forgetting EndObject would nest one object inside another, which no viewer would forgive and no error message would explain.
The two shapes an object takes
//+-------------------------------------------------------------------+ //| WriteDictionary - function | //+-------------------------------------------------------------------+ bool CPdfWriter::WriteDictionary(const int id, const string dictionary) { if(!BeginObject(id)) return(false); m_out.PutLine(dictionary); return(EndObject()); }
Almost every object in a PDF is a dictionary, and at this stage of the library the caller supplies it as text, brackets included. That is deliberately crude — a later part replaces it with a dictionary class that builds the text from typed keys — but it keeps this article about offsets rather than about syntax, and it lets the demo reproduce Part 1's file line for line.
The other shape is the one that removes Part 1's hard-coded 43:
//+-------------------------------------------------------------------+ //| Writes an object whose value is a stream. | //+-------------------------------------------------------------------+ bool CPdfWriter::WriteStream(const int id, CPdfBuffer *content, const string extra_keys) { if(CheckPointer(content) == POINTER_INVALID) { Fail(StringFormat("object %d was given no content", id)); return(false); } if(!BeginObject(id)) return(false); m_out.PutText("<< /Length "); m_out.PutInt(content.Length()); if(extra_keys != "") { m_out.PutText(" "); m_out.PutText(extra_keys); } m_out.PutLine(" >>"); m_out.PutLine("stream"); m_out.PutBuffer(content); m_out.PutText(PDF_NL); m_out.PutLine("endstream"); return(EndObject()); }

Figure 5. The content is built and measured before the dictionary is written.
Figure 5 shows the ordering problem and its solution side by side. A stream's dictionary comes before its data in the file and has to state the size of data that has not been written yet. Part 1 solved this by counting characters. Here the content lives in its own buffer, so by the time the dictionary is written the answer is content.Length() — a number nobody typed and nobody can get wrong.
The PutText(PDF_NL) after the content is a small point that Part 2 spent time on. The specification allows an end-of-line between the stream data and the keyword endstream which is not counted in /Length. Writing it makes the file agree with what most generators produce, and Part 2's stream check accepts either form precisely because both are legal.
extra_keys is an opening for later parts. A compressed stream needs /Filter /FlateDecode in the same dictionary, and an image needs half a dozen keys; passing them as text means neither of those parts has to change this method. What that flexibility costs is checking: the dictionary and the extra keys go into the file as text, so the writer counts the bytes for you but does not validate PDF syntax, and a duplicated /Length or an unbalanced >> stays the caller's responsibility.
//+-------------------------------------------------------------------+ //| The same, for content that already exists as a byte array. | //| | //| Image pixels and compressed blocks arrive this way. | //+-------------------------------------------------------------------+ bool CPdfWriter::WriteRawStream(const int id, const uchar &bytes[], const int count, const string extra_keys) { //--- /Length has to equal the bytes that actually follow it, and PutArray //--- copies no more than the array holds. The count is clamped here, and //--- a caller who asked for more is told about it instead of being handed //--- a stream whose length is a lie. int n = (count < 0) ? 0 : MathMin(count, ArraySize(bytes)); if(n != count) Fail(StringFormat("object %d: /Length %d was asked for, %d bytes exist", id, count, n)); if(!BeginObject(id)) return(false); m_out.PutText("<< /Length "); m_out.PutInt(n); if(extra_keys != "") { m_out.PutText(" "); m_out.PutText(extra_keys); } m_out.PutLine(" >>"); m_out.PutLine("stream"); m_out.PutArray(bytes, n); m_out.PutText(PDF_NL); m_out.PutLine("endstream"); return(EndObject()); }
The same method for content that is already a byte array rather than a buffer. Image pixels and compressed blocks arrive that way. count is the one length in the whole class that a caller supplies, so it is clamped to the size of the array before it becomes /Length: asking for more bytes than exist produces a message, not a stream whose header lies about its size. The object itself is still written, with the clamped length, so the file stays well formed; refusing it is Save()'s job.
Finishing
//+-------------------------------------------------------------------+ //| Writes the cross-reference table, the trailer and %%EOF. | //+-------------------------------------------------------------------+ bool CPdfWriter::Finish(const int root_id, const int info_id) { if(m_finished) { Fail("Finish was already called for this document"); return(false); } if(m_open >= 0) { Fail(StringFormat("object %d is still open", m_open)); return(false); } if(root_id < 1 || root_id >= m_count) { Fail(StringFormat("root object %d was never allocated", root_id)); return(false); } //--- /Info is optional, but a reference to it is a promise like any other if(info_id > 0 && info_id >= m_count) { Fail(StringFormat("info object %d was never allocated", info_id)); return(false); } //--- Every allocated id must have been written, or the table would //--- promise an object that is not in the file. Catching it here names //--- the object that was forgotten. for(int i = 1; i < m_count; i++) if(m_offset[i] < 0) { Fail(StringFormat("object %d was allocated but never written", i)); return(false); }
That loop is the payoff for the -1 sentinel. Without it, forgetting to write one object produces an xref entry of 0000000000, which points at the file header; the viewer would find %PDF-1.4 where it expected an object and fall back on repair mode. The message here names the number instead.
//--- The position of the word "xref" is what startxref must carry, and //--- it is observed for the same reason every other offset is. int xref_at = m_out.Length(); m_out.PutLine("xref"); m_out.PutText("0 "); m_out.PutInt(m_count); m_out.PutText(PDF_NL); //--- Entry 0 heads the list of free objects. Generation 65535 is the //--- largest the field holds and never changes. m_out.PutPadded(0, 10); m_out.PutText(" 65535 f "); m_out.PutText(PDF_NL); //--- Ten digits, space, five digits, space, flag, space, line ending: //--- twenty bytes, which is what lets a viewer jump to entry i instead //--- of reading the i-1 entries above it. for(int i = 1; i < m_count; i++) { m_out.PutPadded(m_offset[i], 10); m_out.PutText(" "); m_out.PutPadded(PDF_GENERATION, 5); m_out.PutText(" n "); m_out.PutText(PDF_NL); }
Compare this loop with Part 2's hello_space.pdf, the file whose entries were nineteen bytes because a trailing space had been tidied away. Here the space is inside a string literal, written once, in one place, by a loop that cannot produce a different width for different entries. The bug Part 2 demonstrated is now impossible to introduce by editing text, which is a better outcome than being able to detect it.
m_out.PutLine("trailer"); m_out.PutText("<< /Size "); m_out.PutInt(m_count); m_out.PutText(" /Root "); m_out.PutInt(root_id); m_out.PutText(" 0 R"); if(info_id > 0) { m_out.PutText(" /Info "); m_out.PutInt(info_id); m_out.PutText(" 0 R"); } m_out.PutLine(" >>"); m_out.PutLine("startxref"); m_out.PutInt(xref_at); m_out.PutText(PDF_NL); m_out.PutLine("%%EOF"); m_finished = true; //--- The appends above are not tested one by one. The buffer remembers //--- instead, and this is where that memory is read: if any of them ran //--- out of memory, the document is short and must not be saved. if(m_out.Failed()) Fail("the buffer ran out of memory while the file was being built"); return(!m_failed); }
/Size is m_count, which is the number of objects plus the free entry — exactly the number of rows the table just wrote, because both come from the same variable. /Info is optional and unused until metadata arrives in a later part; the parameter is here so that adding it does not change this method's signature once other code calls it.
//+-------------------------------------------------------------------+ //| Save - function | //+-------------------------------------------------------------------+ bool CPdfWriter::Save(const string filename) { if(!m_finished) { Print("CPdfWriter: refusing to save before Finish() wrote the xref"); return(false); } if(m_failed || m_out.Failed()) { Print("CPdfWriter: refusing to save a document that failed to build"); return(false); } return(m_out.SaveToFile(filename)); } #endif // PDF5_WRITER_MQH //+------------------------------------------------------------------+
Refusing is the right behavior. A half-built PDF that opens in one viewer and fails in another is worse than no file, because it will be discovered by somebody else, later, with no log to look at.
The demo, and what it proves
Demo03_HelloWriter.mq5 rebuilds Part 1's file:
//+-------------------------------------------------------------------+ //| Script entry point. | //+-------------------------------------------------------------------+ void OnStart(void) { CPdfWriter writer; writer.Begin(); //--- All five object numbers are reserved first. The catalog has to //--- name the page tree before the page tree exists, so the numbers //--- must be available before any object is written. int id_catalog = writer.NewObjectId(); int id_pages = writer.NewObjectId(); int id_page = writer.NewObjectId(); int id_content = writer.NewObjectId(); int id_font = writer.NewObjectId(); //--- Object 1: the catalog. writer.WriteDictionary(id_catalog, "<< /Type /Catalog /Pages " + IntegerToString(id_pages) + " 0 R >>"); //--- Object 2: the page tree. writer.WriteDictionary(id_pages, "<< /Type /Pages /Kids [" + IntegerToString(id_page) + " 0 R] /Count 1 >>");
Every reference is built from a variable rather than a literal. Renumbering the document — inserting a page, adding a font — changes the ids and nothing else, which is the second half of the same principle the offsets follow.
//--- Object 3: the page. Every reference is built from an id we were //--- given, so renumbering the document changes nothing here. writer.WriteDictionary(id_page, "<< /Type /Page /Parent " + IntegerToString(id_pages) + " 0 R /MediaBox [0 0 " + IntegerToString(PDF_A4_WIDTH) + " " + IntegerToString(PDF_A4_HEIGHT) + "]" + PDF_NL + " /Resources << /Font << /F1 " + IntegerToString(id_font) + " 0 R >> >>" + PDF_NL + " /Contents " + IntegerToString(id_content) + " 0 R >>");
The embedded PDF_NL values reproduce Part 1's three-line layout of that dictionary. PDF does not care — whitespace between tokens is whitespace — and keeping the shape makes the two files directly comparable.
//--- Object 4: the content stream. //--- //--- The drawing commands are built in their own buffer. That is what //--- lets WriteStream determine /Length: by the time the dictionary is //--- written, the content already exists and can be measured. Part 1 //--- had to count those 43 bytes by hand. CPdfBuffer content; content.PutLine("BT"); content.PutLine("/F1 36 Tf"); content.PutLine("72 720 Td"); content.PutLine("(Hello, PDF!) Tj"); content.PutLine("ET"); writer.WriteStream(id_content, GetPointer(content)); //--- Object 5: the font. writer.WriteDictionary(id_font, "<< /Type /Font /Subtype /Type1" " /BaseFont /Helvetica >>"); //--- The xref table and the trailer are written from the offsets the //--- writer recorded as it went. writer.Finish(id_catalog);
Change Hello, PDF! to Hello, world! in that block and run it again. In Part 1 that edit produced two false numbers and a file that only opened because viewers are forgiving. Here it produces a correct file, because /Length is measured and every offset below the stream is observed after the change rather than before it.
if(!writer.Save(path_folder + InpFileName)) return; PrintFormat("%s: %d bytes, %d objects", path_folder + InpFileName, writer.Length(), writer.ObjectCount()); //--- What the writer observed, printed so it can be compared against //--- the numbers Part 1 counted by hand. Print("byte offsets the writer recorded:"); for(int i = 1; i <= writer.ObjectCount(); i++) PrintFormat(" object %d starts at byte %d", i, writer.OffsetOf(i)); //--- And the check that matters: Part 2's validator, run on our own //--- output. A generator that cannot pass its own structural test is //--- not finished. Print(""); CPdfValidator validator; validator.Check(path_folder + InpFileName); validator.PrintReport(path_folder + InpFileName); } //+------------------------------------------------------------------+
Running it prints:
MQLPDF\Part03\hello_generated.pdf: 599 bytes, 5 objects
byte offsets the writer recorded:
object 1 starts at byte 15
object 2 starts at byte 64
object 3 starts at byte 121
object 4 starts at byte 253
object 5 starts at byte 346
--- MQLPDF\Part03\hello_generated.pdf: 599 bytes, 5 objects found by scanning
no problems no problems is Part 2's validator, run by the generator on its own output. It is worth doing this in every part of the series: the test costs three lines and catches structural mistakes at the moment they are introduced rather than three articles later. It checks structure, not appearance: a file can pass every one of its tests and still draw a blank page.
Now compare the numbers with the ones Part 1 counted.

Figure 6. Every offset moved, and nobody recalculated anything.
Read the difference column of Figure 6. Objects 1 to 4 moved by exactly +6, which is the six bytes of the binary marker comment Begin() writes after the header. Object 5 and the xref table moved by +7 — the same six bytes, plus the one newline WriteStream puts in front of endstream.
Nobody worked those numbers out. They are what the buffer reported. That is the whole argument of this part in one table: the file changed in two places, six offsets changed as a result, and the source code that produced them contains no number that had to be revised.
The take-away tool
Demo03_TextToPdf.mq5 is the part you can use for something. It reads a text file from MQL5\Files and prints it, or — with no file name — prints a summary of the current account, which is what Figure 1 shows.
The parts worth reading are the geometry and the page loop. First, how many lines fit:
//+-------------------------------------------------------------------+ //| Script entry point. | //+-------------------------------------------------------------------+ void OnStart(void) { //--- 1. Get the text string text = ""; if(InpSource != "") { if(!ReadTextFile(path_folder + InpSource, text)) return; } else text = AccountSummary(); //--- 2. Work out the page geometry double leading = InpFontSize * 1.35; double usable_w = PDF_A4_WIDTH - InpMargin * 2.0; double usable_h = PDF_A4_HEIGHT - InpMargin * 2.0; int max_chars = (int)MathFloor(usable_w / (InpFontSize * 0.6)); int per_page = (int)MathFloor(usable_h / leading) - 1; // room for a footer if(per_page < 1) per_page = 1;
InpFontSize * 0.6 is the only reason this demo can wrap text at all. Courier is monospaced and every glyph in it advances 600 units out of 1000, so the width of a line is its character count times 0.6 times the font size, and the number of characters that fit is a division. A proportional font has no such formula — you have to add up the width of every glyph — which is why this demo is set in Courier and why Part 6 is entirely about measuring text properly. The demo also trusts its inputs: a font size of zero or a margin wider than the sheet produces a structurally valid PDF with unusable geometry rather than an error message.
string lines[]; int line_count = SplitLines(text, max_chars, lines); int page_count = (line_count + per_page - 1) / per_page; if(page_count < 1) page_count = 1; PrintFormat("%d lines, %d per page, %d pages", line_count, per_page, page_count);
The rounding-up division is the standard idiom: adding per_page - 1 before dividing turns a truncating division into a ceiling, so 47 lines at 46 per page gives two pages rather than one.
//--- 3. Reserve the object numbers //--- //--- Two objects per page, plus the catalog, the page tree and the //--- font. Reserving them up front is what lets the page tree list //--- pages that have not been written yet. CPdfWriter writer; writer.Begin(); int id_catalog = writer.NewObjectId(); int id_pages = writer.NewObjectId(); int id_font = writer.NewObjectId(); int id_page[]; int id_content[]; ArrayResize(id_page, page_count); ArrayResize(id_content, page_count); for(int p = 0; p < page_count; p++) { id_page[p] = writer.NewObjectId(); id_content[p] = writer.NewObjectId(); }
Two objects per page, all reserved before any is written, because the page tree below has to list every page.
//--- 4. The catalog and the page tree writer.WriteDictionary(id_catalog, "<< /Type /Catalog /Pages " + IntegerToString(id_pages) + " 0 R >>"); string kids = ""; for(int p = 0; p < page_count; p++) { if(p > 0) kids += " "; kids += IntegerToString(id_page[p]) + " 0 R"; } //--- /MediaBox and /Resources are put on the page tree node rather //--- than on each page. Both are inheritable attributes, so every page //--- below the node sees them, and a 40-page document carries one copy //--- of each instead of forty. writer.WriteDictionary(id_pages, "<< /Type /Pages /Kids [" + kids + "] /Count " + IntegerToString(page_count) + " /MediaBox [0 0 " + IntegerToString(PDF_A4_WIDTH) + " " + IntegerToString(PDF_A4_HEIGHT) + "]" + " /Resources << /Font << /F1 " + IntegerToString(id_font) + " 0 R >> >> >>");
Inheritance is worth knowing about now because the library relies on it from here on. A handful of page attributes — the media box, the resources, the rotation — can be set on any node of the page tree and apply to everything below it. Setting them once at the root is both smaller and easier to keep consistent than repeating them per page.
//--- 5. One page and one content stream per screenful CPdfBuffer content; for(int p = 0; p < page_count; p++) { writer.WriteDictionary(id_page[p], "<< /Type /Page /Parent " + IntegerToString(id_pages) + " 0 R /Contents " + IntegerToString(id_content[p]) + " 0 R >>"); //--- The same buffer is reused for every page. Clear() keeps the //--- memory it already allocated, so page forty costs no more //--- allocations than page two. content.Clear(); content.PutLine("BT"); content.PutText("/F1 "); content.PutReal(InpFontSize); content.PutLine(" Tf");
A page dictionary of two keys, because everything else was inherited. Then the content, in a buffer that is cleared rather than recreated.
//--- TL sets the line spacing once; T* then moves down by it. //--- That is two bytes per line instead of a fresh Td with two //--- coordinates, which on a 60-line page is worth having. content.PutReal(leading); content.PutLine(" TL"); content.PutReal(InpMargin); content.PutText(" "); content.PutReal(PDF_A4_HEIGHT - InpMargin); content.PutLine(" Td"); int first = p * per_page; int last = MathMin(first + per_page, line_count); for(int i = first; i < last; i++) { content.PutText("("); content.PutText(EscapePdf(lines[i])); content.PutLine(") Tj"); content.PutLine("T*"); } content.PutLine("ET");
Two new text operators appear here. TL sets the leading — the distance between baselines — and T* moves the pen down by it and back to the left edge. Part 1 moved the pen with an explicit 0 -18 Td on every row; T* is the same idea with the distance stated once, and on a sixty-line page it saves about four hundred bytes.
//--- A footer, positioned from the bottom of the sheet. content.PutLine("BT"); content.PutLine("/F1 8 Tf"); content.PutReal(InpMargin); content.PutText(" "); content.PutReal(InpMargin * 0.5); content.PutLine(" Td"); content.PutText("(page "); content.PutInt(p + 1); content.PutText(" of "); content.PutInt(page_count); content.PutLine(") Tj"); content.PutLine("ET"); writer.WriteStream(id_content[p], GetPointer(content)); }
The footer uses its own BT/ET pair because the text matrix resets at each BT. This lets us position it absolutely without disturbing the block above. page 2 of 7 is easy here only because the page count was known before any page was written — a luxury that disappears as soon as pages break automatically, which is a problem a later part has to solve properly.
The escaping is minimal and honest about it:
//+-------------------------------------------------------------------+ //| Escapes the three characters that have meaning inside a PDF | //| string: the two brackets and the backslash. | //+-------------------------------------------------------------------+ string EscapePdf(const string text) { string out = text; StringReplace(out, "\\", "\\\\"); StringReplace(out, "(", "\\("); StringReplace(out, ")", "\\)"); return(out); }
Three characters have meaning inside a PDF literal string: the two brackets and the backslash. The backslash is replaced first, on purpose — doing it after the brackets would escape the backslashes that the bracket replacements just added, and every ( in the input would come out as \\(, which prints a literal backslash and breaks the string. Those three are all it escapes. Control characters and anything above ASCII 126 need an encoding decision this part has not made, so Part 5 replaces this function.
When it goes wrong
refusing to save a document that failed to build. Something above it printed the real reason. Scroll up in the Experts log for the first CPdfWriter: line; the rest are consequences.
object N was allocated but never written. A NewObjectId() call has no matching write. Usually a branch that returns early, or an object reserved for a feature that was later removed.
The file opens but the page is blank. The structure is fine and the drawing is not, so the validator reports nothing — this is the split Part 2 warned about. Check that the content stream names a font that the resources actually declare: /F1 36 Tf with no /F1 in /Resources draws nothing and reports nothing.
The offsets in the log look plausible but the validator disagrees. Something wrote to m_out outside BeginObject and EndObject. The PutText and PutLine passthroughs on the writer make that easy to do by accident; they exist for writing inside an open object, not between objects.
The cheat card

Figure 7. The seven calls a document is built from, and the rule behind them.
Seven calls, and none of them takes a byte position:
- Begin() writes the %PDF- header and the binary marker comment, and puts the writer in the state where objects may be written.
- NewObjectId() reserves the next object number and returns it. Nothing is written to the file, which is exactly why a reference can be made before its target exists.
- WriteDictionary(id, text) writes one id 0 obj ... endobj around a dictionary you supply, recording where it landed as it opens.
- WriteStream(id, buffer) does the same for a stream, and takes the /Length from the buffer rather than from the caller.
- Finish(root) writes the cross-reference table from the recorded positions, then the trailer, then startxref and %%EOF. It is also where an id that was reserved and never written is caught.
- Save(name) writes the accumulated bytes into MQL5\Files.
- OffsetOf(id) reports where an object actually ended up, which is what the demo compares against Part 1's hand-counted numbers.
The line under the card is the whole part in four words. Not one of the seven takes a byte offset, and none of them takes a length. The single method that does take one, WriteRawStream, clamps it to the bytes that really exist before it becomes /Length. The class carries a few more members — WriteRawStream, ObjectCount, OffsetOf, Length, Failed — but these seven are what a document is built from. That is the difference between a format that is hard and a format that is merely detailed.
Project structure
MQL5/ ├── Scripts/ │ └── MQLPDF/ │ └── Part 03/ │ ├── Demo03_HelloWriter.mq5 // rebuilds Part 1's file, then validates it │ └── Demo03_TextToPdf.mq5 // prints any text file to a paginated PDF │ └── Include/ │ └── MQLPDF/ │ ├── PdfDefines.mqh // Part 3 - shared constants │ ├── PdfBuffer.mqh // Part 3 - bytes, and the current offset │ ├── PdfWriter.mqh // Part 3 - objects, the xref table, the trailer │ └── PdfValidate.mqh // Part 2 - carried over unchanged └── Files/ └── MQLPDF/ └── Part 03/ ├── hello_generated.pdf // (output file) ├── text.pdf // (output file) └── sample_text.txt // (input file)
| # | File | Directory | Holds |
|---|---|---|---|
| 1 | PdfValidate.mqh | MQL5/Include/MQLPDF/ | To check the validation of PDF file and list the problems |
| 2 | PdfDefines.mqh | MQL5/Include/MQLPDF/ | shared constants for the MQLPDF library |
| 3 | PdfBuffer.mqh | MQL5/Include/MQLPDF/ | class and functions to handles bytes, and the current offset |
| 4 | PdfWriter.mqh | MQL5/Include/MQLPDF/ | class and functions to write objects, the xref table, the trailer |
| 5 | Demo03_HelloWriter.mq5 | MQL5/Scripts/MQLPDF/Part 03/ | rebuilds Part 1's file, then validates it |
| 6 | Demo03_TextToPdf.mq5 | MQL5/Scripts/MQLPDF/Part 03/ | prints an ASCII text file to a paginated PDF |
| 7 | sample_text.txt | MQL5/Files/MQLPDF/Part 03/ | sample text file to copy its content in the pdf file |
| 8 | MQLPDF Library - Part 03.zip | archive containing all the attached files and their paths relative to the terminal's root folder. |
Unzip into MQL5\Scripts\, MQL5\Include\ and MQL5\Files\, then compile both scripts. Output appears in MQL5\Files\MQLPDF\Part 03\.
Conclusion
Applying the rule never compute a byte offset — observe it leaves two practical building blocks. CPdfBuffer owns the bytes and answers Length(), which is the current byte position by definition. CPdfWriter allocates object ids, records where each object actually landed at BeginObject(), and writes the cross-reference table, the trailer and startxref from those observed values. The result is not only less pain while editing; it is a small API and a set of invariants you can rely on.
What you get now
- A compact, usable API — Begin(), NewObjectId(), WriteDictionary(), WriteStream(), WriteRawStream(), Finish(), Save() and OffsetOf() — in which no call takes a byte offset or a stream length as a literal.
- /Length is measured from the content buffer, every xref entry is written from a recorded offset, and startxref is the buffer length at the moment the table starts.
- The writer refuses to Save() until Finish() has written a consistent table and nothing in the build has failed, and an id that was reserved but never written is named at Finish() instead of becoming a zero offset.
- A ready tool: a script that turns an ASCII text file, or the state of the account, into a paginated PDF with page numbering and a basic layout.
What remains manual
- PDF syntax is still assembled as text. Dictionary keys, resource names and string escaping are the caller's business here, and this part escapes only the two parentheses and the backslash. Arbitrary text encodings, proportional font metrics and drawing primitives come in later parts.
In short, the byte-level bookkeeping is now derived from the bytes actually written, which removes a whole class of fragile, hand-counted bugs. What you have is a small, testable generator that validates its own structure — the demo runs Part 2's validator on its own output, a check on the structure and not on the appearance — and a script you can use immediately.
What the library still cannot do is draw. Everything on the page so far has been text placed with the four operators Part 1 introduced, on an A4 sheet whose origin is in the bottom-left corner where nobody expects it, in the one color PDF assumes when you do not choose one.
The next part fixes all three. We put a sane coordinate system on the page — top-left origin, y downward, millimeters if you want them — with a single transformation rather than by flipping every value. Then the path model: m, l, c, re for building shapes, S, f and B for painting them, the difference between the two winding rules, line widths, caps, joins and dashes. Colors arrive as a type rather than three loose numbers. The demo is a letterhead: a colored header band, a rule, a framed footer, and rounded corners drawn with the Bezier constant we derive on the way past.
The project is supported on MQL5 Algo Forge. Each part of this series has its own release, frozen at exactly the code that part explains, so whichever article you are reading, its release is the one to download.
Part 3 is here: https://forge.mql5.io/SandroBegashvil/MQLPDF/releases/tag/part-03
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.