Skip to content

matlab/matlab-agentic-toolkit / skills-catalog/reporting-and-database-access/matlab-generate-report

matlab-generate-report

Verified

Unified skill for all MATLAB and Simulink report generation tasks. Covers report generation, PDF report, document generation, mlreportgen, Report Generator, template, TitlePage, Chapter, multipage HTML, HTMLPage, html-multipage, custom reporter, customizeReporter, template hole, page header, page border, company style package, branded reporters, buildTemplates, Simulink report, model documentation, slreportgen, block diagram report, model report, subsystem documentation, SystemDiagramFinder, SystemIO, ExecutionOrder, LookupTable, template style, page footer, TemplateSrc, report package, table variants, multiple HTML pages, PDF report generation, Word report, DOM API, FormalTable, BaseTable, Figure, FormalImage, Section.

references/custom-reporters.md

View on GitHub
# Custom Reporters

Create custom reporters that extend built-in Report API reporters with custom templates, holes, and page layout across PDF, Word, and HTML output formats.

---

## Three Approaches

1. **Template-based reporter** — uses `customizeReporter` scaffold with holes filled by properties or `get<HoleId>()` methods
2. **Derived reporter** — extends an existing reporter, overrides `getImpl` to add content
3. **DOM-only reporter** — overrides `getImpl` to return DOM objects directly (no template)

### Choosing an Approach

| Scenario | Approach |
|----------|----------|
| Content layout should be restyled by end users | Template-based (1) |
| Need to fill placeholders with dynamic data | Template with holes (1) |
| Extending built-in reporter with extra features | Derived reporter (2) |
| Fully programmatic content, no restyling needed | DOM-only reporter (3) |
| Simple one-off content addition | DOM-only reporter (3) |

---

## Template-Only vs Custom Reporter

If you only need to change **appearance** (styles, colors, fonts, header/footer layout) without adding new properties or holes, copy the reporter's default template, modify it, and set `TemplateSrc` on a standard reporter instance (`ch.TemplateSrc = "path/to/custom.pdftx"`). No custom class needed.

**Create a custom reporter class when:** you need new properties that fill template holes with dynamic content (e.g., a thumbnail image that varies per chapter).

---

## MANDATORY GATE — Scaffold First, No Exceptions

**STOP. Before writing ANY classdef file, ANY `.m` script, or ANY code that defines a custom reporter, you MUST execute `customizeReporter` in a live MATLAB session via `mcp__matlab__evaluate_matlab_code`.**

**Self-check before proceeding:**
- [ ] Have I called `mcp__matlab__evaluate_matlab_code` to run `customizeReporter`?
- [ ] Did I see MATLAB output confirming the files were created?
- [ ] Do the `resources/templates/` directories now exist on disk?

If ANY answer is "no" — STOP. Do not write classdef files. Do not create "setup scripts." Go back and execute the scaffolding via MCP.

**Why:** `customizeReporter` creates binary OPC template archives that cannot be replicated by writing text files. It also overwrites any classdef file at the target path — writing code first means losing it.

**Common evasion patterns (all WRONG):**
- Writing a `.m` setup script that contains `customizeReporter` calls → WRONG. Execute live via MCP.
- Writing classdef files "to plan the structure" → WRONG. Scaffolding overwrites your code.
- Skipping scaffolding because "I'll add templates manually" → WRONG. Templates are binary archives.
- Deferring scaffolding to "after I finish the code" → WRONG. Edit from the scaffolded output.

---

## Step 1: Scaffold the Custom Reporter

**Action:** Call `mcp__matlab__evaluate_matlab_code` with the scaffolding commands. Do this for ALL reporters before editing ANY.

```matlab
% Run in MATLAB via MCP tool — scaffold ALL reporters before editing ANY
mlreportgen.report.Chapter.customizeReporter("+myrpt/@Chapter/Chapter.m");
mlreportgen.report.TitlePage.customizeReporter("+myrpt/@TitlePage/TitlePage.m");
mlreportgen.report.TableOfContents.customizeReporter("+myrpt/@TableOfContents/TableOfContents.m");
mlreportgen.report.Section.customizeReporter("+myrpt/@Section/Section.m");
```

This creates:
- `+myrpt/@Reporter/Reporter.m` — class file extending the parent reporter
- `+myrpt/@Reporter/resources/templates/pdf/default.pdftx` — PDF template
- `+myrpt/@Reporter/resources/templates/docx/default.dotx` — Word template
- `+myrpt/@Reporter/resources/templates/html/default.htmt` — HTML single-file template
- `+myrpt/@Reporter/resources/templates/html/default.htmtx` — HTML multi-file template

**Always use `@ClassName` class directories.** Each reporter must have its own `resources/templates/` directory.

**Fix unqualified class names after scaffolding.** `customizeReporter` generates unqualified references like `TitlePage.getClassFolder()`. When the subclass has the same simple name as the parent, MATLAB resolves the unqualified name to the parent class and the custom template is never found:

```matlab
% WRONG (generated by customizeReporter):
path = TitlePage.getClassFolder();

% CORRECT (manually fix to):
path = myrpt.TitlePage.getClassFolder();
```

Fix in `getDefaultTemplatePath`, `getClassFolder` calls within `createTemplate`, and the second argument to `customizeClass` in the `customizeReporter` method.

