### Regex Text Replacement in JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Provides a JavaScript example for replacing text in a Word document using regular expressions. It demonstrates creating a regex to match specific patterns (e.g., words starting with '#') and replacing them with new text.
```javascript
const doc = wasmModule.Document.Create();
doc.LoadFromFile(inputFileName);
let regex = wasmModule.Regex.Create('\\#\\w+\\b', wasmModule.RegexOptions.None);
doc.Replace(regex, 'Spire.Doc');
doc.Dispose();
```
--------------------------------
### Spire.Doc JavaScript Page Setup
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Modifies page setup properties of document sections in a Word document using Spire.Doc for JavaScript. It demonstrates setting margins and page size for all sections, and also specifically for the first section, including header and footer distances.
```javascript
// Load Word document
let doc = wasmModule.Document.Create();
doc.LoadFromFile(inputFileName);
// Loop through all sections
for (let i = 0; i < doc.Sections.Count; i++) {
let section = doc.Sections.get(i);
// Modify the margins
section.PageSetup.Margins = wasmModule.MarginsF.Create(100, 80, 100, 80);
// Modify the page size
section.PageSetup.PageSize = wasmModule.PageSize.Letter;
}
// Modify only one section (first section)
let section0 = doc.Sections.get_Item(0);
section0.PageSetup.Margins = wasmModule.MarginsF.Create(100, 80, 100, 80);
section0.PageSetup.FooterDistance = 35.4;
section0.PageSetup.HeaderDistance = 34.4;
```
--------------------------------
### Compare Two Word Documents
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example shows how to compare two Word documents using Spire.Doc for JavaScript and highlight the differences. The result is saved as a new document.
```javascript
//Load the first document
let doc1 = wasmModule.Document.Create();
doc1.LoadFromFile(inputFileName1);
//Load the second document
let doc2 = wasmModule.Document.Create();
doc2.LoadFromFile(inputFileName2);
//Compare the two documents
doc1.Compare(doc2, "E-iceblue");
// Save the document to the specified path
doc1.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
```
--------------------------------
### Convert HTML to XML
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example shows how to convert an HTML file into an XML file using Spire.Doc for JavaScript. It loads the HTML and saves the document in XML format.
```javascript
// Create a new document
const doc = wasmModule.Document.Create();
// Load a document from the virtual file system
doc.LoadFromFile({fileName:inputFileName, fileFormat : wasmModule.FileFormat.Html, validationType:wasmModule.XHTMLValidationType.None});
// Define the output file name
const outputFileName = "HtmlToXml-result.xml";
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Xml});
```
--------------------------------
### Clone a Table in a Word Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates how to clone an entire table and add it to a Word document using Spire.Doc for JavaScript. It loads a document, gets the first table, clones it using the Clone() method, modifies the last row of the cloned table, and then adds the cloned table to the section.
```javascript
//Load the document
let doc = wasmModule.Document.Create();
doc.LoadFromFile(inputFileName);
//Get the first section
let se = doc.Sections.get_Item(0);
//Get the first table
let original_Table = se.Tables.get_Item(0);
//Copy the existing table to copied_Table via Table.clone()
let copied_Table = original_Table.Clone();
let st = ["Spire.Presentation for JS", "A professional " +
"PowerPoint® compatible library that enables developers to create, read, " +
"write, modify, convert and Print PowerPoint documents on any JS framework."];
//Get the last row of table
let lastRow = copied_Table.Rows.get(copied_Table.Rows.Count - 1);
//Change last row data
for (let i = 0; i < lastRow.Cells.Count - 1; i++) {
lastRow.Cells.get(i).Paragraphs.get_Item(0).Text = st[i];
}
//Add copied_Table in section
se.Tables.Add(copied_Table);
```
--------------------------------
### Count Words and Characters in a Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example shows how to count the number of characters (with and without spaces) and words in a Word document using Spire.Doc for JavaScript.
```javascript
// Create a new document
const document = wasmModule.Document.Create();
document.LoadFromFile(inputFileName);
// Count the number of words.
let content = [];
content.push("CharCount: " + document.BuiltinDocumentProperties.CharCount + "\n");
content.push("CharCountWithSpace: " + document.BuiltinDocumentProperties.CharCountWithSpace + "\n");
content.push("WordCount: " + document.BuiltinDocumentProperties.WordCount + "\n");
```
--------------------------------
### Insert Table into Textbox
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates how to add a textbox to a Word document and then insert a table with data into that textbox using Spire.Doc for JavaScript.
```javascript
const document = wasmModule.Document.Create();
let section = document.AddSection();
let paragraph = section.AddParagraph();
let textbox = paragraph.AppendTextBox(300, 100);
textbox.Format.HorizontalOrigin = wasmModule.HorizontalOrigin.Page;
textbox.Format.HorizontalPosition = 140;
textbox.Format.VerticalOrigin = wasmModule.VerticalOrigin.Page;
textbox.Format.VerticalPosition = 50;
let textboxParagraph = textbox.Body.AddParagraph();
let textboxRange = textboxParagraph.AppendText("Table 1");
textboxRange.CharacterFormat.FontName = "Arial";
let table = textbox.Body.AddTable({showBorder: true});
table.ResetCells(4, 4);
let data =
[
["Name", "Age", "Gender", "ID"],
["John", "28", "Male", "0023"],
["Steve", "30", "Male", "0024"],
["Lucy", "26", "female", "0025"]
];
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
let tableRange = table.Rows.get(i).Cells.get(j).AddParagraph().AppendText(data[i][j]);
tableRange.CharacterFormat.FontName = "Arial";
}
}
table.ApplyStyle(wasmModule.DefaultTableStyle.TableColorful2);
```
--------------------------------
### Clone a Word Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Provides an example of cloning a Word document using Spire.Doc for JavaScript. It loads an existing document and creates an exact copy of it, ensuring both original and cloned documents are disposed of afterward.
```javascript
wasmModule = window.wasmModule;
const document = wasmModule.Document.Create();
document.LoadFromFile("Template_Docx_1.docx");
let newDoc = document.Clone();
document.Dispose();
newDoc.Dispose();
```
--------------------------------
### Convert Word to XPS using Spire.Doc for JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates converting a Word document to XPS format using Spire.Doc for JavaScript. The process involves creating a document, loading the input file, and saving it to the specified XPS file path.
```javascript
// Create a new document
const doc = wasmModule.Document.Create();
// Load a document from the virtual file system
doc.LoadFromFile(inputFileName);
// Define the output file name
const outputFileName = "ToXPS-result.xps";
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.XPS});
// Clean up resources
doc.Dispose();
```
--------------------------------
### Convert Word Document to Byte Array and Back
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example shows how to convert a Word document into a byte array and then load it back into a document object. It utilizes memory streams for the conversion process.
```javascript
// Create a new document
const doc = wasmModule.Document.Create();
// Load a document from the virtual file system
doc.LoadFromFile(inputFileName);
// Create a new memory stream.
let outStream = wasmModule.Stream.Create();
// Save the document to stream.
doc.SaveToStream({stream: outStream, fileFormat: wasmModule.FileFormat.Docx});
// Convert the document to bytes.
let docBytes = outStream.ToArray();
// Now reverse the steps to load the bytes back into a document object.
let inStream = wasmModule.Stream.CreateByBytes(docBytes);
// Load the stream into a new document object.
let newDoc = wasmModule.Document.Create();
newDoc.LoadFromStream({stream: inStream, fileFormat: wasmModule.FileFormat.Auto});
```
--------------------------------
### Convert Word to HTML
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Provides an example of converting a Word document to HTML format using Spire.Doc for JavaScript. The process involves loading the Word document and saving it as an HTML file.
```javascript
let document = wasmModule.Document.Create();
document.LoadFromFile(inputFileName);
const outputFileName = "ToHtml-result.html";
document.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Html});
document.Dispose();
```
--------------------------------
### Convert Word Document to Encrypted PDF
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates converting a Word document to a PDF file and applying password-based encryption to the resulting PDF. It utilizes the ToPdfParameterList to configure PDF security settings.
```javascript
// Create a new document
const document = wasmModule.Document.Create();
// Load a document from the virtual file system
document.LoadFromFile(inputFileName);
// Create an instance of ToPdfParameterList
let toPdf = wasmModule.ToPdfParameterList.Create();
// Set the user password for the resulted PDF file
toPdf.PdfSecurity.Encrypt("e-iceblue");
// Define the output file name
const outputFileName = "WordToPdfEncrypt.pdf";
// Save the document to the specified path
document.SaveToFile({fileName: outputFileName, paramList: toPdf});
// Clean up resources
document.Dispose();
```
--------------------------------
### Link Headers and Footers Between Word Document Sections
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Provides a JavaScript example for linking headers and footers between sections of Word documents using Spire.Doc. It sets the `LinkToPrevious` property for headers and footers.
```javascript
let srcDoc = wasmModule.Document.Create()
srcDoc.LoadFromFile(inputFileName1);
let dstDoc = wasmModule.Document.Create();
dstDoc.LoadFromFile(inputFileName2);
srcDoc.Sections.get_Item(0).HeadersFooters.Header.LinkToPrevious = true;
srcDoc.Sections.get_Item(0).HeadersFooters.Footer.LinkToPrevious = true;
for (let i = 0; i < srcDoc.Sections.Count; i++) {
let section = srcDoc.Sections.get_Item(i);
dstDoc.Sections.Add(section.Clone());
}
```
--------------------------------
### Merge Word Documents by Cloning Sections
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Illustrates merging two Word documents by cloning their sections. This example shows loading documents with specific formats and appending sections from one to another, then saving the result.
```javascript
let document = wasmModule.Document.Create();
document.LoadFromFile({ fileName: inputFileName1, fileFormat: wasmModule.FileFormat.Doc });
let documentMerge = wasmModule.Document.Create();
documentMerge.LoadFromFile({ fileName: inputFileName2, fileFormat: wasmModule.FileFormat.Docx });
for (let i = 0; i < documentMerge.Sections.Count; i++) {
let section = documentMerge.Sections.get_Item(i);
document.Sections.Add(section.Clone());
}
document.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
```
--------------------------------
### Create Simple and Nested Bookmarks in Word Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This function demonstrates how to create both simple bookmarks and nested bookmarks within a Word document. It includes adding text, applying formatting, and correctly marking the start and end of each bookmark.
```javascript
function CreateBookmarkBase(section) {
let paragraph = section.AddParagraph();
let txtRange = paragraph.AppendText("The following example demonstrates how to create bookmark in a Word document.");
txtRange.CharacterFormat.Italic = true;
section.AddParagraph();
paragraph = section.AddParagraph();
txtRange = paragraph.AppendText("Simple Create Bookmark.");
txtRange.CharacterFormat.TextColor = wasmModule.Color.get_CornflowerBlue();
paragraph.ApplyStyle({builtinStyle : wasmModule.BuiltinStyle.Heading2});
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.AppendBookmarkStart("SimpleCreateBookmark");
paragraph.AppendText("This is a simple bookmark.");
paragraph.AppendBookmarkEnd("SimpleCreateBookmark");
section.AddParagraph();
paragraph = section.AddParagraph();
txtRange = paragraph.AppendText("Nested Create Bookmark.");
txtRange.CharacterFormat.TextColor = wasmModule.Color.get_CornflowerBlue();
paragraph.ApplyStyle({builtinStyle : wasmModule.BuiltinStyle.Heading2});
paragraph = section.AddParagraph();
paragraph.AppendBookmarkStart("Root");
txtRange = paragraph.AppendText(" This is Root data ");
txtRange.CharacterFormat.Italic = true;
paragraph.AppendBookmarkStart("NestedLevel1");
txtRange = paragraph.AppendText(" This is Nested Level1 ");
txtRange.CharacterFormat.Italic = true;
txtRange.CharacterFormat.TextColor = wasmModule.Color.get_DarkSlateGray();
paragraph.AppendBookmarkStart("NestedLevel2");
txtRange = paragraph.AppendText(" This is Nested Level2 ");
txtRange.CharacterFormat.Italic = true;
txtRange.CharacterFormat.TextColor = wasmModule.Color.get_DimGray();
paragraph.AppendBookmarkEnd("NestedLevel2");
paragraph.AppendBookmarkEnd("NestedLevel1");
paragraph.AppendBookmarkEnd("Root");
}
```
--------------------------------
### Set Image Background for Word Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Provides a JavaScript code example using Spire.Doc to set an image as the background for a Word document. It covers loading the document and then setting the background type to Picture and specifying the image file.
```javascript
let document = wasmModule.Document.Create();
document.LoadFromFile(inputFileName1);
document.Background.Type = wasmModule.BackgroundType.Picture;
document.Background.SetPicture(inputFileName2);
```
--------------------------------
### Set Paragraph Before and After Spacing
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example shows how to set the spacing before and after a paragraph in a Word document using Spire.Doc for JavaScript. It creates a new paragraph, appends text with formatting, and then sets the BeforeSpacing and AfterSpacing properties.
```javascript
let document = wasmModule.Document.Create();
let para = wasmModule.Paragraph.Create(document);
let str = 'This is an inserted paragraph.';
let textRange1 = para.AppendText(str);
textRange1.CharacterFormat.TextColor = wasmModule.Color.get_Blue();
textRange1.CharacterFormat.FontSize = 15;
para.Format.BeforeAutoSpacing = false;
para.Format.BeforeSpacing = 10;
para.Format.AfterAutoSpacing = false;
para.Format.AfterSpacing = 10;
document.Sections.get(0).Paragraphs.Insert(1, para);
```
--------------------------------
### Encrypt Word Document with Password
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates how to encrypt a Word document with a password using Spire.Doc for JavaScript. It creates a new document, loads an existing file, and then applies encryption with a specified password.
```javascript
// Create a new document
const document = wasmModule.Document.Create();
// Load a document from the virtual file system
document.LoadFromFile(inputFileName);
// Encrypt document with password
document.Encrypt("E-iceblue");
```
--------------------------------
### Convert HTML String to Word
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Provides an example of converting an HTML string into a Word document using Spire.Doc for JavaScript. It covers creating a document, adding content from an HTML string, and saving the result as a DOCX file.
```javascript
let HTML = "
Spire.Doc
Edition:
";
HTML+=
"- Free Edition
- Trial version
- A month free for trial version
Platform:
";
HTML+=
"- .NET
- WPF
- Silverlight
| Main Functions of Spire.Doc |
|---|
| Convert File Documents with High Quality |
| Richest Word Document Features Support |
";
HTML+=
"| Simple & Easy to Process Pre-Existing Word Documents |
| Other Technical Features |
";
const document = wasmModule.Document.Create();
let section = document.AddSection();
let paragraph = section.AddParagraph();
paragraph.AppendHTML(HTML);
document.SaveToFile({fileName: "HtmlStringToWord-result.docx", fileFormat: wasmModule.FileFormat.Docx2013});
document.Dispose();
```
--------------------------------
### Convert Word to SVG using Spire.Doc for JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example shows how to convert a Word document to SVG format using Spire.Doc for JavaScript. The process includes initializing a document, loading the source file, and saving it as an SVG file.
```javascript
// Create a new document
const doc = wasmModule.Document.Create();
// Load a document from the virtual file system
doc.LoadFromFile("input.docx");
// Save the document to SVG format
doc.SaveToFile({fileName: "output.svg", fileFormat: wasmModule.FileFormat.SVG});
// Clean up resources
doc.Dispose();
```
--------------------------------
### Load and Save Word Document with Macros
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Shows how to use Spire.Doc for JavaScript to load an existing Word document, potentially containing macros, and save it in a macro-enabled format (.docm). The example includes proper resource management by disposing of the document object after saving.
```javascript
// Create a new document
const document = wasmModule.Document.Create();
// Load a document from the virtual file system
document.LoadFromFile(inputFileName);
// Define the output file name
const outputFileName = "Macros.docm";
// Save the document to the specified path with macro enabled format
document.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docm});
// Clean up resources
document.Dispose();
```
--------------------------------
### Get Row and Cell Index in Word Table
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates how to load a Word document, access the first table, and retrieve the index of the table within its section's collection. It also shows how to get the index of the last row and the index of the last cell within that row.
```javascript
let doc = wasmModule.Document.Create();
doc.LoadFromFile(inputFileName);
let section = doc.Sections.get_Item(0);
let table = section.Tables.get_Item(0);
let collections = section.Tables;
let tableIndex = collections.IndexOf(table);
let row = table.LastRow;
let rowIndex = row.GetRowIndex();
let cell = row.LastChild;
let cellIndex = cell.GetCellIndex();
```
--------------------------------
### Create JavaScript Hello World Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Demonstrates how to create a new Word document with 'Hello World!' text using Spire.Doc for JavaScript. It covers document creation, adding sections and paragraphs, appending text, and saving the document.
```javascript
const document = wasmModule.Document.Create();
let section = document.AddSection();
let paragraph = section.AddParagraph();
paragraph.AppendText('Hello World!');
document.SaveToFile({
fileName: 'HelloWorld.docx',
fileFormat: wasmModule.FileFormat.Docx2013,
});
document.Dispose();
```
--------------------------------
### Load and Save Document to Disk
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Demonstrates how to create a new document, download a Word document from a URL, load it from a stream, and save it to disk in a different format. Includes resource cleanup.
```javascript
const document = wasmModule.Document.Create();
const response = await fetch("http://www.e-iceblue.com/images/test.docx");
let buffer = response.arrayBuffer();
let ms = wasmModule.Stream.CreateByBytes(buffer);
document.LoadFromStream({ stream: ms, fileFormat: wasmModule.FileFormat.Docx });
const outputFileName = "DownloadWordFromURL_out.docx";
document.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
document.Dispose();
```
--------------------------------
### Get Alternative Text from Word Document Shapes
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example shows how to load a Word document, iterate through its sections, paragraphs, and child objects to find ShapeObjects. For each ShapeObject, it retrieves and collects the AlternativeText, which can be used for accessibility or descriptive purposes.
```javascript
let document = wasmModule.Document.Create();
document.LoadFromFile(inputFileName);
let builder = [];
for (let i = 0; i < document.Sections.Count; i++) {
let section = document.Sections.get(i);
for (let j = 0; j < section.Paragraphs.Count; j++) {
let para = section.Paragraphs.get_Item(j);
for (let k = 0; k < para.ChildObjects.Count; k++) {
let obj = para.ChildObjects.get(k);
if (obj instanceof wasmModule.ShapeObject) {
let text = obj.AlternativeText;
builder.push(text + "\n");
}
}
}
}
document.Dispose();
```
--------------------------------
### Convert Word to PDF/A using Spire.Doc for JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates converting a Word document to PDF/A format (specifically PDF_A1B conformance level) using Spire.Doc for JavaScript. It involves creating a document, loading the input file, setting PDF conformance parameters, and saving the output.
```javascript
// Create a new document
const doc = wasmModule.Document.Create();
// Load a document from the virtual file system
doc.LoadFromFile(inputFileName);
// Set the Conformance-level of the Pdf file to PDF_A1B.
let toPdf = wasmModule.ToPdfParameterList.Create();
toPdf.PdfConformanceLevel = wasmModule.PdfConformanceLevel.Pdf_A1B;
// Save the file.
doc.SaveToFile({fileName: outputFileName, fileFormat: toPdf});
// Clean up resources
doc.Dispose();
```
--------------------------------
### Extract Content from Form Field
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This JavaScript example demonstrates extracting content starting from a form field in a Word document. It loads a document, finds a text input form field, determines its position in the document body, and copies the subsequent three elements to a new document.
```javascript
let sourceDocument = wasmModule.Document.Create();
sourceDocument.LoadFromFile(inputFileName);
let destinationDoc = wasmModule.Document.Create();
let section = destinationDoc.AddSection();
let index = 0;
let formFields = sourceDocument.Sections.get(0).Body.FormFields;
for (let i = 0; i < formFields.Count; i++) {
let field = formFields.get_Item(i);
if (field.Type == wasmModule.FieldType.FieldFormTextInput) {
let paragraph = field.OwnerParagraph;
index = sourceDocument.Sections.get(0).Body.ChildObjects.IndexOf(paragraph);
break;
}
}
for (let i = index; i < index + 3; i++) {
let doobj = sourceDocument.Sections.get(0).Body.ChildObjects.get(i).Clone();
section.Body.ChildObjects.Add(doobj);
}
```
--------------------------------
### Create Table Directly in Word Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Demonstrates how to create a new Word document, add a section, and then programmatically create a table with specified rows, cells, text, and formatting including background color and alignment.
```javascript
let doc = wasmModule.Document.Create();
let section = doc.AddSection();
let table = wasmModule.Table.Create(doc, false);
table.PreferredWidth = wasmModule.PreferredWidth.Create(wasmModule.WidthType.Percentage, 100);
table.TableFormat.Borders.BorderType = wasmModule.BorderStyle.Single;
let row = wasmModule.TableRow.Create(doc, false);
row.Height = 50.0;
table.Rows.Add(row);
let cell1 = wasmModule.TableCell.Create(doc);
let para1 = cell1.AddParagraph();
para1.AppendText("Row 1, Cell 1");
para1.Format.HorizontalAlignment = wasmModule.HorizontalAlignment.Center;
cell1.CellFormat.BackColor = wasmModule.Color.get_CadetBlue();
cell1.CellFormat.VerticalAlignment = wasmModule.VerticalAlignment.Middle;
row.Cells.Add(cell1);
let cell2 = wasmModule.TableCell.Create(doc);
let para2 = cell2.AddParagraph();
para2.AppendText("Row 1, Cell 2");
para2.Format.HorizontalAlignment = wasmModule.HorizontalAlignment.Center;
cell2.CellFormat.BackColor = wasmModule.Color.get_CadetBlue();
cell2.CellFormat.VerticalAlignment = wasmModule.VerticalAlignment.Middle;
row.Cells.Add(cell2);
section.Tables.Add(table);
```
--------------------------------
### Create and Style Document Paragraphs in JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Demonstrates how to initialize a document, add sections, create and modify various built-in styles (Title, Normal, Heading1, Heading2), and apply these styles to paragraphs. It also shows how to create and apply a custom bulleted list style.
```javascript
let document = wasmModule.Document.Create();
let sec = document.AddSection();
//Add default title style to document and modify
let titleStyle = document.AddStyle(wasmModule.BuiltinStyle.Title);
titleStyle.CharacterFormat.FontName = "cambria";
titleStyle.CharacterFormat.FontSize = 28;
titleStyle.CharacterFormat.TextColor = wasmModule.Color.FromArgb(42, 123, 136);
//judge if it is Paragraph Style and then set paragraph format
if (titleStyle instanceof wasmModule.ParagraphStyle) {
let ps = titleStyle;
ps.ParagraphFormat.Borders.Bottom.BorderType = wasmModule.BorderStyle.Single;
ps.ParagraphFormat.Borders.Bottom.Color = wasmModule.Color.FromArgb(42, 123, 136);
ps.ParagraphFormat.Borders.Bottom.LineWidth = 1.5;
ps.ParagraphFormat.HorizontalAlignment = wasmModule.HorizontalAlignment.Left;
}
//Add default normal style and modify
let normalStyle = document.AddStyle(wasmModule.BuiltinStyle.Normal);
normalStyle.CharacterFormat.FontName = "cambria";
normalStyle.CharacterFormat.FontSize = 11;
//Add default heading1 style
let heading1Style = document.AddStyle(wasmModule.BuiltinStyle.Heading1);
heading1Style.CharacterFormat.FontName = "cambria";
heading1Style.CharacterFormat.FontSize = 14;
heading1Style.CharacterFormat.Bold = true;
heading1Style.CharacterFormat.TextColor = wasmModule.Color.FromArgb(42, 123, 136);
//Add default heading2 style
let heading2Style = document.AddStyle(wasmModule.BuiltinStyle.Heading2);
heading2Style.CharacterFormat.FontName = "cambria";
heading2Style.CharacterFormat.FontSize = 12;
heading2Style.CharacterFormat.Bold = true;
//List style
let bulletList = wasmModule.ListStyle.Create(document, wasmModule.ListType.Bulleted);
bulletList.CharacterFormat.FontName = "cambria";
bulletList.CharacterFormat.FontSize = 12;
bulletList.Name = "bulletList";
document.ListStyles.Add(bulletList);
//Apply the style
let paragraph = sec.AddParagraph();
paragraph.AppendText("Your Name");
paragraph.ApplyStyle({builtinStyle : wasmModule.BuiltinStyle.Title});
paragraph = sec.AddParagraph();
paragraph.AppendText("Address, City, ST ZIP Code | Telephone | Email");
paragraph.ApplyStyle({builtinStyle : wasmModule.BuiltinStyle.Normal});
paragraph = sec.AddParagraph();
paragraph.AppendText("Objective");
paragraph.ApplyStyle({builtinStyle : wasmModule.BuiltinStyle.Heading1});
paragraph = sec.AddParagraph();
paragraph.AppendText("To get started right away, just click any placeholder text (such as this) and start typing to replace it with your own.");
paragraph.ApplyStyle({builtinStyle : wasmModule.BuiltinStyle.Normal});
paragraph = sec.AddParagraph();
paragraph.AppendText("Education");
paragraph.ApplyStyle({builtinStyle : wasmModule.BuiltinStyle.Heading1});
paragraph = sec.AddParagraph();
paragraph.AppendText("DEGREE | DATE EARNED | SCHOOL");
paragraph.ApplyStyle({builtinStyle : wasmModule.BuiltinStyle.Heading2});
paragraph = sec.AddParagraph();
paragraph.AppendText("Major:Text");
paragraph.ListFormat.ApplyStyle("bulletList");
paragraph = sec.AddParagraph();
paragraph.AppendText("Minor:Text");
paragraph.ListFormat.ApplyStyle("bulletList");
paragraph = sec.AddParagraph();
paragraph.AppendText("Related coursework:Text");
paragraph.ListFormat.ApplyStyle("bulletList");
```
--------------------------------
### Add Gutter to Word Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Illustrates how to add a gutter to a Word document's page setup using Spire.Doc for JavaScript. This involves accessing the section's page setup and setting the Gutter property.
```javascript
let document = wasmModule.Document.Create();
document.LoadFromFile(inputFileName);
let section = document.Sections.get(0);
section.PageSetup.Gutter = 100;
```
--------------------------------
### Convert HTML to XPS using Spire.Doc for JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This snippet demonstrates how to load an HTML document and save it as an XPS file using Spire.Doc for JavaScript. It initializes a new document, loads the HTML file with specified validation, saves it to XPS format, and then disposes of the document resources.
```javascript
const doc = wasmModule.Document.Create();
doc.LoadFromFile({
fileName: inputFileName,
fileFormat: wasmModule.FileFormat.Html,
validationType: wasmModule.XHTMLValidationType.None
});
const outputFileName = "HtmlToXps-result.xps";
doc.SaveToFile({
fileName: outputFileName,
fileFormat: wasmModule.FileFormat.XPS
});
doc.Dispose();
```
--------------------------------
### Remove Textbox
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates how to load a Word document and remove the first textbox from it using Spire.Doc for JavaScript.
```javascript
const document = wasmModule.Document.Create();
document.LoadFromFile("TextBoxTemplate.docx");
document.TextBoxes.RemoveAt(0);
document.Dispose();
```
--------------------------------
### Create Paragraph with Multiple Styles
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates how to create a single paragraph in a Word document and apply different character formatting (font name, size, color, bold, underline) to different text ranges within that paragraph using Spire.Doc for JavaScript.
```javascript
let doc = wasmModule.Document.Create();
let section = doc.AddSection();
let para = section.AddParagraph();
let range = para.AppendText("Spire.Doc for JavaScript ");
range.CharacterFormat.FontName = "Calibri";
range.CharacterFormat.FontSize = 16;
range.CharacterFormat.TextColor = wasmModule.Color.get_Blue();
range.CharacterFormat.Bold = true;
range.CharacterFormat.UnderlineStyle = wasmModule.UnderlineStyle.Single;
range = para.AppendText("is a professional Word JavaScript library");
range.CharacterFormat.FontName = "Calibri";
range.CharacterFormat.FontSize = 15;
```
--------------------------------
### Convert Word to PostScript using Spire.Doc for JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This snippet shows how to convert a Word document to PostScript format using Spire.Doc for JavaScript. It covers initializing a document, loading the Word file, defining the output PostScript file name, saving the document, and cleaning up resources.
```javascript
const doc = wasmModule.Document.Create();
doc.LoadFromFile(inputFileName);
const outputFileName = "ToPostScript-result.ps";
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.PostScript});
doc.Dispose();
```
--------------------------------
### Convert RTF to HTML using Spire.Doc for JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates converting an RTF (Rich Text Format) document to HTML format using Spire.Doc for JavaScript. The process includes initializing a document, loading the RTF file, and saving it as an HTML file, followed by resource cleanup.
```javascript
const doc = wasmModule.Document.Create();
doc.LoadFromFile(inputFileName);
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Html});
doc.Dispose();
```
--------------------------------
### Insert Image into Textbox
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This snippet shows how to create a textbox, set its position and size, and fill it with an image using Spire.Doc for JavaScript.
```javascript
const document = wasmModule.Document.Create();
let section = document.AddSection();
let paragraph = section.AddParagraph();
let tb = paragraph.AppendTextBox(220, 220);
tb.Format.HorizontalOrigin = wasmModule.HorizontalOrigin.Page;
tb.Format.HorizontalPosition = 50;
tb.Format.VerticalOrigin = wasmModule.VerticalOrigin.Page;
tb.Format.VerticalPosition = 50;
tb.Format.FillEfects.Type = wasmModule.BackgroundType.Picture;
tb.Format.FillEfects.SetPicture(inputFileName);
```
--------------------------------
### Extract Text from Word Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates how to extract all text content from a Word document using Spire.Doc for JavaScript. It loads the document and then retrieves the plain text.
```javascript
//Load the document from disk.
let document = wasmModule.Document.Create();
document.LoadFromFile(inputFileName);
//get text from document
let text = document.GetText();
```
--------------------------------
### Remove Specific Paragraph from Word Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates how to remove a specific paragraph, in this case, the first paragraph from the first section of a Word document, using Spire.Doc for JavaScript.
```javascript
let document = wasmModule.Document.Create();
document.LoadFromFile(inputFileName);
document.Sections.get(0).Paragraphs.RemoveAt(0);
```
--------------------------------
### Convert Word to PCL using Spire.Doc for JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates converting a Word document to PCL (Printer Command Language) format using Spire.Doc for JavaScript. The process involves creating a document, loading the Word file, specifying the output PCL file name, saving the document, and disposing of resources.
```javascript
const doc = wasmModule.Document.Create();
doc.LoadFromFile(inputFileName);
const outputFileName = "ToPCL-result.pcl";
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.PCL});
doc.Dispose();
```
--------------------------------
### Get Field Text from Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Retrieves the text content of all fields within a loaded Word document. It iterates through each field, extracts its `FieldText` property, and collects it into a string for display or further processing.
```javascript
const document = wasmModule.Document.Create();
document.LoadFromFile(inputFileName);
let sb = [];
let fields = document.Fields;
for (let i = 0; i < fields.Count; i++) {
let field = fields.get_Item(i);
let fieldText = field.FieldText;
sb.push("The field text is \"" + fieldText + ".\r\n");
}
let content = sb.join("\n");
```
--------------------------------
### Modify Hyperlink Text in Word Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates how to load a Word document, find all hyperlinks within it, and then modify the display text of a specific hyperlink using Spire.Doc for JavaScript.
```javascript
//Load Document
let doc = wasmModule.Document.Create();
doc.LoadFromFile(inputFileName);
//Find all hyperlinks in the Word document
let hyperlinks = [];
for (let i = 0; i < doc.Sections.Count; i++) {
let section = doc.Sections.get(i);
for (let j = 0; j < section.Body.ChildObjects.Count; j++) {
let sec = section.Body.ChildObjects.get(j);
if (sec.DocumentObjectType == wasmModule.DocumentObjectType.Paragraph) {
for (let k = 0; k < sec.ChildObjects.Count; k++) {
let para = sec.ChildObjects.get(k);
if (para.DocumentObjectType == wasmModule.DocumentObjectType.Field) {
let field = para;
if (field.Type == wasmModule.FieldType.FieldHyperlink) {
hyperlinks.push(field);
}
}
}
}
}
}
//Reset the property of hyperlinks[0].FieldText by using the index of the hyperlink
hyperlinks[0].FieldText = "Spire.Doc component";
```
--------------------------------
### Convert Image to PDF using Spire.Doc for JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example shows how to convert an image file into a PDF document using Spire.Doc for JavaScript. It creates a new document, adds a section and a paragraph, appends the image to the paragraph, saves the document as a PDF, and cleans up resources.
```javascript
const doc = wasmModule.Document.Create();
let section = doc.AddSection();
let paragraph = section.AddParagraph();
paragraph.AppendPicture({imgFile: inputFileName});
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.PDF});
doc.Dispose();
```
--------------------------------
### Create Table from HTML in Word Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Shows how to create a Word document and insert a table by parsing an HTML string. The HTML string defines the table structure, rows, and cells, which are then rendered within the Word document.
```javascript
let HTML = "" +
"" +
"| Row 1, Cell 1 | " +
"Row 1, Cell 2 | " +
"
" +
"" +
"| Row 2, Cell 2 | " +
"Row 2, Cell 2 | " +
"
" +
"
";
let document = wasmModule.Document.Create();
let section = document.AddSection();
section.AddParagraph().AppendHTML(HTML);
document.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2013});
```
--------------------------------
### Remove Field from Word Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Demonstrates how to remove a specific field from a Word document using Spire.Doc for JavaScript. This involves loading a document, getting a field, finding its owner paragraph and index, and then removing it.
```javascript
// Create a new document
const document = wasmModule.Document.Create();
// Load a document from the virtual file system
document.LoadFromFile(inputFileName);
// Get the first field
let field = document.Fields.get_Item(0);
// Get the paragraph of the field
let par = field.OwnerParagraph;
// Get the index of the field
let index = par.ChildObjects.IndexOf(field);
// Remove field via index
par.ChildObjects.RemoveAt(index);
```
--------------------------------
### Insert Merge Field
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Provides an example of inserting a MERGEFIELD into a Word document using Spire.Doc for JavaScript. It covers document creation, adding a section and paragraph, and appending the merge field with a specified name.
```javascript
// Create a new document
const document = wasmModule.Document.Create();
// Create a new section
let section = document.AddSection();
// Add a new paragraph
let par = section.AddParagraph();
// Add merge field in the paragraph
par.AppendField("MyFieldName", wasmModule.FieldType.FieldMergeField);
```
--------------------------------
### Convert TXT to Word using Spire.Doc for JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This snippet shows how to convert a text file (TXT) to a Word document (DOCX) using Spire.Doc for JavaScript. It includes defining input/output file names, creating a document, loading the TXT file, and saving it in the Docx2013 format.
```javascript
// Define the input file name
let inputFileName = "TxtToWord.txt";
// Create a new document
const doc = wasmModule.Document.Create();
// Load a document from the virtual file system
doc.LoadFromFile(inputFileName);
// Define the output file name
const outputFileName = "TxtToWord-result.docx";
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2013});
// Clean up resources
doc.Dispose();
```
--------------------------------
### Convert Word to Word XML using Spire.Doc for JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates converting a Word document to Word XML format using Spire.Doc for JavaScript. It covers creating a document, loading the input file, and saving it as either WordML (for Word 2003) or Word XML (for Word 2007).
```javascript
// Create a new document
const doc = wasmModule.Document.Create();
// Load a document from the virtual file system
doc.LoadFromFile(inputFileName);
// Define the output file name
const outputFileName = "WordToWordXML-result.xml";
// For word 2003:
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.WordML});
// //For word 2007:
// doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.WordXml});
// Clean up resources
doc.Dispose();
```
--------------------------------
### Convert Word to EPUB
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Demonstrates the conversion of a Word document to EPUB format using Spire.Doc for JavaScript. It includes loading the Word document and saving it in EPUB format.
```javascript
const document = wasmModule.Document.Create();
document.LoadFromFile(inputFileName);
const outputFileName = "ToEpub-result.epub";
document.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.EPub});
document.Dispose();
```
--------------------------------
### Spire.Doc for JavaScript Overview
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/README.md
Spire.Doc for JavaScript is a powerful API for creating, reading, writing, converting, and comparing Word documents. It integrates Word document creation into JavaScript applications without needing Microsoft Word installed.
```JavaScript
/**
* Spire.Doc for JavaScript - A powerful Word processing library.
* Enables creation, reading, editing, and conversion of Word documents in JavaScript.
* Supports formats from Word 97-2003 to 2019.
* No Microsoft Office installation required.
*/
// Example usage (conceptual):
// const document = new Document();
// document.loadFromFile("input.docx");
// document.saveToFile("output.pdf", FileFormat.PDF);
```
--------------------------------
### Configure Repeating Table Header Rows
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Shows how to create a table, add rows, and designate them as header rows that will repeat on each page. It also covers setting background color, cell width, and text alignment for header rows.
```javascript
let table = section.AddTable({showBorder: true});
let row = table.AddRow();
row.IsHeader = true;
row.RowFormat.BackColor = wasmModule.Color.get_LightGray();
let cell = row.AddCell();
cell.SetCellWidth(100, wasmModule.CellWidthType.Percentage);
let parapraph = cell.AddParagraph();
parapraph.AppendText("Row Header 1");
parapraph.Format.HorizontalAlignment = wasmModule.HorizontalAlignment.Center;
row = table.AddRow({isCopyFormat: false, columnsNum: 1});
row.IsHeader = true;
row.RowFormat.BackColor = wasmModule.Color.get_Ivory();
row.Height = 30;
cell = row.Cells.get(0);
cell.SetCellWidth(100, wasmModule.CellWidthType.Percentage);
cell.CellFormat.VerticalAlignment = wasmModule.VerticalAlignment.Middle;
parapraph = cell.AddParagraph();
parapraph.AppendText("Row Header 2");
parapraph.Format.HorizontalAlignment = wasmModule.HorizontalAlignment.Center;
```
--------------------------------
### Add Section from Another Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Illustrates how to add a section from one Word document (source) into another Word document (target). It loads both documents, gets a specific section from the source, clones it, and adds it to the target.
```javascript
const TarDoc = wasmModule.Document.Create();
TarDoc.LoadFromFile(inputFileName1);
let SouDoc = wasmModule.Document.Create();
SouDoc.LoadFromFile(inputFileName2);
let Ssection = SouDoc.Sections.get(1);
TarDoc.Sections.Add(Ssection.Clone());
```
--------------------------------
### Convert Word Document to Image using Spire.Doc for JavaScript
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates converting a Word document into an image format using Spire.Doc for JavaScript. It initializes a document, loads the Word file, and uses the SaveImageToStreams method to convert the first page to a bitmap image. Resources are then disposed.
```javascript
const doc = wasmModule.Document.Create();
doc.LoadFromFile(inputFileName);
let img = doc.SaveImageToStreams({pageIndex: 0, imagetype: wasmModule.ImageType.Bitmap});
doc.Dispose();
```
--------------------------------
### Replace Bookmark Content with Table
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
Demonstrates replacing bookmark content with a table populated with data. This involves creating a table, defining data, filling the table cells, locating the bookmark, creating a TextBodyPart, adding the table to it, and then using ReplaceBookmarkContent to insert the table.
```javascript
let table = wasmModule.Table.Create(doc, true);
table.ResetCells(4,5);
let dt = [
["Name", "Capital", "Continent", "Area", "Population"],
["Argentina", "Buenos Aires", "South America", "2777815", "32300003"],
["Bolivia", "La Paz", "South America", "1098575", "7300000"],
["Brazil", "Brasilia", "South America", "8511196", "150400000"]
];
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 5; j++) {
table.Rows.get(i).Cells.get(j).AddParagraph().AppendText(dt[i][j]);
}
}
let navigator = wasmModule.BookmarksNavigator.Create(doc);
navigator.MoveToBookmark("Test");
let part = wasmModule.TextBodyPart.Create(doc);
part.BodyItems.Add(table);
navigator.ReplaceBookmarkContent({bodyPart : part});
```
--------------------------------
### Lock Header in Word Document
Source: https://github.com/eiceblue/spire.doc-for-javascript/blob/main/JavaScript Examples/doc_vue.md
This example demonstrates how to lock the header in a Word document using Spire.Doc for JavaScript. It involves protecting the document with a specific protection type and then unprotecting the section's form fields.
```javascript
//Load the document
let doc = wasmModule.Document.Create();
doc.LoadFromFile(inputFileName);
//Get the first section
let section = doc.Sections.get(0);
//Protect the document and set the ProtectionType as AllowOnlyFormFields
doc.Protect({type: wasmModule.ProtectionType.AllowOnlyFormFields, password: "123"});
//Set the ProtectForm as false to unprotect the section
section.ProtectForm = false;
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2013});
```