Regira-Packages

Regira Office.PDF

Regira Office.PDF provides a unified abstraction for PDF operations — HTML→PDF, Office documents→PDF, images→PDF, PDF→images, text extraction, merge/split, and printing — across multiple underlying libraries.

Projects

Project Package Backend HTML→PDF Office→PDF PDF ops Print
Common.Office (transitive) Shared abstractions — — — —
PDF.SelectPdf Regira.Office.PDF.SelectPdf Select.HtmlToPdf ✓ full — — —
PDF.Puppeteer Regira.Office.PDF.Puppeteer PuppeteerSharp ✓ full — — —
PDF.Playwright Regira.Office.PDF.MsPlaywright Microsoft.Playwright ✓ full — — —
PDF.Gotenberg Regira.Office.PDF.Gotenberg Gotenberg server (Chromium) ✓ full — — —
PDF.PdfPig Regira.Office.PDF.PdfPig PdfPig + PDFtoImage — — merge, split, img↔pdf, text —
PDF.DocNET Regira.Office.PDF.DocNET Docnet.Core (deprecated) — — merge, split, img↔pdf, text —
PDF.MiniPdf Regira.Office.PDF.MiniPdf MiniPdf — ✓ docx, xlsx, pptx — —
PDF.Spire Regira.Office.PDF.Spire FreeSpire.PDF — — merge, split, pdf→img, text ✓
PDF.PDFtoPrinter Regira.Office.PDF.PDFtoPrinter PDFtoPrinter — — — ✓ (Win)
PDF.PockyBum522 Regira.Office.PDF.PockyBum522 SimpleFreePdfPrinter — — — ✓ (Win)

Installation

<!-- HTML→PDF (recommended — headless Chromium, any OS) -->
<PackageReference Include="Regira.Office.PDF.MsPlaywright" Version="6.*" />
<PackageReference Include="Regira.Office.PDF.Puppeteer" Version="6.*" />

<!-- HTML→PDF through a Gotenberg server (Chromium in a container of its own, none in the application) -->
<PackageReference Include="Regira.Office.PDF.Gotenberg" Version="6.*" />

<!-- HTML→PDF (Windows, up to five pages, nothing to download) -->
<PackageReference Include="Regira.Office.PDF.SelectPdf" Version="6.*" />

<!-- Word, Excel and PowerPoint → PDF (in-process, no licence) -->
<PackageReference Include="Regira.Office.PDF.MiniPdf" Version="6.*" />

<!-- PDF operations (merge, split, text, images) -->
<PackageReference Include="Regira.Office.PDF.PdfPig" Version="6.*" />
<PackageReference Include="Regira.Office.PDF.Spire" Version="6.*" />

<!-- PDF operations on Docnet.Core (deprecated) -->
<PackageReference Include="Regira.Office.PDF.DocNET" Version="6.*" />

<!-- Print (Windows) -->
<PackageReference Include="Regira.Office.PDF.PDFtoPrinter" Version="6.*" />
<PackageReference Include="Regira.Office.PDF.PockyBum522" Version="6.*" />

Quick Start

// HTML → PDF (Playwright)
IHtmlToPdfService pdf = new Regira.Office.PDF.MsPlaywright.PdfManager();
IMemoryFile file = await pdf.Create(new HtmlInput
{
    HtmlContent = "<h1>Hello</h1>",
    Format      = PageSize.A4,
    Orientation = PageOrientation.Portrait
});

// Word, Excel or PowerPoint → PDF (MiniPdf)
IDocumentToPdfService converter = new Regira.Office.PDF.MiniPdf.PdfService();
IMemoryFile reportPdf = await converter.Create(new DocumentInput
{
    Document = File.ReadAllBytes("report.docx").ToMemoryFile(),
    Format   = PageSize.A4
});