---

## Step 2: Determine the Template Contents

**For Chapter/Section reporters:** Read the README files in each format directory.

**For all other reporters:** Introspect the templates directly using the DOM Template API:

```matlab
import mlreportgen.dom.*
templateDir = fullfile(classFolder,"resources","templates");

tpl = Template(fullfile(tempdir,"inspect.pdftx"),"pdf", ...
    fullfile(templateDir,"pdf","default.pdftx"));
open(tpl);
parts = tpl.TemplateDocumentParts;
for i = 1:numel(parts)
    fprintf("Part %d: %s\n",i,parts(i).Name);
    for j = 1:numel(parts(i).Children)
        child = parts(i).Children(j);
        fprintf("  Child %d: %s\n",j,class(child));
    end
end
close(tpl);
```

**Do NOT unzip `.pdftx`, `.htmtx`, or `.dotx` to read or edit template files** — raw HTML/XML doesn't match the DOM object model, and edits made this way bypass framework validation. Always use `Template(out,fmt,src)` → `open` → inspect/modify DOM objects → `close`. **Exception:** unzipping `.dotx` to read `word/styles.xml` for format discovery is valid.

---

## Step 3: Fill Template Holes

Two ways to fill a hole:

**Approach A — Property (simple assignment):** Add a property whose name matches the hole ID. The base `getImpl` fills the hole directly. Property type can be `string`, `char`, `mlreportgen.dom.Image`, a cell array of appendable objects, etc.

**Approach B — `get<HoleId>()` method (processing logic):** Define a method `get<HoleId>` (e.g., `getCompanyLogo` for a `CompanyLogo` hole). The framework calls this to produce content.

### Optional Image Properties

When an Image property may be empty (e.g., not every chapter has a logo), do NOT use a typed `mlreportgen.dom.Image` declaration — an empty 0x0 Image array causes framework errors. Instead, use an untyped property with a custom validator and a `get<HoleId>()` accessor:

```matlab
    properties
        HeaderLogo {mustBeLogoValue} = []   % Accepts [], Image, or file path string
    end

    methods
        function img = getHeaderLogo(obj)
        %getHeaderLogo Return Image for the HeaderLogo hole.
            if isempty(obj.HeaderLogo)
                img = [];
            elseif isa(obj.HeaderLogo,"mlreportgen.dom.Image")
                img = obj.HeaderLogo;
            else
                img = mlreportgen.dom.Image(string(obj.HeaderLogo));
                img.Width = "0.4in";
                img.Height = "0.4in";
            end
        end
    end
end

function mustBeLogoValue(v)
    if isempty(v), return; end
    if isa(v,"mlreportgen.dom.Image"), return; end
    if isstring(v) || ischar(v), return; end
    error("Value must be [], an Image object, or a file path string.");
end
```

The `get<HoleId>()` method is called by the framework to fill the template hole — it handles all three input types gracefully.

### Approach A Example — Property for Header Thumbnail

When the property is **always required** (never empty), a typed declaration is fine:

```matlab
classdef Chapter < mlreportgen.report.Chapter
% File: +myrpt/@Chapter/Chapter.m

    properties
        HeaderThumbnail mlreportgen.dom.Image
    end

    methods
        function obj = Chapter(varargin)
            obj = obj@mlreportgen.report.Chapter(varargin{:});
        end
    end

    % REQUIRED: template infrastructure (generated by customizeReporter)
    methods (Hidden)
        function templatePath = getDefaultTemplatePath(~,rpt)
            path = myrpt.Chapter.getClassFolder();
            templatePath = mlreportgen.report.ReportForm.getFormTemplatePath(path,rpt.Type);
        end
    end

    methods (Static)
        function path = getClassFolder()
            [path] = fileparts(mfilename("fullpath"));
        end
        function createTemplate(templatePath,type)
            path = myrpt.Chapter.getClassFolder();
            mlreportgen.report.ReportForm.createFormTemplate(templatePath,type,path);
        end
        function customizeReporter(toClasspath)
            mlreportgen.report.ReportForm.customizeClass(toClasspath,"myrpt.Chapter");
        end
    end
end
```

**Critical:** The template infrastructure methods are **required**. Without `getDefaultTemplatePath`, your custom templates are never found.

### Approach B Example — `get<HoleId>()` Method

```matlab
classdef TitlePage < mlreportgen.report.TitlePage
% File: +myrpt/@TitlePage/TitlePage.m

    properties
        LogoPath string = "company_logo.png"
    end

    methods
        function obj = TitlePage(varargin)
            obj = obj@mlreportgen.report.TitlePage(varargin{:});
        end

        function content = getCompanyLogo(obj,~)
            % Called by framework to fill the CompanyLogo hole.
            import mlreportgen.dom.*
            content = Image(obj.LogoPath);
            content.Width = "2in";
            content.Height = "1in";
        end
    end

    % REQUIRED: template infrastructure (same pattern)
    methods (Hidden)
        function templatePath = getDefaultTemplatePath(~,rpt)
            path = myrpt.TitlePage.getClassFolder();
            templatePath = mlreportgen.report.ReportForm.getFormTemplatePath(path,rpt.Type);
        end
    end

    methods (Static)
        function path = getClassFolder()
            [path] = fileparts(mfilename("fullpath"));
        end
        function createTemplate(templatePath,type)
            path = myrpt.TitlePage.getClassFolder();
            mlreportgen.report.ReportForm.createFormTemplate(templatePath,type,path);
        end
        function customizeReporter(toClasspath)
            mlreportgen.report.ReportForm.customizeClass(toClasspath,"myrpt.TitlePage");
        end
    end
end
```

