Paginate and render a report
ReportPaginator.Paginate divides a ReportInstance into pages. Every item is positioned, every textbox's text is laid out into lines, and page headers and footers get their page numbers. The resulting ReportPageModel is what a viewer displays, and it renders to PDF and PNG through the same renderers that draw Word documents.
This guide continues from Run a report against your data and uses the same sales.rdl.
Pages and what is on them
using DocWright.Fonts;
using DocWright.Reporting.Pagination;
using DocWright.Reporting.Processing;
var fonts = new FontEngine(); // reads every installed font: build one and share it
using ReportInstance instance = ReportProcessor.Process(definition, SalesData.Provider(), run);
ReportPageModel pages = ReportPaginator.Paginate(instance, fonts);
ReportPage first = pages.Pages[0];
Console.WriteLine($"{pages.Pages.Count} pages of {first.Width.Value / 1440.0}in x {first.Height.Value / 1440.0}in");
foreach (ReportPage page in pages.Pages)
{
string header = string.Concat(page.Items
.Where(i => i.Section == ReportPageSection.PageHeader)
.OfType<ReportPageTextbox>().Select(t => t.Value));
int rows = Flatten(page.Items).OfType<ReportPageTextbox>().Count(t => t.Name == "City");
Console.WriteLine($" page {page.OverallPageNumber}: header \"{header}\", {rows} store rows");
}
// Every item is positioned in twips from the page's top-left corner.
ReportPageTextbox title = first.Items.OfType<ReportPageTextbox>().First(t => t.Name == "Title");
Console.WriteLine($"title \"{title.Value}\" at {title.Left.Value},{title.Top.Value} twips, "
+ $"{title.Width.Value}x{title.Height.Value}, {title.Lines.Count} line(s)");
Output (all output from this page's samples):
2 pages of 8.5in x 11in
page 1: header "Page 1 of 2", 32 store rows
page 2: header "Page 2 of 2", 28 store rows
title "Sales: All regions" at 1440,1368 twips, 9360x504, 1 line(s)
document map:
Sales by region: page 1
Central: page 1
North: page 1
South: page 2
bookmark 'top' on page 1
toggle Central: key 'RegionBox@Detail:1.0x0', expanded True
toggle North: key 'RegionBox@Detail:1.1x0', expanded True
toggle South: key 'RegionBox@Detail:1.2x0', expanded True
North collapsed: 2 page(s), 40 store rows (was 60)
interactive: 6 pages of 4in
pdf: True, png: True
MaxReportPages: Pagination produced more than 1 pages.
Notes (Horizontal): 3 lines
Sales [bold] | up | 4%
• | North
• | South
Side (Rotate270): 1 lines
Quarterly figures

- A page's
ItemsareReportPageTextbox,ReportPageTablix,ReportPageRectangle,ReportPageLine,ReportPageImage, charts, gauges, maps and subreports. Each hasLeft,Top,WidthandHeightin twips from the page's top-left corner (1,440 twips = 1 inch), aStyle(borders and background), andChildren, such as a table's cells. - Each item has a
Section:Body,PageHeaderorPageFooter. - A
ReportPageLineruns from (X1,Y1) to (X2,Y2) with itsStroke. A line with a negative width is stroked from its left end, as Reporting Services strokes it. Every style is one stroke: dotted and dashed with the box border's dash arrays, double as a single solid line, andDefaultandNonesolid too, because Reporting Services draws a line in each of those styles. - A textbox carries its displayed
Value, theRawValuebefore formatting, itsFormatCode, and its laid-outLinesof positioned runs, which is what search and text selection need. - An item that continues onto the next page appears on both pages with the same
Id. Paginatealways needs aFontEngine, because text is measured. Building one reads every installed font and takes about a second, so create one and share it. It is safe to share between threads.
Navigation: the document map and bookmarks
using DocWright.Reporting.Pagination;
static void Map(IReadOnlyList<ReportDocumentMapNode> nodes, string indent)
{
foreach (ReportDocumentMapNode node in nodes)
{
Console.WriteLine($"{indent}{node.Label}: page {node.PageNumber}");
Map(node.Children, indent + " ");
}
}
Console.WriteLine("document map:");
Map(pages.DocumentMap, " ");
foreach (ReportBookmark bookmark in pages.Bookmarks)
{
Console.WriteLine($"bookmark '{bookmark.Name}' on page {bookmark.PageNumber}");
}
Items and groups with a DocumentMapLabel become DocumentMap nodes, nested as the report nests them, each with the page it's on. Items with a Bookmark are listed in Bookmarks. Every item and text run also carries its ToolTip and Actions: a hyperlink, a link to a bookmark, or a drill-through to another report with its parameters. Your application decides what to do with a drill-through.
When the model is rendered to PDF, hyperlinks and bookmark links become clickable links, bookmarks become link targets, and the document map becomes the PDF's outline.
Drill-down toggles
using DocWright.Reporting.Pagination;
// A textbox that shows or hides other rows carries a Toggle with a stable key.
foreach (ReportPageTextbox toggle in pages.Pages.SelectMany(p => Flatten(p.Items))
.OfType<ReportPageTextbox>().Where(t => t.Toggle is not null).DistinctBy(t => t.Toggle!.Key))
{
Console.WriteLine($"toggle {toggle.Value}: key '{toggle.Toggle!.Key}', expanded {toggle.Toggle.IsExpanded}");
}
// Collapse one region by sending its key back. No re-processing: paginate the same instance.
string northKey = pages.Pages.SelectMany(p => Flatten(p.Items)).OfType<ReportPageTextbox>()
.First(t => t.Toggle is not null && t.Value == "North").Toggle!.Key;
var collapsed = new ReportPaginationOptions();
collapsed.ToggledItems.Add(northKey);
ReportPageModel after = ReportPaginator.Paginate(instance, fonts, collapsed);
int storeRows = after.Pages.SelectMany(p => Flatten(p.Items)).OfType<ReportPageTextbox>().Count(t => t.Name == "City");
Console.WriteLine($"North collapsed: {after.Pages.Count} page(s), {storeRows} store rows (was 60)");
A textbox that other rows or items name in their ToggleItem has a Toggle. When the user clicks it, add its Key to ReportPaginationOptions.ToggledItems and paginate the same instance again. There's no need to process the report again, and the same set of keys always gives the same pages. A web server keeps that set between requests.
- The key identifies the textbox and the group instance it's in. A toggle repeated for each region has one key per region, and the same key refers to the same row next time.
IsExpandedis the state of the plus/minus icon. It comes from the textbox'sToggleImage/InitialState, and it flips while the key is inToggledItems. It doesn't depend on whether the rows start hidden, so setInitialStateto match. That's whatsales.rdldoes.
Print pages or screen pages
using DocWright.Reporting.Pagination;
// Soft pages for a screen: the definition's InteractiveHeight, no margins, never cut across.
ReportPageModel soft = ReportPaginator.Paginate(instance, fonts,
new ReportPaginationOptions { Mode = ReportPaginationMode.Interactive });
Console.WriteLine($"interactive: {soft.Pages.Count} pages of {soft.Pages[0].Height.Value / 1440.0}in");
ReportPaginationMode |
Page size | Use it for |
|---|---|---|
Physical (default) |
The definition's PageHeight and PageWidth, with its margins and columns |
PDF, printing, images |
Interactive |
The definition's InteractiveHeight and InteractiveWidth, with no margins and one column. A page is widened to fit its widest item instead of being cut. An InteractiveHeight of 0 makes the whole report one page. |
A viewer on screen |
Keeping things together, page breaks, repeated headers and page numbers follow the same rules in both modes.
Render to PDF and PNG
using DocWright.Core.Diagnostics;
using DocWright.Core.Rendering;
using DocWright.Renderers.Imaging;
using DocWright.Renderers.Pdf;
// The page model lowers to the same LayoutDocument that Word documents render from.
LayoutDocument layout = pages.ToLayoutDocument();
var diagnostics = new CollectingConversionDiagnostics();
using (FileStream pdf = File.Create("sales.pdf"))
{
new PdfLayoutRenderer(fonts).Render(layout, pdf, new RenderOptions(), diagnostics);
}
// And to PNG, one image per page.
var images = new ImageRenderOptions
{
Width = 800,
PageEncoded = (page, png) => File.WriteAllBytes($"sales-page-{page}.png", png),
};
new ImageLayoutRenderer(fonts, images).Render(layout, Stream.Null, new RenderOptions(), diagnostics);
Console.WriteLine($"pdf: {new FileInfo("sales.pdf").Length > 0}, png: {File.Exists("sales-page-1.png")}");
ToLayoutDocument() converts the page model into the same LayoutDocument that Word documents are drawn from, so PdfLayoutRenderer and ImageLayoutRenderer are used unchanged. Tagged PDF and PDF/A work the same way as for Word documents. See Page images for ImageRenderOptions and PDF/A and tagged PDF.
HTML text and turned text
using DocWright.Reporting.Data;
using DocWright.Reporting.Pagination;
using DocWright.Reporting.Processing;
using DocWright.Reporting.Rdl;
// An HTML run and a turned textbox, built in code.
const string Ns = "http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition";
static string Box(string name, string top, string width, string height, string run, string style) =>
$"<Textbox Name=\"{name}\"><CanGrow>true</CanGrow><Paragraphs><Paragraph><TextRuns>{run}</TextRuns><Style /></Paragraph></Paragraphs>" +
$"<Top>{top}</Top><Left>0in</Left><Height>{height}</Height><Width>{width}</Width><Style>{style}</Style></Textbox>";
string html = System.Security.SecurityElement.Escape(
"<b>Sales</b> up <font color='green'>4%</font><ul><li>North</li><li>South</li></ul>")!;
string rdl = $"<Report xmlns=\"{Ns}\"><ReportSections><ReportSection><Body><ReportItems>" +
Box("Notes", "0in", "4in", "0.25in", $"<TextRun><Value>{html}</Value><MarkupType>HTML</MarkupType><Style /></TextRun>", "") +
Box("Side", "1in", "0.4in", "2in", "<TextRun><Value>Quarterly figures</Value><Style /></TextRun>", "<WritingMode>Rotate270</WritingMode>") +
"</ReportItems><Height>3in</Height></Body><Width>4in</Width><Page><PageHeight>4in</PageHeight><PageWidth>4.5in</PageWidth><TopMargin>0.25in</TopMargin><LeftMargin>0.25in</LeftMargin></Page></ReportSection></ReportSections></Report>";
ReportDefinition notes;
using (var input = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(rdl))) { notes = new RdlReader().Read(input); }
using ReportInstance notesInstance = ReportProcessor.Process(notes, new ReportInMemoryDataProvider(), new ReportRunOptions());
ReportPageModel notesPages = ReportPaginator.Paginate(notesInstance, fonts);
foreach (ReportPageTextbox box in notesPages.Pages[0].Items.OfType<ReportPageTextbox>())
{
Console.WriteLine($"{box.Name} ({box.WritingMode}): {box.Lines.Count} lines");
foreach (ReportTextLine line in box.Lines)
{
Console.WriteLine(" " + string.Join(" | ", line.Runs.Select(r => $"{r.Text}{(r.Bold ? " [bold]" : "")}")));
}
}