// Merge PDFs (PdfPig — needs an IImageService for the image-related operations)
IMemoryFile pdf1 = File.ReadAllBytes("1.pdf").ToMemoryFile();
IMemoryFile pdf2 = File.ReadAllBytes("2.pdf").ToMemoryFile();
IMemoryFile pdf3 = File.ReadAllBytes("3.pdf").ToMemoryFile();
IImageService imageService = new Regira.Drawing.SkiaSharp.Services.ImageService();
IPdfMerger merger = new Regira.Office.PDF.PdfPig.PdfService(imageService);
IMemoryFile merged = (await merger.Merge([pdf1, pdf2, pdf3]))!;

// Reading a result — GetBytes() (Regira.IO.Extensions), not .Bytes
byte[] bytes = merged.GetBytes()!;

IMemoryFile extends both IMemoryBytesFile (Bytes) and IMemoryStreamFile (Stream), and a producer fills exactly one. Which one varies per method rather than per backend — DocNET’s Split returns byte-backed files while its Merge returns a stream-backed one — so .Bytes reads null for half the API and yields an empty file with no exception. GetBytes() normalises both and is correct everywhere.

Interfaces

IHtmlToPdfService

Task<IMemoryFile> Create(HtmlInput template, CancellationToken cancellationToken = default);

IDocumentToPdfService

Task<IMemoryFile> Create(DocumentInput input, CancellationToken cancellationToken = default);

Converts a Word document, a spreadsheet or a presentation. A source format or a DocumentInput setting the backend cannot handle throws NotSupportedException rather than being ignored.

IPdfMerger / IPdfSplitter / IPdfEditor

// IPdfMerger
Task<IMemoryFile?>              Merge(IEnumerable<IMemoryFile> items, CancellationToken cancellationToken = default);

// IPdfSplitter
Task<IEnumerable<IMemoryFile>>  Split(IMemoryFile pdf, IEnumerable<PdfSplitRange> ranges, CancellationToken cancellationToken = default);
Task<int>                       GetPageCount(IMemoryFile pdf, CancellationToken cancellationToken = default);

// IPdfEditor : IPdfMerger, IPdfSplitter
Task<IMemoryFile?>              RemovePages(IMemoryFile pdf, IEnumerable<int> pages, CancellationToken cancellationToken = default);

Every backend treats the edges alike:

IPdfToImageService / IImagesToPdfService

Task<IList<IImageFile>>  ToImages(IMemoryFile pdf, PdfToImagesOptions? options = null, CancellationToken cancellationToken = default);
Task<IMemoryFile?>       ImagesToPdf(ImagesInput input, CancellationToken cancellationToken = default);

ToImages returns an image per page, fitted to PdfToImagesOptions.Size either way round — the page’s shorter side to the smaller dimension, its longer side to the larger — keeping the page’s aspect ratio, so the default 1080 × 1920 gives a portrait A4 page 1080 pixels wide and a landscape one 1080 pixels high. Without options it takes PdfDefaults.ImageSize and PdfDefaults.ImageFormat (JPEG). ImagesToPdf without images returns null. PdfClient (Regira.Office.Clients) posts the images only, so the Office API lays them out on its defaults: an ImagesInput with another Format, Orientation or Margins throws NotSupportedException.

IPdfTextExtractor / IPdfTextService

Task<string>          GetText(IMemoryFile pdf, CancellationToken cancellationToken = default);
Task<IList<string>>   GetTextPerPage(IMemoryFile pdf, CancellationToken cancellationToken = default);
Task<IMemoryFile?>    RemoveEmptyPages(IMemoryFile pdf, CancellationToken cancellationToken = default);

IPdfPrinter

string              DefaultPrinter { get; }
Task<IList<string>> List(CancellationToken cancellationToken = default);
Task                Print(PdfPrinterInput input, CancellationToken cancellationToken = default);

IPdfService

Composite: IPdfEditor + IPdfImageService + IPdfTextService. Implemented by PdfPig’s PdfService (and the deprecated DocNET PdfManager).

Input / Output Models

HtmlInput