---

## Step 4: Customize Templates for Each Format

You **must** customize the template for every output format you support.

| Format | Type Argument | Headers/Footers |
|--------|---------------|-----------------|
| PDF (`.pdftx`) | `'pdf'` | `PDFPageHeader`/`PDFPageFooter` on `PDFPageLayout` |
| Word (`.dotx`) | `'docx'` | `DOCXPageHeader`/`DOCXPageFooter` on `DOCXSection` |
| HTML multi-file (`.htmtx`) | `'html'` | N/A (no page concept) |
| HTML single-file (`.htmt`) | `'html-file'` | N/A |

**HTML template types:** Match the type argument to the file extension: use `'html'` for `.htmtx`, use `'html-file'` for `.htmt`.

**`Children` is read-only** on `TemplateDocumentPart`, `PDFPageHeader`, etc. To insert/reorder, create a new object and `append` children (use `clone()` when copying).

**DOCX templates require `TemplateText` spacers between holes.** When adding new holes to a DOCX template, clone an existing spacer from the original.

### Common Procedure

```matlab
import mlreportgen.dom.*

templateDir = fullfile(classFolder,"resources","templates");
srcPath = fullfile(templateDir,"pdf","default.pdftx");
tmpPath = fullfile(templateDir,"pdf","default_new.pdftx");

% 1. Open (MUST use different output path from source)
tpl = Template(tmpPath,"pdf",srcPath);
open(tpl);

% 2. Access template document parts
parts = tpl.TemplateDocumentParts;
section1 = parts(1);  % "Section1" part

% 3. For PDF: modify PDFPageLayout headers/footers
layout = section1.Children(1);  % PDFPageLayout
defaultHeader = layout.PageHeaders(2);  % PageType='default'

% 4. Save changes back
tpl.TemplateDocumentParts(1) = section1;
close(tpl);

% 5. Replace original
movefile(tmpPath,srcPath);
```

### Adding Holes to Page Headers

**Key rules:**
- **ALWAYS use the DOM Template API** (`Template(out,fmt,src)` → `open` → read/modify objects → `close`) to edit templates. NEVER unzip `.pdftx`/`.htmtx` and edit raw HTML/XML with `fileread`/`regexprep`/`fopen`. The DOM API ensures the agent interprets template structure the same way the Report Generator framework does.
- Use a `Table` for side-by-side layout — without one, elements stack vertically
- **Do not use `Table({...})` shorthand with `TemplateHole`** — build via `TableEntry` + `append(entry,hole)`
- **Holes inside Paragraphs are inline holes** — can only accept inline content (Text, Image)
- **PDF column widths:** Use `TableColSpecGroup` + `TableColSpec` with `ResizeToFitContents(false)` on the table
- **Word:** Build new `DOCXPageHeader` objects from scratch — do NOT modify `TemplateText`
- **Modify ALL page headers** — "first", "default", and "even". The "first" page header renders on the chapter's opening page. Skipping it means headers only appear on page 2+.
- **Omit StyleRef from the first-page header.** The chapter title is already displayed as the heading on page 1 — repeating it in the header is redundant. Use StyleRef only in "default" and "even" headers (where the reader needs wayfinding). The first-page header can still contain logos, tickers, or a rule.

### PDF Header Example — 3-Column Layout

```matlab
function customizePdfChapterTemplate(classFolder)
    import mlreportgen.dom.*

    templateDir = fullfile(classFolder,"resources","templates","pdf");
    srcPath = fullfile(templateDir,"default.pdftx");
    tmpPath = fullfile(templateDir,"default_new.pdftx");

    tpl = Template(tmpPath,"pdf",srcPath);
    open(tpl);

    parts = tpl.TemplateDocumentParts;
    for i = 1:numel(parts)
        if strcmp(parts(i).Name,"Section1")
            section1 = parts(i);
            sectionIdx = i;
            break
        end
    end

    layout = section1.Children(1);

    for k = 1:numel(layout.PageHeaders)
        pageType = layout.PageHeaders(k).PageType;
        newHeader = PDFPageHeader(pageType);

            imgPara = Paragraph("");
            append(imgPara,TemplateHole("HeaderThumbnail"));

            % Center cell: StyleRef on default/even only (not first page)
            % First page already displays the chapter title as a heading —
            % repeating it in the header is redundant (standard book design).
            titlePara = Paragraph("");
            titlePara.HAlign = "center";
            titlePara.Style = [titlePara.Style, {FontSize("10pt")}];
            if ~strcmp(pageType,"first")
                append(titlePara,StyleRef("SectionTitle1"));
            end

            spacerPara = Paragraph(" ");

            e1 = TableEntry(imgPara);
            e1.Style = {Width("1in")};
            e2 = TableEntry(titlePara);
            e2.Style = {Width("5in")};
            e3 = TableEntry(spacerPara);
            e3.Style = {Width("1in")};

            row = TableRow();
            append(row,e1);
            append(row,e2);
            append(row,e3);

            headerTable = Table();
            append(headerTable,row);
            headerTable.Width = "100%";
            headerTable.Style = {Border("none"),ResizeToFitContents(false)};
            headerTable.TableEntriesVAlign = "bottom";
            append(newHeader,headerTable);

            hrPara = Paragraph("");
            hrPara.Style = {HAlign("center"),OuterMargin("0","0","3pt","0"),...
                Border("solid","#000000","0.5pt")};
            append(newHeader,hrPara);

        layout.PageHeaders(k) = newHeader;
    end

    tpl.TemplateDocumentParts(sectionIdx) = section1;
    close(tpl);
    movefile(tmpPath,srcPath);
end
```

