MMOframework
Why AI Playground Libraries Developers Agency
FR EN
Build a project live
Building applications · intermediate

Documents in and out

Write a PDF and a workbook; read a PDF, a Word document or a workbook as Markdown (md-convert). - **You will have:** `quotes/{id}.pdf`, a quote as a PDF; `quotes.xlsx`, every quote in a workbook; `inbox?file=terms.docx`, a document received -- a PDF, a Word document or a workbook -- as Markdown; and their tests. - **You need:** **Your first controller** done. Reading a PDF needs poppler's `pdftotext` (`poppler-utils`); a scanned page, Tesseract. Writing needs nothing: mmo.pdf bundles FPDF, and mmo.core writes the `.xlsx` itself. ## 1. Add mmo.pdf A PDF is mmo.pdf's; a workbook and a Word document are mmo.core's. Add mmo.pdf to the dependencies of `mmo.json`: ```json from=mmo.json "dependencies": { "mmo.core": "21.*", "mmo.client": "4.*", "mmo.pdf": "3.*" }, ``` ## 2. A controller whose routes answer files A file is no JSON: the controller extends the plain `aController`, and each route builds its own response. The quotes come from the configuration, as the team did in **Your first controller**: ```php from=src/controllers/QuoteController.php class QuoteController extends aController { /** @var list<array{id: int, customer: string, date: string, lines: list<array{label: string, quantity: int, price: float|int}>}> */ public array $quotes = []; /** the folder of the documents received */ public string $inbox = '{root}/data/inbox'; ``` ```json from=configs/config.json "AcmePortal\\controllers\\QuoteController": { "quotes": [ {"id": 1, "customer": "Globex", "date": "2026-11-02", "lines": [ {"label": "Design, per day", "quantity": 2, "price": 450}, {"label": "Hosting, per year", "quantity": 1, "price": 120} ]}, ``` Register it in `routes`, before the PageController, and require it in `src/bootstrap.php`, as any controller. ## 3. Write a PDF `SimplePdf` writes a document from top to bottom: a heading, labelled fields, a table, totals, a paragraph. Every method returns the document, so they chain; `response()` is what the route returns. ```php from=src/controllers/QuoteController.php #[APIRoute('GET|quotes/{id}.pdf', 'One quote, as a PDF')] public function routePdf(Route $route): iResponse { $quote = $this->quote((int)$route->get('id'), $route); $lines = array_map(fn($line) => [$line['label'], $line['quantity'], static::Money($line['price']), static::Money($line['quantity'] * $line['price'])], $quote['lines']); $pdf = (new SimplePdf("Quote {$quote['id']}")) ->heading("Quote {$quote['id']}") ->fields(['Customer' => $quote['customer'], 'Date' => date('d/m/Y', strtotime($quote['date']))]) ->table(['Item', 'Qty', 'Unit price', 'Total'], $lines, ['L', 'R', 'R', 'R']) ->totals(['Total' => static::Money(static::Total($quote))]) ->text('Valid for 30 days.', 'I'); return $pdf->response("quote-{$quote['id']}.pdf"); } ``` - **The texts are UTF-8**: accents and `€` print. A character outside the core fonts' encoding (cp1252: Greek, an emoji) prints as `?`. - **The table** sizes its columns to their content and to the page; a long one goes on to the next page, its header repeated. The third argument aligns each column. - `response($name)` shows it in the browser; `response($name, false)` downloads it; `output()` gives its bytes, `save($file)` writes it. For what SimplePdf does not draw (an image, a line), `fpdf()` gives FPDF itself. ## 4. Write a workbook `xlsx\Document` is a workbook: add a sheet, then set its cells by their name. A value is a string, a number, a date or a boolean; an array sets the value and its style together. ```php from=src/controllers/QuoteController.php #[APIRoute('GET|quotes.xlsx', 'The quotes, as a workbook')] public function routeWorkbook(Route $route): Response { $workbook = new Xlsx(); $sheet = $workbook->addSheet('Quotes'); //a cell by its name; an array sets its value and its style foreach (['A1' => 'Quote', 'B1' => 'Customer', 'C1' => 'Date', 'D1' => 'Total'] as $cell => $title) { $sheet[$cell] = ['value' => $title, 'fill' => 'DDDDDD']; } foreach ($this->quotes as $i => $quote) { $row = $i + 2; $sheet["A$row"] = $quote['id']; $sheet["B$row"] = $quote['customer']; $sheet["C$row"] = new \DateTime($quote['date']); // a date, formatted as one $sheet["D$row"] = static::Total($quote); } foreach (range(0, 3) as $column) {$sheet->autoColumnWidth($column);} return Response::Xlsx($workbook, headers: ['Content-Disposition' => 'attachment; filename="quotes.xlsx"']); } ``` `Response::Xlsx()` sends it with its media type; `$workbook->save($file)` writes it to a file instead. The same class reads one: `Xlsx::File('prices.xlsx')['Quotes']['B2']` is a cell's value. **A list of rows to export** needs none of this: a `RepositoryController` collection answers `data/{repository}/{collection}.xlsx` already (mmo.core's `Entities.md`). ## 5. Read a document as Markdown A document received -- a supplier's quote, a contract, a price list -- is easier to search, index or hand to an AI agent as text. `MarkdownConverter` reads the three formats: a PDF through mmo.pdf's `PdfReader`, a `.docx` and a `.xlsx` through mmo.core (and a `.doc`, `.odt`, `.xls`, `.ods` through LibreOffice, when it is installed). ```php from=src/controllers/QuoteController.php #[APIRoute('GET|inbox', 'A document received, as Markdown')] public function routeInbox(Route $route): Response { //a name, never a path: nothing outside the inbox is read $filename = \MMO\filename($this->inbox) . '/' . basename((string)$route->get('file', '')); if (!is_file($filename)) {throw new e404($this, $route, 'no document [{file}].', ['file' => basename($filename)]);} //its .md written beside it, and read again only when the file changes ['output' => $md] = MarkdownConverter::Shared()->convert($filename); return Response::Text([(string)file_get_contents($md)], headers: ['Content-Type' => 'text/markdown; charset=utf-8']); } ``` `convert()` writes `terms.md` beside `terms.docx`, its front matter naming the file and its `sha1`: the next call finds it up to date and converts nothing. `toMarkdown($file)` gives the Markdown without writing it. What the PDF of quote 1 reads as: ````md --- source: "quote-1.pdf" sha1: "7569e75d39ee681280e7c145bbdd1f5bbe27f03f" format: "pdf" converter: "md-convert" pages: 1 title: "Quote 1" producer: "FPDF 1.86" created: "2026-11-30 12:30" --- <!-- page 1 --> ```text Quote 1 Customer Globex Date 02/11/2026 Item Qty Unit price Total Design, per day 2 450,00 € 900,00 € Hosting, per year 1 120,00 € 120,00 € Total 1 020,00 € Valid for 30 days. ``` ```` Text laid out in columns stays as it is laid out, in a `text` block: a Markdown table would mix a description going on below its line with the next one. A page with almost no letters is taken for a scan and read by Tesseract. The readers are there one by one, when you need only one of them: ```php from=tests/unit/TestDocuments.php $markdown = Docx::File(\MMO\filename('{root}/data/inbox/terms.docx'))->toMarkdown(); $this->assertStringStartsWith("# Terms of sale\n", $markdown); $this->assertStringContainsString("- A deposit of **30 %** on signature.\n", $markdown); $this->assertStringContainsString("| Design, per day | 450,00 € |", $markdown); ``` ```php from=tests/unit/TestDocuments.php $markdown = Xlsx::File($this->receive('quotes.xlsx', 'quotes.xlsx'))->toMarkdown(); $this->assertStringContainsString("## Quotes\n\n| Quote | Customer | Date | Total |\n| --- | --- | --- | --- |\n| 1 | Globex | 2026-11-02 | 1020 |", $markdown); ``` ```php from=tests/unit/TestDocuments.php $pages = PdfReader::Shared()->pages($this->receive('quotes/1.pdf', 'quote-1.pdf')); $this->assertCount(1, $pages); $this->assertStringContainsString('Quote 1', $pages[1]['text']); ``` A Word document gives its headings, bold and italic text, lists, tables and links; a workbook, a `## {sheet}` and a table per sheet, a date as `Y-m-d`, a formula as its last value; a PDF, each page's text (`pages()`) or the whole Markdown (`toMarkdown()`). ## 6. From the command line The same conversion, without writing code -- for a script, or for an AI agent asked to read a file: ```bash php libs/pdf/scripts/md-convert.php data/inbox/terms.docx ``` It prints the `.md` it wrote. `--stdout` prints the Markdown instead, `-o <folder/>` writes elsewhere, `--no-ocr` leaves scans unread, `--force` converts a file again. The hub's `mmo-to-markdown` skill has an agent run it on any PDF, Word or Excel file it is given, before reading it. ## 7. Try it, and test it ```bash php -S localhost:8000 -t www www/index.php ``` Open <http://localhost:8000/quotes/1.pdf>, <http://localhost:8000/quotes.xlsx> and <http://localhost:8000/inbox?file=terms.docx>. In a test, a file sent by the site is its response's body: ```php from=tests/unit/TestDocuments.php public function testAQuoteIsAPdf(): void { $response = $this->http('GET', 'quotes/1.pdf'); $this->assertSame(200, $response->getStatusCode()); $this->assertSame('application/pdf', $response->getHeaderLine('Content-Type')); $this->assertStringStartsWith('%PDF-', (string)$response->getBody()); $this->assertSame(404, $this->http('GET', 'quotes/9.pdf')->getStatusCode()); } ``` Saved to a file, it reads back with the classes of step 5: ```php from=tests/unit/TestDocuments.php protected function receive(string $uri, string $name): string { $filename = \MMO\filename('{root}/data/inbox') . "/$name"; file_put_contents($filename, (string)$this->http('GET', $uri)->getBody()); return $this->written[] = $filename; } ``` ```bash phpunit ``` ## Common mistakes - **An `aDataController`.** Its routes return arrays, sent as JSON: a file's route returns its response, from a plain `aController`. - **A path from the request.** `?file=../configs/config.json` would read your configuration: keep its `basename()`, in a folder of your own. - **`new \FPDF()` for what SimplePdf does not do.** Use `$pdf->fpdf()`: it reads images and fonts only from the folders allowed (mmo.pdf's `helpers\Resources`), never an address a user gave. - **Reading a PDF without poppler.** `PdfReader` throws when `pdftotext` is missing: install `poppler-utils` on the server too. - **Cells by row and column numbers.** A sheet's cells are named as in a spreadsheet, `A1`, `D2`; `Xlsx::Cell()` makes a name from numbers. ## Going further - [Documents](https://mmoframework.fr/en/documentation/mmo.core/Documents.md): mmo.core's documents, and its readers of Word documents and workbooks. - [mmo.pdf](https://mmoframework.fr/en/documentation/mmo.pdf/mcp/Overview.md): SimplePdf, filling an existing PDF form with PDFTK, and the PDF reader's settings.
Your next step

Try it yourself, or build the first one with us.

I'm a developer

Try it now. Nothing to install, nobody to call.

Build a project live

Read the guides

I lead a team

A working prototype of your AI product, on your data, in one week.

Prototype in a week

Open the page for your team