Property Type Default Description
HtmlContent string? null HTML to convert
HeaderHtmlContent string? null Repeating page header: the band’s markup, a fragment such as a <div>, not a document
FooterHtmlContent string? null Repeating page footer: the band’s markup, a fragment such as a <div>, not a document
HeaderHeight int? null Header height in mm; null is 45 pt
FooterHeight int? null Footer height in mm; null is 35 pt
Format PageSize A4 Paper size
Orientation PageOrientation Portrait Portrait / Landscape
Margins Margins 10mm all Page margins, in units of DPI; Margins.ModifyDpi measures them at another. A float[] gives one value for every side, two for left and right then top and bottom, three for top, left and right, bottom, four for top, right, bottom, left. A new Margins() starts every side at Margins.DEFAULT_MARGIN (70.85, 25 mm at 72 DPI), not at this default: set all four sides
DPI int 96 Units per inch of Margins. Pass it to the constructor (new HtmlInput(72), new ImagesInput(300)): the default Margins are computed from the constructor’s DPI, so new ImagesInput { DPI = 300 } keeps 37.8 units, 3.2 mm at 300

DocumentInput

The page settings override the document’s own page setup; each one left null keeps what the document says.

Property Type Default Description
Document IMemoryFile (required) Document to convert
Format PageSize? null Paper size
Orientation PageOrientation? null Portrait / Landscape
Margins Margins? null Page margins (in points)

ImagesInput

Same base properties as HtmlInput plus:

Property Type Description
Images ICollection<byte[]> One image per page

PdfToImagesOptions

Property Type Default Description
Size ImageSize? 1080 × 1920 The box each page image fits, either way round
Format ImageFormat Jpeg Output image format

PdfSplitRange

Property Type Description
Start int First page (1-indexed)
End int? Last page, included (null = last page of document)

PdfPrinterInput

Property Type Default Description
PdfFile IMemoryFile (required) PDF to print
PrinterName string? default printer Target printer
PageSize PageSize A4 Paper size
PageOrientation PageOrientation Portrait Orientation

Implementation notes

Both render in headless Chromium and apply every HtmlInput setting, on Windows, Linux and macOS, with no page limit; Playwright is the recommended one. Chromium is installed (Playwright) or downloaded (Puppeteer) on first use, guarded by a process-wide lock, so the first conversion needs network access and writable disk, or a browser installed in advance. Each conversion starts a browser of its own, which takes one to three seconds.

Gotenberg — HTML→PDF without a browser in the application

PdfService posts the HTML to the Chromium route of a Gotenberg server (MIT, a Docker image bundling Chromium and LibreOffice). It applies every HtmlInput setting as Playwright does: page, margins, header and footer bands and page numbers are those described above, and backgrounds are left out. Nothing runs or downloads in the application, and Chromium stays running in the container, so a one-page PDF takes about a tenth of a second once the server is warm. Pick it for container setups: an application image that must stay slim or may download nothing at run time, or a deployment that already runs Gotenberg for Word.Gotenberg.

Start a server and register the service. The hardening flags follow the image’s gotenberg command; single quotes keep a shell from reading the ! and the parentheses of the pattern:

docker run --rm -p 3000:3000 gotenberg/gotenberg:8
# HTML that needs nothing from the network
docker run --rm -p 3000:3000 gotenberg/gotenberg:8 gotenberg '--chromium-deny-list=^(https?://|file:(?!//\/tmp/)).*'
# HTML built from user input that loads public URLs
docker run --rm -p 3000:3000 gotenberg/gotenberg:8 gotenberg --chromium-deny-private-ips
using Microsoft.Extensions.DependencyInjection;
using Regira.Office.PDF.Gotenberg.DependencyInjection;

IServiceCollection services = new ServiceCollection();

services.AddGotenbergPdf(o =>
{
    o.BaseUrl = "http://localhost:3000";
    o.Timeout = TimeSpan.FromMinutes(2);
});

AddGotenbergPdf registers IHtmlToPdfService on an HttpClient named ServiceCollectionExtensions.HttpClientName — add handlers or resilience through services.AddHttpClient(ServiceCollectionExtensions.HttpClientName) — which keeps its own base address and credentials beside Word.Gotenberg’s, even when both point at one server. Username and Password send basic authentication, for a server started with --api-enable-basic-auth. Without DI, construct PdfService with an HttpClient whose BaseAddress points at the server.

SelectPdf — HTML→PDF on Windows, up to five pages