### Adding a Body Hole (Between Title and Content)

```matlab
function addBodyHoleToPdfTemplate(classFolder,holeName)
    import mlreportgen.dom.*

    templateDir = fullfile(classFolder,"resources","templates","pdf");
    srcPath = fullfile(templateDir,"default.pdftx");
    tmpPath = fullfile(templateDir,"default_new.pdftx");

    tpl = Template(tmpPath,"pdf",srcPath);
    open(tpl);

    parts = tpl.TemplateDocumentParts;
    for i = 1:numel(parts)
        if strcmp(parts(i).Name,"Section1")
            oldSection = parts(i);
            sectionIdx = i;
            break
        end
    end

    newSection = TemplateDocumentPart("Section1");
    for k = 1:numel(oldSection.Children)
        child = oldSection.Children(k);
        append(newSection,clone(child));
        if isa(child,"mlreportgen.dom.TemplateHole") && ...
                strcmp(child.HoleId,"Title")
            newHole = TemplateHole(holeName);
            newHole.Description = upper(holeName);
            append(newSection,newHole);
        end
    end

    tpl.TemplateDocumentParts(sectionIdx) = newSection;
    close(tpl);
    movefile(tmpPath,srcPath);
end
```

---

## Step 5: Test the Custom Reporter

```matlab
for fmt = ["pdf","docx","html"]
    rpt = Report("Test_" + fmt,fmt);
    ch = myrpt.Chapter("Test");
    img = Image("thumbnail.png");
    img.Width = "0.5in";
    ch.HeaderThumbnail = img;
    append(rpt,ch);
    close(rpt);
    rptview(rpt);
end
```

---

## Step 6: Recovering from Template Corruption

If template edits produce unexpected results, re-scaffold:

```matlab
mlreportgen.report.Chapter.customizeReporter("+myrpt/@Chapter/Chapter.m");
```

Then re-apply classdef edits and re-run `buildTemplates`.

**When to suspect corruption:**
- TOC shows "No table of contents entries found"
- Template holes stop rendering content
- Styles look different from what `buildTemplates` specifies
- Error messages reference template structure that shouldn't be affected

---

## Customizing Chapter/Section Numbering (Without Template Edits)

The Chapter reporter's `getTitleReporter()` returns a `SectionTitle` with `NumberPrefix` and `NumberSuffix`:

**Inline approach:**

```matlab
ch = Chapter("Title","Introduction");
titleRptr = getTitleReporter(ch);
titleRptr.NumberPrefix = "";      % Removes "Chapter" prefix
titleRptr.NumberSuffix = ". ";    % "1. Introduction"
ch.Title = titleRptr;
```

**Subclass approach:**

```matlab
classdef Chapter < mlreportgen.report.Chapter
    methods
        function rptr = getTitleReporter(ch)
            rptr = getTitleReporter@mlreportgen.report.Chapter(ch);
            rptr.NumberPrefix = "Section";  % "Section 1. Introduction"
        end
    end
end
```

---

## DOM-Only Reporter (No Template)

Override `getImpl` to return DOM objects directly. Use when content is entirely programmatic:

```matlab
classdef TestResultCard < mlreportgen.report.Reporter
% File: +myrpt/@TestResultCard/TestResultCard.m

    properties
        TestName (1,1) string = ""
        Result (1,1) string {mustBeMember(Result,["Pass","Fail","Skip"])} = "Pass"
        Duration (1,1) double = 0
    end

    methods
        function obj = TestResultCard(name,result,duration)
            obj = obj@mlreportgen.report.Reporter();
            if nargin > 0,obj.TestName = name; end
            if nargin > 1,obj.Result = result; end
            if nargin > 2,obj.Duration = duration; end
        end

        function content = getImpl(obj,rpt) %#ok<INUSD>
            import mlreportgen.dom.*
            grp = Group();
            namePara = Paragraph(obj.TestName);
            namePara.Style = {Bold(true),FontSize("12pt")};
            append(grp,namePara);

            switch obj.Result
                case "Pass", clr = "green";
                case "Fail", clr = "red";
                case "Skip", clr = "orange";
            end
            statusPara = Paragraph(upper(obj.Result));
            statusPara.Style = {Bold(true),Color(clr)};
            append(grp,statusPara);

            durPara = Paragraph(sprintf("Duration: %.1f s",obj.Duration));
            durPara.Style = {FontSize("9pt"),Color("gray")};
            append(grp,durPara);
            append(grp,HorizontalRule());
            content = grp;
        end
    end
end
```

