Interface IDocxEditor
- Namespace
- DocToolkit.Extensions.DependencyInjection
- Assembly
- DocToolkit.Extensions.DependencyInjection.dll
Creates, reads and edits Word (.docx) documents. Registered by AddDocToolkit(IServiceCollection, Action<DocToolkitOptions>?).
public interface IDocxEditor
Methods
AddBookmark(byte[], int, string)
Adds a bookmark named name to the paragraph at
paragraphIndex, and returns the updated document.
byte[] AddBookmark(byte[] docx, int paragraphIndex, string name)
Parameters
docxbyte[]The document to edit. It is not modified.
paragraphIndexintThe 0-based paragraph to mark.
namestringThe bookmark name.
Returns
- byte[]
A new document; the input is not modified.
Remarks
paragraphIndex is 0-based, matching everything else this interface
indexes.
Exceptions
- ArgumentNullException
docxornameis null.- ArgumentException
docxis empty, ornameis blank.- ArgumentOutOfRangeException
paragraphIndexis negative, or at or beyond the paragraph count.- DocumentConversionException
The document could not be opened or written.
AddBookmarkAsync(Stream, int, string, Stream, CancellationToken)
Adds a bookmark named name to the paragraph at
paragraphIndex, and returns the updated document.
Task AddBookmarkAsync(Stream source, int paragraphIndex, string name, Stream destination, CancellationToken ct = default)
Parameters
sourceStreamThe stream the document is read from.
paragraphIndexintThe 0-based paragraph to mark.
namestringThe bookmark name.
destinationStreamThe stream the updated document is written to.
ctCancellationTokenCancels the read, the edit and the write.
Returns
Remarks
source is read to its end and destination is
written; neither is disposed, closed or sought.
Exceptions
- ArgumentNullException
An argument is null.
- ArgumentException
sourceis not readable or held no bytes,nameis blank, ordestinationis not writable.- ArgumentOutOfRangeException
paragraphIndexis negative, or at or beyond the paragraph count.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The document could not be opened or written.
AddEndnote(byte[], string, string)
Adds an endnote at every occurrence of placeholder, inline, across the
document body.
byte[] AddEndnote(byte[] docx, string placeholder, string endnoteText)
Parameters
Returns
- byte[]
Exceptions
- ArgumentNullException
Any of the three required arguments is null.
- ArgumentException
docxis empty, orplaceholderis blank.- DocumentConversionException
The package could not be edited, or
placeholderdoes not appear in the body.
AddEndnoteAsync(Stream, string, string, Stream, CancellationToken)
Reads a .docx from source, adds an endnote at every occurrence of
placeholder, and writes the result to destination —
see AddEndnote(byte[], string, string). Neither stream is disposed, closed or sought.
Task AddEndnoteAsync(Stream source, string placeholder, string endnoteText, Stream destination, CancellationToken ct = default)
Parameters
sourceStreamplaceholderstringendnoteTextstringdestinationStreamctCancellationToken
Returns
Exceptions
- ArgumentNullException
Any argument is null.
- ArgumentException
sourceis not readable or held no bytes,destinationis not writable, orplaceholderis blank.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The package could not be edited, or the placeholder was not found.
AddFootnote(byte[], string, string)
Adds a footnote at every occurrence of placeholder, inline, across the
document body.
byte[] AddFootnote(byte[] docx, string placeholder, string footnoteText)
Parameters
Returns
- byte[]
Exceptions
- ArgumentNullException
Any of the three required arguments is null.
- ArgumentException
docxis empty, orplaceholderis blank.- DocumentConversionException
The package could not be edited, or
placeholderdoes not appear in the body.
AddFootnoteAsync(Stream, string, string, Stream, CancellationToken)
Reads a .docx from source, adds a footnote at every occurrence of
placeholder, and writes the result to destination —
see AddFootnote(byte[], string, string). Neither stream is disposed, closed or sought.
Task AddFootnoteAsync(Stream source, string placeholder, string footnoteText, Stream destination, CancellationToken ct = default)
Parameters
sourceStreamplaceholderstringfootnoteTextstringdestinationStreamctCancellationToken
Returns
Exceptions
- ArgumentNullException
Any argument is null.
- ArgumentException
sourceis not readable or held no bytes,destinationis not writable, orplaceholderis blank.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The package could not be edited, or the placeholder was not found.
AddTableOfContents(byte[], string, int, int)
Replaces the paragraph containing only placeholder with a table of
contents spanning heading levels minLevel through
maxLevel.
byte[] AddTableOfContents(byte[] docx, string placeholder, int minLevel = 1, int maxLevel = 3)
Parameters
Returns
- byte[]
Exceptions
- ArgumentNullException
Either required argument is null.
- ArgumentException
docxis empty,placeholderis blank, orminLevelis greater thanmaxLevel.- ArgumentOutOfRangeException
minLevelormaxLevelis outside 1-9.- DocumentConversionException
The package could not be edited; no paragraph containing only the placeholder was found; the paragraph holding it also holds content other than plain text; that paragraph's
w:pPrcarries aw:sectPr, so replacing it would discard a section break; or more than one paragraph's text exactly matches the placeholder.
AddTableOfContentsAsync(Stream, string, Stream, int, int, CancellationToken)
Reads a .docx from source, replaces the paragraph containing only
placeholder with a table of contents, and writes the result to
destination — see AddTableOfContents(byte[], string, int, int). Neither stream is
disposed, closed or sought.
Task AddTableOfContentsAsync(Stream source, string placeholder, Stream destination, int minLevel = 1, int maxLevel = 3, CancellationToken ct = default)
Parameters
Returns
Exceptions
- ArgumentNullException
Any argument is null.
- ArgumentException
sourceis not readable or held no bytes,destinationis not writable,placeholderis blank, orminLevelis greater thanmaxLevel.- ArgumentOutOfRangeException
minLevelormaxLevelis outside 1-9.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The package could not be edited; no matching paragraph was found; the paragraph holding the placeholder also holds content other than plain text; that paragraph's
w:pPrcarries aw:sectPr, so replacing it would discard a section break; or more than one paragraph's text exactly matches the placeholder.
AddWatermark(byte[], string)
Stamps text across the page as a watermark, and returns the updated
document.
byte[] AddWatermark(byte[] docx, string text)
Parameters
Returns
- byte[]
A new document; the input is not modified.
Remarks
Applied to every section the document reports, which is not always one per
w:sectPr in the body. Measured: a document produced by
Merge(IEnumerable<byte[]>) carries two w:sectPr elements but
reports a single section, so it receives one watermark rather than one per merged
document — pages belonging to the later part may therefore be unmarked. See the package
README's Known Limitations.
Exceptions
- ArgumentNullException
docxortextis null.- ArgumentException
docxis empty, ortextis blank.- DocumentConversionException
The document could not be opened or written.
AddWatermarkAsync(Stream, string, Stream, CancellationToken)
Stamps text across the page as a watermark, and returns the updated
document.
Task AddWatermarkAsync(Stream source, string text, Stream destination, CancellationToken ct = default)
Parameters
sourceStreamThe stream the document is read from.
textstringThe watermark text.
destinationStreamThe stream the stamped document is written to.
ctCancellationTokenCancels the read, the edit and the write.
Returns
Remarks
Applied to every section, for the reason AddWatermark(byte[], string) records.
source is read to its end and destination is
written; neither is disposed, closed or sought.
Exceptions
- ArgumentNullException
An argument is null.
- ArgumentException
sourceis not readable or held no bytes,textis blank, ordestinationis not writable.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The document could not be opened or written.
Create(IEnumerable<DocxBlock>)
Builds a document from blocks — headings, paragraphs, tables and inline
images. Content comes from data rather than markup, so there is no HTML to escape and a value
containing < cannot corrupt the document's structure. An empty sequence is valid.
byte[] Create(IEnumerable<DocxBlock> blocks)
Parameters
blocksIEnumerable<DocxBlock>
Returns
- byte[]
Exceptions
- ArgumentNullException
blocksis null.- ArgumentException
An element of
blocksis null.- DocumentConversionException
The document could not be built.
Create(IEnumerable<DocxBlock>, PageSetup)
As above, laid out on page rather than the A4 default.
byte[] Create(IEnumerable<DocxBlock> blocks, PageSetup page)
Parameters
blocksIEnumerable<DocxBlock>The content, written in order.
pagePageSetupThe page size, orientation and margins.
Returns
- byte[]
Exceptions
- ArgumentNullException
blocksorpageis null.- ArgumentException
An element of
blocksis null.- DocumentConversionException
The document could not be built.
CreateAsync(IEnumerable<DocxBlock>, PageSetup, Stream, CancellationToken)
As above, laid out on page rather than the A4 default.
Task CreateAsync(IEnumerable<DocxBlock> blocks, PageSetup page, Stream destination, CancellationToken ct = default)
Parameters
blocksIEnumerable<DocxBlock>The content, written in order.
pagePageSetupThe page size, orientation and margins.
destinationStreamThe stream the document is written to.
ctCancellationTokenCancels the build and the write.
Returns
Exceptions
- ArgumentNullException
Any argument is null.
- ArgumentException
An element of
blocksis null, ordestinationis not writable.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The document could not be built or written.
CreateAsync(IEnumerable<DocxBlock>, Stream, CancellationToken)
Builds a document from blocks and writes it to
destination. See Create(IEnumerable<DocxBlock>) for the block semantics.
destination is written and is neither disposed, closed nor sought,
so an HTTP response body is a valid destination.
Task CreateAsync(IEnumerable<DocxBlock> blocks, Stream destination, CancellationToken ct = default)
Parameters
blocksIEnumerable<DocxBlock>destinationStreamctCancellationToken
Returns
Exceptions
- ArgumentNullException
blocksordestinationis null.- ArgumentException
An element of
blocksis null, ordestinationis not writable.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The document could not be built or written.
ExtractText(byte[])
Returns the plain text of the document body. Headers, footers, footnotes and endnotes are not included.
string ExtractText(byte[] docx)
Parameters
docxbyte[]
Returns
Exceptions
- ArgumentNullException
docxis null.- ArgumentException
docxis empty.- DocumentConversionException
The package could not be opened or read.
ExtractText(byte[], bool)
Returns the plain text of the document. When includeHeadersAndFooters is true, headers and footers follow the body text; footnotes and endnotes are never included.
string ExtractText(byte[] docx, bool includeHeadersAndFooters)
Parameters
Returns
Exceptions
- ArgumentNullException
docxis null.- ArgumentException
docxis empty.- DocumentConversionException
The package could not be opened or read.
ExtractTextAsync(Stream, bool, CancellationToken)
Reads a .docx from source and returns its plain text. See
ExtractText(byte[], bool) for what includeHeadersAndFooters
controls. source is read to its end and is neither disposed, closed
nor sought.
Task<string> ExtractTextAsync(Stream source, bool includeHeadersAndFooters, CancellationToken ct = default)
Parameters
sourceStreamincludeHeadersAndFootersboolctCancellationToken
Returns
Exceptions
- ArgumentNullException
sourceis null.- ArgumentException
sourceis not readable or held no bytes.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The package could not be opened or read.
ExtractTextAsync(Stream, CancellationToken)
Reads a .docx from source and returns the plain text of its body. Headers,
footers, footnotes and endnotes are not included. source is read to
its end and is neither disposed, closed nor sought.
Task<string> ExtractTextAsync(Stream source, CancellationToken ct = default)
Parameters
sourceStreamctCancellationToken
Returns
Exceptions
- ArgumentNullException
sourceis null.- ArgumentException
sourceis not readable or held no bytes.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The package could not be opened or read.
FillRows(byte[], string, IEnumerable<IReadOnlyDictionary<string, string>>)
Expands a template table row once per record. A row holding {{collection.Field}}
markers becomes one row per record, each keeping the template row's formatting.
byte[] FillRows(byte[] docx, string collection, IEnumerable<IReadOnlyDictionary<string, string>> rows)
Parameters
docxbyte[]collectionstringrowsIEnumerable<IReadOnlyDictionary<string, string>>
Returns
- byte[]
Exceptions
- ArgumentNullException
Any argument is null.
- ArgumentException
docxis empty, orcollectionis blank.- DocumentConversionException
The package could not be opened or edited.
FillRowsAsync(Stream, string, IEnumerable<IReadOnlyDictionary<string, string>>, Stream, CancellationToken)
Reads a .docx from source, expands the template row once per record, and
writes the result to destination. See FillRows(byte[], string, IEnumerable<IReadOnlyDictionary<string, string>>) for the
expansion rules. Neither stream is disposed, closed or sought.
Task FillRowsAsync(Stream source, string collection, IEnumerable<IReadOnlyDictionary<string, string>> rows, Stream destination, CancellationToken ct = default)
Parameters
sourceStreamcollectionstringrowsIEnumerable<IReadOnlyDictionary<string, string>>destinationStreamctCancellationToken
Returns
Exceptions
- ArgumentNullException
Any argument is null.
- ArgumentException
sourceis not readable or held no bytes,destinationis not writable, orcollectionis blank.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The package could not be opened or edited.
InspectSignatures(byte[])
Inspects docx for digital signatures — whether it carries one, how
many, and who claims to have signed it. Does not validate anything cryptographically; see
ValidateSignatures(byte[], DocumentSignatureValidationOptions?).
DocumentSignatureInfo InspectSignatures(byte[] docx)
Parameters
docxbyte[]
Returns
Exceptions
- ArgumentNullException
docxis null.- ArgumentException
docxis empty.- DocumentConversionException
The document could not be inspected.
InspectSignaturesAsync(Stream, CancellationToken)
Reads a .docx from source and inspects it for digital signatures — see
InspectSignatures(byte[]). source is read to its end and is
neither disposed, closed nor sought.
Task<DocumentSignatureInfo> InspectSignaturesAsync(Stream source, CancellationToken ct = default)
Parameters
sourceStreamctCancellationToken
Returns
Exceptions
- ArgumentNullException
sourceis null.- ArgumentException
sourceis not readable or held no bytes.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The document could not be inspected.
IsProtected(byte[])
Whether docx is encrypted - that is, whether the other members here
will refuse it. Reads the file signature; needs no password.
bool IsProtected(byte[] docx)
Parameters
docxbyte[]
Returns
Exceptions
- ArgumentNullException
docxis null.
IsProtectedAsync(Stream, CancellationToken)
Whether docx is encrypted - that is, whether the other members here
will refuse it. Reads the file signature; needs no password.
Task<bool> IsProtectedAsync(Stream source, CancellationToken ct = default)
Parameters
sourceStreamThe stream the document is read from.
ctCancellationTokenCancels the read.
Returns
Remarks
source is read to its end and is neither disposed, closed nor
sought. Unlike IsProtected(byte[]), which answers false
for an empty array, an empty source is rejected - every Stream
overload in this package treats a source that held no bytes as a caller error rather
than as content.
Exceptions
- ArgumentNullException
sourceis null.- ArgumentException
sourceis not readable or held no bytes.- OperationCanceledException
ctwas cancelled.
Merge(IEnumerable<byte[]>)
Joins docx end to end, in order, into one document — the DOCX
counterpart of Merge(IEnumerable<byte[]>).
byte[] Merge(IEnumerable<byte[]> docx)
Parameters
docxIEnumerable<byte[]>The documents to join, in order. At least one.
Returns
- byte[]
A new document; none of the inputs is modified.
Remarks
Each document keeps its own page setup, as its own section, so merging an A4 document with a Letter one produces a two-section file.
Where two documents define the same style id differently, the FIRST definition wins and the later content adopts it, silently — no error is raised and no text is lost, only the appearance changes. Give the documents distinct style ids, or merge documents that share a template. Both behaviours were measured; see the package README's Known Limitations.
Exceptions
- ArgumentNullException
docx, or an element of it, is null.- ArgumentException
docxis empty, or an element holds no bytes.- DocumentConversionException
A document could not be opened or the result could not be written.
MergeAsync(IEnumerable<Stream>, Stream, CancellationToken)
Joins docx end to end, in order, into one document — the DOCX
counterpart of Merge(IEnumerable<byte[]>).
Task MergeAsync(IEnumerable<Stream> sources, Stream destination, CancellationToken ct = default)
Parameters
sourcesIEnumerable<Stream>The streams the documents are read from, in order. At least one.
destinationStreamThe stream the joined document is written to.
ctCancellationTokenCancels the reads, the merge and the write.
Returns
Remarks
Every stream in sources is read to its end and
destination is written; none is disposed, closed or sought.
Exceptions
- ArgumentNullException
sourcesordestinationis null.- ArgumentException
sourcesis empty, one of them is not readable or held no bytes, ordestinationis not writable.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
A document could not be opened or the result could not be written.
Protect(byte[], string)
A copy of docx encrypted with password.
byte[] Protect(byte[] docx, string password)
Parameters
Returns
- byte[]
Remarks
File encryption, not the "restrict editing" flag. The result is a compound file rather than a DOCX package, so every other member here refuses it - call Unprotect(byte[], string) first.
Exceptions
- ArgumentNullException
docxorpasswordis null.- ArgumentException
docxis empty, orpasswordis empty.- DocumentConversionException
It could not be read or encrypted.
ProtectAsync(Stream, Stream, string, CancellationToken)
Reads a document from source and writes the encrypted copy to
destination. Neither stream is disposed, closed or sought.
Task ProtectAsync(Stream source, Stream destination, string password, CancellationToken ct = default)
Parameters
sourceStreamdestinationStreampasswordstringctCancellationToken
Returns
Exceptions
- ArgumentNullException
Either stream is null, or
passwordis null.- ArgumentException
A stream is unusable, or
passwordis empty.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
It could not be encrypted.
ReadBookmarks(byte[])
Every bookmark name in the document, in the order the document declares them.
IReadOnlyList<string> ReadBookmarks(byte[] docx)
Parameters
docxbyte[]The document to read.
Returns
- IReadOnlyList<string>
The bookmark names, in declaration order.
Remarks
Names only. A bookmark's position matters to Word and to AddTableOfContents, but there
is no public position type here to return one against, and inventing one is a larger decision
than reading the names.
Exceptions
- ArgumentNullException
docxis null.- ArgumentException
docxis empty.- DocumentConversionException
The document could not be opened or read.
ReadBookmarksAsync(Stream, CancellationToken)
Every bookmark name in the document, in the order the document declares them.
Task<IReadOnlyList<string>> ReadBookmarksAsync(Stream source, CancellationToken ct = default)
Parameters
sourceStreamThe stream the document is read from.
ctCancellationTokenCancels the read.
Returns
- Task<IReadOnlyList<string>>
The bookmark names, in declaration order.
Remarks
source is read to its end and is neither disposed, closed nor sought.
Exceptions
- ArgumentNullException
sourceis null.- ArgumentException
sourceis not readable or held no bytes.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The document could not be opened or read.
ReadMetadata(byte[])
The document properties docx carries.
DocumentMetadata ReadMetadata(byte[] docx)
Parameters
docxbyte[]
Returns
Exceptions
- ArgumentNullException
docxis null.- ArgumentException
docxis empty.- DocumentConversionException
The document could not be read.
ReadMetadataAsync(Stream, CancellationToken)
The document properties docx carries.
Task<DocumentMetadata> ReadMetadataAsync(Stream source, CancellationToken ct = default)
Parameters
sourceStreamThe stream the document is read from.
ctCancellationTokenCancels the read.
Returns
Remarks
source is read to its end and is neither disposed, closed nor sought.
Exceptions
- ArgumentNullException
sourceis null.- ArgumentException
sourceis not readable or held no bytes.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The document could not be read.
ReadTable(byte[], int)
The table at index, as rows of cell text.
IReadOnlyList<IReadOnlyList<string>> ReadTable(byte[] docx, int index)
Parameters
docxbyte[]The .docx content to read.
indexint0-based, indexing what TableCount(byte[]) reports.
Returns
Remarks
Cell text is produced the same way ExtractText(byte[]) produces it, so a cell holding several paragraphs is separated by newlines and a nested table keeps its own structure.
Rows are returned with the shape they have. A horizontally merged cell means a row genuinely holds fewer cells than its neighbours; padding the grid to a rectangle would invent cells that are not in the document.
Exceptions
- ArgumentNullException
docxis null.- ArgumentException
docxis empty.- ArgumentOutOfRangeException
indexis negative, or at or beyond TableCount(byte[]).- DocumentConversionException
The package could not be read.
ReadTableAsync(Stream, int, CancellationToken)
The table at index, as rows of cell text.
Task<IReadOnlyList<IReadOnlyList<string>>> ReadTableAsync(Stream source, int index, CancellationToken ct = default)
Parameters
sourceStreamindexint0-based, indexing what TableCount(byte[]) reports.
ctCancellationToken
Returns
Remarks
Cell text is produced the same way ExtractText(byte[]) produces it, so a cell holding several paragraphs is separated by newlines and a nested table keeps its own structure.
Rows are returned with the shape they have. A horizontally merged cell means a row genuinely holds fewer cells than its neighbours; padding the grid to a rectangle would invent cells that are not in the document.
Exceptions
- ArgumentNullException
docxis null.- ArgumentException
docxis empty.- ArgumentOutOfRangeException
indexis negative, or at or beyond TableCount(byte[]).- DocumentConversionException
The package could not be read.
RemoveWatermarks(byte[])
Removes every watermark from every section, and returns the updated document. A document with none comes back unchanged rather than refused.
byte[] RemoveWatermarks(byte[] docx)
Parameters
docxbyte[]The document to clear. It is not modified.
Returns
- byte[]
A new document; the input is not modified.
Exceptions
- ArgumentNullException
docxis null.- ArgumentException
docxis empty.- DocumentConversionException
The document could not be opened or written.
RemoveWatermarksAsync(Stream, Stream, CancellationToken)
Removes every watermark from every section, and returns the updated document. A document with none comes back unchanged rather than refused.
Task RemoveWatermarksAsync(Stream source, Stream destination, CancellationToken ct = default)
Parameters
sourceStreamThe stream the document is read from.
destinationStreamThe stream the cleared document is written to.
ctCancellationTokenCancels the read, the edit and the write.
Returns
Remarks
source is read to its end and destination is
written; neither is disposed, closed or sought.
Exceptions
- ArgumentNullException
sourceordestinationis null.- ArgumentException
sourceis not readable or held no bytes, ordestinationis not writable.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The document could not be opened or written.
ReplaceImage(byte[], string, byte[], double?, double?)
Replaces a text placeholder with an image, sized from the image's own header unless a dimension is given. PNG and JPEG only, decided by magic bytes rather than by filename.
byte[] ReplaceImage(byte[] docx, string placeholder, byte[] image, double? widthPoints = null, double? heightPoints = null)
Parameters
Returns
- byte[]
Exceptions
- ArgumentNullException
Any argument is null.
- ArgumentException
docxorimageis empty,placeholderis blank, or the image is neither PNG nor JPEG.- ArgumentOutOfRangeException
A supplied size is zero or negative, or the resulting size is larger than a drawing extent can hold.
- DocumentConversionException
The package could not be opened or edited.
ReplaceImageAsync(Stream, string, byte[], Stream, double?, double?, CancellationToken)
Reads a .docx from source, replaces the placeholder with an image, and
writes the result to destination. See ReplaceImage(byte[], string, byte[], double?, double?) for
sizing and format rules. Neither stream is disposed, closed or sought.
Task ReplaceImageAsync(Stream source, string placeholder, byte[] image, Stream destination, double? widthPoints = null, double? heightPoints = null, CancellationToken ct = default)
Parameters
sourceStreamplaceholderstringimagebyte[]destinationStreamwidthPointsdouble?heightPointsdouble?ctCancellationToken
Returns
Exceptions
- ArgumentNullException
Any argument is null.
- ArgumentException
sourceis not readable or held no bytes,destinationis not writable,placeholderis blank, or the image is neither PNG nor JPEG.- ArgumentOutOfRangeException
A supplied size is zero or negative, or the resulting size is larger than a drawing extent can hold.
- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The package could not be opened or edited.
ReplaceText(byte[], IReadOnlyDictionary<string, string>)
Replaces every key with its value across the document body, headers, footers, footnotes and endnotes.
byte[] ReplaceText(byte[] docx, IReadOnlyDictionary<string, string> replacements)
Parameters
docxbyte[]replacementsIReadOnlyDictionary<string, string>
Returns
- byte[]
Exceptions
- ArgumentNullException
Either argument is null.
- ArgumentException
docxis empty.- DocumentConversionException
The package could not be opened or edited.
ReplaceText(byte[], Regex, string)
Replaces every match of pattern with replacement,
across the body, headers, footers, footnotes and endnotes (A116).
byte[] ReplaceText(byte[] docx, Regex pattern, string replacement)
Parameters
docxbyte[]The .docx package to edit.
patternRegexThe pattern to find. Must have a finite
MatchTimeout.replacementstringThe substitution template applied to each match.
Returns
- byte[]
Remarks
The dictionary overload above matches literal keys; this one matches a pattern. Everything else is identical - the same walk, the same splice, the same run-boundary handling.
replacement is a substitution TEMPLATE, not a literal. $1
and friends expand to captured groups the way Regex.Replace expands them, so a
literal \(</code> must be written <code>$\).
Zero-width matches are skipped, because one consumes no characters and inserting a replacement for it would not advance through the text.
pattern must carry a match timeout, and an unbounded one is refused.
A pattern that can backtrack catastrophically has no upper bound on its running time, and a
hang is worse than a failure because the caller cannot catch it. Construct it as
new Regex(text, RegexOptions.None, TimeSpan.FromSeconds(1)).
Exceptions
- ArgumentNullException
Any argument is null.
- ArgumentException
docxis empty, orpatternwas built without a match timeout.- DocumentConversionException
The package could not be opened or edited.
ReplaceTextAsync(Stream, IReadOnlyDictionary<string, string>, Stream, CancellationToken)
Reads a .docx from source, replaces every key with its value, and writes
the result to destination. See ReplaceText(byte[], IReadOnlyDictionary<string, string>) for exactly what
counts as a match. source is read to its end and
destination is written; neither is disposed, closed or sought.
Task ReplaceTextAsync(Stream source, IReadOnlyDictionary<string, string> replacements, Stream destination, CancellationToken ct = default)
Parameters
sourceStreamreplacementsIReadOnlyDictionary<string, string>destinationStreamctCancellationToken
Returns
Exceptions
- ArgumentNullException
Any argument is null.
- ArgumentException
sourceis not readable or held no bytes, ordestinationis not writable.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The package could not be opened or edited.
ReplaceTextAsync(Stream, Regex, string, Stream, CancellationToken)
Replaces every match of pattern with replacement,
across the body, headers, footers, footnotes and endnotes (A116).
Task ReplaceTextAsync(Stream source, Regex pattern, string replacement, Stream destination, CancellationToken ct = default)
Parameters
sourceStreamThe stream the .docx package is read from.
patternRegexThe pattern to find. Must have a finite
MatchTimeout.replacementstringThe substitution template applied to each match.
destinationStreamThe stream the edited .docx package is written to.
ctCancellationTokenCancels the read, the edit and the write.
Returns
Remarks
source is read to its end and destination is written;
neither is disposed, closed or sought.
This remarks replaces the one on
ReplaceText(byte[], Regex, string) rather than adding to it, so its warnings
are restated: replacement is a template in which $1 expands
to a captured group, zero-width matches are skipped, and an unbounded pattern is
refused.
Exceptions
- OperationCanceledException
ctwas cancelled.
TableCount(byte[])
How many tables the document body holds.
int TableCount(byte[] docx)
Parameters
docxbyte[]
Returns
Remarks
Top-level tables only. A table nested inside a cell is part of that cell's text rather than an entry of its own, so this count and the indexes it bounds stay stable.
Exceptions
- ArgumentNullException
docxis null.- ArgumentException
docxis empty.- DocumentConversionException
The package could not be read.
TableCountAsync(Stream, CancellationToken)
How many tables the document body holds.
Task<int> TableCountAsync(Stream source, CancellationToken ct = default)
Parameters
sourceStreamctCancellationToken
Returns
Remarks
Top-level tables only. A table nested inside a cell is part of that cell's text rather than an entry of its own, so this count and the indexes it bounds stay stable.
Exceptions
- ArgumentNullException
docxis null.- ArgumentException
docxis empty.- DocumentConversionException
The package could not be read.
Unprotect(byte[], string)
A copy of docx with its encryption removed.
byte[] Unprotect(byte[] docx, string password)
Parameters
Returns
- byte[]
Exceptions
- ArgumentNullException
docxorpasswordis null.- ArgumentException
docxis empty, orpasswordis empty.- DocumentConversionException
The password was wrong, the document was not encrypted, or it could not be read.
UnprotectAsync(Stream, Stream, string, CancellationToken)
Reads an encrypted document from source and writes the unprotected copy to
destination. Neither stream is disposed, closed or sought.
Task UnprotectAsync(Stream source, Stream destination, string password, CancellationToken ct = default)
Parameters
sourceStreamdestinationStreampasswordstringctCancellationToken
Returns
Exceptions
- ArgumentNullException
Either stream is null, or
passwordis null.- ArgumentException
A stream is unusable, or
passwordis empty.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The password was wrong, or it could not be read.
ValidateSignatures(byte[], DocumentSignatureValidationOptions?)
Validates every digital signature docx carries, returning the
report-level tamper-detection verdict alongside each signature's own certificate chain
trust and revocation status. Never performs revocation checking or certificate downloads
over the network, regardless of options — see
DocumentSignatureValidationOptions's own remarks.
DocumentSignatureValidationReport ValidateSignatures(byte[] docx, DocumentSignatureValidationOptions? options = null)
Parameters
docxbyte[]optionsDocumentSignatureValidationOptions
Returns
Exceptions
- ArgumentNullException
docxis null.- ArgumentException
docxis empty.- DocumentConversionException
The document could not be validated.
ValidateSignaturesAsync(Stream, DocumentSignatureValidationOptions?, CancellationToken)
Reads a .docx from source and validates its digital signatures — see
ValidateSignatures(byte[], DocumentSignatureValidationOptions?). source is read to its end and is
neither disposed, closed nor sought.
Task<DocumentSignatureValidationReport> ValidateSignaturesAsync(Stream source, DocumentSignatureValidationOptions? options = null, CancellationToken ct = default)
Parameters
sourceStreamoptionsDocumentSignatureValidationOptionsctCancellationToken
Returns
Exceptions
- ArgumentNullException
sourceis null.- ArgumentException
sourceis not readable or held no bytes.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The document could not be validated.
WithMetadata(byte[], DocumentMetadata)
A copy of docx carrying metadata.
byte[] WithMetadata(byte[] docx, DocumentMetadata metadata)
Parameters
docxbyte[]metadataDocumentMetadata
Returns
- byte[]
Remarks
A null property leaves what the document already had in place, so stamping a title does not silently erase an author. Pass an empty string to clear one.
Exceptions
- ArgumentNullException
docxormetadatais null.- ArgumentException
docxis empty.- DocumentConversionException
The document could not be read or written.
WithMetadataAsync(Stream, DocumentMetadata, Stream, CancellationToken)
A copy of docx carrying metadata.
Task WithMetadataAsync(Stream source, DocumentMetadata metadata, Stream destination, CancellationToken ct = default)
Parameters
sourceStreamThe stream the document is read from.
metadataDocumentMetadataThe properties to stamp.
destinationStreamThe stream the updated document is written to.
ctCancellationTokenCancels the read, the edit and the write.
Returns
Remarks
source is read to its end and destination is
written; neither is disposed, closed or sought, and neither has to be seekable.
Exceptions
- ArgumentNullException
An argument is null.
- ArgumentException
sourceis not readable or held no bytes, ordestinationis not writable.- OperationCanceledException
ctwas cancelled.- DocumentConversionException
The document could not be read or written.