### Start Liferay Portal Instance with Docker Source: https://docs.aspose.com/words/net/work-with-document-stored-in-liferay Use this command to start a Liferay Portal instance using Docker. Ensure you have Docker installed. You can use a different Liferay Portal version if needed. ```bash docker run -it -m 8g -p 8080:8080 liferay/portal:7.4.3.92-ga92 ``` -------------------------------- ### Install Aspose.Words for .NET via Composer Source: https://docs.aspose.com/words/net/aspose-words-net-for-php This command installs the Aspose.Words for .NET package for your PHP project using Composer. Ensure Composer is installed and accessible in your project directory. ```bash composer install ``` -------------------------------- ### Start, Track, and Accept Revisions in Document Source: https://docs.aspose.com/words/net/track-changes-in-a-document Demonstrates how to start tracking revisions, add/remove content which registers as insert/delete revisions, accept all revisions, and stop tracking. Use this to manage document edits as formal revisions. ```csharp // For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. Document doc = new Document(); Body body = doc.FirstSection.Body; Paragraph para = body.FirstParagraph; // Add text to the first paragraph, then add two more paragraphs. para.AppendChild(new Run(doc, "Paragraph 1. ")); body.AppendParagraph("Paragraph 2. "); body.AppendParagraph("Paragraph 3. "); // We have three paragraphs, none of which registered as any type of revision // If we add/remove any content in the document while tracking revisions, // they will be displayed as such in the document and can be accepted/rejected. doc.StartTrackRevisions("John Doe", DateTime.Now); // This paragraph is a revision and will have the according "IsInsertRevision" flag set. para = body.AppendParagraph("Paragraph 4. "); Assert.True(para.IsInsertRevision); // Get the document's paragraph collection and remove a paragraph. ParagraphCollection paragraphs = body.Paragraphs; Assert.AreEqual(4, paragraphs.Count); para = paragraphs[2]; para.Remove(); // Since we are tracking revisions, the paragraph still exists in the document, will have the "IsDeleteRevision" set // and will be displayed as a revision in Microsoft Word, until we accept or reject all revisions. Assert.AreEqual(4, paragraphs.Count); Assert.True(para.IsDeleteRevision); // The delete revision paragraph is removed once we accept changes. doc.AcceptAllRevisions(); Assert.AreEqual(3, paragraphs.Count); Assert.That(para, Is.Empty); // Stopping the tracking of revisions makes this text appear as normal text. // Revisions are not counted when the document is changed. doc.StopTrackRevisions(); // Save the document. doc.Save(ArtifactsDir + "WorkingWithRevisions.AcceptRevisions.docx"); ``` -------------------------------- ### Install Aspose.Words NuGet Package Source: https://docs.aspose.com/words/net/hello-world-example Install the Aspose.Words NuGet package via the Package Manager Console to add the library and its dependencies to your project. ```powershell Install-Package Aspose.Words ``` -------------------------------- ### Install Aspose.Words.dll in GAC Source: https://docs.aspose.com/words/net/automerge-for-dynamics-crm Use this command in the Visual Studio Command Prompt to install the Aspose.Words.dll library into the Global Assembly Cache (GAC) on the CRM server. ```bash gacutil -i Aspose.Words.dll ``` -------------------------------- ### Enable Revision Rendering and Display Source: https://docs.aspose.com/words/net/specify-layout-options Enable revision rendering by configuring `RevisionOptions` and `CommentDisplayMode`. This example sets `RevisionOptions.ShowRevisions` to true and displays revisions in balloons. ```csharp Document doc = new Document("tracked.docx"); LayoutOptions layout = doc.LayoutOptions; layout.RevisionOptions.ShowRevisions = true; layout.CommentDisplayMode = CommentDisplayMode.ShowInBalloons; doc.Save("tracked_output.pdf"); ``` -------------------------------- ### Implement Consent Delegate - C# Source: https://docs.aspose.com/words/net/work-with-document-market-by-sensitivity-label Implement the IConsentDelegate interface to handle user consent. This example automatically accepts consent. ```csharp using Microsoft.InformationProtection; namespace SensitivityLabelsExample { public class ConsentDelegate : IConsentDelegate { public Consent GetUserConsent(string url) { return Consent.Accept; } } } ``` -------------------------------- ### Customize Page Setup for Current Section Source: https://docs.aspose.com/words/net/working-with-sections Sets page size, orientation, and left margin for the current section. Ensure Aspose.Words is referenced in your project. ```csharp Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.PageSetup.Orientation = Orientation.Landscape; builder.PageSetup.LeftMargin = 50; builder.PageSetup.PaperSize = PaperSize.Paper10x14; doc.Save(ArtifactsDir + "WorkingWithDocumentOptionsAndSettings.PageSetupAndSectionFormatting.docx"); ``` -------------------------------- ### Add Picture using Aspose.Words Source: https://docs.aspose.com/words/net/add-picture This Aspose.Words example demonstrates creating a new document, inserting an image using DocumentBuilder, and saving the document. ```csharp CopyDocument doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); //Add picture builder.InsertImage(MyDir + "download.jpg"); doc.Save("Adding Picture.doc"); ``` -------------------------------- ### Generate 'Hello World' Document with LINQ Reporting Source: https://docs.aspose.com/words/net/hello-world-example Loads a template document, creates a 'Sender' object with data, and uses the ReportingEngine to build and save the report. Ensure the 'Sender' class is defined and the template file exists. ```csharp // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LINQ(); string fileName = "HelloWorld.doc"; // Load the template document. Document doc = new Document(dataDir + fileName); // Create an instance of sender class to set it's properties. Sender sender = new Sender { Name = "LINQ Reporting Engine", Message = "Hello World" }; // Create a Reporting Engine. ReportingEngine engine = new ReportingEngine(); // Execute the build report. engine.BuildReport(doc, sender, "sender"); dataDir = dataDir + RunExamples.GetOutputFilePath(fileName); // Save the finished document to disk. doc.Save(dataDir); ``` -------------------------------- ### Get Available Fonts Source: https://docs.aspose.com/words/net/specifying-truetype-fonts-location Retrieve a list of available fonts, which can be used for rendering documents. This example shows how to add a folder source and iterate through the physical font information. ```csharp FontSettings fontSettings = new FontSettings(); List fontSources = new List(fontSettings.GetFontsSources()); // Add a new folder source which will instruct Aspose.Words to search the following folder for fonts. FolderFontSource folderFontSource = new FolderFontSource(MyDir, true); // Add the custom folder which contains our fonts to the list of existing font sources. fontSources.Add(folderFontSource); FontSourceBase[] updatedFontSources = fontSources.ToArray(); foreach (PhysicalFontInfo fontInfo in updatedFontSources[0].GetAvailableFonts()) { Console.WriteLine("FontFamilyName : " + fontInfo.FontFamilyName); Console.WriteLine("FullFontName : " + fontInfo.FullFontName); Console.WriteLine("Version : " + fontInfo.Version); Console.WriteLine("FilePath : " + fontInfo.FilePath); } ``` -------------------------------- ### Dockerfile for SDK to Runtime Image Build (Ubuntu) Source: https://docs.aspose.com/words/net/how-to-run-aspose-words-in-docker This Dockerfile demonstrates building an application in an SDK image and then copying it to a smaller runtime image. It includes installing font configuration packages required for Linux. ```docker FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build WORKDIR /app # copy csproj and restore as distinct layers COPY Aspose.Words.Docker.Sample/*.csproj ./Aspose.Words.Docker.Sample/ WORKDIR /app/Aspose.Words.Docker.Sample RUN dotnet restore # copy and publish app and libraries WORKDIR /app/ COPY Aspose.Words.Docker.Sample/. ./Aspose.Words.Docker.Sample/ WORKDIR /app/Aspose.Words.Docker.Sample RUN dotnet publish -c Release -o out # copy to runtime environment FROM mcr.microsoft.com/dotnet/core/runtime:2.2 AS runtime WORKDIR /app # libfontconfig1 is required to properly work with fonts in Linux. RUN apt-get update && apt-get install -y libfontconfig1 RUN apt install libharfbuzz-icu0 COPY --from=build /app/Aspose.Words.Docker.Sample/out ./ ENTRYPOINT ["dotnet", "Aspose.Words.Docker.Sample.dll"] ``` -------------------------------- ### Print Document using Aspose.Words Source: https://docs.aspose.com/words/net/faq Print a document using Aspose.Words. This example shows two methods: printing to the default printer or specifying a printer by name from the installed printers list. ```csharp CopyDocument doc = new Document(MyDir + "PrintMe.docx"); // Below are two ways of printing our document. // 1 - Print using the default printer: doc.Print(); // 2 - Specify a printer that we wish to print the document with by name: string myPrinter = PrinterSettings.InstalledPrinters[4]; doc.Print(myPrinter); ``` -------------------------------- ### Create AiModel Instance Source: https://docs.aspose.com/words/net/supported-ai-models Shows how to create a new instance of the AiModel class using the Create method. This is the entry point for accessing AI-powered features. ```csharp public static AiModel Create(AiModelType modelType) ``` -------------------------------- ### Define Person Class for Examples Source: https://docs.aspose.com/words/net/appendix-a-enumeration-extension-methods This class definition is used in the examples to demonstrate enumeration extension methods. ```csharp public class Person { public String Name { get { ... } } public int Age { get { ... } } public IEnumerable Children { get { ... } } ... } ``` -------------------------------- ### Add Scenario Logic to Program in .NET Source: https://docs.aspose.com/words/net/work-with-document-stored-in-liferay This C# code sets up the necessary configurations, including Liferay site ID, login credentials, and portal URL. It then uploads two documents, downloads them, compares them using Aspose.Words, and uploads the comparison result back to Liferay. Ensure all placeholder values like 'TODO' are replaced with actual credentials and paths. ```.NET using Aspose.Words; using LiferayExample; try { await RunCodeExample(); } catch(Exception ex) { Console.WriteLine($"Failed to execute code example: {ex}"); } static async Task RunCodeExample() { // Settings. const string siteId = "TODO"; // For example: 20119 const string login = "TODO"; // For example test@liferay.com const string password = "TODO"; // Fill actual password for the "test@liferay.com" user. const string basePortalUrl = "TODO"; // For example: http://localhost:8080 const string asposeWordsLicensePath = "TODO"; // For example: Aspose.Words.NET.lic const string fileA = "DocumentA.docx"; const string fileB = "DocumentB.docx"; const string fileCompared = "DocumentCompared.docx"; // Set licenses. License lic = new License(); lic.SetLicense(asposeWordsLicensePath); // Logic of the scenario. Console.WriteLine("Code example started."); var client = new DocumentClient(basePortalUrl, new SecurityContext(siteId, login, password)); var fileAUploadData = await client.Upload(File.OpenRead($ ``` ```.NET "./Docs/" + fileA), fileA); Console.WriteLine($"\"{fileAUploadData.FileName}\" uploaded successfully. Assigned identifier is \"{fileAUploadData.Id}\"."); var fileBUploadData = await client.Upload(File.OpenRead($ ``` ```.NET "./Docs/" + fileB), fileB); Console.WriteLine($"\"{fileBUploadData.FileName}\" uploaded successfully. Assigned identifier is \"{fileBUploadData.Id}\"."); var fileAData = await client.Download(fileAUploadData.Id); Console.WriteLine($"\"{fileAUploadData.FileName}\" downloaded successfully."); var fileBData = await client.Download(fileBUploadData.Id); Console.WriteLine($"\"{fileBUploadData.FileName}\" downloaded successfully."); var docA = new Document(fileAData); var docB = new Document(fileBData); docA.Compare(docB, "Aspose", DateTime.Now); Console.WriteLine($"Documents compared successfully."); using var comparedDocument = new MemoryStream(); docA.Save(comparedDocument, SaveFormat.Docx); comparedDocument.Seek(0, SeekOrigin.Begin); var fileComparedUploadData = await client.Upload(comparedDocument, fileCompared); Console.WriteLine($"Comparison result \"{fileComparedUploadData.FileName}\" uploaded successfully. Assigned identifier is \"{fileComparedUploadData.Id}\"."); Console.WriteLine("Code example completed."); } ``` -------------------------------- ### Define Person Class for Examples Source: https://docs.aspose.com/words/net/working-with-table-column-conditional-blocks Defines a simple Person class with Name, Age, and Representative properties, used in subsequent examples. ```csharp public class Person { public String Name { get { ... } } public int Age { get { ... } } public String Representative { get { ... } } ... } ``` -------------------------------- ### Build a Table with Applied Style and Options Source: https://docs.aspose.com/words/net/working-with-tablestyle Creates a table and applies a predefined style (MediumShading1Accent1) along with specific style options like first column, row bands, and first row formatting. It also sets cell padding and autofits the table to its content. ```csharp Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Table table = builder.StartTable(); // We must insert at least one row first before setting any table formatting. builder.InsertCell(); // Set the table style used based on the unique style identifier. table.StyleIdentifier = StyleIdentifier.MediumShading1Accent1; // Apply which features should be formatted by the style. table.StyleOptions = TableStyleOptions.FirstColumn | TableStyleOptions.RowBands | TableStyleOptions.FirstRow; table.AutoFit(AutoFitBehavior.AutoFitToContents); builder.Writeln("Item"); builder.CellFormat.RightPadding = 40; builder.InsertCell(); builder.Writeln("Quantity (kg)"); builder.EndRow(); builder.InsertCell(); builder.Writeln("Apples"); builder.InsertCell(); builder.Writeln("20"); builder.EndRow(); builder.InsertCell(); builder.Writeln("Bananas"); builder.InsertCell(); builder.Writeln("40"); builder.EndRow(); builder.InsertCell(); builder.Writeln("Carrots"); builder.InsertCell(); builder.Writeln("50"); builder.EndRow(); doc.Save(ArtifactsDir + "WorkingWithTableStylesAndFormatting.BuildTableWithStyle.docx"); ``` -------------------------------- ### Create HelloWorld Document in PHP Source: https://docs.aspose.com/words/net/helloworld-example-in-php This snippet demonstrates how to create a new Word document, add 'Hello world!' text, and save it as a DOCX file using PHP and Aspose.Words. ```php $dataDir = '.'; $doc = new \COM("Aspose.Words.Document"); $builder = new \COM("Aspose.Words.DocumentBuilder"); $builder->Document = $doc; $builder->Write("Hello world!"); $doc->Save($dataDir . "/HelloWorld Out.docx"); ``` -------------------------------- ### Hello World Console Application for Docker Source: https://docs.aspose.com/words/net/how-to-run-aspose-words-in-docker A basic console application that generates a 'Hello World!' document in multiple formats. This application is designed to be built and run within a Docker container. ```csharp using System; using System.IO; using Aspose.Words; namespace AsposeWordsDockerHelloWorld { class Program { static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("./"); // Create an empty Word document. Document doc = new Document(); // Get the document's body and append a paragraph with text. DocumentBuilder builder = new DocumentBuilder(doc); builder.Write("Hello World!"); // Save the document in all supported formats. doc.Save(dataDir + "HelloWorld.doc"); doc.Save(dataDir + "HelloWorld.docx"); doc.Save(dataDir + "HelloWorld.pdf"); doc.Save(dataDir + "HelloWorld.rtf"); doc.Save(dataDir + "HelloWorld.txt"); doc.Save(dataDir + "HelloWorld.html"); doc.Save(dataDir + "HelloWorld.xml"); doc.Save(dataDir + "HelloWorld.odt"); doc.Save(dataDir + "HelloWorld.epub"); Console.WriteLine("Document generated successfully."); } } } ``` -------------------------------- ### Get Field Display Result Source: https://docs.aspose.com/words/net/customize-field-properties Use the DisplayResult property to get the calculated value of a field. This is useful for fields that do not have a field separator node, mimicking MS Word's on-the-fly calculation. ```csharp Document document = new Document(MyDir + "Various fields.docx"); document.UpdateFields(); foreach (Field field in document.Range.Fields) Console.WriteLine(field.DisplayResult); ``` -------------------------------- ### Aspose .NET Export GridView To Word Control Example Source: https://docs.aspose.com/words/net/visual-studio-export-gridview-to-word-control This example demonstrates the usage of the Aspose.Words.GridViewExport.ExportGridViewToWord control with various properties configured. Ensure the control is correctly referenced and the necessary license file is available. ```aspx ``` -------------------------------- ### Execute Style Queries and Display Results in C# Source: https://docs.aspose.com/words/net/working-with-styles-and-themes This example demonstrates how to use the previously defined methods to find paragraphs and runs with specific styles and then print the count and content to the console. It requires a 'Document' object and the style names to query. ```csharp Document doc = new Document(MyDir + "Styles.docx"); List paragraphs = ParagraphsByStyleName(doc, "Heading 1"); Console.WriteLine($"Paragraphs with \"Heading 1\" styles ({paragraphs.Count}):"); foreach (Paragraph paragraph in paragraphs) Console.Write(paragraph.ToString(SaveFormat.Text)); List runs = RunsByStyleName(doc, "Intense Emphasis"); Console.WriteLine($"\nRuns with \"Intense Emphasis\" styles ({runs.Count}):"); foreach (Run run in runs) ``` -------------------------------- ### Create VBA Project and Module Source: https://docs.aspose.com/words/net/working-with-vba-macros Demonstrates creating a new VBA project and a procedural module with specified name and source code. The document is then saved as a macro-enabled file (.docm). ```csharp Document doc = new Document(); VbaProject project = new VbaProject(); project.Name = "AsposeProject"; doc.VbaProject = project; // Create a new module and specify a macro source code. VbaModule module = new VbaModule(); module.Name = "AsposeModule"; module.Type = VbaModuleType.ProceduralModule; module.SourceCode = "New source code"; // Add module to the VBA project. doc.VbaProject.Modules.Add(module); doc.Save(ArtifactsDir + "WorkingWithVba.CreateVbaProject.docm"); ``` -------------------------------- ### Multicolored Numbered List Template Example Source: https://docs.aspose.com/words/net/typical-templates A template for a numbered list where even and odd items might be styled differently (though the example only shows numbering). It uses conditional logic based on the index. ```plaintext We provide support for the following clients:1. <><><<[Name]>> 2. <><<[Name]>><><> ``` -------------------------------- ### Integrate Self-hosted LLM with Aspose.Words Source: https://docs.aspose.com/words/net/supported-ai-models Demonstrates how to integrate a self-hosted LLM, specifically one based on OpenAI's generative language model, for document translation. Requires setting an API key and defining a custom model class to point to a local endpoint. ```csharp public void SelfHostedModel() { Document doc = new Document(MyDir + "Big document.docx"); string apiKey = Environment.GetEnvironmentVariable("API_KEY"); // Use OpenAI generative language models. AiModel model = new CustomAiModel().WithApiKey(apiKey); Document translatedDoc = model.Translate(doc, Language.Russian); translatedDoc.Save(ArtifactsDir + "AI.SelfHostedModel.docx"); } // Custom self-hosted AI model. internal class CustomAiModel : OpenAiModel { protected override string Url { get { return "https://localhost/"; } } protected override string Name { get { return "my-model-24b"; } } } ``` -------------------------------- ### Append Document with Custom Page Setup Source: https://docs.aspose.com/words/net/insert-and-append-documents Appends one document to another while controlling page setup to ensure content flows correctly and page numbering restarts. This is useful when merging documents with potentially different page dimensions or orientations. ```csharp Document srcDoc = new Document(MyDir + "Document source.docx"); Document dstDoc = new Document(MyDir + "Northwind traders.docx"); // Set the source document to continue straight after the end of the destination document. srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.Continuous; // Restart the page numbering on the start of the source document. srcDoc.FirstSection.PageSetup.RestartPageNumbering = true; srcDoc.FirstSection.PageSetup.PageStartingNumber = 1; // To ensure this does not happen when the source document has different page setup settings, make sure the // settings are identical between the last section of the destination document. // If there are further continuous sections that follow on in the source document, // this will need to be repeated for those sections. srcDoc.FirstSection.PageSetup.PageWidth = dstDoc.LastSection.PageSetup.PageWidth; srcDoc.FirstSection.PageSetup.PageHeight = dstDoc.LastSection.PageSetup.PageHeight; srcDoc.FirstSection.PageSetup.Orientation = dstDoc.LastSection.PageSetup.Orientation; // Iterate through all sections in the source document. foreach (Paragraph para in srcDoc.GetChildNodes(NodeType.Paragraph, true)) { para.ParagraphFormat.KeepWithNext = true; } dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting); dstDoc.Save(ArtifactsDir + "JoinAndAppendDocuments.DifferentPageSetup.docx"); ``` -------------------------------- ### Initialize Aspose.Words License Source: https://docs.aspose.com/words/net/integration-in-aws-lambda Sets the Aspose.Words license by embedding the license file as a resource. This should be done once before creating any `Document` instances. ```csharp static Function() { // Uncomment this code and embed your license file as a resource in this project and this code // will find and activate the license. Aspose.Wods licensing needs to execute only once // before any Document instance is created and a static ctor is a good place. // Aspose.Words.License lic = new Aspose.Words.License(); // lic.SetLicense("Aspose.Words.lic"); } ``` -------------------------------- ### Set Document Page Setup Options Source: https://docs.aspose.com/words/net/work-with-word-document-options-and-appearance Use this code to set the layout mode, characters per line, and lines per page for a document. This affects how the document grid behaves and can be mirrored in Microsoft Word's Page Setup dialog. ```csharp Document doc = new Document(MyDir + "Document.docx"); // Set the layout mode for a section allowing to define the document grid behavior. // Note that the Document Grid tab becomes visible in the Page Setup dialog of MS Word // if any Asian language is defined as editing language. doc.FirstSection.PageSetup.LayoutMode = SectionLayoutMode.Grid; doc.FirstSection.PageSetup.CharactersPerLine = 30; doc.FirstSection.PageSetup.LinesPerPage = 10; doc.Save(ArtifactsDir + "WorkingWithDocumentOptionsAndSettings.DocumentPageSetup.docx"); ``` -------------------------------- ### Aspose Export ListView To Word Control Example Source: https://docs.aspose.com/words/net/visual-studio-export-listview-to-word-control This example demonstrates the usage of the Aspose Export ListView To Word control with various properties configured, including text, CSS class, output format, landscape orientation, server path, heading, license path, and layout templates. ```aspx Copy
Product Id Product Name Units In Stock
<%# Eval("Product Id")%> <%# Eval("Product Name")%> <%# Eval("Units In Stock")%>
``` -------------------------------- ### Get FontFallbackSettings Instance Source: https://docs.aspose.com/words/net/manipulating-and-substitution-truetype-fonts Retrieve the FontFallbackSettings object from FontSettings to configure fallback behavior. ```csharp FontFallbackSettings settings = fontSettings.FallbackSettings; ``` -------------------------------- ### Create and Save a Simple Document - C# Source: https://docs.aspose.com/words/net/hello-world This snippet demonstrates creating a new document, adding text, appending another document, and saving the result as a PDF. It's useful for basic document generation and manipulation tasks. ```csharp // For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. Document docA = new Document(); DocumentBuilder builder = new DocumentBuilder(docA); // Insert text to the document start. builder.MoveToDocumentStart(); builder.Write("First Hello World paragraph"); Document docB = new Document(MyDir + "Document.docx"); // Add document B to the and of document A, preserving document B formatting. docA.AppendDocument(docB, ImportFormatMode.KeepSourceFormatting); docA.Save(ArtifactsDir + "HelloWorld.SimpleHelloWorld.pdf"); ``` -------------------------------- ### Detect File Format and Organize Source: https://docs.aspose.com/words/net/detect-file-format-and-check-format-compatibility Iterates through a list of files, detects their format using `FileFormatUtil.DetectFileFormat`, and sorts them into subdirectories based on format type (supported, unknown, encrypted, pre-97). Creates necessary directories if they don't exist. Ensure System.IO and System.IO.Path namespaces are imported. ```csharp string supportedDir = ArtifactsDir + "Supported"; string unknownDir = ArtifactsDir + "Unknown"; string encryptedDir = ArtifactsDir + "Encrypted"; string pre97Dir = ArtifactsDir + "Pre97"; // Create the directories if they do not already exist. if (Directory.Exists(supportedDir) == false) Directory.CreateDirectory(supportedDir); if (Directory.Exists(unknownDir) == false) Directory.CreateDirectory(unknownDir); if (Directory.Exists(encryptedDir) == false) Directory.CreateDirectory(encryptedDir); if (Directory.Exists(pre97Dir) == false) Directory.CreateDirectory(pre97Dir); IEnumerable fileList = Directory.GetFiles(MyDir).Where(name => !name.EndsWith("Corrupted document.docx")); foreach (string fileName in fileList) { string nameOnly = Path.GetFileName(fileName); Console.Write(nameOnly); FileFormatInfo info = FileFormatUtil.DetectFileFormat(fileName); // Display the document type switch (info.LoadFormat) { case LoadFormat.Doc: Console.WriteLine("\tMicrosoft Word 97-2003 document."); break; case LoadFormat.Dot: Console.WriteLine("\tMicrosoft Word 97-2003 template."); break; case LoadFormat.Docx: Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Document."); break; case LoadFormat.Docm: Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Document."); break; case LoadFormat.Dotx: Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Template."); break; case LoadFormat.Dotm: Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Template."); break; case LoadFormat.FlatOpc: Console.WriteLine("\tFlat OPC document."); break; case LoadFormat.Rtf: Console.WriteLine("\tRTF format."); break; case LoadFormat.WordML: Console.WriteLine("\tMicrosoft Word 2003 WordprocessingML format."); break; case LoadFormat.Html: Console.WriteLine("\tHTML format."); break; case LoadFormat.Mhtml: Console.WriteLine("\tMHTML (Web archive) format."); break; case LoadFormat.Odt: Console.WriteLine("\tOpenDocument Text."); break; case LoadFormat.Ott: Console.WriteLine("\tOpenDocument Text Template."); break; case LoadFormat.DocPreWord60: Console.WriteLine("\tMS Word 6 or Word 95 format."); break; case LoadFormat.Unknown: Console.WriteLine("\tUnknown format."); break; } if (info.IsEncrypted) { Console.WriteLine("\tAn encrypted document."); File.Copy(fileName, Path.Combine(encryptedDir, nameOnly), true); } else { switch (info.LoadFormat) { case LoadFormat.DocPreWord60: File.Copy(fileName, Path.Combine(pre97Dir, nameOnly), true); break; case LoadFormat.Unknown: File.Copy(fileName, Path.Combine(unknownDir, nameOnly), true); break; default: File.Copy(fileName, Path.Combine(supportedDir, nameOnly), true); break; } } } ``` -------------------------------- ### Invoice Data Classes Source: https://docs.aspose.com/words/net/merging-table-cells-dynamically Defines the data structure for invoices and invoice items, used in the template examples. ```csharp public class Invoice { public int Number { get { ... } } public IEnumerable Items { get { ... } } ... } public class InvoiceItem { public String Ware { get { ... } } public String Pack { get { ... } } public int Quantity { get { ... } } ... } ``` -------------------------------- ### COMPARE Field Example Source: https://docs.aspose.com/words/net/fields-overview Shows a COMPARE field used for evaluating a mathematical expression against a given value. ```plaintext COMPARE 3+5/34 < 4.6/3/2 ``` -------------------------------- ### Get Form Field Collection Source: https://docs.aspose.com/words/net/working-with-form-fields Retrieves all form fields from a document. Ensure the document is loaded correctly. ```csharp Document doc = new Document(MyDir + "Form fields.docx"); FormFieldCollection formFields = doc.Range.FormFields; ``` -------------------------------- ### Remove All Digital Signatures Source: https://docs.aspose.com/words/net/working-with-digital-signatures This example demonstrates how to remove all digital signatures from a document using filenames or file streams. ```APIDOC ## Remove All Digital Signatures Aspose.Words allows you to remove all digital signatures from a signed document using the `RemoveAllSignatures` method. ### Method 1: Using Filename Strings ```csharp DigitalSignatureUtil.RemoveAllSignatures(MyDir + "Digitally signed.docx", ArtifactsDir + "DigitalSignatureUtil.LoadAndRemove.FromString.docx"); ``` ### Method 2: Using File Streams ```csharp using (Stream streamIn = new FileStream(MyDir + "Digitally signed.docx", FileMode.Open)) { using (Stream streamOut = new FileStream(ArtifactsDir + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx", FileMode.Create)) { DigitalSignatureUtil.RemoveAllSignatures(streamIn, streamOut); } } ``` ### Verification ```csharp Assert.That(DigitalSignatureUtil.LoadSignatures(ArtifactsDir + "DigitalSignatureUtil.LoadAndRemove.FromString.docx"), Is.Empty); Assert.That(DigitalSignatureUtil.LoadSignatures(ArtifactsDir + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx"), Is.Empty); ``` **Note:** You cannot remove only one digital signature within your document. The `RemoveAllSignatures` method removes all existing signatures. ``` -------------------------------- ### Apply License from File Source: https://docs.aspose.com/words/net/licensing Call SetLicense with the license file name. The method attempts to find the license file in embedded resources or assembly folders. Ensure the license file is accessible. ```csharp // For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. License license = new License(); // This line attempts to set a license from several locations relative to the executable and Aspose.Words.dll. // You can also use the additional overload to load a license from a stream, this is useful, // for instance, when the license is stored as an embedded resource. try { license.SetLicense("Aspose.Words.lic"); Console.WriteLine("License set successfully."); } catch (Exception e) { // We do not ship any license with this example, // visit the Aspose site to obtain either a temporary or permanent license. Console.WriteLine("\nThere was an error setting the license: " + e.Message); } ``` -------------------------------- ### Create a Simple Table using NPOI XWPF Source: https://docs.aspose.com/words/net/create-tables-in-npoi Create a table with a specified number of rows and columns using XWPFDocument. Access cells and rows to set text and apply formatting. ```C# using NPOI.XWPF.UserModel; XWPFDocument doc = new XWPFDocument(); XWPFParagraph para= doc.CreateParagraph(); XWPFRun r0 = para.CreateRun(); r0.SetText("Title1"); para.BorderTop = Borders.THICK; para.FillBackgroundColor = "EEEEEE"; para.FillPattern = NPOI.OpenXmlFormats.Wordprocessing.ST_Shd.diagStripe; XWPFTable table = doc.CreateTable(3, 3); table.GetRow(1).GetCell(1).SetText("EXAMPLE OF TABLE"); XWPFTableCell c1 = table.GetRow(0).GetCell(0); XWPFParagraph p1 = c1.AddParagraph(); //don't use doc.CreateParagraph XWPFRun r1 = p1.CreateRun(); r1.SetText("The quick brown fox"); r1.SetBold(true); r1.FontFamily = "Courier"; r1.SetUnderline(UnderlinePatterns.DotDotDash); r1.SetTextPosition(100); c1.SetColor("FF0000"); table.GetRow(2).GetCell(2).SetText("only text"); FileStream out1 = new FileStream("simpleTable.docx", FileMode.Create); doc.Write(out1); out1.Close(); ``` -------------------------------- ### Template with Syntax Error Source: https://docs.aspose.com/words/net/inlining-syntax-error-messages-into-templates This is an example of a template containing a syntax error. By default, this would cause an exception during report building. ```plaintext <> ``` -------------------------------- ### Numbered List Template Example Source: https://docs.aspose.com/words/net/typical-templates Illustrates creating a numbered list of client names. The foreach loop iterates through 'clients' and formats each name as a numbered list item. ```plaintext We provide support for the following clients: 1. <><<[Name]>> <> ``` -------------------------------- ### Create a Simple Table with DocumentBuilder Source: https://docs.aspose.com/words/net/introduction-and-creating-tables Use DocumentBuilder.StartTable(), InsertCell(), EndRow(), and EndTable() to construct a basic table. This method applies default Word styling. ```csharp DocumentBuilder builder = new DocumentBuilder(); builder.StartTable(); builder.InsertCell(); builder.Writeln("Row 1, Cell 1"); builder.InsertCell(); builder.Writeln("Row 1, Cell 2"); builder.EndRow(); builder.InsertCell(); builder.Writeln("Row 2, Cell 1"); builder.InsertCell(); builder.Writeln("Row 2, Cell 2"); builder.EndRow(); builder.EndTable(); ``` -------------------------------- ### Get Document Variables Source: https://docs.aspose.com/words/net/work-with-document-properties Enumerate document variables using the Variables property. Variable names and values are stored as strings. ```csharp Document doc = new Document(MyDir + "Document.docx"); string variables = ""; foreach (KeyValuePair entry in doc.Variables) { string name = entry.Key; string value = entry.Value; if (variables == "") variables = "Name: " + name + "," + "Value: {1}" + value; else variables = variables + "Name: " + name + "," + "Value: {1}" + value; } Console.WriteLine("\nDocument have following variables " + variables); ``` -------------------------------- ### Load JSON and Build Report Source: https://docs.aspose.com/words/net/accessing-json-data Demonstrates loading JSON data and using the ReportingEngine to build a report from a template document. ```csharp Document doc = ... // Loading a template document. JsonDataSource dataSource = ... // Loading JSON. ReportingEngine engine = new ReportingEngine(); engine.BuildReport(doc, dataSource, "managers"); ``` -------------------------------- ### Get Current Default Font Name Source: https://docs.aspose.com/words/net/manipulating-and-substitution-truetype-fonts Retrieve the name of the font that Aspose.Words will use as a default when no other substitution rules apply. ```csharp fontSettings.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName; ``` -------------------------------- ### Get Font Information Collection Source: https://docs.aspose.com/words/net/manipulating-and-substitution-truetype-fonts Retrieve the collection of FontInfo objects from a document to access font information used in substitution. ```csharp FontInfoCollection fontInfos = doc.FontInfos; ``` -------------------------------- ### Create a Simple Table using DocumentBuilder Source: https://docs.aspose.com/words/net/create-a-table Use DocumentBuilder.StartTable(), InsertCell(), Writeln(), EndRow(), and EndTable() to build a table with default Word styling. This method is straightforward for basic table generation. ```csharp DocumentBuilder builder = new DocumentBuilder(doc); // Start building the table builder.StartTable(); // Insert cells and content for the first row builder.InsertCell(); builder.Writeln("Row 1, Cell 1"); builder.InsertCell(); builder.Writeln("Row 1, Cell 2"); builder.EndRow(); // Insert cells and content for the second row builder.InsertCell(); builder.Writeln("Row 2, Cell 1"); builder.InsertCell(); builder.Writeln("Row 2, Cell 2"); builder.EndRow(); // Finish building the table builder.EndTable(); doc.UpdateFields(); ``` -------------------------------- ### Dockerfile Configuration for Aspose.Words Application Source: https://docs.aspose.com/words/net/how-to-run-aspose-words-in-docker This Dockerfile sets up a .NET Core SDK environment, installs necessary Linux dependencies for SkiaSharp, copies the application code, publishes it, and defines the entry point for running the Aspose.Words application within a Docker container. ```dockerfile FROM mcr.microsoft.com/dotnet/core/sdk:2.2 WORKDIR /app RUN apt-get update && apt-get install -y libfontconfig1 COPY . ./ RUN dotnet publish -c Release -o out ENTRYPOINT ["dotnet", "Aspose.Words.Docker.Sample/out/Aspose.Words.Docker.Sample.dll"] ``` -------------------------------- ### Common List Template Example Source: https://docs.aspose.com/words/net/typical-templates A basic template to iterate through a collection of managers and display their names. It uses a simple foreach loop. ```plaintext <> <<[Name()]>> <> ``` -------------------------------- ### Get Field Code and Result Source: https://docs.aspose.com/words/net/find-field-properties Iterate through all fields in a document to retrieve their field codes and results. Ensure the document is loaded before processing. ```csharp Document doc = new Document(MyDir + "Hyperlinks.docx"); foreach (Field field in doc.Range.Fields) { string fieldCode = field.GetFieldCode(); string fieldResult = field.Result; } ``` -------------------------------- ### Bulleted List Template Example Source: https://docs.aspose.com/words/net/typical-templates Shows how to generate a bulleted list of client names. It iterates through the 'clients' collection and displays each client's name as a list item. ```plaintext We provide support for the following clients: * <><<[Name]>> <> ``` -------------------------------- ### Get Distinct Elements from an Enumeration Source: https://docs.aspose.com/words/net/appendix-a-enumeration-extension-methods The `Distinct` method returns an enumeration containing only the unique elements from the source enumeration, removing duplicates. ```csharp persons.Distinct() ``` -------------------------------- ### Create GPT-4o AI Model Instance Source: https://docs.aspose.com/words/net/supported-ai-models Instantiate a specific AI model, such as GPT-4o, using the static AiModel.Create method with the corresponding AiModelType. The returned AiModel object can be used for various AI operations. ```csharp AiModel gpt4o = AiModel.Create(AiModelType.OpenAi_Gpt4o); ``` -------------------------------- ### Dynamic Bookmark Name Example Source: https://docs.aspose.com/words/net/inserting-bookmarks-dynamically Define a bookmark name dynamically by placing an expression within the bookmark tag. The expression is evaluated at runtime. ```plaintext <> ```