**Key rules for DOM-only reporters:**
1. Call superclass constructor: `obj = obj@mlreportgen.report.Reporter()`
2. `getImpl` must be public with signature `(obj, rpt)`
3. Return any DOM object appendable to a Document
4. Do NOT use template infrastructure methods (no `getDefaultTemplatePath` etc.)

---

## Customizing Built-In TitlePage

### Template Architecture

The TitlePage template has the same structure across all formats:

| Format | First Child (Layout) | Holes |
|--------|---------------------|-------|
| PDF | `PDFPageLayout` | Title, Subtitle, Image, Author, Publisher, PubDate |
| DOCX | `DOCXSection` + `TemplateText` spacers | Title, Subtitle, Image, Author, Publisher, PubDate |
| HTML | `TemplateText` (structural HTML) | Title, Subtitle, Image, Author, Publisher, PubDate |

**Sub-document part templates** (one per hole): `TitlePageTitle`, `TitlePageSubtitle`, `TitlePageImage`, `TitlePageAuthor`, `TitlePagePublisher`, `TitlePagePubDate`. Each contains a styled `Paragraph` (with `StyleName` matching the part name) wrapping an inline `Content` hole:

```
TitlePageTitle (sub-doc part):
  Paragraph (StyleName = "TitlePageTitle")   ← 24pt bold centered
    └─ TemplateHole("Content")              ← filled with title text
```

The paragraph style controls all formatting — both positioning (centering, margins) and character appearance (font-size, bold). This is the mechanism that styles built-in TitlePage fields without the reporter needing inline style objects.

### How the Reporter Fills Its Template

1. Base `getImpl` creates a `DocumentPart` from the `TitlePage` template
2. Iterates over **all holes** in the template
3. For each hole, checks if the reporter has a `get<HoleId>` method (e.g., `getTitle`)
4. If method exists → calls it. Built-in methods use `InlineContent` reporters backed by sub-doc part templates for styling
5. If no method but a **property with matching name** exists → fills the hole directly with the property value
6. The hole's `DefaultHoleStyleName` (if set and persisted) applies character formatting to the filled content

### Adding Custom Properties and Holes

Add custom string fields (e.g., WindFarmName, CustomerName) with template-driven styling — no `get<HoleId>()` methods needed:

```matlab
classdef TitlePage < mlreportgen.report.TitlePage
% File: +myrpt/@TitlePage/TitlePage.m

    properties
        WindFarmName string = ""
        CustomerName string = ""
    end

    methods
        function obj = TitlePage(varargin)
            obj = obj@mlreportgen.report.TitlePage(varargin{:});
        end
    end

    % REQUIRED: template infrastructure
    methods (Hidden)
        function templatePath = getDefaultTemplatePath(~,rpt)
            path = myrpt.TitlePage.getClassFolder();
            templatePath = mlreportgen.report.ReportForm.getFormTemplatePath(path,rpt.Type);
        end
    end

    methods (Static)
        function path = getClassFolder()
            [path] = fileparts(mfilename("fullpath"));
        end
        function createTemplate(templatePath,type)
            path = myrpt.TitlePage.getClassFolder();
            mlreportgen.report.ReportForm.createFormTemplate(templatePath,type,path);
        end
        function customizeReporter(toClasspath)
            mlreportgen.report.ReportForm.customizeClass(toClasspath,"myrpt.TitlePage");
        end
    end
end
```

**No getters required.** The base `getImpl` iterates over template holes. When it finds a hole whose ID matches a property name, it fills the hole with the property value. Formatting is controlled entirely by template styles.

**When ARE `get<HoleId>()` methods needed?** Only when you need processing logic — e.g., accepting multiple input types (string, Image, DOM object), conditional content, or wrapping content in a sub-reporter. For simple string properties, the template-only approach is sufficient and preferred.

### Inline Hole Pattern for Styled Custom Fields

To add a formatted string field to the TitlePage template, insert a **Paragraph** (with a paragraph style for positioning) containing an **inline TemplateHole** (with `DefaultHoleStyleName` for character formatting):

```
Template structure:
  Paragraph (StyleName = "TitlePageWindFarmName")  ← centering, margins
    └─ TemplateHole("WindFarmName")                ← filled by property value
         DefaultHoleStyleName = "WindFarmNameChar"  ← bold, color, font-size
```

This mirrors how the built-in TitlePage holes work — the sub-document part templates (`TitlePageTitle`, etc.) each contain a styled Paragraph with a `Content` hole. For custom fields, you embed the styled paragraph directly in the main doc part instead of creating sub-doc parts.

### Editing the TitlePage Template (PDF/HTML)

