VegaRise.NET
Back to VDocs

VDocsClass

Definition

Namespace
DOM
Assembly
VDocs.dll

The main entry point for the VDocs document processing framework.

Remarks

serves as the primary façade for creating, opening, editing, and exporting documents in various formats including Word (DOCX), HTML, and PDF. It provides a unified API for all document operations while handling license validation and delegating to appropriate backend services. VDocs The class supports: Creating new documents from scratch Opening existing Word documents Adding and manipulating document elements (paragraphs, tables, images, shapes, etc.) Exporting to HTML and PDF formats Saving back to Word format Theme management All export and save operations are protected by license validation through . If a license is not validated, warning messages are written to the console but operations continue (for evaluation purposes). LicenseManager instances are not thread-safe; do not share one between threads. Separate instances are fully independent (each owns its own package parts and services), so generating documents in parallel with one instance per thread or task is safe. License validation keeps no shared mutable state beyond write-once flags. Thread safety: VDocs

Examples

csharp
1//1. Create a document from scratch and export to every format.
2using var doc = new VDocs();
3
4// Styled heading
5var heading = doc.AddParagraph();
6heading.AddText("Quarterly Report")
7 .SetBold(true)
8 .SetFontSize(20)
9 .SetColor(Color.FromRgb(0, 0, 128));
10heading.SetAlignment(HorizontalAlignmentValues.Center);
11
12// Body text with mixed runs
13var body = doc.AddParagraph();
14body.AddText("This document summarizes the results for Q3 2024.");
15body.AddText(" Revenue grew by 12%.").SetBold(true);
16
17// Image
18var logo = doc.AddImage("company-logo.png");
19logo.SetPosition(50, 50, Units.Pt);
20logo.SetDimensions(150, 75, Units.Pt);
21
22// Table
23var table = doc.AddTable(new Table());
24table.AddRow().AddCell("Product").AddCell("Revenue").AddCell("Growth");
25table.AddRow().AddCell("Widget A").AddCell("$1.2M").AddCell("+8%");
26table.AddRow().AddCell("Widget B").AddCell("$2.4M").AddCell("+15%");
27
28// Export
29doc.SaveAsWord("report.docx");
30doc.SaveAsHtml("report.html");
31doc.SaveAsPdf("report.pdf");
32
csharp
1 //2. Open, modify, and re-save an existing document.
2using (var doc = VDocs.OpenFromWord("invoice.docx"))
3{
4 // Replace placeholders
5 foreach (var p in doc.Paragraphs)
6 {
7 var text = p.Text;
8 if (text != null && text.Contains("{{CUSTOMER_NAME}}"))
9 p.Text = text.Replace("{{CUSTOMER_NAME}}", "Acme Corp");
10 }
11
12 // Add a footer
13 var footer = doc.AddFooter(HeaderFooterType.Default);
14 footer.AddParagraph().AddText("Generated by VDocs");
15
16 doc.SaveAsWord("invoice-filled.docx");
17}
18
csharp
1//3. Stream-based generation (e.g., for web APIs)
2using var doc = new VDocs();
3doc.AddParagraph("Hello from the API!");
4
5byte[] pdfBytes = doc.ToPdfBytes();
6// return File(pdfBytes, "application/pdf", "download.pdf");
7
8// Or write directly to an HTTP response stream:
9// await doc.SaveAsPdfAsync(httpResponse.Body, cancellationToken);
10
csharp
1 //4. Async workflows with cancellation.
2using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
3using var doc = new VDocs();
4doc.AddParagraph("Async generated");
5
6await using (var file = File.Create("output.pdf"))
7{
8 await doc.SaveAsPdfAsync(file, cts.Token);
9}
10
csharp
1 //5. Theme and license configuration.
2using var themed = new VDocs
3{
4 LicensePath = @"C:\Licenses\vdocs.lic"
5};
6themed.SetActiveTheme("Apex");
7themed.AddParagraph("Styled with the Apex theme.");
8themed.SaveAsPdf("themed.pdf");
9
csharp
1 //6. Constructors: file path, stream, and factory methods.
2// From a file path
3using var fromFile = new VDocs(@"C:\Documents\report.docx");
4fromFile.AddParagraph("Appended");
5fromFile.SaveAsWord(@"C:\Documents\report.docx");
6
7// From a stream (stream is NOT disposed by VDocs)
8using var fileStream = File.OpenRead("input.docx");
9using var fromStream = new VDocs(fileStream);
10fromStream.SaveAsHtml("output.html");
11
12// Factory methods
13var viaFactory = VDocs.OpenFromWord("template.docx");
14viaFactory.AddParagraph("Added via factory").SaveAsWord("filled.docx");
15
16// Batch conversion
17foreach (var path in Directory.EnumerateFiles("inbox", "*.docx"))
18{
19 using var d = VDocs.OpenFromWord(path);
20 d.SaveAsPdf(Path.ChangeExtension(path, ".pdf"));
21}
22
csharp
1 //7. Async open from a stream (ASP.NET Core controller).
2[HttpPost("process")]
3public async Task<IActionResult> Process(IFormFile file, CancellationToken ct)
4{
5 await using var input = file.OpenReadStream();
6 using var doc = await VDocs.OpenFromWordAsync(input, ct);
7
8 doc.AddParagraph($"Processed {file.FileName}");
9
10 var output = new MemoryStream();
11 await doc.SaveAsWordAsync(output, ct);
12 output.Position = 0;
13 return File(output,
14 "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
15}
16
csharp
1 //8. Not-yet-implemented imports (PDF / HTML).
2try
3{
4 var doc = VDocs.OpenFromPdf("report.pdf");
5}
6catch (NotImplementedException)
7{
8 Console.WriteLine("PDF import is coming in a future release.");
9}
10
11try
12{
13 var doc = VDocs.OpenFromHtml("page.html");
14}
15catch (NotImplementedException)
16{
17 Console.WriteLine("HTML import is coming in a future release.");
18}
19
csharp
1 //9. Document properties: sections, pages, headers, footers.
2using var doc = new VDocs();
3
4// Inspect sections
5for (int i = 0; i < doc.Sections.Count; i++)
6 Console.WriteLine($"Section {i}: {doc.Sections[i].PageSettings.Orientation}");
7
8// Inspect pages
9Console.WriteLine($"Total pages: {doc.Pages.Count}");
10
11// Inspect headers (may be null)
12if (doc.Headers != null)
13 foreach (var h in doc.Headers)
14 Console.WriteLine($"Header type: {h.Type}");
15
16// Add first-page and even-page footers
17doc.AddFooter(HeaderFooterType.FirstPage)
18 .AddParagraph("First page footer");
19doc.AddFooter(HeaderFooterType.EvenPage)
20 .AddParagraph("Even page footer");
21
csharp
1 //10. Page setup, columns, grid, RTL and vertical alignment.
2using var doc = new VDocs();
3
4// Landscape A4 with custom margins
5doc.PageSettings.Orientation = Orientation.Landscape;
6doc.PageSettings.Width = 29.7;
7doc.PageSettings.Height = 21.0;
8doc.PageSettings.MarginLeft = 2.0;
9doc.PageSettings.MarginRight = 2.0;
10
11// Two-column newsletter
12doc.PageColumns.NumberOfColumns = 2;
13doc.PageColumns.Spacing = 1.0;
14doc.PageColumns.Separator = true;
15
16// Document grid (East Asian typography)
17doc.DocumentGrid.Type = DocumentGridType.LinesAndChars;
18doc.DocumentGrid.LinePitch = 400;
19
20// RTL
21doc.RightToLeftLayout = true;
22doc.TextFlowDirection = TextDirectionValues.RightToLeft;
23
24// Vertical centering (title pages)
25doc.VerticalTextAlignmentOnPage = VerticalJustificationValues.Center;
26
27doc.SaveAsPdf("layout.pdf");
28
csharp
1 //11. Element collections: images, paragraphs, shapes, tables, texts.
2using var doc = VDocs.OpenFromWord("report.docx");
3
4foreach (var img in doc.Images)
5 Console.WriteLine($"Image: {img.Width}x{img.Height} at ({img.X},{img.Y})");
6
7foreach (var p in doc.Paragraphs.Take(5))
8 Console.WriteLine(p.Text);
9
10foreach (var shape in doc.Shapes)
11 Console.WriteLine($"Shape: {shape.ShapeType}");
12
13Console.WriteLine($"Tables: {doc.Tables.Count}, Texts: {doc.Texts.Count}");
14
csharp
1 //12. Adding elements: images, paragraphs, tables, paths, shapes, text.
2using var doc = new VDocs();
3
4// Image from a stream
5using var imageStream = new MemoryStream(File.ReadAllBytes("logo.png"));
6var img = doc.AddImage(imageStream);
7img.SetDimensions(4.0, 2.0, Units.Cm);
8
9// Paragraph with multiple styled runs
10var run1 = new Text("Bold ").SetBold(true);
11var run2 = new Text("and ").SetColor(Color.Red);
12var run3 = new Text("colored.").SetColor(Color.Blue);
13doc.AddParagraph(run1, run2, run3);
14
15// Simple string overload
16doc.AddParagraph("Plain paragraph");
17
18// Table with headers and rows
19var table = new Table();
20var header = table.AddRow();
21header.AddCell("Name").SetBold(true);
22header.AddCell("Value").SetBold(true);
23foreach (var (name, value) in data)
24{
25 var row = table.AddRow();
26 row.AddCell(name);
27 row.AddCell(value.ToString());
28}
29doc.AddTable(table);
30
31// Shape, SVG path and text node
32doc.AddShape(myShape);
33doc.AddPath(mySvgPath);
34doc.AddText("Standalone text node");
35
csharp
1 //13. Headers and footers of a specific type.
2using var doc = new VDocs();
3doc.AddParagraph("Page content");
4
5var footer = doc.AddFooter(HeaderFooterType.Default);
6footer.AddParagraph("Confidential — Generated by VDocs");
7
8var firstHeader = doc.AddHeader(HeaderFooterType.FirstPage);
9firstHeader.AddParagraph()
10 .AddText("Annual Report 2024")
11 .SetFontSize(18)
12 .SetAlignment(HorizontalAlignmentValues.Center);
13
csharp
1 //14. Element tree manipulation: clone, query, insert, remove, replace.
2using var doc = new VDocs();
3doc.AddParagraph("First");
4doc.AddParagraph("Third");
5
6// Insert at a specific child index
7doc.InsertChildToIndex(1, new Paragraph().AddText("Second"));
8
9// Query by element type
10foreach (var t in doc.Elements<ITable>())
11 Console.WriteLine($"Table with {t.Rows.Count} rows");
12
13// Remove a specific paragraph
14var toRemove = doc.Paragraphs.First(p => p.Text == "Third");
15doc.RemoveChildren(toRemove);
16
17// Deep clone (independent copy)
18var clone = (IDocument)doc.Clone();
19clone.AddParagraph("Only in the clone");
20
21// Bulk composition
22doc.AddChild(new IElement[]
23{
24 new Paragraph().AddText("Batch 1"),
25 new Paragraph().AddText("Batch 2")
26});
27
28// Prepend / append convenience overloads
29doc.InsertBefore(new Paragraph().AddText("TITLE").SetFontSize(28));
30doc.InsertAfter(new Paragraph().AddText("Sincerely,"));
31
csharp
1 //15. Export methods: GetHtml, SaveAsHtml, SaveAsPdf, SaveAsWord and byte helpers.
2using var doc = VDocs.OpenFromWord("input.docx");
3
4// HTML preview
5string html = doc.GetHtml();
6Console.WriteLine(html.Substring(0, Math.Min(500, html.Length)));
7// ASP.NET Core: return Content(html, "text/html");
8// Blazor: <div>@((MarkupString)html)</div>
9
10// Save HTML to file or memory
11doc.SaveAsHtml(@"C:\Output\report.html");
12using var htmlMs = new MemoryStream();
13doc.SaveAsHtml(htmlMs);
14
15// Save PDF to file, memory, or blob
16doc.SaveAsPdf("report.pdf");
17byte[] pdf = doc.ToPdfBytes();
18await blobClient.UploadAsync(new MemoryStream(pdf), overwrite: true);
19
20// Save Word to file or memory
21doc.SaveAsWord("output.docx");
22using var wordMs = new MemoryStream();
23doc.SaveAsWord(wordMs);
24Console.WriteLine($"Word package size: {wordMs.Length:N0} bytes");
25byte[] docx = doc.ToWordBytes();
26
27// Async variants
28await using var file = File.Create("async-output.pdf");
29await doc.SaveAsPdfAsync(file, cancellationToken);
30
csharp
1 //16. Sections and themes.
2using var doc = new VDocs();
3
4// Multi-section document: portrait → landscape → portrait
5var cover = doc.AddSection();
6cover.PageSettings.Orientation = Orientation.Portrait;
7cover.AddParagraph("Cover Page").SetAlignment(HorizontalAlignmentValues.Center);
8
9var data = doc.AddSection();
10data.PageSettings.Orientation = Orientation.Landscape;
11data.AddTable(new Table());
12
13var conclusion = doc.AddSection();
14conclusion.PageSettings.Orientation = Orientation.Portrait;
15conclusion.AddParagraph("Conclusion");
16
17// Theme switching
18doc.SetActiveTheme("Office");
19doc.SaveAsPdf("office-theme.pdf");
20
21doc.SetActiveTheme("Apex");
22doc.SaveAsPdf("apex-theme.pdf");
23
24ITheme current = doc.GetActiveTheme();
25Console.WriteLine($"Active theme: {current.Name}");
26
csharp
1 //17. Disposal semantics.
2// Preferred: 'using' releases pooled package streams
3using (var doc = new VDocs())
4{
5 doc.AddParagraph("Generated inside a using block");
6 doc.SaveAsPdf("output.pdf");
7} // disposed here
8
9// Saving after disposal throws ObjectDisposedException
10var d = new VDocs();
11d.Dispose();
12try
13{
14 d.SaveAsPdf("fail.pdf");
15}
16catch (ObjectDisposedException ex)
17{
18 Console.WriteLine($"Expected: {ex.ObjectName} was disposed");
19}
20
21// Dispose is idempotent
22d.Dispose(); // no-op
23

Constructors

VDocs()

Initializes a new, empty document using the default document services. VDocs

VDocs(string filePath)

Opens an existing Word document from the specified file path.

VDocs(Stream input)

Opens an existing Word document from a stream.

Properties

BackgroundColorIColor

Gets or sets the background color of the document.

This value typically maps to the document-level background or page color in the underlying XML representation. It affects all pages of the document.

ChildrenIElement

Gets or sets the direct children elements of this top-level document object.

Child elements typically include sections, paragraphs, tables, and other block-level elements that make up the document content.

DocumentGridIDocumentGrid

Gets or sets the document grid settings used for character/line layout.

The document grid provides a consistent baseline for character and line positioning. It is commonly used in East Asian typography to align text and improve readability.

DocumentStylesIDocumentStyles

Gets or sets the document styles.

Document styles define the formatting for paragraphs, characters, tables, and lists. Styles provide a consistent way to apply formatting and enable easy updates across the entire document.

Gets the document footers.

Footers appear at the bottom of pages and can contain text, images, page numbers, and other content that repeats across pages. Different footers can be defined for odd/even pages or the first page.

Gets the document headers.

Headers appear at the top of pages and can contain text, images, page numbers, and other content that repeats across pages. Different headers can be defined for odd/even pages or the first page.

ImagesIImage

Gets the images contained in the document.

Index

Gets the index of this element in its parent's child collection.

For the top-level document, this property may return 0 or -1 depending on the underlying implementation.

LicensePathLicenseManager

Gets or sets the optional path to a license file.

When set, this path is used by to validate the license before any save or export operation. If the license is invalid, warning messages are displayed but operations continue (evaluation mode). LicenseManager

PageColumnsIPageColumns

Gets or sets the column settings for the document sections.

This property controls how text flows across multiple columns on the page. It allows you to define the number of columns, their width, spacing between columns, and whether a vertical line separates them.

Gets the pages contained by the document.

This property provides access to page-level properties and content. Pages are automatically created based on content flow and section breaks.

PageSettingsIPageSetup

Gets or sets the page setup options for the document.

The page setup defines the physical layout of each page in the document. This includes: Page size (A4, Letter, etc.) Margins (top, bottom, left, right) Orientation (portrait or landscape) Page numbering style

ParagraphsIParagraph

Gets the paragraphs contained in the document.

Returns the parent element of this document.

Gets the SVG paths contained in the document.

RightToLeftLayout

Gets or sets whether the document layout is right-to-left.

This property is used for languages that are written right-to-left, such as Arabic, Hebrew, and Persian. When enabled, text and elements flow from right to left.

SectionBreakTypeSectionMarkValues

Gets or sets the section break type for this document when accessed through the interface. IDocumentSection

Gets the top-level sections of the document.

Sections represent major structural divisions in a document, similar to chapters or parts. Each section can have its own page settings, headers, footers, and columns.

ShapesIShape

Gets the shapes contained in the document.

Gets or sets the status of this document element.

TablesITable

Gets the tables contained in the document.

TextFlowDirectionTextDirectionValues

Gets or sets the text flow direction used by the document.

TextsIText

Gets the text elements contained in the document.

VerticalTextAlignmentOnPageVerticalJustificationValues

Gets or sets the vertical alignment of text on the page.

This property controls how text is distributed vertically within the page margins. For example, "center" will center the text block vertically on the page, which is commonly used for title pages.

Methods

Adds one or more child elements to the document.

Adds a footer to the document.

Adds a header to the document.

Adds an image element to the document.

Adds a new paragraph to the document.

Adds an SVG path element to the document.

Creates and adds a new section to the document.

Adds a shape element to the document.

Adds a table to the document.

Adds a text node with the specified string content to the document.

Creates a deep clone of this document element.

Releases the resources (pooled package part streams) owned by this document.

Exports the document to the specified file format and path.

Gets the currently active theme for the document.

Gets a child element of type by its index. T

Returns an HTML representation of the document.

Obsolete alias of . GetHtml

Inserts elements after the specified source element.

Inserts elements before the specified source element.

Inserts child elements at the specified child index.

Produces a debug-friendly representation of the document object tree.

Opens an existing HTML document.

Asynchronously opens an HTML document from a stream. Not yet implemented.

Opens an existing PDF document.

Asynchronously opens a PDF document from a stream. Not yet implemented.

Opens an existing Word document using a static factory method.

Asynchronously opens an existing Word document from a stream.

Removes this element from its parent's child collection.

Removes all child elements from this document.

Removes the specified child elements from the document.

Replaces this element with in the parent collection. newChild

Saves the document as an HTML file.

Obsolete alias of . SaveAsHtml(string)

Asynchronously saves the document to a stream. Rendering is synchronous (CPU-bound) into a buffer; only the write to is asynchronous. The stream is left open. output

Saves the document as a PDF file.

Asynchronously saves the document to a stream. Rendering is synchronous (CPU-bound) into a buffer; only the write to is asynchronous. The stream is left open. output

Saves the document as a Word (.docx) file.

Asynchronously saves the document to a stream. Rendering is synchronous (CPU-bound) into a buffer; only the write to is asynchronous. The stream is left open. output

Sets the active theme for the document by name.

Renders the document as PDF and returns the bytes.

Renders the document as .docx and returns the bytes.

VegaRiseVDocs.NET

Create Account

Create your VDocs account.

or

Already have an account? Sign in