Rotate270 box reads bottom to top.These textbox properties are applied as Reporting Services applies them. Each was measured against Microsoft's engine.
| Property | What pagination does |
|---|---|
MarkupType HTML |
Reads the subset Reporting Services reads: b/strong, i/em, u, s, font (color, face, size 1–7), span with CSS font-family, font-size, font-weight and color, a href (a hyperlink), br, p, div, h1–h6, ul/ol/li, and a block's text-align and text-indent. An unknown tag is dropped and its text kept. Like the reference, a span's font-style and text-decoration are ignored. |
WritingMode |
Vertical turns the text a quarter turn clockwise, and Rotate270 the other way. The text is laid out along the box's height. ReportPageTextbox.WritingMode says which; a turned box's Lines are in an upright frame, and its documentation gives the mapping to the page. PDF, images and the viewer draw it turned, Word turns the cell and Excel sets textRotation. |
HideDuplicates |
Blanks a value equal to the previous row's in the named scope: a dataset, the region, or a group, which starts again in each group instance. |
NoRowsMessage |
On an empty tablix, the message is drawn in the tablix's place and style instead of its rows. |
Direction RTL |
An unstated alignment becomes right. |
LineHeight, NumeralVariant, RepeatWith beside a data region and FixedData do nothing in Reporting Services' own PDF and image output, and nothing here. A rectangle cut across pages has no border at the cut, whatever OmitBorderOnPageBreak says, because that is what the reference draws.
Diagnostics and the page limit
using DocWright.Core;
using DocWright.Reporting.Pagination;
using DocWright.Reporting.Processing;
foreach (var diagnostic in pages.Diagnostics)
{
Console.WriteLine($"{diagnostic.Code} {diagnostic.Severity}: {diagnostic.Message}");
}
var bounded = new ReportRunOptions { ExecutionTime = run.ExecutionTime };
bounded.Parameters["Region"] = new ReportParameterValue("*");
bounded.Limits.MaxReportPages = 1;
using ReportInstance small = ReportProcessor.Process(definition, SalesData.Provider(), bounded);
try
{
ReportPaginator.Paginate(small, fonts);
}
catch (ResourceLimitExceededException error)
{
Console.WriteLine($"{error.LimitName}: {error.Message}");
}
Pagination reports what it couldn't do in ReportPageModel.Diagnostics, or as it happens through ReportPaginationOptions.Diagnostics:
| Code | Meaning |
|---|---|
DXP9301 |
A chart or gauge panel whose data wasn't processed isn't drawn. It keeps its position and size. |
DXP9303 |
A style value couldn't be read, so its default is used. |
DXP9304 |
A page has no room for its body. |
DXP9306 |
A property is read but not applied: a NoRowsMessage on an empty chart or gauge panel (the empty item is drawn), or right-to-left text, which is drawn in logical order and unshaped. |
MaxReportPages (100,000 by default, in ReportRunOptions.Limits) is checked before each page is built. Cancellation is checked between items and pages. Pagination is stateless and safe to run on several threads over one ReportInstance.
Next steps
- Draw maps: planar and geographic maps coloured by data.
- Export a report to Word, Excel, CSV or text, from the same page model.
- Show reports in a browser with HTML, SVG and a clickable region map.