```matlab
function customizeTitlePageTemplate(classFolder)
    import mlreportgen.dom.*

    templateDir = fullfile(classFolder,"resources","templates","pdf");
    srcPath = fullfile(templateDir,"default.pdftx");
    tmpPath = fullfile(templateDir,"default_new.pdftx");

    tpl = Template(tmpPath,"pdf",srcPath);
    open(tpl);

    % Modify the existing doc part in place (preserves DefaultHoleStyleName)
    mainPart = tpl.TemplateDocumentParts(1);

    % Add page border to existing PDFPageLayout
    mainPart.Children(1).PageBorder = PageBorder("solid","#1B5E20","3pt");
    mainPart.Children(1).PageBorder.MeasureFrom = "pageboundary";

    % Append styled paragraphs with inline holes
    wfPara = Paragraph();
    wfPara.StyleName = "TitlePageWindFarmName";
    wfHole = TemplateHole("WindFarmName");
    wfHole.DefaultHoleStyleName = "WindFarmNameChar";
    append(wfPara,wfHole);
    append(mainPart,wfPara);

    cnPara = Paragraph();
    cnPara.StyleName = "TitlePageCustomerName";
    cnHole = TemplateHole("CustomerName");
    cnHole.DefaultHoleStyleName = "CustomerNameChar";
    append(cnPara,cnHole);
    append(mainPart,cnPara);

    tpl.TemplateDocumentParts(1) = mainPart;

    % Add paragraph styles (positioning)
    ss = tpl.Stylesheet;
    wfPS = TemplateParagraphStyle("TitlePageWindFarmName");
    wfPS.Formats = [HAlign("center"),OuterMargin("0","0","12pt","6pt")];
    addStyle(ss,wfPS);

    cnPS = TemplateParagraphStyle("TitlePageCustomerName");
    cnPS.Formats = [HAlign("center"),OuterMargin("0","0","6pt","6pt")];
    addStyle(ss,cnPS);

    % Add character styles (text formatting)
    wfCS = TemplateTextStyle("WindFarmNameChar");
    wfCS.Formats = [FontSize("16pt"),Bold(true),Color("#1B5E20")];
    addStyle(ss,wfCS);

    cnCS = TemplateTextStyle("CustomerNameChar");
    cnCS.Formats = [FontSize("12pt"),Color("#333333")];
    addStyle(ss,cnCS);

    close(tpl);
    movefile(tmpPath,srcPath);
end
```

**Key points:**
- Append to the **existing** doc part (`tpl.TemplateDocumentParts(1)`) — do NOT rebuild with `TemplateDocumentPart("TitlePage")`. Rebuilding loses `DefaultHoleStyleName` in DOCX.
- `TemplateParagraphStyle` controls paragraph layout (centering, margins)
- `TemplateTextStyle` controls character formatting (font, bold, color)
- `OuterMargin(left,right,top,bottom)` — NOT CSS order. Use `OuterMargin("0","0","12pt","6pt")` for vertical spacing between title page elements
- Use `addStyle` to add new styles to the stylesheet

### Editing the TitlePage Template (DOCX)

DOCX templates do not persist `DefaultHoleStyleName` on inline holes. Use `TemplateLinkedStyle` instead — it combines paragraph AND character formatting in one style:

```matlab
function customizeTitlePageDocxTemplate(classFolder)
    import mlreportgen.dom.*

    templateDir = fullfile(classFolder,"resources","templates","docx");
    srcPath = fullfile(templateDir,"default.dotx");
    tmpPath = fullfile(templateDir,"default_new.dotx");

    tpl = Template(tmpPath,"docx",srcPath);
    open(tpl);

    mainPart = tpl.TemplateDocumentParts(1);

    % Add page border
    mainPart.Children(1).PageBorder = PageBorder("solid","#1B5E20","3pt");
    mainPart.Children(1).PageBorder.MeasureFrom = "pageboundary";

    % Append styled paragraphs with inline holes
    wfPara = Paragraph();
    wfPara.StyleName = "TitlePageWindFarmName";
    append(wfPara,TemplateHole("WindFarmName"));
    append(mainPart,wfPara);

    cnPara = Paragraph();
    cnPara.StyleName = "TitlePageCustomerName";
    append(cnPara,TemplateHole("CustomerName"));
    append(mainPart,cnPara);

    tpl.TemplateDocumentParts(1) = mainPart;

    % Use TemplateLinkedStyle — includes both paragraph and run formatting
    ss = tpl.Stylesheet;
    wfStyle = TemplateLinkedStyle("TitlePageWindFarmName");
    wfStyle.Formats = [HAlign("center"),OuterMargin("0","0","12pt","6pt"),...
        FontSize("16pt"),Bold(true),Color("#1B5E20")];
    addStyle(ss,wfStyle);

    cnStyle = TemplateLinkedStyle("TitlePageCustomerName");
    cnStyle.Formats = [HAlign("center"),OuterMargin("0","0","6pt","6pt"),...
        FontSize("12pt"),Color("#333333")];
    addStyle(ss,cnStyle);

    close(tpl);
    movefile(tmpPath,srcPath);
end
```

**Why `TemplateLinkedStyle` for DOCX:** A linked style creates both a paragraph style (with `w:pPr` for alignment/margins) and a linked character style (with `w:rPr` for font/color/bold). Word applies run properties from the linked style to all runs in the paragraph — achieving the same result as separate paragraph + character styles in PDF/HTML.

**Repeat for ALL formats.** You MUST also customize:
- HTML `.htmtx`: `Template(tmp,"html",src)` — same pattern as PDF (DefaultHoleStyleName persists)
- HTML `.htmt`: `Template(tmp,"html-file",src)` — same pattern as PDF

If you skip HTML templates, content that relies on custom holes will be silently missing in HTML output.

### Page Borders

**Always embed page borders in the template** during customization:

```matlab
% PDF:
pdfLayout.PageBorder = PageBorder("solid","#1B5E20","3pt");
pdfLayout.PageBorder.MeasureFrom = "pageboundary";

% DOCX:
docxSection.PageBorder = PageBorder("solid","#1B5E20","3pt");
docxSection.PageBorder.MeasureFrom = "pageboundary";
```