Applies every HtmlInput property: page size, orientation, margins, headers, footers. Does not require a browser installation.

It runs on Windows only: it renders through System.Drawing.Common, which throws on other platforms. The free Community Edition of Select.HtmlToPdf converts only the first five pages’ worth of a document, and leaves the rest out of the PDF without an error or a notice. For longer documents, use the vendor’s paid edition or Playwright.

It renders a header or footer as a page of its own, with the browser’s default 8px around its body, and shows no page numbers in it. Every page holds the whole document, clipped to its own part, so text extracted from one page is the whole document’s.

MiniPdf — Word, Excel and PowerPoint to PDF

PdfService implements IDocumentToPdfService with MiniPdf: it converts .docx, .xlsx and .pptx in-process, with no Office installation, server, browser or licence. MiniPdf lays documents out itself, so a complex layout comes out less faithful than through LibreOffice or Word; for a Word document that must match Word’s layout, convert it with a Word backend’s IWordConverter.

It applies the DocumentInput settings per source format:

Source Takes Throws NotSupportedException for
.docx Format (with or without Orientation), Margins Orientation without Format — MiniPdf replaces the page size as a whole
.xlsx Orientation Format, Margins
.pptx — (a slide keeps the presentation’s slide size) Format, Orientation, Margins

Any other source — .doc, .xls, .odt, .rtf, a PDF — throws NotSupportedException. The format is read from the package’s parts, not from the file name or content type. Every visible sheet of a workbook is rendered, in order. PdfService applies no fit-to-width: unless the workbook’s own page setup scales a sheet to one page wide (Excel’s Scale to Fit, width 1 page), columns past the page width print on further pages, and the sheet name is not printed. For a wide sheet, use Orientation = PageOrientation.Landscape, fewer or narrower columns, or a .docx table.

Neither MiniPdf nor PdfService limits a document’s size. Each part is read whole into memory, so a small .xlsx, .docx or .pptx whose compressed parts expand to gigabytes exhausts the process’s memory. For uploads, cap the file’s size and the summed Length and count of its zip entries before converting, or convert in a process of its own.

Text renders in the host’s system fonts. On a host with few — a container — register TrueType fonts once at startup; the registration holds for the whole process:

MiniSoftware.MiniPdf.RegisterFont("NotoSans", File.ReadAllBytes("Fonts/NotoSans-Regular.ttf"));

PdfService implements IPdfService: merge, split, page removal, text extraction, and images↔PDF. Merging, splitting, text and images→PDF run on PdfPig, which is fully managed; page images render through PDFtoImage over PDFium, which ships native binaries for Windows, Linux and macOS (x64 and arm64). Both are free for commercial use (Apache-2.0 and MIT). The constructor takes an IImageService, which reads the images going into a PDF and produces the page images coming out of one.

IImageService imageService = new Regira.Drawing.SkiaSharp.Services.ImageService();
var pdf = new Regira.Office.PDF.PdfPig.PdfService(imageService);

DocNET — deprecated

Implements IPdfService on Docnet.Core, which has had no release since 2.6.0 (2023) and bundles a PDFium build from 2022. PDFium parses every PDF it is given, so an outdated build is a risk for uploaded files; use PdfPig. It takes fixes for crashes, data loss and security holes only. ImagesToPdf makes each page the size of its image: the image is scaled down to fit the format’s page less its margins, measured in units of DPI, and the page takes that many points. Requires IImageService in the constructor.

Spire — PDF operations + printing

Implements IPdfMerger, IPdfSplitter, IPdfToImageService and IPdfTextExtractor — not the full IPdfService: there is no RemovePages, ImagesToPdf, GetTextPerPage or RemoveEmptyPages, and image conversion is PDF→image only. Also ships PdfPrinter for Windows printing with page size override support.

FreeSpire.PDF is the vendor’s free edition. Loading or creating a PDF of more than ten pages throws, a merge whose result passes ten included, and ToImages renders only the first three pages, returning blank images for the rest.

Overview

  1. Index — Overview, interfaces, models, and implementation notes
  2. Examples — HTML→PDF, Office documents→PDF, merge, split, text extraction, printing