MQLPDF/MQL5/Scripts/MQLPDF/Part 03/Demo03_TextToPdf.mq5
sandrobegashvil sandrobegashvil 656eb86e01
2026-09-30 09:34:05 +04:00
//+------------------------------------------------------------------+
//| Demo03_TextToPdf.mq5 |
//| Copyright 2026, Sandro Begashvili |
//| https://www.mql5.com/en/users/sandrobegashvil |
//| Telegram: https://t.me/MrMQL5Developer |
//| Building a PDF Creation Library in MQL5 |
//| |
//| |
//| The take-away tool: turns any text into a paginated PDF. |
//| |
//| Point it at a file in MQL5\Files -- a log, a settings dump, a |
//| of optimization results -- or leave the name empty and it prin |
//| a summary of the current account instead. |
//| |
//| It is worth noticing how little the writer had to gain to make |
//| this possible. Part 1 could not have produced a two-page docum |
//| at all, because the offsets of everything on page two depend o |
//| how much text landed on page one. |
//| |
//| Output: MQL5\Files\MQLPDF\Part03\text.pdf |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Sandro Begashvili"
#property link "https://www.mql5.com/en/users/sandrobegashvil"
#property version "1.00"
#property script_show_inputs
#property description "Part 3: prints any text file to a paginated PDF"
#include <MQLPDF/PdfWriter.mqh>
#include <MQLPDF/PdfValidate.mqh>
//--- Every article in the series writes under one shared root folder, with
//--- its own subfolder
#define PDF_ROOT_FOLDER "MQLPDF"
#define PDF_SUB_FOLDER "Part 03"
string path_folder = PDF_ROOT_FOLDER + "//" + PDF_SUB_FOLDER + "//";
input string InpSource = "sample_text.txt"; // Text file in MQL5\Files\MQLPDF\Part 03\
input string InpFileName = "text.pdf"; // Output file
input double InpFontSize = 7.0; // Font size, points
input double InpMargin = 10.0; // Margin, points
//+-------------------------------------------------------------------+
//| Escapes the three characters that have meaning inside a PDF |
//| string: the two brackets and the backslash. |
//| |
//| This is the minimum that keeps the file valid. Part 5 replaces it |
//| with a version that also handles characters outside printable |
//| ASCII, which needs an encoding decision this part has not made |
//| yet. |
//+-------------------------------------------------------------------+
string EscapePdf(const string text)
{
string out = text;
StringReplace(out, "\\", "\\\\");
StringReplace(out, "(", "\\(");
StringReplace(out, ")", "\\)");
return(out);
}
//+-------------------------------------------------------------------+
//| Reads a text file from MQL5\Files into one string. |
//+-------------------------------------------------------------------+
bool ReadTextFile(const string name, string &text)
{
int handle = FileOpen(name, FILE_READ | FILE_TXT | FILE_ANSI);
if(handle == INVALID_HANDLE)
{
PrintFormat("Cannot read %s, error %d", name, GetLastError());
return(false);
}
text = "";
while(!FileIsEnding(handle))
text += FileReadString(handle) + "\n";
FileClose(handle);
return(true);
}
//+-------------------------------------------------------------------+
//| Something to print when no source file was given. |
//+-------------------------------------------------------------------+
string AccountSummary(void)
{
string s = "ACCOUNT SUMMARY\n";
s += "generated " + TimeToString(TimeLocal(), TIME_DATE | TIME_SECONDS);
s += "\n\n";
s += "Login " +
IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN)) + "\n";
s += "Name " + AccountInfoString(ACCOUNT_NAME) + "\n";
s += "Broker " + AccountInfoString(ACCOUNT_COMPANY) + "\n";
s += "Server " + AccountInfoString(ACCOUNT_SERVER) + "\n";
s += "Currency " + AccountInfoString(ACCOUNT_CURRENCY) + "\n";
s += "Leverage 1:" +
IntegerToString(AccountInfoInteger(ACCOUNT_LEVERAGE)) + "\n";
s += "Balance " +
DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE), 2) + "\n";
s += "Equity " +
DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY), 2) + "\n";
s += "Margin " +
DoubleToString(AccountInfoDouble(ACCOUNT_MARGIN), 2) + "\n";
s += "\nSYMBOLS IN MARKET WATCH\n\n";
int total = SymbolsTotal(true);
for(int i = 0; i < total; i++)
{
string symbol = SymbolName(i, true);
s += StringFormat("%-14s bid %-12s ask %-12s spread %d\n", symbol,
DoubleToString(SymbolInfoDouble(symbol, SYMBOL_BID),
(int)SymbolInfoInteger(symbol,
SYMBOL_DIGITS)),
DoubleToString(SymbolInfoDouble(symbol, SYMBOL_ASK),
(int)SymbolInfoInteger(symbol,
SYMBOL_DIGITS)),
(int)SymbolInfoInteger(symbol, SYMBOL_SPREAD));
}
return(s);
}
//+-------------------------------------------------------------------+
//| Splits text into lines short enough for the page. |
//| |
//| Courier is monospaced: every glyph advances 600/1000 of the font |
//| size, so the number of characters that fit is a division rather |
//| than a measurement. That is the only reason this part can wrap |
//| text at all -- Part 6 measures proportional fonts properly and |
//| removes the restriction. |
//+-------------------------------------------------------------------+
int SplitLines(const string text, const int max_chars, string &lines[])
{
string raw[];
int raw_count = StringSplit(text, '\n', raw);
int count = 0;
for(int i = 0; i < raw_count; i++)
{
string line = raw[i];
//--- A tab would be one character wide in the PDF and eight in the
//--- editor the text came from, so it is expanded here instead.
StringReplace(line, "\t", " ");
//--- Trailing carriage returns arrive with every Windows text file.
StringReplace(line, "\r", "");
if(StringLen(line) == 0)
{
ArrayResize(lines, count + 1);
lines[count++] = "";
continue;
}
while(StringLen(line) > max_chars)
{
ArrayResize(lines, count + 1);
lines[count++] = StringSubstr(line, 0, max_chars);
line = StringSubstr(line, max_chars);
}
ArrayResize(lines, count + 1);
lines[count++] = line;
}
return(count);
}
//+-------------------------------------------------------------------+
//| 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;
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);
//--- 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();
}
//--- 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 >> >> >>");
//--- 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");
//--- 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");
//--- 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));
}
//--- 6. The font, the table and the trailer
writer.WriteDictionary(id_font,
"<< /Type /Font /Subtype /Type1"
" /BaseFont /Courier >>");
writer.Finish(id_catalog);
if(!writer.Save(path_folder + InpFileName))
return;
PrintFormat("%s: %d bytes, %d objects, %d pages", path_folder + InpFileName,
writer.Length(), writer.ObjectCount(), page_count);
//--- 7. Check our own output
CPdfValidator validator;
validator.Check(InpFileName);
validator.PrintReport(InpFileName);
Print("Open ", TerminalInfoString(TERMINAL_DATA_PATH),
"//Files//" + path_folder, InpFileName);
}
//+------------------------------------------------------------------+