Key facts:
- `PageBorder` applies only to the reporter's pages (not subsequent chapters)
- `MeasureFrom = "pageboundary"` positions relative to page edge
- HTML has no page concept — `PageBorder` is ignored

---

## Chapter Template Anatomy

### PDF Template Structure

```
┌─────────────────────────────────────────────────────┐
│ Section1 (top-level chapter)                        │
│   ├── <layout> — page size, margins, header/footer  │
│   │     ├── <pheader type="first" .../>             │
│   │     ├── <pfooter type="first" .../>             │
│   │     ├── <pheader type="default" .../>           │
│   │     ├── <pfooter type="default" .../>           │
│   │     ├── <pheader type="even" .../>              │
│   │     └── <pfooter type="even" .../>              │
│   ├── <hole id="Title">                             │
│   └── <hole id="Content">                           │
├─────────────────────────────────────────────────────┤
│ Section2–Section6 (subsections)                     │
│   ├── <hole id="Title">                             │
│   └── <hole id="Content">                           │
├─────────────────────────────────────────────────────┤
│ SectionNumberedTitle1–6 (numbered title format)     │
│   ├── <hole id="NumberPrefix">                      │
│   ├── <autonumber stream-name="sect1"/>             │
│   ├── <hole id="NumberSuffix">                      │
│   └── <hole id="Content">                           │
├─────────────────────────────────────────────────────┤
│ SectionTitle1–6 (unnumbered title format)           │
│   └── <hole id="Content">                           │
├─────────────────────────────────────────────────────┤
│ SectionFirstPageHeader / SectionDefaultPageHeader   │
│ SectionEvenPageHeader / Section*PageFooter          │
└─────────────────────────────────────────────────────┘
```

### How Headers Connect to the Page Layout (PDF)

```html
<layout style="page-margin: 0.5in 1in 0.5in 1in 0.5in 0.5in 0in; page-size: 8.5in 11in portrait">
    <pheader type="first" template-name="SectionFirstPageHeader"/>
    <pfooter type="first" template-name="SectionFirstPageFooter"/>
    <pheader type="default" template-name="SectionDefaultPageHeader"/>
    <pfooter type="default" template-name="SectionDefaultPageFooter"/>
    <pheader type="even" template-name="SectionEvenPageHeader"/>
    <pfooter type="even" template-name="SectionEvenPageFooter"/>
    <pnumber format="1"/>
</layout>
```

### Word Template Structure

```
TemplateDocumentParts (18 parts):
├── Section1              ← Top-level chapter
│   Children:
│     [1] DOCXSection     ← margins, headers, footers, page numbers
│     [2-3] TemplateText  ← whitespace
│     [4] TemplateHole    ← "Title" hole
│     [5] TemplateText    ← whitespace
│     [6] TemplateHole    ← "Content" hole
│     [7-8] TemplateText  ← whitespace
├── Section2–Section6     ← Subsections
├── SectionNumberedTitle1–6
└── SectionTitle1–6
```

Word templates embed headers/footers directly on the `DOCXSection` object (no separate doc parts):

```matlab
docxSection.PageHeaders:
  [1] DOCXPageHeader (PageType="default")  % Odd/all pages
  [2] DOCXPageHeader (PageType="first")    % First page only
docxSection.PageFooters:
  [1] DOCXPageFooter (PageType="default")
  [2] DOCXPageFooter (PageType="first")
```

### HTML Template Structure

HTML templates have **no page headers or footers**. Doc parts contain only Title and Content holes. To add custom content, insert it in the `Section1` doc part body.

### Balanced 3-Column Header Layout Pattern

Use for **"default" and "even"** page headers (where reader needs wayfinding):

```
Page text width = 8.5in - 2×1in = 6.5in

┌──────────┬────────────────────────────┬──────────┐
│  Logo    │     StyleRef (centered)    │  Ticker  │
│  1.25in  │         4.0in             │  1.25in  │
└──────────┴────────────────────────────┴──────────┘
```

For the **"first"** page header, omit StyleRef (the chapter title is already the heading on page 1):

```
┌──────────┬────────────────────────────┬──────────┐
│  Logo    │         (empty)            │  Ticker  │
│  1.25in  │         4.0in             │  1.25in  │
└──────────┴────────────────────────────┴──────────┘
```

Left + Right columns MUST be equal width for true centering.

---

## Modifying Template Styles

**PDF/HTML** — modify `RawFormats` directly (handle semantics):

```matlab
tpl = Template(outPath,"pdf",srcPath);
open(tpl);
styles = getStyle(tpl.Stylesheet,"SectionTitle1");
for i = 1:numel(styles)
    styles(i).RawFormats = regexprep(styles(i).RawFormats, ...
        "color:\s*[^;]+","color: red");
end
close(tpl);
```

**DOCX** — `TemplateDOCXStyle` is read-only; create new and replace:

```matlab
tpl = Template(outPath,"docx",srcPath);
open(tpl);
newStyle = TemplateLinkedStyle("SectionTitle1");
newStyle.Formats = [Bold(true),FontSize("14pt"),Color("red")];
replaceStyle(tpl.Stylesheet,newStyle);
close(tpl);
```

**DOCX table styles:**

```matlab
ts = TemplateTableStyle("BaseTableContent");
ts.Formats = [Border("solid","#333333","0.5pt"),FontSize("10pt")];
ts.HeaderFormats = [Bold(true),BackgroundColor("#1B3A5C"),Color("white")];
replaceStyle(tpl.Stylesheet,ts);
```

See [template-system.md](template-system.md) for complete style modification procedures.

---

## Common Mistakes

| Mistake | Correct Approach |
|---------|-----------------|
| Writing classdef before running `customizeReporter` | Scaffold via MCP first, then edit generated files |
| Scaffolding without `@ClassName` directories | Use `+pkg/@ClassName/ClassName.m` so each has its own `resources/` |
| Leaving unqualified class names from scaffolding | Replace with fully-qualified: `myrpt.TitlePage.getClassFolder()` |
| Removing `getDefaultTemplatePath`/`getClassFolder` | Always keep — directs framework to your templates |
| Only customizing the PDF template | Customize all formats you support |
| Using same path for source and output in `Template()` | Write to temp path, then `movefile` back |
| Editing `.dotx` XML directly | Use DOM Template API: `Template(out,'docx',src)` |
| Modifying `TemplateText` with Word XML | Build new `DOCXPageHeader` from scratch |
| Using `Table({...})` shorthand with `TemplateHole` | Build via `TableEntry` + `append(entry,hole)` |
| Setting column widths without `ResizeToFitContents(false)` | Add to table Style with absolute table width |
| Returning `Paragraph` from `get<HoleId>` for inline hole | Return `Text` or `Image` for holes inside Paragraphs |
| Only modifying "default" and "even" PDF headers | Modify ALL headers: "first", "default", and "even" — "first" is the chapter opening page |
| Using `StyleRef("ChapterTitle1")` | Use `StyleRef("SectionTitle1")` — no ChapterTitle1 exists |
| Overriding `getImpl` on TitlePage to add borders | Embed `PageBorder` on layout during template customization |
| Replacing heading styles without `OutlineLevel(N)` | Always include `OutlineLevel` in replacement heading styles |
| Using `getStyle(ss,name,type)` for PDF/HTML | Use `getStyle(ss,name)` without type; filter by `Selector` |
| Setting `Formats` on `TemplateDOCXStyle` | Read-only — create `TemplateLinkedStyle` + `replaceStyle` |
| Using `addStyle` for PDF/HTML | Modify `RawFormats` on handle from `getStyle` |
| Using 2-arg `Template(path,fmt)` to inspect styles | Use 3-arg: `Template(outPath,fmt,srcPath)` |
| Typing optional Image property as `mlreportgen.dom.Image` | Use untyped `{mustBeLogoValue} = []` with a `get<HoleId>()` accessor that handles [], Image, and path string |

---

## Key Functions

| Class/Function | Purpose |
|----------------|---------|
| `*.customizeReporter` | Scaffold custom reporter class + templates |
| `Template` (3-arg) | Create/edit templates programmatically |
| `TemplateHole` | Define a hole (placeholder) in a template |
| `TemplateDocumentPart` | Define a doc part template |
| `DOCXPageHeader`/`DOCXPageFooter` | Word page header/footer definition |
| `DOCXSection` | Word section break with page layout |
| `PDFPageHeader`/`PDFPageFooter` | PDF page header/footer definition |
| `PDFPageLayout` | PDF page layout (margins, headers, footers) |
| `PageBorder` | Page border specification |
| `StyleRef` | Dynamic running head (works PDF and Word) |
| `getStyle` / `replaceStyle` | Modify template styles |
| `TemplatePDFStyle` / `TemplateHTMLStyle` | PDF/HTML style (CSS via `RawFormats`) |
| `TemplateTextStyle` | Character/inline style for PDF/HTML (font, bold, color) |
| `TemplateLinkedStyle` / `TemplateParagraphStyle` | DOCX style replacements |
| `TemplateTableStyle` | DOCX table style replacement |

----

Copyright 2026 The MathWorks, Inc.

----
canvas-designanthropics/skillsCreate beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
docxanthropics/skillsUse this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include: any mention of 'Word doc', 'word document', '.docx', '.dotx', or requests to produce professional documents with formatting like tables of contents, headings, page numbers, or letterheads. Also use when extracting or reorganizing content from .docx or .dotx files, inserting or replacing images in documents, performing find-and-replace in Word files, working with tracked changes or comments, or converting content into a polished Word document. If the user asks for a 'report', 'memo', 'letter', 'template', or similar deliverable as a Word or .docx file, use this skill. Do NOT use for PDFs, spreadsheets, Google Docs, or general coding tasks unrelated to document generation.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
pdfanthropics/skillsUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple PDFs into one, splitting PDFs apart, rotating pages, adding watermarks, creating new PDFs, filling PDF forms, encrypting/decrypting PDFs, extracting images, and OCR on scanned PDFs to make them searchable. If the user mentions a .pdf file or asks to produce one, use this skill.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
pptxanthropics/skillsUse this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates (.potx), layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx or .potx filename, regardless of what they plan to do with the content afterward. If a .pptx or .potx file needs to be opened, created, or touched, use this skill.Stars: 198kUpdated Claude CodeCodexVerifiedInstall