Samples
The sample programs of the package.
See the folder samples/UsingDOCXLib. Each sample writes a .docx file to the current folder. Each sample name links to its source code in this documentation (below the table) and to the file on GitHub.
Source code#
helloworld.ring#
samples/UsingDOCXLib/helloworld.ring
/*
DOCXLib - Demo (Hello World)
*/
load "docxlib.ring"
? "Generate File: helloworld.docx"
new WordWriter() {
setTitle("My First Document")
setAuthor("Your Name")
setPageSize("a4")
addHeading("Hello, DOCXLib!", 1)
addParagraph("This document was created entirely from Ring code.", [:color = "0000FF"])
addBulletList(["Feature A", "Feature B", "Feature C"])
save("helloworld.docx")
}part1_intro.ring#
samples/UsingDOCXLib/part1_intro.ring
/*
DOCXLib - Demo (Intro)
*/
load "docxlib.ring"
? "=============================================="
? " DOCXLib Demo - Word Creation in Ring"
? "=============================================="
? ""
# Demo 1: Simple Document
? "Demo 1: Creating a simple document..."
doc = new WordWriter()
doc.setTitle("Simple Document")
doc.setAuthor("Ring Programmer")
doc.addHeading("Welcome to DOCXLib", 1)
doc.addParagraph("This is a simple paragraph created with DOCXLib.", NULL)
doc.addParagraph("You can easily create Word documents using Ring!", NULL)
if doc.save("demo1_simple.docx")
? " Created: demo1_simple.docx"
else
? " FAILED: demo1_simple.docx"
ok
# Demo 2: Text Formatting
? "Demo 2: Creating document with text formatting..."
doc = new WordWriter()
doc.setTitle("Formatted Document")
doc.addHeading("Text Formatting Examples", 1)
doc.bold("This text is bold.")
doc.italic("This text is italic.")
doc.underline("This text is underlined.")
doc.addParagraph("This is red text.", [:color = "red"])
doc.addParagraph("This is blue text.", [:color = "blue"])
doc.addParagraph("This is green text.", [:color = "00FF00"])
doc.addParagraph("Custom font and size", [:font = "Arial", :size = 16, :bold = true])
doc.addParagraph("Another style", [:font = "Times New Roman", :size = 14, :italic = true, :color = "purple"])
if doc.save("demo2_formatting.docx")
? " Created: demo2_formatting.docx"
else
? " FAILED: demo2_formatting.docx"
ok
# Demo 3: Headings and Structure
? "Demo 3: Creating document with headings..."
doc = new WordWriter()
doc.setTitle("Structured Document")
doc.addHeading("Main Title", 1)
doc.addParagraph("This is the introduction paragraph.", NULL)
doc.addHeading("Chapter 1: Getting Started", 2)
doc.addParagraph("Content for chapter 1 goes here.", NULL)
doc.addHeading("Section 1.1", 3)
doc.addParagraph("More detailed content in subsection.", NULL)
doc.addHeading("Section 1.2", 3)
doc.addParagraph("Another subsection with content.", NULL)
doc.addHeading("Chapter 2: Advanced Topics", 2)
doc.addParagraph("Content for chapter 2.", NULL)
if doc.save("demo3_headings.docx")
? " Created: demo3_headings.docx"
else
? " FAILED: demo3_headings.docx"
ok
# Demo 4: Lists
? "Demo 4: Creating document with lists..."
doc = new WordWriter()
doc.setTitle("Document with Lists")
doc.addHeading("Lists Demo", 1)
doc.addParagraph("Here is a bullet list:", NULL)
doc.addBulletList([
"First item",
"Second item",
"Third item",
"Fourth item"
])
doc.addParagraph("Here is a numbered list:", NULL)
doc.addNumberedList([
"Step one",
"Step two",
"Step three",
"Step four"
])
if doc.save("demo4_lists.docx")
? " Created: demo4_lists.docx"
else
? " FAILED: demo4_lists.docx"
ok
# Demo 5: Tables
? "Demo 5: Creating document with tables..."
doc = new WordWriter()
doc.setTitle("Document with Tables")
doc.addHeading("Tables Demo", 1)
doc.addParagraph("Here is a simple table:", NULL)
tableData = [
["Name", "Age", "City"],
["Ahmed", "25", "Cairo"],
["Sara", "30", "Riyadh"],
["Omar", "28", "Dubai"],
["Fatima", "22", "Amman"]
]
doc.addSimpleTable(tableData)
doc.addParagraph("Another table without header formatting:", NULL)
doc.addTable([
["Product", "Price", "Quantity"],
["Laptop", "$999", "5"],
["Mouse", "$25", "20"],
["Keyboard", "$75", "15"]
], [:borderStyle = "single"])
if doc.save("demo5_tables.docx")
? " Created: demo5_tables.docx"
else
? " FAILED: demo5_tables.docx"
ok
# Demo 6: Rich Text (Multiple formats in one paragraph)
? "Demo 6: Creating document with rich text..."
doc = new WordWriter()
doc.setTitle("Rich Text Document")
doc.addHeading("Rich Text Examples", 1)
doc.addRichParagraph([
["This is ", []],
["bold", [:bold = true]],
[" and this is ", []],
["italic", [:italic = true]],
[" and this is ", []],
["red", [:color = "red"]],
[".", []]
], NULL)
doc.addRichParagraph([
["Welcome to ", [:size = 14]],
["DOCXLib", [:bold = true, :color = "blue", :size = 16]],
[" - the ", [:size = 14]],
["best", [:italic = true, :underline = true]],
[" Word library for Ring!", [:size = 14]]
], NULL)
if doc.save("demo6_richtext.docx")
? " Created: demo6_richtext.docx"
else
? " FAILED: demo6_richtext.docx"
ok
# Demo 7: Alignment
? "Demo 7: Creating document with alignments..."
doc = new WordWriter()
doc.setTitle("Alignment Demo")
doc.addHeading("Text Alignment Examples", 1)
doc.addParagraph("This text is left aligned (default).", NULL)
doc.centered("This text is centered.")
doc.rightAligned("This text is right aligned.")
doc.justified("This text is justified. It will stretch to fill the entire width of the page when there is enough text. Add more content here to see the justification effect properly.")
if doc.save("demo7_alignment.docx")
? " Created: demo7_alignment.docx"
else
? " FAILED: demo7_alignment.docx"
ok
# Demo 8: Page breaks and special elements
? "Demo 8: Creating document with page breaks..."
doc = new WordWriter()
doc.setTitle("Multi-page Document")
doc.addHeading("Page 1", 1)
doc.addParagraph("This is content on the first page.", NULL)
doc.addHorizontalLine()
doc.addParagraph("More content after a horizontal line.", NULL)
doc.addPageBreak()
doc.addHeading("Page 2", 1)
doc.addParagraph("This is content on the second page.", NULL)
doc.addPageBreak()
doc.addHeading("Page 3", 1)
doc.addParagraph("This is content on the third page.", NULL)
if doc.save("demo8_multipage.docx")
? " Created: demo8_multipage.docx"
else
? " FAILED: demo8_multipage.docx"
ok
# Demo 9: Hyperlinks
? "Demo 9: Creating document with hyperlinks..."
doc = new WordWriter()
doc.setTitle("Document with Links")
doc.addHeading("Hyperlinks Demo", 1)
doc.addParagraph("Click the links below to visit websites:", NULL)
doc.addHyperlink("Visit Ring Language Website", "https://ring-lang.github.io/")
doc.addHyperlink("Visit Google", "https://www.google.com/")
doc.addHyperlink("Visit GitHub", "https://github.com/")
if doc.save("demo9_hyperlinks.docx")
? " Created: demo9_hyperlinks.docx"
else
? " FAILED: demo9_hyperlinks.docx"
ok
# Demo 10: Complete professional document
? "Demo 10: Creating complete professional document..."
doc = new WordWriter()
doc.setTitle("Project Report")
doc.setAuthor("Development Team")
doc.setDefaultFont("Calibri", 11)
doc.addHeading("Project Status Report", 1)
doc.addParagraph("Date: January 2026", NULL)
doc.addParagraph("Prepared by: Development Team", NULL)
doc.addHorizontalLine()
doc.addHeading("Executive Summary", 2)
doc.addParagraph("This report provides an overview of the current project status, including completed milestones, ongoing tasks, and upcoming deliverables.", NULL)
doc.addHeading("Project Milestones", 2)
doc.addSimpleTable([
["Milestone", "Status", "Due Date"],
["Requirements Analysis", "Complete", "Dec 15"],
["Design Phase", "Complete", "Dec 30"],
["Development", "In Progress", "Jan 31"],
["Testing", "Pending", "Feb 15"],
["Deployment", "Pending", "Feb 28"]
])
doc.addHeading("Key Achievements", 2)
doc.addBulletList([
"Completed system architecture design",
"Implemented core functionality",
"Established CI/CD pipeline",
"Conducted code reviews"
])
doc.addHeading("Next Steps", 2)
doc.addNumberedList([
"Complete remaining development tasks",
"Begin integration testing",
"Prepare user documentation",
"Schedule training sessions"
])
doc.addHeading("Risks and Mitigation", 2)
doc.addRichParagraph([
["Risk: ", [:bold = true]],
["Resource availability may impact timeline.", []],
[" Mitigation: ", [:bold = true]],
["Cross-training team members.", []]
], NULL)
doc.addPageBreak()
doc.addHeading("Appendix", 2)
doc.addParagraph("For more information, contact the project manager.", [:bold = true])
doc.addHyperlink("Project Documentation", "https://docs.example.com/project")
if doc.save("demo10_professional.docx")
? " Created: demo10_professional.docx"
else
? " FAILED: demo10_professional.docx"
ok
# Demo 11: Quick document creation
? "Demo 11: Using quick document function..."
quickWord("demo11_quick.docx", "This is a quick document created with a single function call!")
? " Created: demo11_quick.docx"
quickWord("demo12_quick_list.docx", [
"Paragraph 1: Introduction",
"Paragraph 2: Main content goes here.",
"Paragraph 3: Conclusion and summary."
])
? " Created: demo12_quick_list.docx"
# Demo 13: Images
? "Demo 13: Creating document with images..."
doc = new WordWriter()
doc.setTitle("Document with Images")
doc.addHeading("Images Demo", 1)
doc.addParagraph("This document demonstrates how to add images.", NULL)
# Check for image files and add them
doc.addHeading("Test Images", 2)
if fexists("images/test1.png")
doc.addParagraph("Here is images/test1.png:", NULL)
doc.addImage("images/test1.png", 12, 8) # 12cm x 8cm
else
doc.addParagraph("(images/test1.png not found - skipping)", [:color = "gray"])
ok
if fexists("images/test2.jpg")
doc.addParagraph("Here is images/test2.jpg (centered):", NULL)
doc.addImageCentered("images/test2.jpg", 10, 7) # 10cm x 7cm, centered
else
doc.addParagraph("(images/test2.jpg not found - skipping)", [:color = "gray"])
ok
if fexists("images/test3.bmp")
doc.addParagraph("Here is images/test3.bmp:", NULL)
doc.addImage("images/test3.bmp", 8, 6) # 8cm x 6cm
else
doc.addParagraph("(images/test3.bmp not found - skipping)", [:color = "gray"])
ok
doc.addParagraph("End of images demo.", NULL)
if doc.save("demo13_images.docx")
? " Created: demo13_images.docx"
else
? " FAILED: demo13_images.docx"
ok
# Demo 14: Header and Footer
? "Demo 14: Creating document with header and footer..."
doc = new WordWriter()
doc.setTitle("Document with Header/Footer")
doc.setHeader("Company Name - Confidential Document")
doc.setFooter("© 2026 Company Name")
doc.addHeading("Header and Footer Demo", 1)
doc.addParagraph("This document has a header and footer on every page.", NULL)
doc.addParagraph("The header shows 'Company Name - Confidential Document'.", NULL)
doc.addParagraph("The footer shows '© 2026 Company Name'.", NULL)
doc.addPageBreak()
doc.addHeading("Page 2", 1)
doc.addParagraph("Notice how the header and footer appear on this page too.", NULL)
if doc.save("demo14_header_footer.docx")
? " Created: demo14_header_footer.docx"
else
? " FAILED: demo14_header_footer.docx"
ok
# Demo 15: Page Numbers
? "Demo 15: Creating document with page numbers..."
doc = new WordWriter()
doc.setTitle("Document with Page Numbers")
doc.setHeader("Project Documentation")
doc.showPageNumbers("center")
doc.addHeading("Page Numbers Demo", 1)
doc.addParagraph("This document has automatic page numbers in the footer.", NULL)
doc.addParagraph("Page numbers show 'Page X of Y' format.", NULL)
doc.addPageBreak()
doc.addHeading("Chapter 1: Introduction", 1)
doc.addParagraph("This is the second page of the document.", NULL)
doc.addParagraph("Check the footer to see the page number.", NULL)
doc.addPageBreak()
doc.addHeading("Chapter 2: Details", 1)
doc.addParagraph("This is the third page.", NULL)
if doc.save("demo15_page_numbers.docx")
? " Created: demo15_page_numbers.docx"
else
? " FAILED: demo15_page_numbers.docx"
ok
# Demo 16: Styled Tables with Colors
? "Demo 16: Creating document with styled tables..."
doc = new WordWriter()
doc.setTitle("Styled Tables Demo")
doc.addHeading("Styled Tables", 1)
doc.addParagraph("Table with blue header and zebra striping:", NULL)
doc.addStyledTable([
["Product", "Category", "Price", "Stock"],
["Laptop", "Electronics", "$999", "50"],
["Mouse", "Accessories", "$25", "200"],
["Keyboard", "Accessories", "$75", "150"],
["Monitor", "Electronics", "$350", "75"],
["Headphones", "Accessories", "$120", "100"]
], NULL, NULL)
doc.addParagraph("Table with custom colors (green header, light green rows):", NULL)
doc.addStyledTable([
["Name", "Department", "Role"],
["Ahmed", "Engineering", "Developer"],
["Sara", "Marketing", "Manager"],
["Omar", "Sales", "Representative"],
["Fatima", "HR", "Coordinator"]
], "2E7D32", "E8F5E9")
if doc.save("demo16_styled_tables.docx")
? " Created: demo16_styled_tables.docx"
else
? " FAILED: demo16_styled_tables.docx"
ok
# Demo 17: Table Border Customization
? "Demo 17: Creating document with custom table borders..."
doc = new WordWriter()
doc.setTitle("Table Borders Demo")
doc.addHeading("Table Border Styles", 1)
doc.addParagraph("Single border (default):", NULL)
doc.addTable([
["A1", "B1", "C1"],
["A2", "B2", "C2"]
], [:borderStyle = "single", :headerRow = true])
doc.addParagraph("Double border:", NULL)
doc.addTable([
["A1", "B1", "C1"],
["A2", "B2", "C2"]
], [:borderStyle = "double", :headerRow = true])
doc.addParagraph("Dashed border:", NULL)
doc.addTable([
["A1", "B1", "C1"],
["A2", "B2", "C2"]
], [:borderStyle = "dashed", :headerRow = true])
doc.addParagraph("Dotted border:", NULL)
doc.addTable([
["A1", "B1", "C1"],
["A2", "B2", "C2"]
], [:borderStyle = "dotted", :headerRow = true])
doc.addParagraph("Thick red border:", NULL)
doc.addTable([
["A1", "B1", "C1"],
["A2", "B2", "C2"]
], [:borderStyle = "single", :borderSize = 12, :borderColor = "FF0000", :headerRow = true])
doc.addParagraph("No border:", NULL)
doc.addTable([
["A1", "B1", "C1"],
["A2", "B2", "C2"]
], [:borderStyle = "none"])
if doc.save("demo17_table_borders.docx")
? " Created: demo17_table_borders.docx"
else
? " FAILED: demo17_table_borders.docx"
ok
# Demo 18: Complete Professional Report
? "Demo 18: Creating complete professional report..."
doc = new WordWriter()
doc.setTitle("Quarterly Sales Report")
doc.setAuthor("Sales Department")
doc.setDefaultFont("Calibri", 11)
doc.setHeader("Q4 2025 Sales Report - Confidential")
doc.showPageNumbers("right")
doc.addHeading("Q4 2025 Sales Report", 1)
doc.addParagraph("Prepared by: Sales Department", [:italic = true])
doc.addParagraph("Date: January 15, 2026", [:italic = true])
doc.addHorizontalLine()
doc.addHeading("Executive Summary", 2)
doc.addParagraph("This report summarizes the sales performance for the fourth quarter of 2025. Overall, we achieved a 15% increase in revenue compared to Q3.", NULL)
doc.addHeading("Sales by Region", 2)
doc.addStyledTable([
["Region", "Q3 Sales", "Q4 Sales", "Growth"],
["North America", "$2.5M", "$2.9M", "+16%"],
["Europe", "$1.8M", "$2.1M", "+17%"],
["Asia Pacific", "$1.2M", "$1.4M", "+17%"],
["Latin America", "$0.5M", "$0.55M", "+10%"]
], "1565C0", "E3F2FD")
doc.addHeading("Top Products", 2)
doc.addStyledTable([
["Product", "Units Sold", "Revenue"],
["Enterprise Suite", "450", "$1.35M"],
["Professional Edition", "1,200", "$960K"],
["Basic Package", "3,500", "$525K"],
["Add-on Services", "800", "$320K"]
], "2E7D32", "E8F5E9")
doc.addPageBreak()
doc.addHeading("Key Achievements", 2)
doc.addBulletList([
"Exceeded quarterly target by 8%",
"Acquired 45 new enterprise clients",
"Expanded into 3 new markets",
"Reduced customer churn by 12%"
])
doc.addHeading("Challenges", 2)
doc.addBulletList([
"Supply chain delays affected product availability",
"Currency fluctuations impacted European margins",
"Increased competition in Asia Pacific region"
])
doc.addHeading("Q1 2026 Outlook", 2)
doc.addParagraph("Based on current pipeline and market trends, we project continued growth in Q1 2025:", NULL)
doc.addNumberedList([
"Target revenue: $7.5M (+10% vs Q4)",
"Focus markets: North America and Europe",
"New product launch scheduled for February",
"Expanded marketing campaigns in APAC"
])
doc.addHeading("Recommendations", 2)
doc.addRichParagraph([
["Priority 1: ", [:bold = true]],
["Accelerate hiring in sales team to support growth.", []]
], NULL)
doc.addRichParagraph([
["Priority 2: ", [:bold = true]],
["Invest in customer success to reduce churn further.", []]
], NULL)
doc.addRichParagraph([
["Priority 3: ", [:bold = true]],
["Explore partnership opportunities in emerging markets.", []]
], NULL)
if doc.save("demo18_professional_report.docx")
? " Created: demo18_professional_report.docx"
else
? " FAILED: demo18_professional_report.docx"
ok
# Demo 19: Two-Column Layout
? "Demo 19: Creating document with two columns..."
doc = new WordWriter()
doc.setTitle("Two Column Document")
doc.setTwoColumns()
doc.addHeading("Two-Column Layout", 1)
doc.addParagraph("This document uses a two-column layout, which is common in newspapers, magazines, and academic journals. The text will flow from the bottom of the first column to the top of the second column.", NULL)
doc.addParagraph("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.", NULL)
doc.addParagraph("Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident.", NULL)
doc.addColumnBreak()
doc.addHeading("Second Column", 2)
doc.addParagraph("After a column break, content continues in the next column. This is useful for controlling where content appears.", NULL)
doc.addParagraph("Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.", NULL)
if doc.save("demo19_two_columns.docx")
? " Created: demo19_two_columns.docx"
else
? " FAILED: demo19_two_columns.docx"
ok
# Demo 20: Different Page Sizes
? "Demo 20: Creating documents with different page sizes..."
# A4 Document
doc = new WordWriter()
doc.setTitle("A4 Document")
doc.setPageSize("a4")
doc.addHeading("A4 Page Size", 1)
doc.addParagraph("This document uses A4 paper size (210 x 297 mm), which is the international standard for documents.", NULL)
doc.addParagraph("A4 is commonly used in Europe, Asia, and most countries outside North America.", NULL)
if doc.save("demo20a_a4_size.docx")
? " Created: demo20a_a4_size.docx"
else
? " FAILED: demo20a_a4_size.docx"
ok
# A5 Document (smaller, like a booklet)
doc = new WordWriter()
doc.setTitle("A5 Booklet")
doc.setPageSize("a5")
doc.addHeading("A5 Booklet", 1)
doc.addParagraph("This document uses A5 paper size (148 x 210 mm), which is half the size of A4.", NULL)
doc.addParagraph("A5 is perfect for booklets, flyers, and pocket-sized documents.", NULL)
if doc.save("demo20b_a5_size.docx")
? " Created: demo20b_a5_size.docx"
else
? " FAILED: demo20b_a5_size.docx"
ok
# Landscape Document
doc = new WordWriter()
doc.setTitle("Landscape Document")
doc.setPageSize("letter")
doc.setOrientation("landscape")
doc.addHeading("Landscape Orientation", 1)
doc.addParagraph("This document uses landscape orientation, which is wider than it is tall.", NULL)
doc.addParagraph("Landscape is ideal for wide tables, charts, presentations, and certificates.", NULL)
doc.addSimpleTable([
["January", "February", "March", "April", "May", "June"],
["$10,000", "$12,000", "$11,500", "$13,000", "$14,500", "$15,000"]
])
if doc.save("demo20c_landscape.docx")
? " Created: demo20c_landscape.docx"
else
? " FAILED: demo20c_landscape.docx"
ok
# Demo 21: Block Quotes and Captions
? "Demo 21: Creating document with block quotes and captions..."
doc = new WordWriter()
doc.setTitle("Quotes and Captions")
doc.addHeading("Using Block Quotes", 1)
doc.addParagraph("Block quotes are used to highlight important quotations or excerpts:", NULL)
doc.addBlockQuote("The only way to do great work is to love what you do. If you haven't found it yet, keep looking. Don't settle. - Steve Jobs")
doc.addParagraph("Block quotes are indented and styled differently to stand out from regular text.", NULL)
doc.addBlockQuote("In the middle of difficulty lies opportunity. - Albert Einstein")
doc.addHeading("Figure Captions", 2)
doc.addParagraph("Captions are used to describe figures and tables:", NULL)
doc.addHorizontalLine()
doc.addCaption("Figure 1: Sample chart showing quarterly revenue growth")
doc.addParagraph("Tables can also have captions:", NULL)
doc.addSimpleTable([
["Quarter", "Revenue"],
["Q1", "$1.2M"],
["Q2", "$1.5M"]
])
doc.addCaption("Table 1: Quarterly revenue summary")
if doc.save("demo21_quotes_captions.docx")
? " Created: demo21_quotes_captions.docx"
else
? " FAILED: demo21_quotes_captions.docx"
ok
# Demo 22: Research Paper Format
? "Demo 22: Creating research paper format..."
doc = new WordWriter()
doc.setTitle("Research Paper")
doc.setAuthor("Dr. Ahmed Hassan, Prof. Sara Ali")
doc.setPageSize("a4")
doc.setTwoColumns()
doc.setNarrowMargins()
doc.showPageNumbers("center")
# Title (single column would be better but we simulate with centered text)
doc.addHeading("A Novel Approach to Natural Language Processing Using Ring Programming Language", 1)
doc.addParagraph("Dr. Ahmed Hassan¹, Prof. Sara Ali²", [:align = "center"])
doc.addParagraph("¹Department of Computer Science, King Saud University", [:align = "center", :size = 9])
doc.addParagraph("²Faculty of Engineering, Cairo University", [:align = "center", :size = 9])
doc.addHorizontalLine()
doc.addAbstract("This paper presents a novel approach to natural language processing using the Ring programming language. We demonstrate how Ring's unique features enable efficient text processing and analysis. Our experiments show significant improvements in processing speed compared to traditional approaches. The proposed method achieves 95% accuracy on standard benchmarks while reducing computational overhead by 40%.")
doc.addKeywords(["Natural Language Processing", "Ring Programming", "Text Analysis", "Machine Learning"])
doc.addHeading("1. Introduction", 2)
doc.addParagraph("Natural language processing (NLP) has become increasingly important in modern computing applications. From chatbots to sentiment analysis, NLP techniques are used across various domains.", NULL)
doc.addParagraph("In this paper, we explore the use of Ring programming language for NLP tasks. Ring offers several advantages including simplicity, flexibility, and good performance characteristics.", NULL)
doc.addColumnBreak()
doc.addHeading("2. Related Work", 2)
doc.addParagraph("Previous research has explored various programming languages for NLP applications. Python has been the dominant choice due to its extensive library ecosystem.", NULL)
doc.addBlockQuote("The choice of programming language significantly impacts both development time and runtime performance of NLP applications. - Smith et al., 2026")
doc.addHeading("3. Methodology", 2)
doc.addParagraph("Our approach consists of three main components: tokenization, feature extraction, and classification. Each component is implemented using Ring's object-oriented features.", NULL)
doc.addHeading("4. Results", 2)
doc.addStyledTable([
["Method", "Accuracy", "Speed"],
["Baseline", "87%", "1.0x"],
["Python NLP", "92%", "0.8x"],
["Our Method", "95%", "1.4x"]
], "1565C0", "E3F2FD")
doc.addCaption("Table 1: Comparison of different NLP approaches")
doc.addHeading("5. Conclusion", 2)
doc.addParagraph("We have demonstrated that Ring programming language is a viable option for NLP applications. Our method achieves state-of-the-art results while maintaining excellent performance.", NULL)
doc.addHeading("References", 2)
doc.addParagraph("[1] Smith, J. et al. (2023). Programming Languages for NLP. Journal of Computing.", [:size = 9])
doc.addParagraph("[2] Hassan, A. (2024). Ring Language Applications. Tech Report.", [:size = 9])
if doc.save("demo22_research_paper.docx")
? " Created: demo22_research_paper.docx"
else
? " FAILED: demo22_research_paper.docx"
ok
# Demo 23: Custom Page Settings
? "Demo 23: Creating document with custom page settings..."
doc = new WordWriter()
doc.setTitle("Custom Page Settings")
# Custom page size (15cm x 20cm)
doc.setCustomPageSize(15, 20)
doc.setMargins(1.5, 1.5, 2, 2)
doc.addHeading("Custom Page Size", 1)
doc.addParagraph("This document uses a custom page size of 15cm x 20cm with custom margins.", NULL)
doc.addParagraph("Custom page sizes are useful for special print jobs, booklets, or unique document requirements.", NULL)
if doc.save("demo23_custom_page.docx")
? " Created: demo23_custom_page.docx"
else
? " FAILED: demo23_custom_page.docx"
ok
# Demo 24: Three-Column Newsletter
? "Demo 24: Creating three-column newsletter..."
doc = new WordWriter()
doc.setTitle("Company Newsletter")
doc.setPageSize("letter")
doc.setThreeColumns()
doc.setNarrowMargins()
doc.setHeader("Monthly Newsletter - January 2026")
doc.addHeading("Company News", 1)
doc.addHeading("New Product Launch", 3)
doc.addParagraph("We are excited to announce our latest product release. After months of development, the new software is ready for customers.", NULL)
doc.addHeading("Team Updates", 3)
doc.addParagraph("Welcome to our new team members who joined this month. We're growing fast!", NULL)
doc.addColumnBreak()
doc.addHeading("Events", 2)
doc.addHeading("Annual Conference", 3)
doc.addParagraph("Don't miss our annual conference on February 15th. Register now to secure your spot.", NULL)
doc.addHeading("Training Sessions", 3)
doc.addParagraph("New training sessions are available. Check the intranet for the schedule.", NULL)
doc.addColumnBreak()
doc.addHeading("Tips & Tricks", 2)
doc.addHeading("Productivity Tip", 3)
doc.addParagraph("Use keyboard shortcuts to save time. Ctrl+S to save, Ctrl+C to copy.", NULL)
doc.addHeading("Health Corner", 3)
doc.addParagraph("Remember to take regular breaks. Stand up and stretch every hour.", NULL)
if doc.save("demo24_newsletter.docx")
? " Created: demo24_newsletter.docx"
else
? " FAILED: demo24_newsletter.docx"
ok
# Demo 25: Table of Contents
? "Demo 25: Creating document with table of contents..."
doc = new WordWriter()
doc.setTitle("Document with TOC")
doc.setHeader("User Manual")
doc.showPageNumbers("right")
doc.addHeading("User Manual", 1)
doc.addTableOfContents("Contents")
doc.addPageBreak()
doc.addHeading("Chapter 1: Getting Started", 1)
doc.addParagraph("This chapter covers the basics of getting started with the software.", NULL)
doc.addHeading("Installation", 2)
doc.addParagraph("Download the installer from our website and run the setup wizard.", NULL)
doc.addHeading("Configuration", 2)
doc.addParagraph("Configure the software according to your needs using the settings panel.", NULL)
doc.addPageBreak()
doc.addHeading("Chapter 2: Basic Features", 1)
doc.addParagraph("Learn about the basic features of the application.", NULL)
doc.addHeading("Creating Documents", 2)
doc.addParagraph("Click File > New to create a new document.", NULL)
doc.addHeading("Saving Documents", 2)
doc.addParagraph("Click File > Save or press Ctrl+S to save your work.", NULL)
doc.addPageBreak()
doc.addHeading("Chapter 3: Advanced Features", 1)
doc.addParagraph("Explore advanced features for power users.", NULL)
doc.addHeading("Automation", 2)
doc.addParagraph("Use macros to automate repetitive tasks.", NULL)
doc.addHeading("Customization", 2)
doc.addParagraph("Customize the interface to match your workflow.", NULL)
if doc.save("demo25_table_of_contents.docx")
? " Created: demo25_table_of_contents.docx"
else
? " FAILED: demo25_table_of_contents.docx"
ok
? ""
? "=============================================="
? " All demos completed!"
? "=============================================="
? ""
? "Created files:"
? " 1. demo1_simple.docx"
? " 2. demo2_formatting.docx"
? " 3. demo3_headings.docx"
? " 4. demo4_lists.docx"
? " 5. demo5_tables.docx"
? " 6. demo6_richtext.docx"
? " 7. demo7_alignment.docx"
? " 8. demo8_multipage.docx"
? " 9. demo9_hyperlinks.docx"
? " 10. demo10_professional.docx"
? " 11. demo11_quick.docx"
? " 12. demo12_quick_list.docx"
? " 13. demo13_images.docx"
? " 14. demo14_header_footer.docx"
? " 15. demo15_page_numbers.docx"
? " 16. demo16_styled_tables.docx"
? " 17. demo17_table_borders.docx"
? " 18. demo18_professional_report.docx"
? " 19. demo19_two_columns.docx"
? " 20. demo20a_a4_size.docx, demo20b_a5_size.docx, demo20c_landscape.docx"
? " 21. demo21_quotes_captions.docx"
? " 22. demo22_research_paper.docx"
? " 23. demo23_custom_page.docx"
? " 24. demo24_newsletter.docx"
? " 25. demo25_table_of_contents.docx"part2_charts.ring#
samples/UsingDOCXLib/part2_charts.ring
/*
DOCXLib - Demo (Charts)
*/
load "docxlib.ring"
? "============================================="
? " DOCXLib - Charts Demo"
? "============================================="
? ""
outFile = "demo_charts.docx"
# Shared data
aQuarters = ["Q1 2024", "Q2 2024", "Q3 2024", "Q4 2024"]
aMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
aRegions = ["North", "South", "East", "West", "Central"]
aProducts = ["Ring", "PWCT", "Supernova", "PWCT2"]
# -- Build document ------------------------------------------------------------
doc = new WordWriter()
doc.setTitle("DOCXLib - Charts Demo")
doc.setAuthor("Mahmoud Fayed")
doc.setPageSize("a4")
doc.setTheme("Blue")
doc.setHeader("DOCXLib - Native OOXML Charts")
doc.showPageNumbers("right")
doc.setMargins(2, 2, 2.2, 2.2)
# -- Cover ---------------------------------------------------------------------
doc.addHeading("DOCXLib - Native OOXML Chart Support", 1)
doc.addParagraph(
"This document demonstrates native chart types. " +
"Charts are stored as pure OOXML XML inside the DOCX package ", NULL)
doc.addEmptyParagraph()
doc.addTable([
["addColumnChart()", "Vertical bars - best for comparing values across categories"],
["addBarChart()", "Horizontal bars - great for long category labels" ],
["addLineChart()", "Trend lines - ideal for time-series data" ],
["addAreaChart()", "Filled trend areas - stacked variant shows part-to-whole" ],
["addPieChart()", "Slices - single-series, shows proportions" ],
["addDoughnutChart()","Hollow-centre pie - shows proportions with inner space" ]
], [
:headerRow = false,
:evenRowBgColor = "EEF3FA",
:borderStyle = "single",
:colWidths = [5.5, 11.5]
])
doc.addEmptyParagraph()
# -----------------------------------------------------------------------------
# CHART 1 - Column chart
# -----------------------------------------------------------------------------
doc.addHeading("1. Column Chart - Quarterly Revenue vs Costs", 2)
doc.addParagraph(
"A clustered column chart with three series and data labels enabled. " +
"addColumnChart() is the most common chart type for category comparisons.", NULL)
doc.addEmptyParagraph()
doc.addColumnChart(
"Quarterly Revenue vs Costs ($K)",
aQuarters,
[
[:name = "Revenue", :values = [320, 410, 380, 490]],
[:name = "Operating Costs", :values = [210, 255, 230, 290]],
[:name = "Net Profit", :values = [110, 155, 150, 200]]
],
[
:widthCm = 14,
:heightCm = 9,
:centered = true,
:showDataLabels = true,
:showLegend = true,
:legendPos = "b"
])
doc.addCaption("Figure 1 - Clustered column chart, three series, data labels")
doc.addEmptyParagraph()
# -----------------------------------------------------------------------------
# CHART 2 - Line chart
# -----------------------------------------------------------------------------
doc.addHeading("2. Line Chart - Monthly Website Traffic", 2)
doc.addParagraph(
"A smooth-curve line chart comparing two years of monthly visit data. " +
"Pass :smooth = true in options for bezier curves instead of straight segments.", NULL)
doc.addEmptyParagraph()
doc.addLineChart(
"Monthly Website Traffic (Unique Visits)",
aMonths,
[
[:name = "2023", :values = [12000, 14500, 13200, 16800, 18000, 17400]],
[:name = "2024", :values = [15000, 18200, 17500, 21000, 23500, 22800]]
],
[
:widthCm = 14,
:heightCm = 9,
:centered = true,
:smooth = true,
:legendPos = "r"
])
doc.addCaption("Figure 2 - Smooth line chart, year-over-year comparison")
doc.addEmptyParagraph()
# -----------------------------------------------------------------------------
# CHART 3 - Pie chart
# -----------------------------------------------------------------------------
doc.addHeading("3. Pie Chart - Product Revenue Share", 2)
doc.addParagraph(
"A single-series pie chart. Each slice gets an automatic colour from the " +
"default palette. Data labels show the category name and percentage.", NULL)
doc.addEmptyParagraph()
doc.addPieChart(
"Product Revenue Share",
aProducts,
[
[:name = "Revenue ($K)", :values = [450, 280, 160, 110]]
],
[
:widthCm = 12,
:heightCm = 8,
:centered = true,
:showDataLabels = true,
:legendPos = "r"
])
doc.addCaption("Figure 3 - Pie chart with per-slice colours and percent labels")
doc.addEmptyParagraph()
# -----------------------------------------------------------------------------
# CHART 4 - Doughnut chart
# -----------------------------------------------------------------------------
doc.addHeading("4. Doughnut Chart - Market Share by Region", 2)
doc.addParagraph(
"The doughnut variant of the pie chart has a hollow centre (50% hole). " +
"Custom colours are supplied via the :colors option.", NULL)
doc.addEmptyParagraph()
doc.addDoughnutChart(
"Market Share by Region (%)",
aRegions,
[
[:name = "Market Share", :values = [35, 22, 18, 15, 10]]
],
[
:widthCm = 12,
:heightCm = 8,
:centered = true,
:showDataLabels = true,
:legendPos = "r",
:colors = ["1F3864", "2E75B6", "70AD47", "FFC000", "C00000"]
])
doc.addCaption("Figure 4 - Doughnut chart with custom colour palette")
doc.addEmptyParagraph()
# -----------------------------------------------------------------------------
# CHART 5 - Stacked area / column chart
# -----------------------------------------------------------------------------
doc.addHeading("5. Stacked Column Chart - Revenue by Product", 2)
doc.addParagraph(
"A four-series stacked column chart produced by addColumnChart() with the " +
":grouping = 'stacked' option. The total height of each bar equals the " +
"combined revenue across all products for that quarter.", NULL)
doc.addEmptyParagraph()
doc.addColumnChart(
"Stacked Revenue by Product ($K)",
aQuarters,
[
[:name = "Ring", :values = [120, 155, 140, 180]],
[:name = "PWCT", :values = [80, 95, 90, 110]],
[:name = "Supernova", :values = [60, 75, 70, 90]],
[:name = "PWCT2", :values = [40, 55, 50, 70]]
],
[
:widthCm = 14,
:heightCm = 9,
:centered = true,
:grouping = "stacked",
:legendPos = "r"
])
doc.addCaption("Figure 5 - Stacked column chart, four product series")
doc.addEmptyParagraph()
# -----------------------------------------------------------------------------
# CHART 6 - Horizontal bar chart
# -----------------------------------------------------------------------------
doc.addHeading("6. Horizontal Bar Chart - Support Tickets by Region", 2)
doc.addParagraph(
"Horizontal bars are produced by addBarChart(). This orientation works " +
"well when category labels are long. Two series show open vs resolved " +
"tickets per region.", NULL)
doc.addEmptyParagraph()
doc.addBarChart(
"Support Tickets by Region",
aRegions,
[
[:name = "Open", :values = [45, 32, 28, 51, 19]],
[:name = "Resolved", :values = [120, 98, 110, 145, 67]]
],
[
:widthCm = 14,
:heightCm = 9,
:centered = true,
:legendPos = "b"
])
doc.addCaption("Figure 6 - Horizontal bar chart with two series")
doc.addEmptyParagraph()
# -----------------------------------------------------------------------------
# API summary
# -----------------------------------------------------------------------------
doc.addHeading("Chart API Summary", 2)
doc.addTable([
["Method", "Chart type", "Notes" ],
["addColumnChart(t, cats, series, opts)", "Column (vertical bar)", "Most common; supports :grouping"],
["addBarChart(t, cats, series, opts)", "Bar (horizontal)", "Good for long category labels" ],
["addLineChart(t, cats, series, opts)", "Line", ":smooth for bezier curves" ],
["addAreaChart(t, cats, series, opts)", "Area (filled line)", "Stacked variant via :grouping" ],
["addPieChart(t, cats, series, opts)", "Pie", "Uses first series only" ],
["addDoughnutChart(t, cats, series, opts)", "Doughnut", "50% hollow centre" ],
["addChart(type, t, cats, series, opts)", "Any of the above", "Generic entry point" ]
], [
:headerRow = true,
:headerBgColor = "1F3864",
:evenRowBgColor = "EEF3FA",
:borderStyle = "single",
:colWidths = [6.5, 4.5, 6]
])
doc.addEmptyParagraph()
doc.addBorderedParagraph(
"Every series accepts :name (string), :values (list of numbers), and :color (hex string). " +
"Common options: :widthCm, :heightCm, :centered, :showLegend, :legendPos, " +
":showDataLabels, :grouping, :smooth, :colors.",
[:borderStyle = "single", :borderColor = "1E6BB5",
:bgColor = "DEEAF1", :indent = 240])
# -- Save ----------------------------------------------------------------------
? "Building document ..."
if doc.save(outFile)
? "Saved: " + outFile
else
? "Error: save() failed."
okpart2_charts2.ring#
samples/UsingDOCXLib/part2_charts2.ring
/*
DOCXLib - Demo (Charts2)
*/
load "docxlib.ring"
? "================================================="
? " DOCXLib Scatter & Bubble Charts"
? "================================================="
? ""
outFile = "demo_charts2.docx"
doc = new WordWriter()
doc.setTitle("DOCXLib - Scatter & Bubble Chart Demo")
doc.setAuthor("Mahmoud")
doc.setPageSize("a4")
doc.setTheme("Blue")
doc.setHeader("DOCXLib - Scatter & Bubble Charts")
doc.showPageNumbers("right")
doc.setMargins(2, 2, 2.2, 2.2)
# -- Introduction --------------------------------------------------------------
doc.addHeading("DOCXLib - Scatter & Bubble Charts", 1)
doc.addParagraph(
"Unlike column/line/pie charts, scatter and bubble charts have no string " +
"category axis - both axes are fully numeric. Series supply :xValues and " +
":yValues lists instead of :values, and bubble series additionally supply " +
"a :sizes list to control each bubble's area.", NULL)
doc.addEmptyParagraph()
doc.addTable([
["addScatterChart()", "XY scatter - markers, lines+markers, or lines only"],
["addBubbleChart()", "Bubble - XY position plus a third numeric dimension as bubble size"]
], [
:headerRow = false,
:evenRowBgColor = "EEF3FA",
:borderStyle = "single",
:colWidths = [5, 12]
])
doc.addEmptyParagraph()
# =============================================================================
# CHART 1 - Markers-only scatter (default style)
# =============================================================================
doc.addHeading("1. Scatter Chart - Markers Only", 2)
doc.addParagraph(
"The default scatter style shows only markers at each (X, Y) data point. " +
"Three research groups are shown; each series has its own colour from the " +
"automatic palette. Axis labels are set via :xAxisTitle and :yAxisTitle.", NULL)
doc.addEmptyParagraph()
doc.addScatterChart(
"Study Hours vs Exam Score - Three Cohorts",
[
[:name = "Cohort A",
:xValues = [2, 3, 4, 5, 6, 7, 8, 9, 10],
:yValues = [45, 52, 60, 67, 73, 79, 84, 88, 93]],
[:name = "Cohort B",
:xValues = [1, 2, 4, 5, 7, 8, 9, 10, 11],
:yValues = [38, 48, 55, 63, 70, 75, 81, 86, 90]],
[:name = "Cohort C",
:xValues = [3, 4, 5, 6, 7, 8, 9, 10, 12],
:yValues = [50, 58, 65, 71, 76, 82, 87, 91, 96]]
],
[
:widthCm = 14,
:heightCm = 9,
:centered = true,
:legendPos = "r",
:markerStyle = "circle",
:markerSize = 7,
:xAxisTitle = "Daily Study Hours",
:yAxisTitle = "Exam Score (%)"
])
doc.addCaption("Figure 1 - Markers-only scatter, three cohorts, axis titles set")
doc.addEmptyParagraph()
# =============================================================================
# CHART 2 - Lines + markers scatter
# =============================================================================
doc.addHeading("2. Scatter Chart - Lines + Markers", 2)
doc.addParagraph(
"Passing :lines = true connects data points with straight lines. " +
"This variant is ideal for tracking paired measurements over time " +
"when the X values are not evenly spaced. Two sensors are compared.", NULL)
doc.addEmptyParagraph()
doc.addScatterChart(
"Temperature vs Pressure - Two Sensors",
[
[:name = "Sensor A",
:xValues = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
:yValues = [101.2, 100.8, 100.1, 99.6, 99.0, 98.3, 97.8, 97.1, 96.4, 95.8],
:color = "2E75B6"],
[:name = "Sensor B",
:xValues = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
:yValues = [101.5, 101.0, 100.4, 99.9, 99.2, 98.7, 98.0, 97.4, 96.8, 96.1],
:color = "ED7D31"]
],
[
:widthCm = 14,
:heightCm = 9,
:centered = true,
:legendPos = "r",
:lines = true,
:smooth = false,
:markerStyle = "square",
:markerSize = 6,
:xAxisTitle = "Temperature (C)",
:yAxisTitle = "Pressure (kPa)"
])
doc.addCaption("Figure 2 - Lines + markers scatter, two sensor series")
doc.addEmptyParagraph()
# =============================================================================
# CHART 3 - Smooth lines + markers scatter
# =============================================================================
doc.addHeading("3. Scatter Chart - Smooth Curves + Markers", 2)
doc.addParagraph(
"Adding :smooth = true renders bezier curves instead of straight " +
"segments - useful for data that is expected to follow a continuous " +
"function. Here two algorithm performance curves are compared.", NULL)
doc.addEmptyParagraph()
doc.addScatterChart(
"Input Size vs Execution Time (ms)",
[
[:name = "Algorithm A O(n log n)",
:xValues = [100, 500, 1000, 2000, 5000, 10000],
:yValues = [0.8, 5.2, 11.5, 24.8, 68.3, 145.2],
:color = "4472C4"],
[:name = "Algorithm B O(n^2)",
:xValues = [100, 500, 1000, 2000, 5000, 10000],
:yValues = [1.2, 28.5, 112.4, 448.1, 2802.5, 11210.0],
:color = "C00000"]
],
[
:widthCm = 14,
:heightCm = 9,
:centered = true,
:legendPos = "b",
:lines = true,
:smooth = true,
:markerStyle = "diamond",
:markerSize = 7,
:xAxisTitle = "Input Size (n)",
:yAxisTitle = "Time (ms)"
])
doc.addCaption("Figure 3 - Smooth lines + markers, algorithm complexity comparison")
doc.addEmptyParagraph()
# =============================================================================
# CHART 4 - Lines-only scatter (no markers)
# =============================================================================
doc.addHeading("4. Scatter Chart - Lines Only", 2)
doc.addParagraph(
"Setting :markerStyle = 'none' with :lines = true gives a clean " +
"continuous line without point markers - suitable for dense datasets " +
"where markers would clutter the chart.", NULL)
doc.addEmptyParagraph()
aX = []
aY1 = []
aY2 = []
for i = 0 to 36
aX + i
aY1 + (50 + 30 * sin(i * 10 * 3.14159 / 180))
aY2 + (50 + 25 * cos(i * 10 * 3.14159 / 180))
next
doc.addScatterChart(
"Sine vs Cosine Wave",
[
[:name = "sin(x)", :xValues = aX, :yValues = aY1, :color = "2E75B6"],
[:name = "cos(x)", :xValues = aX, :yValues = aY2, :color = "70AD47"]
],
[
:widthCm = 14,
:heightCm = 8,
:centered = true,
:legendPos = "r",
:lines = true,
:smooth = true,
:markerStyle = "none",
:xAxisTitle = "Degrees / 10",
:yAxisTitle = "Amplitude"
])
doc.addCaption("Figure 4 - Lines-only scatter with 37 data points per series")
doc.addEmptyParagraph()
# =============================================================================
# CHART 5 - Bubble chart (basic)
# =============================================================================
doc.addHeading("5. Bubble Chart - Market Analysis", 2)
doc.addParagraph(
"A bubble chart plots (X, Y) coordinates and encodes a third numeric " +
"dimension as the bubble's area. Each bubble below represents a product: " +
"X = market share, Y = growth rate, bubble size = annual revenue ($M). " +
"Each product is its own series so it gets a distinct colour.", NULL)
doc.addEmptyParagraph()
aProducts = [
[:name = "Ring", :xValues = [35], :yValues = [22], :sizes = [450], :color = "4472C4"],
[:name = "PWCT", :xValues = [28], :yValues = [15], :sizes = [280], :color = "ED7D31"],
[:name = "Supernova", :xValues = [18], :yValues = [31], :sizes = [160], :color = "70AD47"],
[:name = "PWCT2", :xValues = [12], :yValues = [28], :sizes = [110], :color = "FFC000"],
[:name = "Other", :xValues = [7], :yValues = [8], :sizes = [60], :color = "5A9BD5"]
]
doc.addBubbleChart(
"Product Portfolio - Market Share / Growth / Revenue",
aProducts,
[
:widthCm = 14,
:heightCm = 9,
:centered = true,
:legendPos = "r",
:xAxisTitle = "Market Share (%)",
:yAxisTitle = "YoY Growth (%)",
:bubble3D = false
])
doc.addCaption("Figure 5 - Bubble chart: X=market share, Y=growth, size=revenue ($M)")
doc.addEmptyParagraph()
# =============================================================================
# CHART 6 - Bubble chart with 3-D shading
# =============================================================================
doc.addHeading("6. Bubble Chart - Research Metrics (3-D shading)", 2)
doc.addParagraph(
"Setting :bubble3D = true renders each bubble with a specular highlight, " +
"giving a glossy sphere appearance. The data shows research projects: " +
"X = team size, Y = months to completion, size = citation count.", NULL)
doc.addEmptyParagraph()
aProjects = [
[:name = "Project Alpha",
:xValues = [3, 5, 8, 12],
:yValues = [6, 9, 14, 18],
:sizes = [45, 120, 280, 500],
:color = "1F3864"],
[:name = "Project Beta",
:xValues = [2, 4, 7, 10],
:yValues = [4, 7, 11, 15],
:sizes = [30, 90, 200, 380],
:color = "C00000"]
]
doc.addBubbleChart(
"Research Projects - Team / Duration / Impact",
aProjects,
[
:widthCm = 14,
:heightCm = 9,
:centered = true,
:legendPos = "r",
:xAxisTitle = "Team Size",
:yAxisTitle = "Months to Completion",
:bubble3D = true,
:showDataLabels = true
])
doc.addCaption("Figure 6 - Bubble chart with 3-D shading and bubble-size labels")
doc.addEmptyParagraph()
# =============================================================================
# Series format summary
# =============================================================================
doc.addHeading("Scatter & Bubble Series Format Summary", 2)
doc.addTable([
["Key", "Scatter", "Bubble", "Description"],
[":name", "Yes", "Yes", "Series label shown in legend"],
[":xValues", "Yes", "Yes", "List of X numeric values"],
[":yValues", "Yes", "Yes", "List of Y numeric values (same length as :xValues)"],
[":sizes", "No", "Yes", "Bubble size values (positive numbers; relative scale)"],
[":color", "Optional","Optional","Hex colour override; palette used if omitted"]
], [
:headerRow = true,
:headerBgColor = "1F3864",
:evenRowBgColor = "EEF3FA",
:borderStyle = "single",
:colWidths = [3.5, 2, 2, 9.5]
])
doc.addEmptyParagraph()
doc.addHeading("Options Reference", 2)
doc.addTable([
["Option", "Type", "Default", "Applies to", "Description"],
[":widthCm", "Number", "14", "Both", "Chart width in centimetres"],
[":heightCm", "Number", "9", "Both", "Chart height in centimetres"],
[":centered", "Bool", "true", "Both", "Centre on page"],
[":showLegend", "Bool", "true", "Both", "Show legend"],
[":legendPos", "String", char(34)+"r"+char(34), "Both", "Legend position: r b t l"],
[":showDataLabels","Bool", "false", "Both", "Show value labels on data points"],
[":xAxisTitle", "String", char(34)+char(34), "Both", "Numeric X axis label"],
[":yAxisTitle", "String", char(34)+char(34), "Both", "Numeric Y axis label"],
[":markerStyle", "String", char(34)+"circle"+char(34),"Scatter only", "circle square diamond triangle x star dot dash none"],
[":markerSize", "Number", "7", "Scatter only", "Marker size (half-points)"],
[":lines", "Bool", "false", "Scatter only", "Connect points with lines"],
[":smooth", "Bool", "false", "Scatter only", "Smooth bezier lines"],
[":bubble3D", "Bool", "false", "Bubble only", "3-D specular shading on bubbles"]
], [
:headerRow = true,
:headerBgColor = "1F3864",
:evenRowBgColor = "EEF3FA",
:borderStyle = "single",
:colWidths = [2.8, 1.8, 2.2, 2.8, 7.4]
])
# -- Save ----------------------------------------------------------------------
? "Building document ..."
if doc.save(outFile)
? "Saved: " + outFile
? ""
? "Charts included:"
? " 1. Scatter - markers only (3 cohorts, custom axis labels)"
? " 2. Scatter - lines + markers (2 sensors, straight lines)"
? " 3. Scatter - smooth lines + markers(2 algorithms, bezier curves)"
? " 4. Scatter - lines only (sine/cosine, 37 points each)"
? " 5. Bubble - basic (5 products, flat shading)"
? " 6. Bubble - 3-D shading (2 projects, glossy bubbles)"
else
? "Error: save() failed."
okpart2_charts3.ring#
samples/UsingDOCXLib/part2_charts3.ring
/*
DOCXLib - Demo (Charts3)
*/
load "docxlib.ring"
/*
Chart Formatting Options Demo
Demonstrates every new axis-formatting option:
:yAxisMin / :yAxisMax — fix value axis bounds
:xAxisMin / :xAxisMax — fix X axis bounds (scatter/bubble)
:yAxisFormat — number format on value axis labels
:xAxisFormat — number format on X axis labels (scatter/bubble)
:yAxisTitle — rotated label on value axis (all chart types)
:xAxisTitle — label on category / X axis (all chart types)
:showGridlines — show or hide major gridlines (default true)
*/
? "================================================="
? " DOCXLib -- Chart Formatting Demo"
? "================================================="
? ""
doc = new WordWriter()
doc.setTitle("DOCXLib -- Chart Formatting Options")
doc.setAuthor("DOCXLib Demo")
doc.setPageSize("a4")
doc.setTheme("Blue")
doc.setHeader("DOCXLib -- Chart Formatting Options")
doc.setFooter("Generated by DOCXLib")
# ---- Cover heading ----------------------------------------------------------
doc.addHeading("Chart Formatting Options", 1)
doc.addParagraph(
"Axis-formatting options that apply to " +
"any chart type. This document demonstrates each option with a concrete " +
"chart and explains when to use it.", NULL)
doc.addEmptyParagraph()
doc.addTable([
["Option", "Type", "Default", "Applies to", "Description"],
[":yAxisMin", "Number", "auto", "All non-pie", "Force value axis lower bound"],
[":yAxisMax", "Number", "auto", "All non-pie", "Force value axis upper bound"],
[":xAxisMin", "Number", "auto", "Scatter / Bubble", "Force X axis lower bound"],
[":xAxisMax", "Number", "auto", "Scatter / Bubble", "Force X axis upper bound"],
[":yAxisFormat", "String", "General", "All non-pie", char(34)+"Number format, e.g. 0.0%, $#,##0"+char(34)],
[":xAxisFormat", "String", "General", "Scatter / Bubble", "Number format on X axis"],
[":yAxisTitle", "String", char(34)+char(34), "All non-pie", "Rotated label on value axis"],
[":xAxisTitle", "String", char(34)+char(34), "All non-pie", "Label on category / X axis"],
[":showGridlines", "Bool", "true", "All non-pie", "Show major gridlines on value axis"]
], [
:headerRow = true,
:headerBgColor = "1F3864",
:evenRowBgColor = "EEF3FA",
:borderStyle = "single",
:colWidths = [2.8, 1.6, 2.0, 3.0, 7.6]
])
doc.addEmptyParagraph()
doc.addPageBreak()
# =============================================================================
# 1. :yAxisMin / :yAxisMax — Column chart
# =============================================================================
doc.addHeading("1. :yAxisMin and :yAxisMax", 2)
doc.addParagraph(
"By default Word auto-scales the value axis. Setting :yAxisMin forces the " +
"axis floor (useful when your lowest value is well above zero and you do not " +
"want the bars to look artificially tall). Setting :yAxisMax prevents the " +
"chart from expanding when you want consistent scales across multiple charts.", NULL)
cats = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
doc.addHeading("Auto-scaled (default):", 3)
doc.addColumnChart(
"Monthly Active Users (auto axis)",
cats,
[[:name = "Users (K)", :values = [82, 85, 88, 91, 87, 93,
96, 99, 95, 102, 105, 110]]],
[:heightCm = 7, :yAxisTitle = "Users (thousands)", :xAxisTitle = "Month"])
doc.addCaption("Figure 1a -- Auto-scaled: axis starts near the data minimum")
doc.addEmptyParagraph()
doc.addHeading("Fixed axis 0-120:", 3)
doc.addColumnChart(
"Monthly Active Users (fixed axis 0-120)",
cats,
[[:name = "Users (K)", :values = [82, 85, 88, 91, 87, 93,
96, 99, 95, 102, 105, 110]]],
[:heightCm = 7, :yAxisMin = 0, :yAxisMax = 120,
:yAxisTitle = "Users (thousands)", :xAxisTitle = "Month"])
doc.addCaption("Figure 1b -- Fixed :yAxisMin=0, :yAxisMax=120: shows true proportion")
doc.addEmptyParagraph()
doc.addPageBreak()
# =============================================================================
# 2. :yAxisFormat — Line chart with currency format
# =============================================================================
doc.addHeading("2. :yAxisFormat -- Value Axis Number Format", 2)
doc.addParagraph(
"The :yAxisFormat option accepts any Excel/OOXML number format string. " +
"Common patterns: " +
char(34) + "$#,##0" + char(34) + " for currency, " +
char(34) + "0.0%" + char(34) + " for percentages, " +
char(34) + "#,##0" + char(34) + " for large integers with thousands separator, " +
char(34) + "0.00" + char(34) + " for two decimal places.", NULL)
doc.addEmptyParagraph()
quarters = ["Q1 2023", "Q2 2023", "Q3 2023", "Q4 2023",
"Q1 2024", "Q2 2024", "Q3 2024", "Q4 2024"]
doc.addHeading("Currency format ($#,##0):", 3)
doc.addLineChart(
"Quarterly Revenue",
quarters,
[
[:name = "Product A", :values = [245000, 280000, 310000, 350000,
290000, 320000, 365000, 410000]],
[:name = "Product B", :values = [180000, 195000, 220000, 250000,
210000, 235000, 270000, 305000]]
],
[:heightCm = 7, :yAxisFormat = "$#,##0", :yAxisMin = 0,
:yAxisTitle = "Revenue (USD)", :xAxisTitle = "Quarter",
:smooth = true, :legendPos = "b"])
doc.addCaption("Figure 2a -- :yAxisFormat=" + char(34) + "$#,##0" + char(34) + " -- dollar sign with comma separator")
doc.addEmptyParagraph()
doc.addHeading("Percentage format (0.0%):", 3)
doc.addBarChart(
"Gross Margin by Region",
["North", "South", "East", "West", "Central", "International"],
[
[:name = "2023", :values = [0.38, 0.42, 0.35, 0.44, 0.31, 0.39]],
[:name = "2024", :values = [0.41, 0.45, 0.38, 0.47, 0.34, 0.43]]
],
[:heightCm = 7, :yAxisFormat = "0.0%", :yAxisMin = 0, :yAxisMax = 0.6,
:yAxisTitle = "Gross Margin", :legendPos = "b"])
doc.addCaption("Figure 2b -- :yAxisFormat=" + char(34) + "0.0%" + char(34) + " -- axis labels shown as percentages")
doc.addEmptyParagraph()
doc.addPageBreak()
# =============================================================================
# 3. :yAxisTitle and :xAxisTitle — Category charts
# =============================================================================
doc.addHeading("3. :yAxisTitle and :xAxisTitle -- Category Charts", 2)
doc.addParagraph(
"Axis titles make standalone charts self-explanatory. :yAxisTitle appears " +
"rotated alongside the value axis; :xAxisTitle appears below the category axis. " +
"Both options work across all non-pie chart types.", NULL)
doc.addEmptyParagraph()
doc.addAreaChart(
"Server Load Over Time",
["00:00", "03:00", "06:00", "09:00", "12:00", "15:00", "18:00", "21:00", "24:00"],
[
[:name = "Web Servers", :values = [12, 8, 6, 45, 78, 82, 70, 55, 20],
:color = "4472C4"],
[:name = "DB Servers", :values = [8, 5, 4, 30, 55, 60, 50, 38, 12],
:color = "ED7D31"],
[:name = "Cache Layer", :values = [3, 2, 2, 12, 22, 25, 20, 15, 5],
:color = "70AD47"]
],
[:heightCm = 8, :yAxisTitle = "CPU Usage (%)", :xAxisTitle = "Time of Day",
:yAxisMin = 0, :yAxisMax = 100,
:yAxisFormat = "0", :grouping = "stacked", :legendPos = "b"])
doc.addCaption("Figure 3 -- :yAxisTitle and :xAxisTitle on a stacked area chart")
doc.addEmptyParagraph()
doc.addPageBreak()
# =============================================================================
# 4. :showGridlines = false
# =============================================================================
doc.addHeading("4. :showGridlines -- Show or Hide Gridlines", 2)
doc.addParagraph(
"Gridlines are on by default. Set :showGridlines = false for a cleaner look, " +
"particularly in presentations or when data labels are already shown.", NULL)
doc.addEmptyParagraph()
products = ["Ring", "PWCT", "Supernova", "PWCT2"]
sales2024 = [450, 280, 160, 110]
doc.addHeading("Default (gridlines visible):", 3)
doc.addColumnChart(
"Annual Sales by Product",
products,
[[:name = "Sales ($K)", :values = sales2024, :color = "2E75B6"]],
[:heightCm = 7, :yAxisMin = 0, :showDataLabels = true,
:yAxisTitle = "Sales ($K)"])
doc.addCaption("Figure 4a -- Default: :showGridlines = true")
doc.addEmptyParagraph()
doc.addHeading("Gridlines hidden (:showGridlines = false):", 3)
doc.addColumnChart(
"Annual Sales by Product",
products,
[[:name = "Sales ($K)", :values = sales2024, :color = "2E75B6"]],
[:heightCm = 7, :yAxisMin = 0, :showDataLabels = true,
:yAxisTitle = "Sales ($K)", :showGridlines = false])
doc.addCaption("Figure 4b -- :showGridlines = false -- cleaner for labelled charts")
doc.addEmptyParagraph()
doc.addPageBreak()
# =============================================================================
# 5. Scatter: :xAxisMin/:xAxisMax + :xAxisFormat + :yAxisFormat
# =============================================================================
doc.addHeading("5. Scatter / Bubble Axis Bounds and Formats", 2)
doc.addParagraph(
"For scatter and bubble charts :xAxisMin, :xAxisMax control the horizontal " +
"axis, while :xAxisFormat and :yAxisFormat format both numeric axes independently. " +
"This is especially useful for scientific or financial scatter plots where " +
"the axis range and units need to be explicit.", NULL)
doc.addEmptyParagraph()
doc.addHeading("Fixed axis bounds + formatted labels:", 3)
doc.addScatterChart(
"Advertising Spend vs Revenue",
[
[:name = "2022",
:xValues = [50000, 80000, 120000, 175000, 240000, 310000],
:yValues = [210000, 340000, 490000, 680000, 870000, 1100000],
:color = "4472C4"],
[:name = "2023",
:xValues = [60000, 95000, 140000, 200000, 275000, 360000],
:yValues = [260000, 410000, 590000, 820000, 1050000, 1350000],
:color = "ED7D31"],
[:name = "2024",
:xValues = [75000, 115000, 165000, 235000, 320000, 420000],
:yValues = [320000, 500000, 720000, 990000, 1280000, 1640000],
:color = "70AD47"]
],
[:xAxisMin = 0, :xAxisMax = 500000,
:yAxisMin = 0, :yAxisMax = 2000000,
:xAxisFormat = "$#,##0", :yAxisFormat = "$#,##0",
:xAxisTitle = "Ad Spend (USD)", :yAxisTitle = "Revenue (USD)",
:markerStyle = "circle", :markerSize = 8,
:heightCm = 9, :legendPos = "b"])
doc.addCaption("Figure 5a -- Scatter: :xAxisMin/Max + :xAxisFormat + :yAxisFormat for financial axes")
doc.addEmptyParagraph()
doc.addHeading("Scientific scatter: fixed axis + decimal format:", 3)
# Build data points for quadratic curve with noise simulation
aX = [] aY1 = [] aY2 = []
for i = 1 to 20
v = i * 0.5
aX + v
aY1 + (v * v * 0.8 + v * 0.3)
aY2 + (v * v * 1.1 + v * 0.2)
next
doc.addScatterChart(
"Drag Coefficient vs Velocity",
[
[:name = "Surface A", :xValues = aX, :yValues = aY1, :color = "C00000"],
[:name = "Surface B", :xValues = aX, :yValues = aY2, :color = "255E91"]
],
[:xAxisMin = 0, :xAxisMax = 11,
:yAxisMin = 0, :yAxisMax = 90,
:xAxisFormat = "0.0", :yAxisFormat = "0.0",
:xAxisTitle = "Velocity (m/s)", :yAxisTitle = "Drag Force (N)",
:lines = true, :smooth = true, :markerStyle = "square",
:heightCm = 8, :legendPos = "r"])
doc.addCaption("Figure 5b -- Scatter: fixed bounds with decimal format for scientific data")
doc.addEmptyParagraph()
doc.addHeading("Bubble: :xAxisFormat = " + char(34) + "0" + char(34) + " + :yAxisFormat = " + char(34) + "0.0%" + char(34) + ":", 3)
doc.addBubbleChart(
"Investment Portfolio",
[
[:name = "Tech", :xValues = [8], :yValues = [0.32], :sizes = [450], :color = "4472C4"],
[:name = "Finance", :xValues = [5], :yValues = [0.18], :sizes = [280], :color = "ED7D31"],
[:name = "Health", :xValues = [12], :yValues = [0.25], :sizes = [320], :color = "70AD47"],
[:name = "Energy", :xValues = [3], :yValues = [0.11], :sizes = [160], :color = "FFC000"],
[:name = "Consumer", :xValues = [7], :yValues = [0.21], :sizes = [240], :color = "5A9BD5"]
],
[:xAxisMin = 0, :xAxisMax = 15,
:yAxisMin = 0, :yAxisMax = 0.4,
:xAxisFormat = "0", :yAxisFormat = "0%",
:xAxisTitle = "P/E Ratio", :yAxisTitle = "Annual Return",
:bubble3D = true, :heightCm = 8, :legendPos = "r"])
doc.addCaption("Figure 5c -- Bubble: integer P/E on X axis, percentage return on Y axis")
doc.addEmptyParagraph()
doc.addPageBreak()
# =============================================================================
# 6. All options combined — showcase chart
# =============================================================================
doc.addHeading("6. All Options Combined", 2)
doc.addParagraph(
"A single column chart using every formatting option together: fixed axis " +
"bounds, currency format, axis titles, hidden gridlines, and data labels.", NULL)
doc.addEmptyParagraph()
doc.addColumnChart(
"Regional Revenue vs Target",
["North", "South", "East", "West", "Central"],
[
[:name = "Actual", :values = [1250000, 980000, 1420000, 1100000, 870000],
:color = "2E75B6"],
[:name = "Target", :values = [1200000, 1050000, 1350000, 1150000, 950000],
:color = "70AD47"],
[:name = "Forecast",:values = [1380000, 1120000, 1550000, 1250000, 1020000],
:color = "ED7D31"]
],
[:yAxisMin = 0, :yAxisMax = 1800000,
:yAxisFormat = "$#,##0",
:yAxisTitle = "Revenue (USD)", :xAxisTitle = "Region",
:showGridlines = false, :showDataLabels = false,
:legendPos = "b", :heightCm = 9, :widthCm = 16])
doc.addCaption(
"Figure 6 -- All options: :yAxisMin=0, :yAxisMax=1800000, :yAxisFormat=" + char(34) + "$#,##0" + char(34) +
", :yAxisTitle, :xAxisTitle, :showGridlines=false")
doc.addEmptyParagraph()
doc.addEmptyParagraph()
# ---- Save -------------------------------------------------------------------
? "Building document ..."
doc.save("demo_charts3.docx")
? "Done -- demo_charts3.docx"part2_charts4.ring#
samples/UsingDOCXLib/part2_charts4.ring
/*
DOCXLib - Demo (Charts3)
*/
load "docxlib.ring"
/*
Demonstrates:
Feature 1 -- Chart Style Presets
doc.setChartDefaults(options) -- apply defaults to every chart
doc.clearChartDefaults() -- remove defaults
Per-chart options still override defaults.
Feature 2 -- Conditional Table Formatting
:conditionalRules option on addTable()
Supported conditions: lt lte gt gte eq neq between contains
Rules can target a specific column (:col = N) or all columns (:col = 0)
Each rule can set :bgColor, :textColor, and :bold independently.
*/
? "==================================================="
? " DOCXLib -- Presets & Conditional Demo"
? "==================================================="
? ""
doc = new WordWriter()
doc.setTitle("DOCXLib -- Presets and Conditional Formatting")
doc.setAuthor("DOCXLib Demo")
doc.setPageSize("a4")
doc.setTheme("Blue")
doc.setHeader("DOCXLib -- Presets and Conditional Formatting")
doc.setFooter("Generated by DOCXLib")
# =============================================================================
# PART 1 — CHART STYLE PRESETS
# =============================================================================
doc.addHeading("Part 1: Chart Style Presets", 1)
doc.addParagraph(
"setChartDefaults() registers a set of options that are automatically " +
"applied to every subsequent chart. Options explicitly passed to the " +
"chart call take priority and override the defaults. Call " +
"clearChartDefaults() to stop applying them.", NULL)
doc.addEmptyParagraph()
# ---- 1a. Without presets — verbose repeated options -------------------------
doc.addHeading("1a. Without Presets (repeated options)", 2)
doc.addParagraph(
"Without presets, every chart must repeat the same boilerplate: " +
"widthCm, heightCm, yAxisMin, yAxisFormat, legendPos, showGridlines. " +
"With three charts this is manageable; with ten it becomes error-prone.", NULL)
doc.addEmptyParagraph()
quarters = ["Q1 2025", "Q2 2025", "Q3 2025", "Q4 2025"]
doc.addColumnChart(
"Revenue by Product",
quarters,
[
[:name = "Ring", :values = [320, 410, 380, 490], :color = "4472C4"],
[:name = "PWCT", :values = [210, 260, 240, 300], :color = "ED7D31"],
[:name = "Supernova", :values = [140, 175, 160, 210], :color = "70AD47"]
],
[:widthCm = 14, :heightCm = 7, :legendPos = "b",
:yAxisMin = 0, :yAxisFormat = "$#,##0", :yAxisTitle = "Revenue ($K)",
:showGridlines = false])
doc.addCaption("Figure 1 -- Column chart: all options repeated manually")
doc.addEmptyParagraph()
doc.addLineChart(
"Quarterly Trend",
quarters,
[
[:name = "Ring", :values = [320, 410, 380, 490], :color = "4472C4"],
[:name = "PWCT", :values = [210, 260, 240, 300], :color = "ED7D31"]
],
[:widthCm = 14, :heightCm = 7, :legendPos = "b",
:yAxisMin = 0, :yAxisFormat = "$#,##0", :yAxisTitle = "Revenue ($K)",
:showGridlines = false, :smooth = true])
doc.addCaption("Figure 2 -- Line chart: same options repeated again")
doc.addEmptyParagraph()
doc.addPageBreak()
# ---- 1b. Register a corporate preset ----------------------------------------
doc.addHeading("1b. With Presets (define once, apply everywhere)", 2)
doc.addParagraph(
"After calling setChartDefaults(), every chart automatically gets those " +
"options. The charts below use exactly the same data but the options " +
"are only written once.", NULL)
doc.addEmptyParagraph()
# Define a corporate house style
doc.setChartDefaults([
:widthCm = 14,
:heightCm = 7,
:legendPos = "b",
:yAxisMin = 0,
:yAxisFormat = "$#,##0",
:yAxisTitle = "Revenue ($K)",
:showGridlines = false
])
doc.addColumnChart(
"Revenue by Product",
quarters,
[
[:name = "Ring", :values = [320, 410, 380, 490], :color = "4472C4"],
[:name = "PWCT", :values = [210, 260, 240, 300], :color = "ED7D31"],
[:name = "Supernova", :values = [140, 175, 160, 210], :color = "70AD47"]
],
[]) # <-- no options needed; defaults apply
doc.addCaption("Figure 3 -- Same column chart; options come from setChartDefaults()")
doc.addEmptyParagraph()
doc.addLineChart(
"Quarterly Trend",
quarters,
[
[:name = "Ring", :values = [320, 410, 380, 490], :color = "4472C4"],
[:name = "PWCT", :values = [210, 260, 240, 300], :color = "ED7D31"]
],
[:smooth = true]) # <-- only the non-default option
doc.addCaption("Figure 4 -- Same line chart; only :smooth = true added to the defaults")
doc.addEmptyParagraph()
doc.addBarChart(
"Market Share by Region",
["North", "South", "East", "West", "Central"],
[
[:name = "2024", :values = [280000, 195000, 340000, 220000, 155000]],
[:name = "2025", :values = [320000, 225000, 390000, 260000, 185000]]
],
[]) # <-- entirely from defaults
doc.addCaption("Figure 5 -- Bar chart: zero per-chart options; entirely from defaults")
doc.addEmptyParagraph()
doc.addPageBreak()
# ---- 1c. Per-chart override --------------------------------------------------
doc.addHeading("1c. Per-Chart Override", 2)
doc.addParagraph(
"Any option passed to the chart call overrides the matching default. " +
"Below, the corporate defaults supply widthCm/heightCm/legendPos/showGridlines, " +
"but this chart overrides yAxisFormat and adds a percentage format.", NULL)
doc.addEmptyParagraph()
doc.addBarChart(
"Gross Margin by Region",
["North", "South", "East", "West", "Central"],
[
[:name = "2024", :values = [0.38, 0.42, 0.35, 0.44, 0.31]],
[:name = "2025", :values = [0.41, 0.45, 0.38, 0.47, 0.34]]
],
# Override yAxisFormat and yAxisMax; rest from defaults
[:yAxisFormat = "0.0%", :yAxisMax = 0.6, :yAxisTitle = "Gross Margin"])
doc.addCaption("Figure 6 -- Bar chart: :yAxisFormat overrides the default " + char(34) + "$#,##0" + char(34) + " with " + char(34) + "0.0%" + char(34))
doc.addEmptyParagraph()
# ---- 1d. Clear defaults and switch to a different preset --------------------
doc.addHeading("1d. Clearing Defaults and Switching Presets", 2)
doc.addParagraph(
"clearChartDefaults() removes all defaults. You can then call " +
"setChartDefaults() again with a different preset for a different " +
"section of the document.", NULL)
doc.addEmptyParagraph()
doc.clearChartDefaults()
# Science / academic preset: decimal format, gridlines on, no legend
doc.setChartDefaults([
:widthCm = 13,
:heightCm = 7,
:legendPos = "r",
:yAxisFormat = "0.00",
:showGridlines = true,
:showDataLabels = false
])
aX = [] aY1 = [] aY2 = []
for i = 1 to 20
v = i * 0.5
aX + v
aY1 + (v * v * 0.05 + v * 0.12)
aY2 + (v * v * 0.07 + v * 0.09)
next
doc.addScatterChart(
"Drag Coefficient vs Velocity",
[
[:name = "Surface A", :xValues = aX, :yValues = aY1, :color = "C00000"],
[:name = "Surface B", :xValues = aX, :yValues = aY2, :color = "255E91"]
],
[:xAxisTitle = "Velocity (m/s)", :yAxisTitle = "Drag Force (N)",
:lines = true, :smooth = true, :markerStyle = "circle"])
doc.addCaption("Figure 7 -- Scatter chart using the science preset (decimal format, gridlines)")
doc.addEmptyParagraph()
# Remove preset before Part 2
doc.clearChartDefaults()
doc.addPageBreak()
# =============================================================================
# PART 2 — CONDITIONAL TABLE FORMATTING
# =============================================================================
doc.addHeading("Part 2: Conditional Table Formatting", 1)
doc.addParagraph(
"The :conditionalRules option accepts a list of rules. Each rule specifies " +
"a column (:col), a condition, a threshold, and the visual treatment to apply " +
"when the condition is met (:bgColor, :textColor, :bold). Rules are evaluated " +
"in order; later rules override earlier ones. The header row is never affected.", NULL)
doc.addEmptyParagraph()
doc.addTable([
["Condition", "Meaning", "Example"],
[char(34)+"lt"+char(34), "Cell value less than threshold", ":condition = lt, :value = 0"],
[char(34)+"lte"+char(34), "Less than or equal", ":condition = lte, :value = 50"],
[char(34)+"gt"+char(34), "Greater than", ":condition = gt, :value = 100"],
[char(34)+"gte"+char(34), "Greater than or equal", ":condition = gte, :value = 90"],
[char(34)+"eq"+char(34), "Equal (numeric or string)", ":condition = eq, :value = 0"],
[char(34)+"neq"+char(34), "Not equal", ":condition = neq, :value = 0"],
[char(34)+"between"+char(34), "Value between :value and :value2", ":condition = between, :value = 60, :value2 = 79"],
[char(34)+"contains"+char(34), "Cell text contains substring", ":condition = contains, :value = FAIL"]
], [
:headerRow = true,
:headerBgColor = "1F3864",
:evenRowBgColor = "EEF3FA",
:borderStyle = "single",
:colWidths = [2.5, 4.5, 10.0]
])
doc.addEmptyParagraph()
doc.addPageBreak()
# ---- 2a. Numeric threshold — KPI scorecard -----------------------------------
doc.addHeading("2a. Numeric Thresholds -- KPI Scorecard", 2)
doc.addParagraph(
"Rules on column 3 (Score): red below 60, amber 60-79, green 80+. " +
"Column 4 (Change): red for negative values, green for positive.", NULL)
doc.addEmptyParagraph()
doc.addTable([
["Department", "Target", "Score", "Change vs Last Year", "Status"],
["Engineering", "85", "91", "+6", "On track"],
["Marketing", "80", "74", "-3", "At risk"],
["Operations", "75", "58", "-12", "Behind"],
["Sales", "90", "88", "+2", "On track"],
["Support", "80", "63", "+1", "At risk"],
["Finance", "85", "82", "-1", "On track"],
["HR", "75", "49", "-8", "Behind"],
["R&D", "70", "95", "+11", "On track"]
], [
:headerRow = true,
:headerBgColor = "1F3864",
:evenRowBgColor = "F5F8FF",
:borderStyle = "single",
:colWidths = [3.5, 2.0, 2.0, 4.5, 3.0],
:conditionalRules = [
# Score column (3): red < 60
[:col = 3, :condition = "lt", :value = 60,
:bgColor = "FDECEA", :textColor = "C00000", :bold = true],
# Score column (3): amber 60-79
[:col = 3, :condition = "between", :value = 60, :value2 = 79,
:bgColor = "FFF2CC", :textColor = "7F4F00"],
# Score column (3): green >= 80
[:col = 3, :condition = "gte", :value = 80,
:bgColor = "E2EFDA", :textColor = "375623"],
# Change column (4): red if negative (contains "-")
[:col = 4, :condition = "lt", :value = 0,
:bgColor = "FDECEA", :textColor = "C00000"],
# Change column (4): green if positive (> 0)
[:col = 4, :condition = "gt", :value = 0,
:bgColor = "E2EFDA", :textColor = "375623"]
]
])
doc.addCaption("Table 1 -- KPI scorecard: score traffic-light, change positive/negative")
doc.addEmptyParagraph()
doc.addPageBreak()
# ---- 2b. Stock / financial data table ----------------------------------------
doc.addHeading("2b. Financial Data -- Price Change Highlighting", 2)
doc.addParagraph(
"Column 4 (Day Change %): any cell with a negative value gets a red background. " +
"Column 5 (P/E Ratio): highlight cells above 30 as overvalued (amber) and " +
"below 10 as potentially undervalued (light blue).", NULL)
doc.addEmptyParagraph()
doc.addTable([
["Ticker", "Company", "Price", "Day Change %", "P/E Ratio", "52W High"],
["RING", "Ring Tech", "142.50", "+2.3", "24.5", "158.00"],
["PWCT", "PWCT Systems", "87.30", "-1.4", "18.2", "95.50"],
["NOVA", "Supernova Inc", "215.80", "+0.8", "35.1", "225.00"],
["PWCT2", "PWCT2 Corp", "56.20", "-3.1", "8.7", "78.40"],
["RNGX", "RingX Ltd", "334.10", "+4.5", "41.2", "340.00"],
["VISL", "Visual Labs", "23.40", "-0.2", "12.3", "31.20"],
["CODX", "CodeX Systems", "189.70", "-2.8", "9.1", "210.50"],
["AUTOM", "AutoML Inc", "445.30", "+1.1", "52.8", "460.00"]
], [
:headerRow = true,
:headerBgColor = "1F3864",
:evenRowBgColor = "F5F8FF",
:borderStyle = "single",
:colWidths = [2.0, 3.8, 2.5, 3.2, 2.8, 2.7],
:conditionalRules = [
# Day Change: negative = red
[:col = 4, :condition = "lt", :value = 0,
:bgColor = "FDECEA", :textColor = "C00000"],
# Day Change: positive = green
[:col = 4, :condition = "gt", :value = 0,
:bgColor = "E2EFDA", :textColor = "375623"],
# P/E: potentially undervalued (< 10)
[:col = 5, :condition = "lt", :value = 10,
:bgColor = "DEEAF1", :textColor = "1F3864"],
# P/E: overvalued (> 30)
[:col = 5, :condition = "gt", :value = 30,
:bgColor = "FFF2CC", :textColor = "7F4F00"],
# P/E: extreme overvalued (> 45)
[:col = 5, :condition = "gt", :value = 45,
:bgColor = "FDECEA", :textColor = "C00000", :bold = true]
]
])
doc.addCaption("Table 2 -- Stock data: change direction coloured, P/E ratio banded")
doc.addEmptyParagraph()
doc.addPageBreak()
# ---- 2c. Student grades — string-based and numeric rules --------------------
doc.addHeading("2c. Student Grades -- Mixed Numeric and Text Rules", 2)
doc.addParagraph(
"Numeric rules on the mark columns, and a text " + char(34) + "contains" + char(34) +
" rule that highlights any cell containing " + char(34) + "FAIL" + char(34) +
" across all columns (:col = 0).", NULL)
doc.addEmptyParagraph()
doc.addTable([
["Student", "Maths", "Science", "English", "History", "Average", "Result"],
["Alice M.", "92", "88", "91", "85", "89.0", "PASS"],
["Bob K.", "74", "81", "68", "72", "73.8", "PASS"],
["Carol L.", "58", "62", "55", "60", "58.8", "PASS"],
["David P.", "45", "38", "51", "42", "44.0", "FAIL"],
["Emma R.", "88", "94", "90", "92", "91.0", "PASS"],
["Frank T.", "61", "55", "48", "58", "55.5", "FAIL"],
["Grace W.", "79", "83", "77", "81", "80.0", "PASS"],
["Henry X.", "96", "91", "95", "94", "94.0", "PASS"],
["Iris Y.", "52", "49", "57", "44", "50.5", "FAIL"]
], [
:headerRow = true,
:headerBgColor = "1F3864",
:evenRowBgColor = "F5F8FF",
:borderStyle = "single",
:colWidths = [3.0, 2.0, 2.5, 2.5, 2.5, 2.5, 2.0],
:conditionalRules = [
# Subject mark cols 2-5 and average col 6: red < 50
[:col = 2, :condition = "lt", :value = 50, :bgColor = "FDECEA", :textColor = "C00000"],
[:col = 3, :condition = "lt", :value = 50, :bgColor = "FDECEA", :textColor = "C00000"],
[:col = 4, :condition = "lt", :value = 50, :bgColor = "FDECEA", :textColor = "C00000"],
[:col = 5, :condition = "lt", :value = 50, :bgColor = "FDECEA", :textColor = "C00000"],
[:col = 6, :condition = "lt", :value = 50, :bgColor = "FDECEA", :textColor = "C00000"],
# Amber: 50-69
[:col = 2, :condition = "between", :value = 50, :value2 = 69, :bgColor = "FFF2CC"],
[:col = 3, :condition = "between", :value = 50, :value2 = 69, :bgColor = "FFF2CC"],
[:col = 4, :condition = "between", :value = 50, :value2 = 69, :bgColor = "FFF2CC"],
[:col = 5, :condition = "between", :value = 50, :value2 = 69, :bgColor = "FFF2CC"],
[:col = 6, :condition = "between", :value = 50, :value2 = 69, :bgColor = "FFF2CC"],
# Green: >= 85
[:col = 2, :condition = "gte", :value = 85, :bgColor = "E2EFDA", :textColor = "375623"],
[:col = 3, :condition = "gte", :value = 85, :bgColor = "E2EFDA", :textColor = "375623"],
[:col = 4, :condition = "gte", :value = 85, :bgColor = "E2EFDA", :textColor = "375623"],
[:col = 5, :condition = "gte", :value = 85, :bgColor = "E2EFDA", :textColor = "375623"],
[:col = 6, :condition = "gte", :value = 85, :bgColor = "E2EFDA", :textColor = "375623"],
# FAIL in any column: bold red background (col=0 means ALL columns)
[:col = 0, :condition = "contains", :value = "FAIL",
:bgColor = "C00000", :textColor = "FFFFFF", :bold = true]
]
])
doc.addCaption("Table 3 -- Student grades: traffic-light per subject, FAIL highlighted across row via :col=0")
doc.addEmptyParagraph()
doc.addPageBreak()
# ---- 2d. Inventory / stock level table ---------------------------------------
doc.addHeading("2d. Inventory Status -- Multi-Column Rules", 2)
doc.addParagraph(
"Stock level rules on column 3: critical (red) below 20 units, " +
"low (amber) between 20-49, healthy (green) 50+. " +
"Column 5 (Days to Reorder): urgent (red) if 0, soon (amber) between 1-7.", NULL)
doc.addEmptyParagraph()
doc.addTable([
["SKU", "Product", "Stock", "Reorder Pt", "Days to Reorder", "Status"],
["SKU-001", "Ring IDE Pro", "145", "50", "28", "OK"],
["SKU-002", "PWCT Desktop", "38", "30", "5", "Low"],
["SKU-003", "Supernova Cloud", "12", "25", "0", "Critical"],
["SKU-004", "PWCT2 Enterprise", "67", "40", "14", "OK"],
["SKU-005", "Ring Mobile", "8", "20", "0", "Critical"],
["SKU-006", "Ring Server", "52", "35", "10", "OK"],
["SKU-007", "PWCT Web", "24", "30", "3", "Low"],
["SKU-008", "Supernova Local", "91", "45", "20", "OK"],
["SKU-009", "Ring Analytics", "17", "25", "0", "Critical"]
], [
:headerRow = true,
:headerBgColor = "1F3864",
:evenRowBgColor = "F5F8FF",
:borderStyle = "single",
:colWidths = [2.2, 4.2, 2.0, 2.8, 3.5, 2.3],
:conditionalRules = [
# Stock (col 3): critical
[:col = 3, :condition = "lt", :value = 20,
:bgColor = "FDECEA", :textColor = "C00000", :bold = true],
# Stock (col 3): low
[:col = 3, :condition = "between", :value = 20, :value2 = 49,
:bgColor = "FFF2CC", :textColor = "7F4F00"],
# Stock (col 3): healthy
[:col = 3, :condition = "gte", :value = 50,
:bgColor = "E2EFDA", :textColor = "375623"],
# Days to reorder (col 5): urgent — overdue
[:col = 5, :condition = "eq", :value = 0,
:bgColor = "FDECEA", :textColor = "C00000", :bold = true],
# Days to reorder (col 5): soon
[:col = 5, :condition = "between", :value = 1, :value2 = 7,
:bgColor = "FFF2CC", :textColor = "7F4F00"],
# Status column (col 6): Critical text
[:col = 6, :condition = "contains", :value = "Critical",
:bgColor = "C00000", :textColor = "FFFFFF", :bold = true],
# Status column (col 6): Low text
[:col = 6, :condition = "contains", :value = "Low",
:bgColor = "FFF2CC", :textColor = "7F4F00"]
]
])
doc.addCaption("Table 4 -- Inventory: stock level banding + reorder urgency + status text colouring")
doc.addEmptyParagraph()
doc.addPageBreak()
# ---- 2e. Combining chart presets + conditional tables in one report ----------
doc.addHeading("2e. Combined: Preset Charts + Conditional Table", 2)
doc.addParagraph(
"A typical report section: one setChartDefaults() call at the top, " +
"several charts with minimal per-chart options, followed by a conditional " +
"table summarising the same data.", NULL)
doc.addEmptyParagraph()
doc.setChartDefaults([
:widthCm = 14,
:heightCm = 7,
:legendPos = "b",
:yAxisMin = 0,
:yAxisFormat = "$#,##0",
:showGridlines = false
])
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
revA = [85000, 92000, 88000, 105000, 118000, 124000]
revB = [62000, 68000, 71000, 79000, 85000, 91000]
revC = [43000, 47000, 45000, 52000, 58000, 63000]
doc.addLineChart(
"Monthly Revenue H1 2025",
months,
[
[:name = "Product A", :values = revA, :color = "4472C4"],
[:name = "Product B", :values = revB, :color = "ED7D31"],
[:name = "Product C", :values = revC, :color = "70AD47"]
],
[:smooth = true, :yAxisTitle = "Revenue (USD)"])
doc.addCaption("Figure 8 -- H1 revenue (preset provides widthCm, heightCm, legendPos, yAxisFormat etc.)")
doc.addEmptyParagraph()
# Summary table with conditional formatting
doc.addTable([
["Month", "Product A", "Product B", "Product C", "Total", "vs Target"],
["Jan", "$85,000", "$62,000", "$43,000", "$190,000", "-5.0%"],
["Feb", "$92,000", "$68,000", "$47,000", "$207,000", "+2.5%"],
["Mar", "$88,000", "$71,000", "$45,000", "$204,000", "+1.0%"],
["Apr", "$105,000", "$79,000", "$52,000", "$236,000", "+17.4%"],
["May", "$118,000", "$85,000", "$58,000", "$261,000", "+8.3%"],
["Jun", "$124,000", "$91,000", "$63,000", "$278,000", "+12.1%"]
], [
:headerRow = true,
:headerBgColor = "1F3864",
:evenRowBgColor = "F5F8FF",
:borderStyle = "single",
:colWidths = [2.0, 3.0, 3.0, 3.0, 3.0, 3.0],
:conditionalRules = [
# vs Target: negative = red, positive = green
[:col = 6, :condition = "contains", :value = "-",
:bgColor = "FDECEA", :textColor = "C00000"],
[:col = 6, :condition = "contains", :value = "+",
:bgColor = "E2EFDA", :textColor = "375623"]
]
])
doc.addCaption("Table 5 -- Monthly summary: vs Target column coloured by sign")
doc.addEmptyParagraph()
doc.clearChartDefaults()
# ---- Save -------------------------------------------------------------------
? "Building document ..."
doc.save("demo_charts4.docx")
? "Done -- demo_charts4.docx"part3_shapes.ring#
samples/UsingDOCXLib/part3_shapes.ring
/*
DOCXLib - Demo (Shapes)
*/
load "docxlib.ring"
doc = new WordWriter()
doc.setTitle("Drawing Shapes Demo")
doc.setAuthor("Mahmoud")
doc.setPageSize("a4")
doc.setHeader("DOCXLib - Drawing Shapes")
doc.showPageNumbers("right")
doc.addHeading("Drawing Shapes", 1)
doc.addParagraph("Inline DrawingML shapes with fill, border, and text.", NULL)
doc.addParagraph("", NULL)
# -- Rectangles --
doc.addHeading("Rectangles", 2)
doc.addRect([:width=6, :height=1.4, :fillColor="1E6BB5", :lineColor="0D4A8A",
:text="Standard Rectangle", :textColor="FFFFFF"])
doc.addParagraph("", NULL)
doc.addRect([:width=6, :height=1.4, :fillColor="E2EFDA", :lineColor="375623",
:lineWidth=2, :text="Rounded Rectangle", :textColor="375623", :rounded=true])
doc.addParagraph("", NULL)
doc.addRect([:width=6, :height=1.4, :noFill=true, :lineColor="C00000",
:lineWidth=2, :text="No Fill - Border Only", :textColor="C00000"])
doc.addParagraph("", NULL)
# -- Ellipses --
doc.addHeading("Ellipses", 2)
doc.addEllipse([:width=6, :height=1.8, :fillColor="7030A0", :lineColor="4B0082",
:text="Ellipse Shape", :textColor="FFFFFF"])
doc.addParagraph("", NULL)
doc.addEllipse([:width=2.5, :height=2.5, :fillColor="ED7D31", :lineColor="C55A11",
:text="Circle", :textColor="FFFFFF", :textBold=true, :textSize=14])
doc.addParagraph("", NULL)
# -- Other shapes --
doc.addHeading("Diamond and Triangle", 2)
doc.addDiamond([:width=5, :height=2.2, :fillColor="FFC000", :lineColor="C09000",
:text="Diamond", :textColor="000000"])
doc.addParagraph("", NULL)
doc.addShape("triangle", [:width=5, :height=2.2, :fillColor="C00000", :lineColor="8B0000",
:text="Triangle", :textColor="FFFFFF"])
doc.addParagraph("", NULL)
# -- Lines --
doc.addHeading("Horizontal Lines", 2)
doc.addLine([:width=14, :height=0.08, :fillColor="1E6BB5", :noBorder=true])
doc.addParagraph("", NULL)
doc.addLine([:width=14, :height=0.20, :fillColor="ED7D31", :noBorder=true])
doc.addParagraph("", NULL)
doc.addLine([:width=14, :height=0.08, :fillColor="595959", :noBorder=true])
filename = "demo_shapes.docx"
if doc.save(filename)
? "OK - Saved: " + filename
else
? "ERROR - Failed to save"
okpart4_watermark.ring#
samples/UsingDOCXLib/part4_watermark.ring
/*
DOCXLib - Demo (Watermark)
*/
load "docxlib.ring"
/*
Demonstrates text watermark support:
1. Simple "DRAFT" watermark with default styling
2. Custom text, color, opacity, rotation and font
3. Watermark combined with header/footer text
*/
# -- Demo 1: Default "DRAFT" watermark ---------------------------------------
doc1 = new WordWriter()
doc1.setTitle("Watermark Demo 1 – Default DRAFT")
doc1.setWatermarkText("DRAFT")
doc1.addHeading("Invoice #1042", 1)
doc1.addParagraph("Date: 2026-05-01", NULL)
doc1.addParagraph("Bill To: Acme Corporation", NULL)
doc1.addParagraph("Amount Due: $4,500.00", NULL)
doc1.addParagraph("This document is still a draft and has not been finalised.", NULL)
if doc1.save("demo_watermark_draft.docx")
? "Created: demo_watermark_draft.docx"
else
? "Error creating demo_watermark_draft.docx"
ok
# -- Demo 2: Custom watermark (CONFIDENTIAL, red, 40% opacity) ---------------
doc2 = new WordWriter()
doc2.setTitle("Watermark Demo 2 – Confidential")
doc2.setWatermark("CONFIDENTIAL", [
:color = "FF4444",
:opacity = 40,
:rotation = -45,
:font = "Arial",
:size = 80
])
doc2.addHeading("Q3 Financial Report", 1)
doc2.addParagraph("Revenue: $12,300,000", NULL)
doc2.addParagraph("Expenses: $8,750,000", NULL)
doc2.addParagraph("Net Profit: $3,550,000", NULL)
doc2.addParagraph("This report contains sensitive financial information.", NULL)
if doc2.save("demo_watermark_confidential.docx")
? "Created: demo_watermark_confidential.docx"
else
? "Error creating demo_watermark_confidential.docx"
ok
# -- Demo 3: Watermark + header text + footer + page numbers -----------------
doc3 = new WordWriter()
doc3.setTitle("Watermark Demo 3 – Combined")
doc3.setHeader("Acme Corp – Internal Use Only")
doc3.setFooter("Strictly Confidential")
doc3.showPageNumbers("center")
doc3.setWatermark("INTERNAL", [
:color = "AAAAAA",
:opacity = 35,
:font = "Calibri"
])
doc3.addHeading("Project Alpha – Status Update", 1)
doc3.addParagraph("This memo combines a watermark with a custom header and footer.", NULL)
doc3.addParagraph("The watermark appears on every page alongside the regular header.", NULL)
doc3.addBulletList(["Milestone 1 – Complete", "Milestone 2 – In Progress", "Milestone 3 – Pending"])
doc3.addPageBreak()
doc3.addHeading("Appendix", 2)
doc3.addParagraph("Supporting data on page 2 also carries the watermark.", NULL)
if doc3.save("demo_watermark_combined.docx")
? "Created: demo_watermark_combined.docx"
else
? "Error creating demo_watermark_combined.docx"
ok
# -- Demo 4: Diagonal variation – 0° (horizontal watermark) ------------------
doc4 = new WordWriter()
doc4.setTitle("Watermark Demo 4 – Horizontal")
doc4.setWatermark("DO NOT COPY", [
:color = "CCCCCC",
:opacity = 60,
:rotation = 0,
:font = "Times New Roman",
:size = 60
])
doc4.addHeading("Certificate of Completion", 1)
doc4.addParagraph("Awarded to: John Smith", [:bold = true])
doc4.addParagraph("Course: Advanced Ring Programming", NULL)
doc4.addParagraph("Date: May 2026", NULL)
if doc4.save("demo_watermark_horizontal.docx")
? "Created: demo_watermark_horizontal.docx"
else
? "Error creating demo_watermark_horizontal.docx"
ok
? ""
? "All watermark demos created successfully."part4_watermark2.ring#
samples/UsingDOCXLib/part4_watermark2.ring
/*
DOCXLib - Demo (Watermark2)
*/
load "docxlib.ring"
/*
Demonstrates setImageWatermark() with:
1. PNG image watermark – default size and opacity
2. JPG image watermark – custom size and lower opacity
3. BMP image watermark – small size, full opacity
4. Image watermark combined with header text and footer
5. Image watermark combined with a text watermark (both at once)
6. removeImageWatermark() – disable mid-build (doc without watermark)
*/
# -- Demo 1: PNG – default size (15 × 15 cm) and opacity (50%) ---------------
doc1 = new WordWriter()
doc1.setTitle("Image Watermark – PNG Default")
doc1.setAuthor("DOCXLib Demo")
doc1.setImageWatermark("images/test1.png", NULL)
doc1.addHeading("Image Watermark – PNG (Default Settings)", 1)
doc1.addParagraph("This document uses a PNG image as a watermark.", NULL)
doc1.addParagraph("Default settings: 15 cm × 15 cm, 50 % opacity, centred on every page.", NULL)
doc1.addParagraph("The watermark is anchored inside the header so it repeats automatically on every page.", NULL)
doc1.addLineBreak()
doc1.addParagraph("Body text sits on top of the watermark because the image shape has a negative z-index (-251653120), which places it behind the document text layer.", NULL)
doc1.addPageBreak()
doc1.addHeading("Page 2 – Watermark Repeats", 2)
doc1.addParagraph("The image watermark is visible here too – it is part of the page header, so Word renders it on every page automatically.", NULL)
if doc1.save("demo_watermark2_png_default.docx")
? "Created: demo_watermark2_png_default.docx"
else
? "Error creating demo_watermark2_png_default.docx"
ok
# -- Demo 2: JPG – custom size and opacity ------------------------------------
doc2 = new WordWriter()
doc2.setTitle("Image Watermark – JPG Custom")
doc2.setAuthor("DOCXLib Demo")
doc2.setImageWatermark("images/test2.jpg", [
:width = 10, # 10 cm wide
:height = 10, # 10 cm tall
:opacity = 30 # 30 % opacity – very faint
])
doc2.addHeading("Image Watermark – JPG (Custom Size & Opacity)", 1)
doc2.addParagraph("This document uses a JPG image watermark with custom settings.", NULL)
doc2.addParagraph("Settings: 10 cm × 10 cm, 30 % opacity.", NULL)
doc2.addLineBreak()
doc2.addParagraph("A lower opacity value makes the watermark less intrusive, which is useful when the document content needs to remain easy to read.", NULL)
doc2.addHeading("Table with Image Watermark", 2)
doc2.addSimpleTable([
["Product", "Qty", "Unit Price", "Total"],
["Widget A", "10", "$5.00", "$50.00"],
["Widget B", "25", "$3.50", "$87.50"],
["Widget C", "5", "$12.00", "$60.00"],
["", "", "Grand Total","$197.50"]
])
if doc2.save("demo_watermark2_jpg_custom.docx")
? "Created: demo_watermark2_jpg_custom.docx"
else
? "Error creating demo_watermark2_jpg_custom.docx"
ok
# -- Demo 3: BMP – small logo stamp, full opacity -----------------------------
doc3 = new WordWriter()
doc3.setTitle("Image Watermark – BMP Small Logo")
doc3.setAuthor("DOCXLib Demo")
doc3.setImageWatermark("images/test3.bmp", [
:width = 6, # 6 cm wide – smaller stamp-style
:height = 6,
:opacity = 100 # full opacity – stamp effect
])
doc3.addHeading("Image Watermark – BMP (Small Stamp, Full Opacity)", 1)
doc3.addParagraph("A BMP image is used here at full opacity (100 %) with a small 6 × 6 cm size.", NULL)
doc3.addParagraph("This produces a logo-stamp effect rather than a washed-out background watermark.", NULL)
doc3.addHeading("Use Cases", 2)
doc3.addBulletList([
"Company logo stamped on internal memos",
"Approval stamp on signed documents",
"Brand mark on certificates"
])
if doc3.save("demo_watermark2_bmp_stamp.docx")
? "Created: demo_watermark2_bmp_stamp.docx"
else
? "Error creating demo_watermark2_bmp_stamp.docx"
ok
# -- Demo 4: Image watermark + header text + footer + page numbers -------------
doc4 = new WordWriter()
doc4.setTitle("Image Watermark + Header/Footer")
doc4.setAuthor("DOCXLib Demo")
doc4.setHeader("Acme Corporation – Confidential")
doc4.setFooter("Internal Use Only")
doc4.showPageNumbers("center")
doc4.setImageWatermark("images/test1.png", [
:width = 12,
:height = 12,
:opacity = 40
])
doc4.addHeading("Combined: Image Watermark + Header + Footer", 1)
doc4.addParagraph("This document demonstrates that an image watermark coexists correctly with a custom header text, footer text, and page numbers.", NULL)
doc4.addParagraph("The header text 'Acme Corporation – Confidential' appears at the top, the image watermark floats behind the page content, and the footer shows page numbers.", NULL)
doc4.addPageBreak()
doc4.addHeading("Second Page", 2)
doc4.addParagraph("All three elements – header, watermark, and footer – repeat on this page too.", NULL)
if doc4.save("demo_watermark2_combined_header_footer.docx")
? "Created: demo_watermark2_combined_header_footer.docx"
else
? "Error creating demo_watermark2_combined_header_footer.docx"
ok
# -- Demo 5: Image watermark + text watermark simultaneously ------------------
doc5 = new WordWriter()
doc5.setTitle("Image + Text Watermark Together")
doc5.setAuthor("DOCXLib Demo")
# Text watermark at 25 % opacity so the image behind it is still visible
doc5.setWatermark("DRAFT", [
:color = "CC0000",
:opacity = 25,
:rotation = -45
])
# Image watermark at 20 % – very faint so the text watermark dominates
doc5.setImageWatermark("images/test2.jpg", [
:width = 14,
:height = 14,
:opacity = 20
])
doc5.addHeading("Image Watermark + Text Watermark (Layered)", 1)
doc5.addParagraph("Both a text watermark ('DRAFT' in red) and an image watermark (images/test2.jpg, 20 % opacity) are active on this page.", NULL)
doc5.addParagraph("The image watermark uses z-index -251653120 and is emitted before the text watermark paragraph in the header XML, so it sits furthest behind the text layer.", NULL)
doc5.addParagraph("The text watermark sits in front of the image watermark but still behind the body text.", NULL)
if doc5.save("demo_watermark2_image_and_text.docx")
? "Created: demo_watermark2_image_and_text.docx"
else
? "Error creating demo_watermark2_image_and_text.docx"
ok
# -- Demo 6: removeImageWatermark() – build with watermark then remove it ------
doc6 = new WordWriter()
doc6.setTitle("removeImageWatermark Demo")
doc6.setAuthor("DOCXLib Demo")
# Enable image watermark …
doc6.setImageWatermark("images/test1.png", [:opacity = 50])
# … then remove it before saving
doc6.removeImageWatermark()
doc6.addHeading("removeImageWatermark() Demo", 1)
doc6.addParagraph("setImageWatermark() was called with images/test1.png, but removeImageWatermark() was called immediately after.", NULL)
doc6.addParagraph("The saved document should have NO watermark – a clean page.", NULL)
if doc6.save("demo_watermark2_removed.docx")
? "Created: demo_watermark2_removed.docx"
else
? "Error creating demo_watermark2_removed.docx"
ok
? ""
? "All image watermark demos created successfully."part5_bordersandrtl.ring#
samples/UsingDOCXLib/part5_bordersandrtl.ring
/*
DOCXLib - Demo (BordersAndRTL)
*/
load "docxlib.ring"
/*
Demonstrates:
1. setSimplePageBorder()
2. setPageBorder() with custom style, color, size
3. Decorative / artistic border styles
4. Per-side borders (top + bottom only, left only, ...)
5. removePageBorder()
6. RTL paragraph-level (mixed LTR/RTL in one document)
7. RTL run-level (inline bidi with Arabic/Hebrew font)
8. setDocumentRTL() – full document default RTL
9. RTL + page border combined
*/
# ============================================================================
# Demo 1 – Simple page border (all four sides, single 3pt black line)
# ============================================================================
doc1 = new WordWriter()
doc1.setTitle("Page Borders – Simple")
doc1.setAuthor("RingWordLib Demo")
doc1.setSimplePageBorder()
doc1.addHeading("Simple Page Border", 1)
doc1.addParagraph("This document has a thin single-line black border on all four sides, applied using setSimplePageBorder() – the zero-configuration shortcut.", NULL)
doc1.addLineBreak()
doc1.addParagraph("The border is declared inside <w:sectPr> / <w:pgBorders> with offsetFrom='page', which means it is measured from the page edge rather than the text area.", NULL)
doc1.addHeading("Usage", 2)
doc1.addBulletList([
"doc.setSimplePageBorder() – one-line setup",
"doc.removePageBorder() – remove at any time",
"doc.setPageBorder([...]) – full control over all options"
])
if doc1.save("demo_bordersandrtl_1_simple.docx")
? "Created: demo_bordersandrtl_1_simple.docx"
else
? "Error: demo_bordersandrtl_1_simple.docx"
ok
# ============================================================================
# Demo 2 – Custom border: thick, colored, further from edge
# ============================================================================
doc2 = new WordWriter()
doc2.setTitle("Page Borders – Custom Thick Color")
doc2.setAuthor("RingWordLib Demo")
doc2.setPageBorder([
:style = "single",
:color = "2E74B5", # Blue
:size = 6, # 6pt thick
:space = 36 # 36pt from page edge
])
doc2.addHeading("Custom Page Border – Thick Blue", 1)
doc2.addParagraph("A 6-point thick blue border (color #2E74B5) set 36 points from the page edge.", NULL)
doc2.addParagraph("The :size option accepts points and is converted internally to OOXML eighths-of-a-point (1 pt = 8 units).", NULL)
doc2.addLineBreak()
doc2.addSimpleTable([
["Option", "Value", "Effect"],
[":style", "single", "Solid line border"],
[":color", "2E74B5", "Microsoft blue"],
[":size", "6", "6pt = 48 eighths"],
[":space", "36", "36pt from page edge"]
])
if doc2.save("demo_bordersandrtl_2_custom_color.docx")
? "Created: demo_bordersandrtl_2_custom_color.docx"
else
? "Error: demo_bordersandrtl_2_custom_color.docx"
ok
# ============================================================================
# Demo 3 – Decorative border styles
# ============================================================================
doc3 = new WordWriter()
doc3.setTitle("Page Borders – Decorative Styles")
doc3.setAuthor("RingWordLib Demo")
doc3.setPageBorder([
:style = "wave",
:color = "70AD47", # Green
:size = 6,
:space = 20
])
doc3.addHeading("Decorative Border – Wave", 1)
doc3.addParagraph("This document uses the 'wave' border style in green. Many decorative styles are available in the OOXML specification.", NULL)
doc3.addLineBreak()
doc3.addParagraph("Style name reference:", NULL)
doc3.addBulletList([
"single – standard thin line",
"double – two parallel lines",
"triple – three parallel lines",
"thick – single thick line",
"dashed – dashed line",
"dotted – dotted line",
"wave – wavy line",
"doubleWave – double wavy line",
"thinThickSmallGap – thin outer, thick inner",
"thickThinSmallGap – thick outer, thin inner",
"threeDEmboss – 3-D embossed effect",
"threeDEngrave – 3-D engraved effect",
"inset – inset shadow",
"outset – outset shadow"
])
if doc3.save("demo_bordersandrtl_3_wave.docx")
? "Created: demo_bordersandrtl_3_wave.docx"
else
? "Error: demo_bordersandrtl_3_wave.docx"
ok
# ============================================================================
# Demo 4 – Per-side borders (top and bottom only)
# ============================================================================
doc4 = new WordWriter()
doc4.setTitle("Page Borders – Top and Bottom Only")
doc4.setAuthor("RingWordLib Demo")
doc4.setPageBorder([
:style = "double",
:color = "C00000", # Dark red
:size = 4,
:space = 24,
:sides = ["top", "bottom"]
])
doc4.addHeading("Per-Side Borders – Top & Bottom Only", 1)
doc4.addParagraph("Only the top and bottom edges have a double red border. The left and right edges are plain.", NULL)
doc4.addParagraph("Use the :sides list to specify any combination of 'top', 'left', 'bottom', 'right'.", NULL)
doc4.addLineBreak()
doc4.addHeading("Other useful combinations", 2)
doc4.addBulletList([
'["top"] – header underline effect',
'["top", "bottom"] – newspaper-style rules',
'["left"] – sidebar accent',
'["top", "left", "right"] – three-sided frame'
])
if doc4.save("demo_bordersandrtl_4_top_bottom.docx")
? "Created: demo_bordersandrtl_4_top_bottom.docx"
else
? "Error: demo_bordersandrtl_4_top_bottom.docx"
ok
# ============================================================================
# Demo 5 – removePageBorder (set then remove before saving)
# ============================================================================
doc5 = new WordWriter()
doc5.setTitle("Page Borders – Remove Demo")
doc5.setAuthor("RingWordLib Demo")
doc5.setSimplePageBorder() # enabled ...
doc5.removePageBorder() # ... then removed
doc5.addHeading("removePageBorder() Demo", 1)
doc5.addParagraph("setSimplePageBorder() was called, then removePageBorder() was called immediately after. The saved file has no page border.", NULL)
if doc5.save("demo_bordersandrtl_5_removed.docx")
? "Created: demo_bordersandrtl_5_removed.docx"
else
? "Error: demo_bordersandrtl_5_removed.docx"
ok
# ============================================================================
# Demo 6 – RTL paragraph-level (mixed LTR + RTL in one document)
# ============================================================================
doc6 = new WordWriter()
doc6.setTitle("RTL Demo – Paragraph Level")
doc6.setAuthor("RingWordLib Demo")
doc6.addHeading("Paragraph-Level RTL / BiDi", 1)
doc6.addParagraph("This document is LTR by default. Individual paragraphs can be switched to RTL using the :rtl option.", NULL)
doc6.addHeading("Normal LTR Paragraphs", 2)
doc6.addParagraph("This is a normal left-to-right paragraph in English.", NULL)
doc6.addParagraph("Second LTR paragraph. Text flows from left to right.", NULL)
doc6.addHeading("RTL Paragraphs (Arabic placeholder text)", 2)
# RTL paragraphs – using the convenience wrapper
doc6.addRTLParagraph("هذه فقرة باللغة العربية تسير من اليمين إلى اليسار.", NULL)
doc6.addRTLParagraph("البرمجة بلغة رينج سهلة وممتعة.", NULL)
# RTL paragraph – manually via addParagraph with options
doc6.addParagraph("النص العربي يُظهر الاتجاه الصحيح من اليمين إلى اليسار.",
[:rtl = true, :align = "right"])
doc6.addHeading("Hebrew placeholder text", 2)
doc6.addRTLParagraph("זהו טקסט לדוגמה בעברית הנכתב מימין לשמאל.", NULL)
doc6.addHeading("Mixed BiDi in a Rich Paragraph", 2)
doc6.addParagraph("A rich paragraph can mix LTR and RTL runs. The Unicode Bidirectional Algorithm handles display direction automatically, but explicit run-level :rtl marks help Word render it correctly.", NULL)
# Rich paragraph with one LTR run followed by one RTL run
doc6.addRichParagraph([
["English text on the left | ", [:bold = true]],
["النص العربي على اليمين", [:rtl = true, :csFont = "Arial"]]
], [:rtl = true])
doc6.addHeading(":ltr Option – Force LTR Inside RTL Context", 2)
doc6.addParagraph("When the document or paragraph is RTL, use :ltr=true to force a specific paragraph back to left-to-right:", NULL)
doc6.addParagraph("This paragraph is explicitly LTR even if the document defaults were changed.", [:ltr = true, :align = "left"])
if doc6.save("demo_bordersandrtl_6_paragraph_level.docx")
? "Created: demo_bordersandrtl_6_paragraph_level.docx"
else
? "Error: demo_bordersandrtl_6_paragraph_level.docx"
ok
# ============================================================================
# Demo 7 – RTL run-level with complex-script font (:csFont)
# ============================================================================
doc7 = new WordWriter()
doc7.setTitle("RTL Demo – Run Level & csFont")
doc7.setAuthor("RingWordLib Demo")
doc7.addHeading("Run-Level RTL and Complex-Script Font", 1)
doc7.addParagraph("The :rtl and :csFont options work at the individual run level inside addRichParagraph, giving full control over mixed-script inline text.", NULL)
doc7.addHeading("Inline Arabic within English Sentence", 2)
doc7.addRichParagraph([
["The Arabic word for 'hello' is ", NULL],
["مرحبا", [:rtl = true, :csFont = "Arial", :bold = true]],
[" and for 'thank you' is ", NULL],
["شكراً", [:rtl = true, :csFont = "Arial", :bold = true]],
[".", NULL]
], NULL)
doc7.addHeading("Inline Hebrew within English Sentence", 2)
doc7.addRichParagraph([
["The Hebrew word for 'peace' is ", NULL],
["שָׁלוֹם", [:rtl = true, :csFont = "David", :bold = true, :color = "2E74B5"]],
[" (shalom).", NULL]
], NULL)
doc7.addHeading("csFont without rtl – Complex-Script Font Only", 2)
doc7.addParagraph("Use :csFont alone (without :rtl) to set the complex-script font for a run that contains both LTR text and characters that need a specific CS font rendering.", NULL)
doc7.addRichParagraph([
["Normal font run then ", NULL],
["مرحبا (Arabic) rendered with Times New Roman CS", [:csFont = "Times New Roman"]]
], NULL)
doc7.addHeading("Combining :font and :csFont", 2)
doc7.addRichParagraph([
["You can specify both the LTR font and CS font in the same run: ", NULL],
["Hello مرحبا", [:font = "Georgia", :csFont = "Arial", :rtl = false]]
], NULL)
if doc7.save("demo_bordersandrtl_7_run_level.docx")
? "Created: demo_bordersandrtl_7_run_level.docx"
else
? "Error: demo_bordersandrtl_7_run_level.docx"
ok
# ============================================================================
# Demo 8 – setDocumentRTL() – full document RTL default
# Every paragraph, heading, and list item is automatically RTL.
# No :rtl=true needed on individual paragraphs.
# ============================================================================
doc8 = new WordWriter()
doc8.setTitle("مستند عربي بالكامل")
doc8.setAuthor("RingWordLib Demo")
doc8.showPageNumbers("right")
doc8.setPageBorder([
:style = "single",
:color = "1F4E79",
:size = 3,
:space = 24
])
# One call flips the entire document to RTL
doc8.setDocumentRTL(true)
doc8.addHeading("مستند عربي بالكامل", 1)
doc8.addParagraph("هذا المستند تم تعيينه ليكون من اليمين إلى اليسار على مستوى الوثيقة بأكملها باستخدام setDocumentRTL(true). لاحظ أن جميع الفقرات تبدأ من الجانب الأيمن للصفحة.", NULL)
doc8.addParagraph("لا حاجة إلى إضافة الخيار :rtl = true في كل فقرة على حدة — فور تفعيل setDocumentRTL يصبح الاتجاه الافتراضي من اليمين إلى اليسار لجميع المحتوى.", NULL)
doc8.addHeading("قائمة بالنقاط", 2)
doc8.addBulletList([
"العنصر الأول في القائمة",
"العنصر الثاني في القائمة",
"العنصر الثالث في القائمة"
])
doc8.addHeading("قائمة مرقمة", 2)
doc8.addNumberedList([
"الخطوة الأولى",
"الخطوة الثانية",
"الخطوة الثالثة"
])
doc8.addHeading("فقرة محاذاة للوسط", 2)
doc8.addParagraph("هذه الفقرة محاذاة للوسط داخل مستند RTL.", [:align = "center"])
doc8.addHeading("إجبار فقرة على الاتجاه LTR داخل مستند RTL", 2)
doc8.addParagraph("This paragraph is forced LTR using :ltr=true — even inside a full RTL document.",
[:ltr = true])
doc8.addHeading("نص مختلط (عربي + إنجليزي)", 2)
doc8.addRichParagraph([
["هذه الجملة تحتوي على ", NULL],
["English words", [:ltr = true, :bold = true]],
[" داخل نص عربي.", NULL]
], NULL)
if doc8.save("demo_bordersandrtl_8_document_level.docx")
? "Created: demo_bordersandrtl_8_document_level.docx"
else
? "Error: demo_bordersandrtl_8_document_level.docx"
ok
# ============================================================================
# Demo 9 – RTL + page border combined
# ============================================================================
doc9 = new WordWriter()
doc9.setTitle("RTL + Page Border Combined")
doc9.setAuthor("RingWordLib Demo")
doc9.setDocumentRTL(true)
doc9.setPageBorder([
:style = "double",
:color = "1F5C2E", # Dark green
:size = 4,
:space = 20
])
doc9.addHeading("مستند عربي مع إطار الصفحة", 1)
doc9.addParagraph("هذا المستند يجمع بين الاتجاه من اليمين إلى اليسار وإطار الصفحة المزدوج باللون الأخضر الداكن.", NULL)
doc9.addParagraph("يمكن الجمع بين أي ميزات المكتبة بحرية تامة: الاتجاه، الإطارات، العلامات المائية، الهوامش المخصصة وغيرها.", NULL)
doc9.addHeading("English section inside RTL doc", 2)
doc9.addParagraph("This English paragraph is forced LTR using :ltr=true.",
[:ltr = true, :align = "left"])
doc9.addRichParagraph([
["Mixed: English ", [:ltr = true]],
["عربي", [:rtl = true, :csFont = "Arial", :bold = true]],
[" English again", [:ltr = true]]
], [:ltr = true])
if doc9.save("demo_bordersandrtl_9_combined_border.docx")
? "Created: demo_bordersandrtl_9_combined_border.docx"
else
? "Error: demo_bordersandrtl_9_combined_border.docx"
ok
# ============================================================================
# Summary
# ============================================================================
? ""
? "All demos created successfully."part6_richcells.ring#
samples/UsingDOCXLib/part6_richcells.ring
/*
DOCXLib - Demo (RichCells)
*/
load "docxlib.ring"
/*
Demonstrates the WordCell feature for full control
over table cell contents: formatted text, images, alignment,
background colors, column spanning, vertical alignment, etc.
*/
? "=============================================="
? " DOCXLib - Rich Table Cells Demos"
? "=============================================="
? ""
# =====================================================================
# Demo 1: Formatted Text in Cells
# =====================================================================
? "Demo 1: Table with formatted text in cells..."
doc = new WordWriter()
doc.setTitle("Rich Table Cells - Formatted Text")
doc.setAuthor("Ring Programmer")
doc.addHeading("Formatted Text in Table Cells", 1)
doc.addParagraph("Each cell can have its own font, size, color, and style.", NULL)
tableData = [
[
wordCell("Name", [:bold = true, :align = "center"]),
wordCell("Description", [:bold = true, :align = "center"]),
wordCell("Status", [:bold = true, :align = "center"])
],
[
wordCell("Ring Language", [:bold = true, :color = "blue", :font = "Arial"]),
wordCell("A practical general-purpose programming language", [:italic = true]),
wordCell("Active", [:bold = true, :color = "green", :align = "center"])
],
[
wordCell("PWCT", [:bold = true, :color = "purple", :font = "Arial"]),
wordCell("Programming Without Coding Technology", [:italic = true]),
wordCell("Active", [:bold = true, :color = "green", :align = "center"])
],
[
wordCell("Supernova", [:bold = true, :color = "orange", :font = "Arial"]),
wordCell("A domain-specific programming language", [:italic = true]),
wordCell("In Development", [:bold = true, :color = "orange", :align = "center"])
]
]
doc.addTable(tableData, [:borderStyle = "single", :headerVAlign = "center", :cellVAlign = "center"])
if doc.save("demo_richcell_1_formatted_text.docx")
? " Created: demo_richcell_1_formatted_text.docx"
else
? " FAILED: demo_richcell_1_formatted_text.docx"
ok
# =====================================================================
# Demo 2: Multi-Run Rich Text in Cells
# =====================================================================
? "Demo 2: Table with multi-run rich text in cells..."
doc = new WordWriter()
doc.setTitle("Rich Table Cells - Multi-Run Text")
doc.addHeading("Multiple Text Styles in One Cell", 1)
doc.addParagraph("A single cell can contain multiple text runs with different formatting.", NULL)
# Build cells with multiple runs
cell1 = new WordCell()
cell1.addRun("Feature", [:bold = true, :size = 14])
cell1.setAlign("center")
cell1.setBgColor("1565C0")
cell2 = new WordCell()
cell2.addRun("Details", [:bold = true, :size = 14])
cell2.setAlign("center")
cell2.setBgColor("1565C0")
cell3 = new WordCell()
cell3.addRun("Bold text, ", [:bold = true])
cell3.addRun("italic text, ", [:italic = true])
cell3.addRun("and ", [])
cell3.addRun("colored text", [:color = "red"])
cell3.addRun(" all in one cell!", [])
cell4 = new WordCell()
cell4.addRun("Mixed formatting: ", [])
cell4.addRun("Font sizes ", [:size = 8])
cell4.addRun("can vary ", [:size = 12])
cell4.addRun("within ", [:size = 16])
cell4.addRun("a cell", [:size = 20])
cell5 = new WordCell()
cell5.addRun("Ring", [:bold = true, :color = "blue", :size = 16, :font = "Georgia"])
cell5.addRun(" is ", [:size = 11])
cell5.addRun("awesome!", [:bold = true, :italic = true, :color = "green", :size = 14])
cell6 = new WordCell()
cell6.addRun("Underline", [:underline = true])
cell6.addRun(" + ", [])
cell6.addRun("Strikethrough", [:strike = true])
cell6.addRun(" + ", [])
cell6.addRun("Highlight", [:highlight = "yellow"])
tableData = [
[cell1, cell2],
[cell3, cell4],
[cell5, cell6]
]
doc.addTable(tableData, [:borderStyle = "single"])
if doc.save("demo_richcell_2_multirun.docx")
? " Created: demo_richcell_2_multirun.docx"
else
? " FAILED: demo_richcell_2_multirun.docx"
ok
# =====================================================================
# Demo 3: Vertical Centering in Tables
# =====================================================================
? "Demo 3: Table with vertical centering..."
doc = new WordWriter()
doc.setTitle("Rich Table Cells - Vertical Centering")
doc.addHeading("Vertical Centering in Tables", 1)
# --- Table 1: Using headerHeight + headerVAlign (plain strings) ---
doc.addHeading("Table-Level Vertical Centering (Plain Strings)", 2)
doc.addParagraph("Using headerHeight to make header taller, headerVAlign to center text:", NULL)
doc.addTable([
["Feature", "Ring", "Python", "Java"],
["Dynamic Typing", "YES", "YES", "NO"],
["Object-Oriented", "YES", "YES", "YES"],
["PWCT2", "YES", "NO", "NO"]
], [
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "37474F",
:headerHeight = 720,
:headerVAlign = "center",
:cellVAlign = "center"
])
# --- Table 2: Per-cell vertical alignment with tall rows ---
doc.addHeading("Per-Cell Vertical Alignment (Top / Center / Bottom)", 2)
doc.addParagraph("A tall reference cell shows the difference between top, center, and bottom:", NULL)
# Tall cell
tallCell = new WordCell()
tallCell.addRun("Line 1", [:bold = true])
tallCell.addLineBreak()
tallCell.addRun("Line 2", [])
tallCell.addLineBreak()
tallCell.addRun("Line 3", [])
tallCell.addLineBreak()
tallCell.addRun("Line 4", [])
tallCell.addLineBreak()
tallCell.addRun("Line 5", [])
tallCell.addLineBreak()
tallCell.addRun("Line 6", [:italic = true])
tallCell.setBgColor("F5F5F5")
topCell = new WordCell()
topCell.addRun("TOP", [:bold = true, :size = 14, :color = "red"])
topCell.setVerticalAlign("top")
topCell.setAlign("center")
topCell.setBgColor("FFEBEE")
centerCell = new WordCell()
centerCell.addRun("CENTER", [:bold = true, :size = 14, :color = "green"])
centerCell.setVerticalAlign("center")
centerCell.setAlign("center")
centerCell.setBgColor("E8F5E9")
bottomCell = new WordCell()
bottomCell.addRun("BOTTOM", [:bold = true, :size = 14, :color = "blue"])
bottomCell.setVerticalAlign("bottom")
bottomCell.setAlign("center")
bottomCell.setBgColor("E3F2FD")
# Headers
hRef = wordCell("Reference", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
hTop = wordCell("vAlign=top", [:bold = true, :color = "white", :bgColor = "C62828", :align = "center", :verticalAlign = "center"])
hCtr = wordCell("vAlign=center", [:bold = true, :color = "white", :bgColor = "2E7D32", :align = "center", :verticalAlign = "center"])
hBot = wordCell("vAlign=bottom", [:bold = true, :color = "white", :bgColor = "1565C0", :align = "center", :verticalAlign = "center"])
doc.addTable([
[hRef, hTop, hCtr, hBot],
[tallCell, topCell, centerCell, bottomCell]
], [:borderStyle = "single", :headerHeight = 600])
# --- Table 3: Styled table with headerHeight ---
doc.addHeading("Styled Table with Vertical Centering", 2)
doc.addTable([
["Product", "Category", "Price", "Stock"],
["Laptop Pro 15", "Electronics", "$1,299", "45"],
["Wireless Mouse", "Accessories", "$29", "500"],
["USB-C Hub", "Accessories", "$49", "200"],
["4K Monitor 27 inch", "Electronics", "$449", "78"]
], [
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "1565C0",
:evenRowBgColor = "E3F2FD",
:headerHeight = 700,
:headerVAlign = "center",
:cellVAlign = "center"
])
if doc.save("demo_richcell_3_alignment.docx")
? " Created: demo_richcell_3_alignment.docx"
else
? " FAILED: demo_richcell_3_alignment.docx"
ok
# =====================================================================
# Demo 4: Cell Background Colors
# =====================================================================
? "Demo 4: Table with custom cell background colors..."
doc = new WordWriter()
doc.setTitle("Rich Table Cells - Colors")
doc.addHeading("Cell Background Colors", 1)
doc.addParagraph("Each cell can have its own background color, independent of row-level styling.", NULL)
tableData = [
[
wordCell("Red", [:bold = true, :color = "white", :bgColor = "FF0000", :align = "center"]),
wordCell("Green", [:bold = true, :color = "white", :bgColor = "00AA00", :align = "center"]),
wordCell("Blue", [:bold = true, :color = "white", :bgColor = "0000FF", :align = "center"])
],
[
wordCell("Orange", [:bold = true, :bgColor = "FFA500", :align = "center"]),
wordCell("Purple", [:bold = true, :color = "white", :bgColor = "800080", :align = "center"]),
wordCell("Teal", [:bold = true, :color = "white", :bgColor = "008080", :align = "center"])
],
[
wordCell("Light Yellow", [:bgColor = "FFFFCC", :align = "center"]),
wordCell("Light Pink", [:bgColor = "FFCCCC", :align = "center"]),
wordCell("Light Blue", [:bgColor = "CCE5FF", :align = "center"])
],
[
wordCell("Gold", [:bold = true, :bgColor = "FFD700", :align = "center"]),
wordCell("Silver", [:bgColor = "C0C0C0", :align = "center"]),
wordCell("Coral", [:color = "white", :bgColor = "FF6B6B", :align = "center"])
]
]
doc.addTable(tableData, [:borderStyle = "single"])
if doc.save("demo_richcell_4_colors.docx")
? " Created: demo_richcell_4_colors.docx"
else
? " FAILED: demo_richcell_4_colors.docx"
ok
# =====================================================================
# Demo 5: Column Spanning (Merged Cells)
# =====================================================================
? "Demo 5: Table with merged cells (column span)..."
doc = new WordWriter()
doc.setTitle("Rich Table Cells - Column Spanning")
doc.addHeading("Column Spanning (Merged Cells)", 1)
doc.addParagraph("Cells can span multiple columns using setColSpan().", NULL)
# Title row spanning all 3 columns
titleCell = new WordCell()
titleCell.addRun("Quarterly Sales Report 2026", [:bold = true, :size = 16, :color = "white"])
titleCell.setAlign("center")
titleCell.setBgColor("1565C0")
titleCell.setColSpan(3)
# Header row
h1 = wordCell("Region", [:bold = true, :align = "center", :bgColor = "90CAF9"])
h2 = wordCell("Q1 Sales", [:bold = true, :align = "center", :bgColor = "90CAF9"])
h3 = wordCell("Q2 Sales", [:bold = true, :align = "center", :bgColor = "90CAF9"])
# Data rows
r1c1 = wordCell("North America", [:bold = true])
r1c2 = wordCell("$2.5M", [:align = "right"])
r1c3 = wordCell("$2.8M", [:align = "right", :color = "green"])
r2c1 = wordCell("Europe", [:bold = true])
r2c2 = wordCell("$1.8M", [:align = "right"])
r2c3 = wordCell("$2.1M", [:align = "right", :color = "green"])
r3c1 = wordCell("Asia Pacific", [:bold = true])
r3c2 = wordCell("$1.2M", [:align = "right"])
r3c3 = wordCell("$1.4M", [:align = "right", :color = "green"])
# Total row spanning
totalLabel = new WordCell()
totalLabel.addRun("Total Revenue", [:bold = true, :size = 12])
totalLabel.setAlign("right")
totalLabel.setBgColor("E3F2FD")
totalLabel.setColSpan(2)
totalValue = new WordCell()
totalValue.addRun("$11.8M", [:bold = true, :size = 14, :color = "1565C0"])
totalValue.setAlign("right")
totalValue.setBgColor("E3F2FD")
tableData = [
[titleCell, "", ""],
[h1, h2, h3],
[r1c1, r1c2, r1c3],
[r2c1, r2c2, r2c3],
[r3c1, r3c2, r3c3],
[totalLabel, "", totalValue]
]
doc.addTable(tableData, [:borderStyle = "single"])
if doc.save("demo_richcell_5_colspan.docx")
? " Created: demo_richcell_5_colspan.docx"
else
? " FAILED: demo_richcell_5_colspan.docx"
ok
# =====================================================================
# Demo 6: Line Breaks Within Cells
# =====================================================================
? "Demo 6: Table with line breaks in cells..."
doc = new WordWriter()
doc.setTitle("Rich Table Cells - Line Breaks")
doc.addHeading("Line Breaks Within Cells", 1)
doc.addParagraph("Cells can contain multiple lines of text using addLineBreak().", NULL)
# Header
h1 = wordCell("Contact", [:bold = true, :align = "center", :bgColor = "2E7D32", :color = "white"])
h2 = wordCell("Details", [:bold = true, :align = "center", :bgColor = "2E7D32", :color = "white"])
# Multi-line cells
contact1 = new WordCell()
contact1.addRun("Ahmed Hassan", [:bold = true, :size = 12])
contact1.addLineBreak()
contact1.addRun("Senior Developer", [:italic = true, :color = "gray"])
contact1.addLineBreak()
contact1.addRun("ahmed@example.com", [:color = "blue", :underline = true])
details1 = new WordCell()
details1.addRun("Department: ", [:bold = true])
details1.addRun("Engineering", [])
details1.addLineBreak()
details1.addRun("Office: ", [:bold = true])
details1.addRun("Building A, Room 301", [])
details1.addLineBreak()
details1.addRun("Phone: ", [:bold = true])
details1.addRun("+966 50 123 4567", [])
contact2 = new WordCell()
contact2.addRun("Sara Ali", [:bold = true, :size = 12])
contact2.addLineBreak()
contact2.addRun("Project Manager", [:italic = true, :color = "gray"])
contact2.addLineBreak()
contact2.addRun("sara@example.com", [:color = "blue", :underline = true])
details2 = new WordCell()
details2.addRun("Department: ", [:bold = true])
details2.addRun("Management", [])
details2.addLineBreak()
details2.addRun("Office: ", [:bold = true])
details2.addRun("Building B, Room 205", [])
details2.addLineBreak()
details2.addRun("Phone: ", [:bold = true])
details2.addRun("+966 50 987 6543", [])
tableData = [
[h1, h2],
[contact1, details1],
[contact2, details2]
]
doc.addTable(tableData, [:borderStyle = "single"])
if doc.save("demo_richcell_6_linebreaks.docx")
? " Created: demo_richcell_6_linebreaks.docx"
else
? " FAILED: demo_richcell_6_linebreaks.docx"
ok
# =====================================================================
# Demo 7: Cell Padding and Borders
# =====================================================================
? "Demo 7: Table with custom cell padding and borders..."
doc = new WordWriter()
doc.setTitle("Rich Table Cells - Padding and Borders")
doc.addHeading("Cell Padding and Individual Borders", 1)
doc.addParagraph("Cells can have custom padding and individual border styles.", NULL)
# Cell with large padding
padded = new WordCell()
padded.addRun("This cell has large padding (0.5cm all around)", [:size = 10])
padded.setPadding(0.5, 0.5, 0.5, 0.5)
padded.setBgColor("FFF9C4")
# Cell with custom border
bordered = new WordCell()
bordered.addRun("This cell has a red dashed border", [:bold = true])
bordered.setBorder("dashed", "FF0000")
bordered.setAlign("center")
# Cell with double border
doubleBorder = new WordCell()
doubleBorder.addRun("Double blue border", [:bold = true, :color = "blue"])
doubleBorder.setBorder("double", "0000FF")
doubleBorder.setAlign("center")
# Normal cell for comparison
normal = wordCell("Normal cell (default)", NULL)
tableData = [
[padded, bordered],
[doubleBorder, normal]
]
doc.addTable(tableData, [:borderStyle = "single"])
if doc.save("demo_richcell_7_padding_borders.docx")
? " Created: demo_richcell_7_padding_borders.docx"
else
? " FAILED: demo_richcell_7_padding_borders.docx"
ok
# =====================================================================
# Demo 8: Images in Table Cells
# =====================================================================
? "Demo 8: Table with images in cells..."
doc = new WordWriter()
doc.setTitle("Rich Table Cells - Images")
doc.addHeading("Images Inside Table Cells", 1)
doc.addParagraph("Images can be placed inside table cells alongside text.", NULL)
# Pre-register images with the document
img1Info = doc.registerImage("images/test1.png")
img2Info = doc.registerImage("images/test2.jpg")
img3Info = doc.registerImage("images/test3.bmp")
# Header
h1 = wordCell("Item", [:bold = true, :align = "center", :bgColor = "1565C0", :color = "white"])
h2 = wordCell("Preview", [:bold = true, :align = "center", :bgColor = "1565C0", :color = "white"])
h3 = wordCell("Details", [:bold = true, :align = "center", :bgColor = "1565C0", :color = "white"])
# Row 1
itemCell = new WordCell()
itemCell.addRun("Product A", [:bold = true, :size = 12])
itemCell.addLineBreak()
itemCell.addRun("SKU: PRD-001", [:size = 9, :color = "gray"])
itemCell.setVerticalAlign("center")
imageCell = new WordCell()
if len(img1Info[:relId]) > 0
imageCell.addCellImage("images/test1.png", 2, 2)
imageCell.setCellImageRel(1, img1Info[:relId], img1Info[:imageId])
else
imageCell.addRun("(images/test1.png not found)", [:color = "gray", :size = 9])
ok
imageCell.setAlign("center")
imageCell.setVerticalAlign("center")
detailsCell = new WordCell()
detailsCell.addRun("Price: ", [:bold = true])
detailsCell.addRun("$49.99", [:color = "green", :bold = true])
detailsCell.addLineBreak()
detailsCell.addRun("Stock: ", [:bold = true])
detailsCell.addRun("In Stock (150 units)", [])
detailsCell.setVerticalAlign("center")
# Row 2
itemCell2 = new WordCell()
itemCell2.addRun("Product B", [:bold = true, :size = 12])
itemCell2.addLineBreak()
itemCell2.addRun("SKU: PRD-002", [:size = 9, :color = "gray"])
itemCell2.setVerticalAlign("center")
imageCell2 = new WordCell()
if len(img2Info[:relId]) > 0
imageCell2.addCellImage("images/test2.jpg", 2, 2)
imageCell2.setCellImageRel(1, img2Info[:relId], img2Info[:imageId])
else
imageCell2.addRun("(images/test2.jpg not found)", [:color = "gray", :size = 9])
ok
imageCell2.setAlign("center")
imageCell2.setVerticalAlign("center")
detailsCell2 = new WordCell()
detailsCell2.addRun("Price: ", [:bold = true])
detailsCell2.addRun("$89.99", [:color = "green", :bold = true])
detailsCell2.addLineBreak()
detailsCell2.addRun("Stock: ", [:bold = true])
detailsCell2.addRun("Low Stock (12 units)", [:color = "red"])
detailsCell2.setVerticalAlign("center")
# Row 3
itemCell3 = new WordCell()
itemCell3.addRun("Product C", [:bold = true, :size = 12])
itemCell3.addLineBreak()
itemCell3.addRun("SKU: PRD-003", [:size = 9, :color = "gray"])
itemCell3.setVerticalAlign("center")
imageCell3 = new WordCell()
if len(img3Info[:relId]) > 0
imageCell3.addCellImage("images/test3.bmp", 2, 2)
imageCell3.setCellImageRel(1, img3Info[:relId], img3Info[:imageId])
else
imageCell3.addRun("(images/test3.bmp not found)", [:color = "gray", :size = 9])
ok
imageCell3.setAlign("center")
imageCell3.setVerticalAlign("center")
detailsCell3 = new WordCell()
detailsCell3.addRun("Price: ", [:bold = true])
detailsCell3.addRun("$29.99", [:color = "green", :bold = true])
detailsCell3.addLineBreak()
detailsCell3.addRun("Stock: ", [:bold = true])
detailsCell3.addRun("In Stock (500 units)", [])
detailsCell3.setVerticalAlign("center")
tableData = [
[h1, h2, h3],
[itemCell, imageCell, detailsCell],
[itemCell2, imageCell2, detailsCell2],
[itemCell3, imageCell3, detailsCell3]
]
doc.addTable(tableData, [:borderStyle = "single", :cellVAlign = "center"])
if doc.save("demo_richcell_8_images.docx")
? " Created: demo_richcell_8_images.docx"
else
? " FAILED: demo_richcell_8_images.docx"
ok
# =====================================================================
# Demo 9: Mixed Plain Strings and WordCell Objects
# =====================================================================
? "Demo 9: Table mixing plain strings and WordCell objects..."
doc = new WordWriter()
doc.setTitle("Rich Table Cells - Mixed Content")
doc.addHeading("Mixing Plain Strings and WordCell Objects", 1)
doc.addParagraph("You can mix plain strings and WordCell objects in the same table. Existing code continues to work!", NULL)
tableData = [
["Name", "Role", wordCell("Status", [:bold = true, :align = "center", :bgColor = "333333", :color = "white"])],
["Ahmed", "Developer", wordCell("Active", [:bold = true, :color = "green", :align = "center", :bgColor = "E8F5E9"])],
["Sara", "Manager", wordCell("Active", [:bold = true, :color = "green", :align = "center", :bgColor = "E8F5E9"])],
["Omar", "Designer", wordCell("On Leave", [:bold = true, :color = "orange", :align = "center", :bgColor = "FFF3E0"])],
["Fatima", "QA Lead", wordCell("Inactive", [:color = "red", :align = "center", :bgColor = "FFEBEE"])]
]
doc.addTable(tableData, [:headerRow = true, :borderStyle = "single", :headerBgColor = "333333"])
if doc.save("demo_richcell_9_mixed.docx")
? " Created: demo_richcell_9_mixed.docx"
else
? " FAILED: demo_richcell_9_mixed.docx"
ok
# =====================================================================
# Demo 10: Professional Invoice with Rich Cells
# =====================================================================
? "Demo 10: Professional invoice using rich cells..."
doc = new WordWriter()
doc.setTitle("Invoice #2026-001")
doc.setAuthor("Mahmoud's Software Company")
# Invoice Header
doc.addHeading("INVOICE", 1)
doc.addRichParagraph([
["Invoice #: ", [:bold = true]],
["2026-001", [:color = "1565C0"]]
], NULL)
doc.addRichParagraph([
["Date: ", [:bold = true]],
["March 1, 2026", []]
], NULL)
doc.addRichParagraph([
["Due Date: ", [:bold = true]],
["March 31, 2026", [:color = "red"]]
], NULL)
doc.addHorizontalLine()
# Company Info Table (no borders)
fromCell = new WordCell()
fromCell.addRun("FROM:", [:bold = true, :size = 9, :color = "gray"])
fromCell.addLineBreak()
fromCell.addRun("Ring Software Solutions", [:bold = true, :size = 12])
fromCell.addLineBreak()
fromCell.addRun("123 Tech Street", [])
fromCell.addLineBreak()
fromCell.addRun("Riyadh, Saudi Arabia", [])
fromCell.addLineBreak()
fromCell.addRun("contact@ringsoftware.com", [:color = "blue"])
toCell = new WordCell()
toCell.addRun("TO:", [:bold = true, :size = 9, :color = "gray"])
toCell.addLineBreak()
toCell.addRun("ABC Corporation", [:bold = true, :size = 12])
toCell.addLineBreak()
toCell.addRun("456 Business Avenue", [])
toCell.addLineBreak()
toCell.addRun("Dubai, UAE", [])
toCell.addLineBreak()
toCell.addRun("billing@abccorp.com", [:color = "blue"])
doc.addTable([[fromCell, toCell]], [:borderStyle = "none"])
doc.addEmptyParagraph()
# Items Table
hItem = wordCell("Item", [:bold = true, :color = "white", :align = "center"])
hDesc = wordCell("Description", [:bold = true, :color = "white", :align = "center"])
hQty = wordCell("Qty", [:bold = true, :color = "white", :align = "center"])
hRate = wordCell("Rate", [:bold = true, :color = "white", :align = "center"])
hTotal = wordCell("Total", [:bold = true, :color = "white", :align = "center"])
item1 = new WordCell()
item1.addRun("Ring Development", [:bold = true])
item1.addLineBreak()
item1.addRun("Custom library development", [:size = 9, :color = "gray"])
item2 = new WordCell()
item2.addRun("PWCT Training", [:bold = true])
item2.addLineBreak()
item2.addRun("5-day workshop", [:size = 9, :color = "gray"])
item3 = new WordCell()
item3.addRun("Technical Support", [:bold = true])
item3.addLineBreak()
item3.addRun("Monthly support package", [:size = 9, :color = "gray"])
# Subtotal row with span
subtotalLabel = new WordCell()
subtotalLabel.addRun("Subtotal", [:bold = true])
subtotalLabel.setAlign("right")
subtotalLabel.setColSpan(4)
subtotalValue = wordCell("$9,700.00", [:bold = true, :align = "right"])
# Tax row
taxLabel = new WordCell()
taxLabel.addRun("VAT (15%)", [])
taxLabel.setAlign("right")
taxLabel.setColSpan(4)
taxValue = wordCell("$1,455.00", [:align = "right"])
# Total row
totalLabel = new WordCell()
totalLabel.addRun("TOTAL DUE", [:bold = true, :size = 14])
totalLabel.setAlign("right")
totalLabel.setBgColor("1565C0")
totalLabel.setColSpan(4)
totalValue = new WordCell()
totalValue.addRun("$11,155.00", [:bold = true, :size = 14, :color = "white"])
totalValue.setAlign("right")
totalValue.setBgColor("1565C0")
tableData = [
[hItem, hDesc, hQty, hRate, hTotal],
[
"1", item1,
wordCell("40 hrs", [:align = "center"]),
wordCell("$150.00", [:align = "right"]),
wordCell("$6,000.00", [:align = "right"])
],
[
"2", item2,
wordCell("1", [:align = "center"]),
wordCell("$2,500.00", [:align = "right"]),
wordCell("$2,500.00", [:align = "right"])
],
[
"3", item3,
wordCell("1", [:align = "center"]),
wordCell("$1,200.00", [:align = "right"]),
wordCell("$1,200.00", [:align = "right"])
],
[subtotalLabel, "", "", "", subtotalValue],
[taxLabel, "", "", "", taxValue],
[totalLabel, "", "", "", totalValue]
]
doc.addTable(tableData, [
:borderStyle = "single",
:headerRow = true,
:headerBgColor = "1565C0",
:evenRowBgColor = "F5F5F5",
:headerVAlign = "center",
:cellVAlign = "center"
])
doc.addEmptyParagraph()
doc.addParagraph("Payment Terms: Net 30 days", [:bold = true])
doc.addParagraph("Please make payment to: Ring Software Solutions, Bank Account: SA12 3456 7890 1234 5678 9012", [:size = 9, :color = "gray"])
doc.addEmptyParagraph()
doc.addParagraph("Thank you for your business!", [:italic = true, :align = "center", :size = 12])
if doc.save("demo_richcell_10_invoice.docx")
? " Created: demo_richcell_10_invoice.docx"
else
? " FAILED: demo_richcell_10_invoice.docx"
ok
# =====================================================================
# Demo 11: Color-Coded Dashboard Table
# =====================================================================
? "Demo 11: Color-coded dashboard table..."
doc = new WordWriter()
doc.setTitle("Project Dashboard")
doc.addHeading("Project Status Dashboard", 1)
doc.addParagraph("Real-time project tracking with color-coded status indicators.", NULL)
# Headers
hProject = wordCell("Project", [:bold = true, :color = "white", :align = "center"])
hLead = wordCell("Lead", [:bold = true, :color = "white", :align = "center"])
hProg = wordCell("Progress", [:bold = true, :color = "white", :align = "center"])
hStatus = wordCell("Status", [:bold = true, :color = "white", :align = "center"])
# Project rows with status coloring
proj1Name = new WordCell()
proj1Name.addRun("Ring 1.26", [:bold = true, :size = 12])
proj1Name.addLineBreak()
proj1Name.addRun("New language features", [:size = 9, :color = "gray"])
proj1Status = wordCell("Delayed", [:bold = true, :color = "white", :bgColor = "FF9800", :align = "center"])
proj2Name = new WordCell()
proj2Name.addRun("RingSlint UI", [:bold = true, :size = 12])
proj2Name.addLineBreak()
proj2Name.addRun("UI toolkit integration", [:size = 9, :color = "gray"])
proj2Status = wordCell("On Track", [:bold = true, :color = "white", :bgColor = "4CAF50", :align = "center"])
proj3Name = new WordCell()
proj3Name.addRun("Rust Bindings", [:bold = true, :size = 12])
proj3Name.addLineBreak()
proj3Name.addRun("Language interop layer", [:size = 9, :color = "gray"])
proj3Status = wordCell("On Track", [:bold = true, :color = "white", :bgColor = "4CAF50", :align = "center"])
proj4Name = new WordCell()
proj4Name.addRun("Closures", [:bold = true, :size = 12])
proj4Name.addLineBreak()
proj4Name.addRun("Language core feature", [:size = 9, :color = "gray"])
proj4Status = wordCell("At Risk", [:bold = true, :color = "white", :bgColor = "F44336", :align = "center"])
proj5Name = new WordCell()
proj5Name.addRun("Archive Package", [:bold = true, :size = 12])
proj5Name.addLineBreak()
proj5Name.addRun("Compression library", [:size = 9, :color = "gray"])
proj5Status = wordCell("Complete", [:bold = true, :color = "white", :bgColor = "2196F3", :align = "center"])
tableData = [
[hProject, hLead, hProg, hStatus],
[proj1Name, "Mahmoud", wordCell("65%", [:align = "center", :bold = true]), proj1Status],
[proj2Name, "Youssef", wordCell("70%", [:align = "center", :bold = true]), proj2Status],
[proj3Name, "Youssef", wordCell("85%", [:align = "center", :bold = true]), proj3Status],
[proj4Name, "Mahmoud", wordCell("20%", [:align = "center", :bold = true]), proj4Status],
[proj5Name, "Youssef", wordCell("100%", [:align = "center", :bold = true, :color = "green"]), proj5Status]
]
doc.addTable(tableData, [
:borderStyle = "single",
:headerRow = true,
:headerBgColor = "263238",
:headerVAlign = "center",
:cellVAlign = "center"
])
if doc.save("demo_richcell_11_dashboard.docx")
? " Created: demo_richcell_11_dashboard.docx"
else
? " FAILED: demo_richcell_11_dashboard.docx"
ok
# =====================================================================
# Demo 12: Feature Comparison Table
# =====================================================================
? "Demo 12: Feature comparison table..."
doc = new WordWriter()
doc.setTitle("Feature Comparison")
doc.addHeading("Programming Language Feature Comparison", 1)
# Check mark and X mark using text
checkMark = "YES"
crossMark = "NO"
# Headers
hFeature = wordCell("Feature", [:bold = true, :color = "white", :align = "center"])
hRing = wordCell("Ring", [:bold = true, :color = "white", :align = "center"])
hPython = wordCell("Python", [:bold = true, :color = "white", :align = "center"])
hJava = wordCell("Java", [:bold = true, :color = "white", :align = "center"])
# Feature rows
features = [
["Dynamic Typing", checkMark, checkMark, crossMark],
["Object-Oriented", checkMark, checkMark, checkMark],
["Functional Style", checkMark, checkMark, checkMark],
["PWCT2", checkMark, crossMark, crossMark],
]
tableData = [[hFeature, hRing, hPython, hJava]]
for feature in features
featureCell = wordCell(feature[1], [:bold = true])
cells = [featureCell]
for i = 2 to 4
if feature[i] = checkMark
cells + wordCell(checkMark, [:bold = true, :color = "green", :align = "center", :bgColor = "E8F5E9"])
else
cells + wordCell(crossMark, [:color = "red", :align = "center", :bgColor = "FFEBEE"])
ok
next
tableData + cells
next
doc.addTable(tableData, [
:borderStyle = "single",
:headerRow = true,
:headerBgColor = "37474F",
:headerVAlign = "center",
:cellVAlign = "center"
])
if doc.save("demo_richcell_12_comparison.docx")
? " Created: demo_richcell_12_comparison.docx"
else
? " FAILED: demo_richcell_12_comparison.docx"
ok
# =====================================================================
# Summary
# =====================================================================
? ""
? "=============================================="
? " All Rich Table Cell Demos Completed!"
? "=============================================="
? ""
? "Created files:"
? " 1. demo_richcell_1_formatted_text.docx - Formatted text in cells"
? " 2. demo_richcell_2_multirun.docx - Multiple text styles per cell"
? " 3. demo_richcell_3_alignment.docx - Horizontal & vertical alignment"
? " 4. demo_richcell_4_colors.docx - Custom cell background colors"
? " 5. demo_richcell_5_colspan.docx - Column spanning (merged cells)"
? " 6. demo_richcell_6_linebreaks.docx - Line breaks within cells"
? " 7. demo_richcell_7_padding_borders.docx - Cell padding & individual borders"
? " 8. demo_richcell_8_images.docx - Images inside table cells"
? " 9. demo_richcell_9_mixed.docx - Mixed plain strings & WordCell"
? " 10. demo_richcell_10_invoice.docx - Professional invoice"
? " 11. demo_richcell_11_dashboard.docx - Color-coded dashboard"
? " 12. demo_richcell_12_comparison.docx - Feature comparison table"
? ""part6_richcells2.ring#
samples/UsingDOCXLib/part6_richcells2.ring
/*
DOCXLib - Demo (RichCells2)
*/
load "docxlib.ring"
/*
DOCXLib - Cell Content Demos
Demonstrates lists, hyperlinks, and nested tables inside table cells.
*/
? "=============================================="
? " DOCXLib - Cell Content Demos"
? "=============================================="
# =====================================================================
# Demo 1: Bullet Lists Inside Table Cells
# =====================================================================
? "Demo 1: Bullet lists in cells..."
doc = new WordWriter()
doc.setTitle("Cell Content - Bullet Lists")
doc.addHeading("Bullet Lists Inside Table Cells", 1)
doc.addParagraph("Each cell can contain a bullet list alongside other content.", NULL)
# Register list numbering definitions
bulletId1 = doc.registerCellList(WORD_LIST_BULLET)
bulletId2 = doc.registerCellList(WORD_LIST_BULLET)
bulletId3 = doc.registerCellList(WORD_LIST_BULLET)
# Header
h1 = wordCell("Department", [:bold = true, :color = "white", :bgColor = "1565C0", :align = "center", :verticalAlign = "center"])
h2 = wordCell("Responsibilities", [:bold = true, :color = "white", :bgColor = "1565C0", :align = "center", :verticalAlign = "center"])
h3 = wordCell("Tools", [:bold = true, :color = "white", :bgColor = "1565C0", :align = "center", :verticalAlign = "center"])
# Row 1
dept1 = new WordCell()
dept1.addRun("Engineering", [:bold = true, :size = 12, :color = "1565C0"])
dept1.setVerticalAlign("center")
resp1 = new WordCell()
resp1.addRun("Key Tasks:", [:bold = true])
resp1.addCellBulletList(["Software development", "Code review", "Architecture design", "Testing & QA"], bulletId1)
tools1 = new WordCell()
tools1.addCellBulletList(["Ring Language", "Git", "VS Code", "Docker"], bulletId2)
# Row 2
dept2 = new WordCell()
dept2.addRun("Marketing", [:bold = true, :size = 12, :color = "2E7D32"])
dept2.setVerticalAlign("center")
resp2 = new WordCell()
resp2.addRun("Key Tasks:", [:bold = true])
resp2.addCellBulletList(["Brand strategy", "Content creation", "Social media", "Analytics"], bulletId3)
tools2 = wordCell("Various marketing tools", [])
tableData = [
[h1, h2, h3],
[dept1, resp1, tools1],
[dept2, resp2, tools2]
]
doc.addTable(tableData, [
:borderStyle = "single",
:headerHeight = 600,
:cellVAlign = "top"
])
if doc.save("demo_richcells2_lists.docx")
? " Created: demo_richcells2_lists.docx"
else
? " FAILED: demo_richcells2_lists.docx"
ok
# =====================================================================
# Demo 2: Numbered Lists Inside Table Cells
# =====================================================================
? "Demo 2: Numbered lists in cells..."
doc = new WordWriter()
doc.setTitle("Cell Content - Numbered Lists")
doc.addHeading("Numbered Lists Inside Table Cells", 1)
doc.addParagraph("Cells can contain numbered step-by-step instructions.", NULL)
numId1 = doc.registerCellList(WORD_LIST_NUMBER)
numId2 = doc.registerCellList(WORD_LIST_NUMBER)
h1 = wordCell("Recipe", [:bold = true, :color = "white", :bgColor = "E65100", :align = "center", :verticalAlign = "center"])
h2 = wordCell("Steps", [:bold = true, :color = "white", :bgColor = "E65100", :align = "center", :verticalAlign = "center"])
h3 = wordCell("Notes", [:bold = true, :color = "white", :bgColor = "E65100", :align = "center", :verticalAlign = "center"])
# Row 1
recipe1 = new WordCell()
recipe1.addRun("Pasta Carbonara", [:bold = true, :size = 12])
recipe1.addLineBreak()
recipe1.addRun("Serves 4", [:italic = true, :color = "gray"])
recipe1.setVerticalAlign("center")
steps1 = new WordCell()
steps1.addCellNumberedList(["Boil pasta in salted water", "Fry pancetta until crispy", "Mix eggs with pecorino", "Combine hot pasta with egg mix", "Add pancetta and serve"], numId1)
notes1 = new WordCell()
notes1.addRun("Important: ", [:bold = true, :color = "red"])
notes1.addRun("Do not scramble the eggs! Remove pan from heat before mixing.", [])
notes1.setVerticalAlign("center")
# Row 2
recipe2 = new WordCell()
recipe2.addRun("Quick Salad", [:bold = true, :size = 12])
recipe2.addLineBreak()
recipe2.addRun("Serves 2", [:italic = true, :color = "gray"])
recipe2.setVerticalAlign("center")
steps2 = new WordCell()
steps2.addCellNumberedList(["Wash and chop lettuce", "Slice tomatoes and cucumber", "Add olive oil and lemon"], numId2)
notes2 = wordCell("Ready in 5 minutes!", [:italic = true, :color = "green"])
notes2.setVerticalAlign("center")
doc.addTable([
[h1, h2, h3],
[recipe1, steps1, notes1],
[recipe2, steps2, notes2]
], [
:borderStyle = "single",
:headerHeight = 600,
:cellVAlign = "top"
])
if doc.save("demo_richcells2_numbered.docx")
? " Created: demo_richcells2_numbered.docx"
else
? " FAILED: demo_richcells2_numbered.docx"
ok
# =====================================================================
# Demo 3: Hyperlinks Inside Table Cells
# =====================================================================
? "Demo 3: Hyperlinks in cells..."
doc = new WordWriter()
doc.setTitle("Cell Content - Hyperlinks")
doc.addHeading("Hyperlinks Inside Table Cells", 1)
doc.addParagraph("Cells can contain clickable hyperlinks to external URLs.", NULL)
# Register hyperlinks
link1 = doc.registerHyperlink("https://ring-lang.github.io")
link2 = doc.registerHyperlink("https://doublesvsoop.sf.net")
link3 = doc.registerHyperlink("https://supernova.sf.net")
link4 = doc.registerHyperlink("https://ring-lang.github.io/doc1.26/index.html")
link5 = doc.registerHyperlink("https://github.com/PWCT/PWCT2")
h1 = wordCell("Project", [:bold = true, :color = "white", :bgColor = "37474F", :align = "center", :verticalAlign = "center"])
h2 = wordCell("Description", [:bold = true, :color = "white", :bgColor = "37474F", :align = "center", :verticalAlign = "center"])
h3 = wordCell("Links", [:bold = true, :color = "white", :bgColor = "37474F", :align = "center", :verticalAlign = "center"])
# Row 1
proj1 = new WordCell()
proj1.addRun("Ring Language", [:bold = true, :size = 12, :color = "1565C0"])
proj1.setVerticalAlign("center")
desc1 = new WordCell()
desc1.addRun("Practical general-purpose multi-paradigm programming language.", [])
desc1.setVerticalAlign("center")
links1 = new WordCell()
links1.addRun("Resources:", [:bold = true])
links1.addCellHyperlink("Ring Official Website", link1)
links1.addCellHyperlink("Ring Documentation", link4)
# Row 2
proj2 = new WordCell()
proj2.addRun("PWCT2", [:bold = true, :size = 12, :color = "2E7D32"])
proj2.setVerticalAlign("center")
desc2 = new WordCell()
desc2.addRun("Programming Without Coding Technology - visual programming environment.", [])
desc2.setVerticalAlign("center")
links2 = new WordCell()
links2.addRun("Resources:", [:bold = true])
links2.addCellHyperlink("PWCT2 on GitHub", link5)
doc.addTable([
[h1, h2, h3],
[proj1, desc1, links1],
[proj2, desc2, links2]
], [
:borderStyle = "single",
:headerHeight = 600,
:cellVAlign = "top"
])
if doc.save("demo_richcells2_hyperlinks.docx")
? " Created: demo_richcells2_hyperlinks.docx"
else
? " FAILED: demo_richcells2_hyperlinks.docx"
ok
# =====================================================================
# Demo 4: Nested Tables Inside Table Cells
# =====================================================================
? "Demo 4: Nested tables in cells..."
doc = new WordWriter()
doc.setTitle("Cell Content - Nested Tables")
doc.addHeading("Nested Tables Inside Table Cells", 1)
doc.addParagraph("A table cell can contain another table for complex layouts.", NULL)
# Generate the nested table XML
nestedXml1 = doc.generateNestedTable([
["Q1", "Q2", "Q3", "Q4"],
["$12K", "$15K", "$18K", "$22K"]
], [
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "4472C4"
])
nestedXml2 = doc.generateNestedTable([
["Q1", "Q2", "Q3", "Q4"],
["$8K", "$9K", "$11K", "$14K"]
], [
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "4472C4"
])
# Outer table
h1 = wordCell("Product Line", [:bold = true, :color = "white", :bgColor = "1B5E20", :align = "center", :verticalAlign = "center"])
h2 = wordCell("Quarterly Revenue", [:bold = true, :color = "white", :bgColor = "1B5E20", :align = "center", :verticalAlign = "center"])
h3 = wordCell("Status", [:bold = true, :color = "white", :bgColor = "1B5E20", :align = "center", :verticalAlign = "center"])
prod1 = new WordCell()
prod1.addRun("Enterprise Suite", [:bold = true, :size = 11])
prod1.addLineBreak()
prod1.addRun("B2B software platform", [:italic = true, :size = 9, :color = "gray"])
prod1.setVerticalAlign("center")
revenue1 = new WordCell()
revenue1.addRun("2025 Revenue Breakdown:", [:bold = true, :size = 9])
revenue1.addCellTable(nestedXml1)
status1 = new WordCell()
status1.addRun("Growing", [:bold = true, :color = "green", :size = 14])
status1.setAlign("center")
status1.setVerticalAlign("center")
status1.setBgColor("E8F5E9")
prod2 = new WordCell()
prod2.addRun("Consumer App", [:bold = true, :size = 11])
prod2.addLineBreak()
prod2.addRun("Mobile application", [:italic = true, :size = 9, :color = "gray"])
prod2.setVerticalAlign("center")
revenue2 = new WordCell()
revenue2.addRun("2025 Revenue Breakdown:", [:bold = true, :size = 9])
revenue2.addCellTable(nestedXml2)
status2 = new WordCell()
status2.addRun("Stable", [:bold = true, :color = "orange", :size = 14])
status2.setAlign("center")
status2.setVerticalAlign("center")
status2.setBgColor("FFF8E1")
doc.addTable([
[h1, h2, h3],
[prod1, revenue1, status1],
[prod2, revenue2, status2]
], [
:borderStyle = "single",
:headerHeight = 600,
:cellVAlign = "top"
])
if doc.save("demo_richcells2_nested_tables.docx")
? " Created: demo_richcells2_nested_tables.docx"
else
? " FAILED: demo_richcells2_nested_tables.docx"
ok
# =====================================================================
# Demo 5: Mixed Content - All Features Combined
# =====================================================================
? "Demo 5: Mixed content (lists + hyperlinks + tables combined)..."
doc = new WordWriter()
doc.setTitle("Cell Content - Mixed Content")
doc.addHeading("All Cell Content Types Combined", 1)
doc.addParagraph("A single cell can contain text, lists, hyperlinks, and nested tables.", NULL)
# Register resources
bulletId = doc.registerCellList(WORD_LIST_BULLET)
numId = doc.registerCellList(WORD_LIST_NUMBER)
linkRing = doc.registerHyperlink("https://ring-lang.github.io")
linkDocs = doc.registerHyperlink("https://ring-lang.github.io/doc1.26/index.html")
nestedXml = doc.generateNestedTable([
["Feature", "Status"],
["Closures", "New"],
["RingSlint", "New"],
["Rust Bindings", "New"]
], [
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "1565C0"
])
# Header
h1 = wordCell("Overview", [:bold = true, :color = "white", :bgColor = "4A148C", :align = "center", :verticalAlign = "center"])
h2 = wordCell("Details", [:bold = true, :color = "white", :bgColor = "4A148C", :align = "center", :verticalAlign = "center"])
# Row: Rich content cell
overview = new WordCell()
overview.addRun("Ring 1.26", [:bold = true, :size = 14, :color = "4A148C"])
overview.addLineBreak()
overview.addRun("Latest Release", [:italic = true, :color = "gray"])
overview.setVerticalAlign("center")
overview.setAlign("center")
details = new WordCell()
details.addRun("Ring 1.26 is the latest release with many improvements.", [])
details.addLineBreak()
details.addLineBreak()
details.addRun("Key Highlights:", [:bold = true])
details.addCellBulletList(["New closures support", "RingSlint UI framework", "Archive package", "Proc package"], bulletId)
details.addRun("Setup Steps:", [:bold = true])
details.addCellNumberedList(["Download from website", "Run installer", "Open Ring Notepad"], numId)
details.addRun("Useful Links:", [:bold = true])
details.addCellHyperlink("Ring Official Website", linkRing)
details.addCellHyperlink("Ring Documentation", linkDocs)
details.addRun("New Features Table:", [:bold = true])
details.addCellTable(nestedXml)
doc.addTable([
[h1, h2],
[overview, details]
], [
:borderStyle = "single",
:headerHeight = 600,
:cellVAlign = "top"
])
if doc.save("demo_richcells2_mixed.docx")
? " Created: demo_richcells2_mixed.docx"
else
? " FAILED: demo_richcells2_mixed.docx"
ok
? ""
? "=============================================="
? " All demos completed!"
? "=============================================="
? ""part6_richcells3.ring#
samples/UsingDOCXLib/part6_richcells3.ring
/*
DOCXLib - Demo (RichCells3)
*/
load "docxlib.ring"
/*
Column Widths & Cell Quotes/Captions Demo
Demonstrates custom column widths and block quotes/captions inside table cells.
*/
? "=============================================="
? " DOCXLib - Column Widths & Quotes Demo"
? "=============================================="
# =====================================================================
# Demo 1: Custom Column Widths
# =====================================================================
? "Demo 1: Custom column widths..."
doc = new WordWriter()
doc.setTitle("Custom Column Widths")
doc.addHeading("Custom Column Widths", 1)
# --- Table 1: Simple custom widths ---
doc.addHeading("Narrow ID + Wide Description", 2)
doc.addParagraph("First column 2cm, second 6cm, third 3cm, fourth 5.5cm:", NULL)
doc.addTable([
["ID", "Description", "Status", "Assigned To"],
["1", "Design new user dashboard with responsive layout", "In Progress", "Ahmed"],
["2", "Fix login timeout bug on mobile devices", "Done", "Sara"],
["3", "Write API documentation for v2.0 endpoints", "Pending", "Omar"],
["4", "Optimize database queries for reports module", "In Progress", "Fatima"]
], [
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "1565C0",
:evenRowBgColor = "E3F2FD",
:headerHeight = 600,
:headerVAlign = "center",
:cellVAlign = "center",
:colWidths = [2, 6, 3, 5.5]
])
doc.addEmptyParagraph()
# --- Table 2: Narrow label + wide value (form-like layout) ---
doc.addHeading("Form-Style Layout (Label : Value)", 2)
doc.addTable([
["Field", "Value"],
["Full Name", "Mahmoud Fayed"],
["Email", "msfclipper@yahoo.com"],
["Position", "Programming Language Designer & Researcher"],
["Languages Created", "Ring, PWCT, PWCT2, Supernova"],
["Research Areas", "Compiler Design, Visual Programming, Machine Learning"]
], [
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "37474F",
:headerHeight = 600,
:headerVAlign = "center",
:colWidths = [4.5, 12]
])
doc.addEmptyParagraph()
# --- Table 3: Mixed with WordCell and custom widths ---
doc.addHeading("Product Catalog with Custom Widths", 2)
h1 = wordCell("SKU", [:bold = true, :color = "white", :bgColor = "4A148C", :align = "center", :verticalAlign = "center"])
h2 = wordCell("Product Name", [:bold = true, :color = "white", :bgColor = "4A148C", :align = "center", :verticalAlign = "center"])
h3 = wordCell("Description", [:bold = true, :color = "white", :bgColor = "4A148C", :align = "center", :verticalAlign = "center"])
h4 = wordCell("Price", [:bold = true, :color = "white", :bgColor = "4A148C", :align = "center", :verticalAlign = "center"])
row1a = wordCell("RL-001", [:align = "center"])
row1a.setVerticalAlign("center")
row1b = new WordCell()
row1b.addRun("Ring Language Book", [:bold = true])
row1b.setVerticalAlign("center")
row1c = new WordCell()
row1c.addRun("Comprehensive guide to the Ring programming language covering all paradigms, libraries, and advanced features with practical examples.", [])
row1d = wordCell("$0.00", [:bold = true, :color = "green", :align = "center"])
row1d.setVerticalAlign("center")
row2a = wordCell("PW-002", [:align = "center"])
row2a.setVerticalAlign("center")
row2b = new WordCell()
row2b.addRun("PWCT Course", [:bold = true])
row2b.setVerticalAlign("center")
row2c = new WordCell()
row2c.addRun("Online video course for Programming Without Coding Technology with hands-on exercises.", [])
row2d = wordCell("$0.00", [:bold = true, :color = "green", :align = "center"])
row2d.setVerticalAlign("center")
doc.addTable([
[h1, h2, h3, h4],
[row1a, row1b, row1c, row1d],
[row2a, row2b, row2c, row2d]
], [
:borderStyle = "single",
:headerHeight = 600,
:cellVAlign = "center",
:colWidths = [2, 4, 8, 2.5]
])
if doc.save("demo_richcells3_widths.docx")
? " Created: demo_richcells3_widths.docx"
else
? " FAILED: demo_richcells3_widths.docx"
ok
# =====================================================================
# Demo 2: Block Quotes in Table Cells
# =====================================================================
? "Demo 2: Block quotes in cells..."
doc = new WordWriter()
doc.setTitle("Cell Block Quotes")
doc.addHeading("Block Quotes Inside Table Cells", 1)
doc.addParagraph("Cells can contain styled block quotes with left border accent.", NULL)
h1 = wordCell("Topic", [:bold = true, :color = "white", :bgColor = "1B5E20", :align = "center", :verticalAlign = "center"])
h2 = wordCell("Content", [:bold = true, :color = "white", :bgColor = "1B5E20", :align = "center", :verticalAlign = "center"])
topic1 = new WordCell()
topic1.addRun("Programming", [:bold = true, :size = 12, :color = "1B5E20"])
topic1.setVerticalAlign("center")
topic1.setAlign("center")
content1 = new WordCell()
content1.addRun("Why Ring Language?", [:bold = true, :size = 11])
content1.addCellBlockQuote("Ring is designed to be a practical general-purpose language that is simple, natural, and encourages organized programming.")
content1.addRun("Ring supports multiple programming paradigms:", [:bold = true])
bulletId1 = doc.registerCellList(WORD_LIST_BULLET)
content1.addCellBulletList(["Procedural programming", "Object-Oriented programming", "Functional programming", "Declarative programming"], bulletId1)
content1.addCellBlockQuote("The language is designed to produce small executables and can be embedded in C/C++ projects with just a few files.")
topic2 = new WordCell()
topic2.addRun("Research", [:bold = true, :size = 12, :color = "1B5E20"])
topic2.setVerticalAlign("center")
topic2.setAlign("center")
content2 = new WordCell()
content2.addRun("Visual Programming Research:", [:bold = true, :size = 11])
content2.addCellBlockQuote("Visual programming reduces the barrier to entry for new programmers by representing code as visual elements rather than text.")
content2.addRun("Key findings from published papers demonstrate significant improvements in learning outcomes when visual tools are combined with traditional coding.", [])
doc.addTable([
[h1, h2],
[topic1, content1],
[topic2, content2]
], [
:borderStyle = "single",
:headerHeight = 600,
:colWidths = [3, 13.5],
:cellVAlign = "top"
])
if doc.save("demo_richcells3_quotes.docx")
? " Created: demo_richcells3_quotes.docx"
else
? " FAILED: demo_richcells3_quotes.docx"
ok
# =====================================================================
# Demo 3: Captions in Table Cells
# =====================================================================
? "Demo 3: Captions in cells..."
doc = new WordWriter()
doc.setTitle("Cell Captions")
doc.addHeading("Captions Inside Table Cells", 1)
doc.addParagraph("Captions provide centered, italic descriptive text, useful for labeling images or data within cells.", NULL)
h1 = wordCell("Chart", [:bold = true, :color = "white", :bgColor = "0D47A1", :align = "center", :verticalAlign = "center"])
h2 = wordCell("Summary", [:bold = true, :color = "white", :bgColor = "0D47A1", :align = "center", :verticalAlign = "center"])
# Row 1 - Sales chart placeholder
chart1 = new WordCell()
chart1.addRun("Q1 2026", [:bold = true, :size = 18, :color = "1565C0"])
chart1.addLineBreak()
chart1.addRun("$1.2M Revenue", [:size = 14])
chart1.setAlign("center")
chart1.setBgColor("E3F2FD")
chart1.addCellCaption("Figure 1: Q1 2026 Revenue Overview")
summary1 = new WordCell()
summary1.addRun("Key Metrics:", [:bold = true])
numId1 = doc.registerCellList(WORD_LIST_NUMBER)
summary1.addCellNumberedList(["Revenue up 23% YoY", "New customers: 450", "Retention rate: 94%"], numId1)
summary1.addCellCaption("Source: Internal Sales Dashboard, March 2026")
summary1.setVerticalAlign("center")
# Row 2
chart2 = new WordCell()
chart2.addRun("Q2 2026", [:bold = true, :size = 18, :color = "2E7D32"])
chart2.addLineBreak()
chart2.addRun("$1.5M Revenue", [:size = 14])
chart2.setAlign("center")
chart2.setBgColor("E8F5E9")
chart2.addCellCaption("Figure 2: Q2 2026 Revenue Overview")
summary2 = new WordCell()
summary2.addRun("Key Metrics:", [:bold = true])
numId2 = doc.registerCellList(WORD_LIST_NUMBER)
summary2.addCellNumberedList(["Revenue up 25% QoQ", "New customers: 520", "Retention rate: 96%"], numId2)
summary2.addCellCaption("Source: Internal Sales Dashboard, May 2026")
summary2.setVerticalAlign("center")
doc.addTable([
[h1, h2],
[chart1, summary1],
[chart2, summary2]
], [
:borderStyle = "single",
:headerHeight = 600,
:colWidths = [7, 9.5],
:cellVAlign = "top"
])
if doc.save("demo_richcells3_captions.docx")
? " Created: demo_richcells3_captions.docx"
else
? " FAILED: demo_richcells3_captions.docx"
ok
# =====================================================================
# Demo 4: Combined - Project Report Table
# =====================================================================
? "Demo 4: Combined project report table..."
doc = new WordWriter()
doc.setTitle("Project Status Report")
doc.addHeading("Project Status Report", 1)
doc.addParagraph("A realistic example combining column widths, quotes, captions, lists, and rich formatting.", NULL)
# Register resources
bulletId = doc.registerCellList(WORD_LIST_BULLET)
numId = doc.registerCellList(WORD_LIST_NUMBER)
linkRing = doc.registerHyperlink("https://ring-lang.github.io")
# Header
h1 = wordCell("#", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
h2 = wordCell("Project", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
h3 = wordCell("Details & Progress", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
h4 = wordCell("Status", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
# Row 1 - Ring 1.26
num1 = wordCell("1", [:bold = true, :align = "center"])
num1.setVerticalAlign("center")
proj1 = new WordCell()
proj1.addRun("Ring 1.26", [:bold = true, :size = 12, :color = "1565C0"])
proj1.addLineBreak()
proj1.addRun("Programming Language", [:italic = true, :size = 9, :color = "gray"])
proj1.setVerticalAlign("center")
details1 = new WordCell()
details1.addRun("Release Highlights:", [:bold = true])
details1.addCellBulletList(["Closures support", "RingSlint UI toolkit", "Rust language bindings", "Archive and Proc packages"], bulletId)
details1.addCellBlockQuote("Ring 1.26 represents a major step forward with modern language features while maintaining backward compatibility.")
details1.addRun("Links:", [:bold = true])
details1.addCellHyperlink("Ring Official Website", linkRing)
details1.addCellCaption("Released: February 2026")
status1 = new WordCell()
status1.addRun("RELEASED", [:bold = true, :color = "green", :size = 11])
status1.setAlign("center")
status1.setVerticalAlign("center")
status1.setBgColor("E8F5E9")
# Row 2 - Research paper
num2 = wordCell("2", [:bold = true, :align = "center"])
num2.setVerticalAlign("center")
proj2 = new WordCell()
proj2.addRun("Research Paper", [:bold = true, :size = 12, :color = "E65100"])
proj2.addLineBreak()
proj2.addRun("MDPI Electronics", [:italic = true, :size = 9, :color = "gray"])
proj2.setVerticalAlign("center")
details2 = new WordCell()
details2.addRun("Submission Progress:", [:bold = true])
numId2 = doc.registerCellList(WORD_LIST_NUMBER)
details2.addCellNumberedList(["Initial submission", "Reviewer feedback received", "Revisions completed", "Resubmission done"], numId2)
details2.addCellBlockQuote("The paper presents a novel approach to prompt-driven development using Ring language for TUI framework creation.")
details2.addCellCaption("Journal: MDPI Electronics, Impact Factor: 2.6")
status2 = new WordCell()
status2.addRun("REVIEW", [:bold = true, :color = "orange", :size = 11])
status2.setAlign("center")
status2.setVerticalAlign("center")
status2.setBgColor("FFF8E1")
# Row 3 - Website
num3 = wordCell("3", [:bold = true, :align = "center"])
num3.setVerticalAlign("center")
proj3 = new WordCell()
proj3.addRun("Ring Website", [:bold = true, :size = 12, :color = "2E7D32"])
proj3.addLineBreak()
proj3.addRun("Bootstrap 5 Migration", [:italic = true, :size = 9, :color = "gray"])
proj3.setVerticalAlign("center")
details3 = new WordCell()
details3.addRun("Migration Tasks:", [:bold = true])
bulletId3 = doc.registerCellList(WORD_LIST_BULLET)
details3.addCellBulletList(["Updated to Bootstrap 5", "Responsive design improvements", "New documentation pages", "Performance optimization"], bulletId3)
details3.addCellCaption("Completion: 95%")
status3 = new WordCell()
status3.addRun("ACTIVE", [:bold = true, :color = "blue", :size = 11])
status3.setAlign("center")
status3.setVerticalAlign("center")
status3.setBgColor("E3F2FD")
doc.addTable([
[h1, h2, h3, h4],
[num1, proj1, details1, status1],
[num2, proj2, details2, status2],
[num3, proj3, details3, status3]
], [
:borderStyle = "single",
:headerHeight = 600,
:cellVAlign = "top",
:colWidths = [1.2, 3.5, 9.5, 2.3]
])
if doc.save("demo_richcells3_report.docx")
? " Created: demo_richcells3_report.docx"
else
? " FAILED: demo_richcells3_report.docx"
ok
? ""
? "=============================================="
? " All demos completed!"
? "=============================================="
? ""part6_richcells4.ring#
samples/UsingDOCXLib/part6_richcells4.ring
/*
DOCXLib - Demo (RichCells4)
*/
load "docxlib.ring"
/*
Row Span & Landscape Sections Demo
Demonstrates vertical merge (row span) and mixed orientation sections.
*/
? "=============================================="
? " DOCXLib - Row Span & Landscape Demo"
? "=============================================="
# =====================================================================
# Demo 1: Basic Row Span (Vertical Merge)
# =====================================================================
? "Demo 1: Basic row span..."
doc = new WordWriter()
doc.setTitle("Row Span Demo")
doc.addHeading("Vertical Cell Merge (Row Span)", 1)
doc.addParagraph("Cells can span multiple rows using setRowSpan() and wordMergeCell().", NULL)
# --- Table 1: Simple row span ---
doc.addHeading("Category Grouping", 2)
cat1 = new WordCell()
cat1.addRun("Electronics", [:bold = true, :size = 12, :color = "1565C0"])
cat1.setRowSpan(3)
cat1.setVerticalAlign("center")
cat1.setAlign("center")
cat1.setBgColor("E3F2FD")
cat2 = new WordCell()
cat2.addRun("Software", [:bold = true, :size = 12, :color = "2E7D32"])
cat2.setRowSpan(2)
cat2.setVerticalAlign("center")
cat2.setAlign("center")
cat2.setBgColor("E8F5E9")
h1 = wordCell("Category", [:bold = true, :color = "white", :bgColor = "37474F", :align = "center", :verticalAlign = "center"])
h2 = wordCell("Product", [:bold = true, :color = "white", :bgColor = "37474F", :align = "center", :verticalAlign = "center"])
h3 = wordCell("Price", [:bold = true, :color = "white", :bgColor = "37474F", :align = "center", :verticalAlign = "center"])
h4 = wordCell("Stock", [:bold = true, :color = "white", :bgColor = "37474F", :align = "center", :verticalAlign = "center"])
doc.addTable([
[h1, h2, h3, h4],
[cat1, "Laptop Pro 15", "$1,299", "45"],
[wordMergeCell(), "Wireless Mouse", "$29", "500"],
[wordMergeCell(), "4K Monitor", "$449", "78"],
[cat2, "Ring Language", "Free", "Unlimited"],
[wordMergeCell(), "PWCT2", "Free", "Unlimited"]
], [
:headerRow = true,
:borderStyle = "single",
:headerHeight = 600,
:headerVAlign = "center",
:cellVAlign = "center",
:colWidths = [3.5, 5, 3, 3]
])
if doc.save("demo_richcells4_basic.docx")
? " Created: demo_richcells4_basic.docx"
else
? " FAILED: demo_richcells4_basic.docx"
ok
# =====================================================================
# Demo 2: Row Span with Rich Content
# =====================================================================
? "Demo 2: Row span with rich content..."
doc = new WordWriter()
doc.setTitle("Row Span with Rich Content")
doc.addHeading("Row Span with Rich Cell Content", 1)
bulletId1 = doc.registerCellList(WORD_LIST_BULLET)
bulletId2 = doc.registerCellList(WORD_LIST_BULLET)
# Department spanning rows
dept1 = new WordCell()
dept1.addRun("Engineering", [:bold = true, :size = 14, :color = "white"])
dept1.setRowSpan(3)
dept1.setVerticalAlign("center")
dept1.setAlign("center")
dept1.setBgColor("1565C0")
dept2 = new WordCell()
dept2.addRun("Marketing", [:bold = true, :size = 14, :color = "white"])
dept2.setRowSpan(2)
dept2.setVerticalAlign("center")
dept2.setAlign("center")
dept2.setBgColor("E65100")
# Headers
h1 = wordCell("Department", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
h2 = wordCell("Employee", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
h3 = wordCell("Role", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
h4 = wordCell("Skills", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
# Engineering employees
emp1 = new WordCell()
emp1.addRun("Ahmed", [:bold = true])
emp1.setVerticalAlign("center")
role1 = wordCell("Senior Developer", [])
role1.setVerticalAlign("center")
skills1 = new WordCell()
skills1.addCellBulletList(["Ring", "C/C++", "Python"], bulletId1)
emp2 = wordCell("Sara", [:bold = true])
emp2.setVerticalAlign("center")
role2 = wordCell("QA Engineer", [])
role2.setVerticalAlign("center")
skills2 = wordCell("Testing, Automation", [])
skills2.setVerticalAlign("center")
emp3 = wordCell("Omar", [:bold = true])
emp3.setVerticalAlign("center")
role3 = wordCell("DevOps", [])
role3.setVerticalAlign("center")
skills3 = wordCell("Docker, CI/CD", [])
skills3.setVerticalAlign("center")
# Marketing employees
emp4 = wordCell("Fatima", [:bold = true])
emp4.setVerticalAlign("center")
role4 = wordCell("Content Lead", [])
role4.setVerticalAlign("center")
skills4 = new WordCell()
skills4.addCellBulletList(["SEO", "Copywriting", "Social Media"], bulletId2)
emp5 = wordCell("Khalid", [:bold = true])
emp5.setVerticalAlign("center")
role5 = wordCell("Designer", [])
role5.setVerticalAlign("center")
skills5 = wordCell("Figma, Photoshop", [])
skills5.setVerticalAlign("center")
doc.addTable([
[h1, h2, h3, h4],
[dept1, emp1, role1, skills1],
[wordMergeCell(), emp2, role2, skills2],
[wordMergeCell(), emp3, role3, skills3],
[dept2, emp4, role4, skills4],
[wordMergeCell(), emp5, role5, skills5]
], [
:headerRow = true,
:borderStyle = "single",
:headerHeight = 600,
:cellVAlign = "center",
:colWidths = [3, 3, 3.5, 5]
])
if doc.save("demo_richcells4_rich.docx")
? " Created: demo_richcells4_rich.docx"
else
? " FAILED: demo_richcells4_rich.docx"
ok
# =====================================================================
# Demo 3: Combined Row Span + Column Span
# =====================================================================
? "Demo 3: Combined row span and column span..."
doc = new WordWriter()
doc.setTitle("Combined Row and Column Span")
doc.addHeading("Combined Row Span and Column Span", 1)
doc.addParagraph("Row spans and column spans can be used together in the same table.", NULL)
# Top-left corner spanning 2 rows and 2 columns
corner = new WordCell()
corner.addRun("Q4 2024", [:bold = true, :size = 16, :color = "white"])
corner.addLineBreak()
corner.addRun("Sales Report", [:italic = true, :size = 10, :color = "E0E0E0"])
corner.setRowSpan(2)
corner.setColSpan(2)
corner.setVerticalAlign("center")
corner.setAlign("center")
corner.setBgColor("1B5E20")
# Region headers
regionUS = wordCell("USA", [:bold = true, :color = "white", :bgColor = "1565C0", :align = "center", :verticalAlign = "center"])
regionEU = wordCell("Europe", [:bold = true, :color = "white", :bgColor = "1565C0", :align = "center", :verticalAlign = "center"])
regionAsia = wordCell("Asia", [:bold = true, :color = "white", :bgColor = "1565C0", :align = "center", :verticalAlign = "center"])
# Month rows
oct = wordCell("October", [:bold = true, :bgColor = "E8F5E9"])
oct.setVerticalAlign("center")
nov = wordCell("November", [:bold = true, :bgColor = "E8F5E9"])
nov.setVerticalAlign("center")
dec = wordCell("December", [:bold = true, :bgColor = "E8F5E9"])
dec.setVerticalAlign("center")
# Total spanning row
total = new WordCell()
total.addRun("TOTAL", [:bold = true, :color = "white", :size = 12])
total.setColSpan(2)
total.setAlign("center")
total.setVerticalAlign("center")
total.setBgColor("37474F")
totalUS = wordCell("$450K", [:bold = true, :color = "white", :bgColor = "37474F", :align = "center", :verticalAlign = "center"])
totalEU = wordCell("$320K", [:bold = true, :color = "white", :bgColor = "37474F", :align = "center", :verticalAlign = "center"])
totalAsia = wordCell("$280K", [:bold = true, :color = "white", :bgColor = "37474F", :align = "center", :verticalAlign = "center"])
# Merge continuation for the 2x2 corner
cornerCont = wordMergeCell()
cornerCont.setColSpan(2)
doc.addTable([
[corner, "", regionUS, regionEU, regionAsia],
[cornerCont, "", "", "", ""],
[oct, "", "$150K", "$100K", "$90K"],
[nov, "", "$140K", "$110K", "$95K"],
[dec, "", "$160K", "$110K", "$95K"],
[total, "", totalUS, totalEU, totalAsia]
], [
:borderStyle = "single",
:cellVAlign = "center",
:colWidths = [2.5, 2.5, 3.5, 3.5, 3.5]
])
if doc.save("demo_richcells4_combined.docx")
? " Created: demo_richcells4_combined.docx"
else
? " FAILED: demo_richcells4_combined.docx"
ok
# =====================================================================
# Demo 4: Landscape Section
# =====================================================================
? "Demo 4: Landscape section..."
doc = new WordWriter()
doc.setTitle("Mixed Orientation Document")
doc.addHeading("Portrait Section", 1)
doc.addParagraph("This page is in portrait orientation. The next page will switch to landscape for a wide table.", NULL)
doc.addParagraph("Portrait orientation is ideal for regular text, paragraphs, and narrow tables.", NULL)
# --- Switch to landscape ---
doc.addLandscapeStart()
doc.addHeading("Landscape Section", 1)
doc.addParagraph("This page is in landscape orientation, providing extra width for wide tables and charts.", NULL)
# Wide table that benefits from landscape
doc.addTable([
["ID", "Project Name", "Lead", "Start Date", "End Date", "Budget", "Spent", "Status", "Priority", "Notes"],
["P-001", "Ring 1.26 Release", "Mahmoud", "2024-01-15", "2025-01-25", "$50K", "$48K", "Done", "High", "Major release with closures"],
["P-002", "PWCT2 Development", "Mahmoud", "2024-03-01", "2025-06-30", "$30K", "$18K", "Active", "High", "Visual programming platform"],
["P-003", "Ring Website Redesign", "Ahmed", "2024-06-01", "2024-12-31", "$10K", "$9K", "Done", "Medium", "Bootstrap 5 migration"],
["P-004", "Research Paper", "Mahmoud", "2024-09-01", "2025-03-30", "$5K", "$3K", "Review", "Medium", "Journal"],
["P-005", "Supernova Language", "Mahmoud", "2024-01-01", "2025-12-31", "$20K", "$8K", "Active", "Low", "Domain-specific VPL"]
], [
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "1565C0",
:evenRowBgColor = "E3F2FD",
:headerHeight = 600,
:headerVAlign = "center",
:cellVAlign = "center",
:colWidths = [1.5, 4, 2.5, 2.5, 2.5, 2, 2, 1.8, 1.8, 5]
])
# --- Return to portrait ---
doc.addLandscapeEnd()
doc.addHeading("Back to Portrait", 1)
doc.addParagraph("This page is back to portrait orientation. You can switch between portrait and landscape as many times as needed within a single document.", NULL)
if doc.save("demo_richcells4_landscape.docx")
? " Created: demo_richcells4_landscape.docx"
else
? " FAILED: demo_richcells4_landscape.docx"
ok
# =====================================================================
# Demo 5: Complete Report with All Features
# =====================================================================
? "Demo 5: Complete report combining all features..."
doc = new WordWriter()
doc.setTitle("Annual Report 2024")
doc.setAuthor("Mahmoud")
doc.setHeader("Annual Report 2024")
doc.showPageNumbers("center")
# --- Page 1: Title and summary (portrait) ---
doc.addHeading("Annual Report 2024", 1)
doc.addParagraph("A comprehensive overview of projects, financials, and team performance.", NULL)
doc.addHeading("Team Overview", 2)
bulletId = doc.registerCellList(WORD_LIST_BULLET)
dept1 = new WordCell()
dept1.addRun("R&D", [:bold = true, :size = 14, :color = "white"])
dept1.setRowSpan(3)
dept1.setVerticalAlign("center")
dept1.setAlign("center")
dept1.setBgColor("0D47A1")
dept2 = new WordCell()
dept2.addRun("QA", [:bold = true, :size = 14, :color = "white"])
dept2.setRowSpan(2)
dept2.setVerticalAlign("center")
dept2.setAlign("center")
dept2.setBgColor("E65100")
h1 = wordCell("Dept", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
h2 = wordCell("Name", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
h3 = wordCell("Role", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
h4 = wordCell("Focus Areas", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
focus1 = new WordCell()
focus1.addCellBulletList(["Ring Language core", "Compiler optimization", "VM performance"], bulletId)
doc.addTable([
[h1, h2, h3, h4],
[dept1, "Mahmoud", "Lead Developer", focus1],
[wordMergeCell(), "Youssef", "Senior Developer", "Libraries & Extensions"],
[wordMergeCell(), "Omar", "Junior Developer", "Documentation & Testing"],
[dept2, "Sara", "QA Lead", "Test automation"],
[wordMergeCell(), "Fatima", "QA Engineer", "Manual & integration testing"]
], [
:headerRow = true,
:borderStyle = "single",
:headerHeight = 600,
:cellVAlign = "center",
:colWidths = [2, 3, 4, 7.5]
])
# --- Page 2: Wide financial table (landscape) ---
doc.addLandscapeStart()
doc.addHeading("Financial Overview", 1)
doc.addParagraph("Quarterly breakdown of project budgets and expenditures across all departments.", NULL)
# Row span for department grouping
fin1 = new WordCell()
fin1.addRun("R&D", [:bold = true, :color = "white"])
fin1.setRowSpan(3)
fin1.setVerticalAlign("center")
fin1.setAlign("center")
fin1.setBgColor("0D47A1")
fin2 = new WordCell()
fin2.addRun("QA", [:bold = true, :color = "white"])
fin2.setRowSpan(2)
fin2.setVerticalAlign("center")
fin2.setAlign("center")
fin2.setBgColor("E65100")
fh1 = wordCell("Dept", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
fh2 = wordCell("Project", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
fh3 = wordCell("Q1 Budget", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
fh4 = wordCell("Q1 Actual", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
fh5 = wordCell("Q2 Budget", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
fh6 = wordCell("Q2 Actual", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
fh7 = wordCell("Q3 Budget", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
fh8 = wordCell("Q3 Actual", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
fh9 = wordCell("Q4 Budget", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
fh10 = wordCell("Q4 Actual", [:bold = true, :color = "white", :bgColor = "263238", :align = "center", :verticalAlign = "center"])
doc.addTable([
[fh1, fh2, fh3, fh4, fh5, fh6, fh7, fh8, fh9, fh10],
[fin1, "Ring 1.26", "$12K", "$11K", "$13K", "$12K", "$13K", "$13K", "$12K", "$12K"],
[wordMergeCell(), "PWCT2", "$7K", "$6K", "$8K", "$7K", "$8K", "$8K", "$7K", "$7K"],
[wordMergeCell(), "Supernova", "$5K", "$4K", "$5K", "$5K", "$5K", "$4K", "$5K", "$5K"],
[fin2, "Automation", "$3K", "$3K", "$3K", "$3K", "$4K", "$4K", "$4K", "$3K"],
[wordMergeCell(), "Manual QA", "$2K", "$2K", "$2K", "$2K", "$2K", "$2K", "$3K", "$2K"]
], [
:headerRow = true,
:borderStyle = "single",
:headerHeight = 600,
:headerVAlign = "center",
:cellVAlign = "center",
:evenRowBgColor = "F5F5F5",
:colWidths = [2, 3, 2.3, 2.3, 2.3, 2.3, 2.3, 2.3, 2.3, 2.3]
])
doc.addLandscapeEnd()
# --- Page 3: Back to portrait ---
doc.addHeading("Summary & Next Steps", 1)
doc.addParagraph("All projects are on track. Key priorities for 2025:", NULL)
doc.addBulletList([
"Complete Ring 1.26 release with new features",
"Publish research papers",
"Expand PWCT2 visual programming capabilities",
"Grow community and documentation"
])
doc.addParagraph("Overall budget utilization: 93% - within acceptable range.", NULL)
if doc.save("demo_richcells4_report.docx")
? " Created: demo_richcells4_report.docx"
else
? " FAILED: demo_richcells4_report.docx"
ok
? ""
? "=============================================="
? " All demos completed!"
? "=============================================="
? ""part7_comments.ring#
samples/UsingDOCXLib/part7_comments.ring
/*
DOCXLib - Demo (Comments)
*/
load "docxlib.ring"
/*
Demonstrates three features:
1. Comments (annotations)
2. SEQ captions (auto-numbered figures and tables)
3. Mail merge fields
*/
doc = new WordWriter()
doc.setTitle("DOCXLib — Features Demo")
doc.setAuthor("Mahmoud")
doc.setPageSize("a4")
doc.setHeader("DOCXLib — Features Demo")
doc.showPageNumbers("right")
# -------------------------------------------------------
# PAGE 1 — Overview
# -------------------------------------------------------
doc.addHeading("DOCXLib — Three Features", 1)
doc.addParagraph("Three features are introduced in this sample.", NULL)
doc.addParagraph("", NULL)
doc.addTable(
[
["#", "Feature", "Key Methods"],
["1", "Comments (annotations)", "addCommentedParagraph() / addComment()"],
["2", "SEQ captions", "addFigureCaption() / addTableCaption()"],
["3", "Mail merge fields", "addMergeFieldParagraph() / addMergeTemplate()"]
],
[
:headerRow = true, :borderStyle = "single",
:headerBgColor = "1F4E79", :headerTextColor = "FFFFFF",
:evenRowBgColor = "EEF3F8", :colWidths = [1, 5, 8.5]
]
)
doc.addPageBreak()
# -------------------------------------------------------
# PAGE 2 — Feature 1: Comments
# -------------------------------------------------------
doc.addHeading("Feature 1 — Comments (Annotations)", 1)
doc.addParagraph("Comments let you embed reviewer notes into a document programmatically. Each comment is anchored to a specific paragraph and visible in Word's comment pane or as a balloon in the margin.", NULL)
doc.addParagraph("", NULL)
doc.addBorderedParagraph(
"API: addCommentedParagraph(text, commentText, options) attaches a comment to a paragraph. " +
"Use :commentAuthor and :commentDate in options to set the reviewer name and timestamp.",
[:borderStyle = "single", :borderColor = "2E75B6", :bgColor = "DEEAF1",
:spaceBefore = 80, :spaceAfter = 80, :indent = 240]
)
doc.addParagraph("", NULL)
doc.addHeading("Example Comments", 2)
doc.addCommentedParagraph(
"The Ring programming language is an open-source project.",
"Consider adding a citation or reference link here.",
[:commentAuthor = "Editor", :commentDate = "2025-03-01T09:00:00Z"]
)
doc.addCommentedParagraph(
"DOCXLib supports rich document generation including tables, images, headers, footers, watermarks, and comments.",
"Great feature list",
[:commentAuthor = "Reviewer", :commentDate = "2025-03-01T10:30:00Z"]
)
doc.addCommentedParagraph(
"Performance benchmarks show that Ring generates a 50-page document in under 200ms on a standard desktop.",
"Please verify this number against the latest benchmark run before publishing.",
[:commentAuthor = "QA Team", :commentDate = "2025-03-02T14:15:00Z", :bold = true]
)
doc.addParagraph("", NULL)
doc.addParagraph("Each paragraph above has a comment attached. Open this file in Microsoft Word and switch to Review → Show Comments to see all three annotations in the comment pane.", [:italic = true, :color = "595959"])
doc.addParagraph("", NULL)
doc.addHeading("Multiple Reviewers Example", 2)
doc.addCommentedParagraph(
"Section 2.1 — Architecture Overview",
"This section needs a diagram. Use addImage() to insert the architecture PNG.",
[:commentAuthor = "Mahmoud", :commentDate = "2025-03-03T08:00:00Z", :style = "Heading3"]
)
doc.addCommentedParagraph(
"The virtual machine uses a stack-based design.",
"Too technical for the introduction — move this paragraph to the implementation section.",
[:commentAuthor = "Technical Writer", :commentDate = "2025-03-03T09:45:00Z"]
)
doc.addPageBreak()
# -------------------------------------------------------
# PAGE 3 — Feature 2: SEQ Captions
# -------------------------------------------------------
doc.addHeading("Feature 2 — SEQ Captions (Auto-Numbered)", 1)
doc.addParagraph("SEQ captions insert a Word SEQ field that automatically increments when the document is updated (F9). This produces 'Figure 1', 'Figure 2', 'Table 1', 'Table 2' labels that renumber themselves if items are added or removed.", NULL)
doc.addParagraph("", NULL)
doc.addBorderedParagraph(
"API: addFigureCaption(text) inserts a 'Figure N — text' caption. " +
"addTableCaption(text) inserts a 'Table N — text' caption. " +
"Both use Word's SEQ field internally — press F9 in Word to update all numbers.",
[:borderStyle = "single", :borderColor = "375623", :bgColor = "E2EFDA",
:spaceBefore = 80, :spaceAfter = 80, :indent = 240]
)
doc.addParagraph("", NULL)
# --- Figure captions ---
doc.addHeading("Figure Captions", 2)
doc.addParagraph("The three grey boxes below represent image placeholders. Each is followed by an auto-numbered figure caption.", NULL)
doc.addParagraph("", NULL)
# Simulate figure with a shaded paragraph as placeholder
doc.addParagraph("[ Image placeholder: Ring language logo ]",
[:align = "center", :bgColor = "D0D0D0", :italic = true,
:spaceBefore = 120, :spaceAfter = 0])
doc.addFigureCaption("The Ring programming language logo")
doc.addParagraph("", NULL)
doc.addParagraph("[ Image placeholder: PWCT2 screenshot ]",
[:align = "center", :bgColor = "D0D0D0", :italic = true,
:spaceBefore = 120, :spaceAfter = 0])
doc.addFigureCaption("PWCT2 visual programming environment")
doc.addParagraph("", NULL)
doc.addParagraph("[ Image placeholder: Supernova IDE screenshot ]",
[:align = "center", :bgColor = "D0D0D0", :italic = true,
:spaceBefore = 120, :spaceAfter = 0])
doc.addFigureCaption("Supernova language integrated development environment")
doc.addParagraph("", NULL)
# --- Table captions ---
doc.addHeading("Table Captions", 2)
doc.addParagraph("Tables can also carry auto-numbered captions using addTableCaption().", NULL)
doc.addParagraph("", NULL)
doc.addTableCaption("Ring language release history")
doc.addTable(
[
["Version", "Year", "Major Features"],
["1.0", "2016", "Initial public release"],
["1.12", "2020", "List of features 1"],
["1.18", "2023", "List of features 2"],
["1.22", "2024", "List of features 3"],
["1.26", "2026", "List of features 4"]
],
[
:headerRow = true, :borderStyle = "single",
:headerBgColor = "375623", :headerTextColor = "FFFFFF",
:evenRowBgColor = "E2EFDA", :colWidths = [2.5, 2.5, 9.5]
]
)
doc.addParagraph("", NULL)
doc.addTableCaption("DOCXLib feature coverage by version")
doc.addTable(
[
["Version", "Features Added"],
["0.1 – 0.5", "Paragraphs, headings, tables, images, headers, footers, lists"],
["0.6", "Text boxes, first-page headers, rich cells, paragraph shading"],
["0.7", "Odd/even headers, paragraph borders, landscape sections, page background"],
["0.8", "Bookmarks, cross-references, tab stops with leaders, line numbers"],
["0.9", "Comments, SEQ captions, mail merge fields"]
],
[
:headerRow = true, :borderStyle = "single",
:headerBgColor = "1F4E79", :headerTextColor = "FFFFFF",
:evenRowBgColor = "DEEAF1", :colWidths = [3, 11.5]
]
)
doc.addPageBreak()
# -------------------------------------------------------
# PAGE 4 — Feature 3: Mail Merge Fields
# -------------------------------------------------------
doc.addHeading("Feature 3 — Mail Merge Fields", 1)
doc.addParagraph("Mail merge fields are MERGEFIELD placeholders embedded in a template document. When Word merges the template with a data source (Excel, CSV, database), each placeholder is replaced with the actual data value for that record.", NULL)
doc.addParagraph("", NULL)
doc.addBorderedParagraph(
"API: addMergeFieldParagraph(fields, options) adds a paragraph where strings are " +
"literal text and lists [:field='Name'] are MERGEFIELD codes. " +
"addMergeTemplate(lines) adds a series of such paragraphs at once.",
[:borderStyle = "single", :borderColor = "7030A0", :bgColor = "EDE7F6",
:spaceBefore = 80, :spaceAfter = 80, :indent = 240]
)
doc.addParagraph("", NULL)
# -- Example 1: Formal letter template --
doc.addHeading("Example 1 — Formal Letter Template", 2)
doc.addParagraph("A classic merge letter. Each «field» marker will be replaced by Word during merge.", NULL)
doc.addParagraph("", NULL)
doc.addMergeFieldParagraph([[:field="RecipientName"]], [:bold = true, :size = 13])
doc.addMergeFieldParagraph([[:field="CompanyName"]], NULL)
doc.addMergeFieldParagraph([[:field="Address"]], NULL)
doc.addMergeFieldParagraph([[:field="City"], ", ", [:field="Country"]], NULL)
doc.addParagraph("", NULL)
doc.addMergeFieldParagraph(["Date: ", [:field="LetterDate"]], NULL)
doc.addParagraph("", NULL)
doc.addMergeFieldParagraph(["Dear ", [:field="Salutation"], " ", [:field="LastName"], ","], NULL)
doc.addParagraph("", NULL)
doc.addMergeFieldParagraph(
["We are pleased to confirm your registration for the ", [:field="EventName"],
" scheduled on ", [:field="EventDate"], " in ", [:field="EventCity"], "."],
NULL
)
doc.addParagraph("", NULL)
doc.addMergeFieldParagraph(
["Your registration number is ", [:field="RegNumber"],
" and your seat assignment is ", [:field="SeatNumber"], "."],
NULL
)
doc.addParagraph("", NULL)
doc.addParagraph("Yours sincerely,", NULL)
doc.addParagraph("", NULL)
doc.addMergeFieldParagraph([[:field="SenderName"]], [:bold = true])
doc.addMergeFieldParagraph([[:field="SenderTitle"]], NULL)
doc.addMergeFieldParagraph([[:field="Organisation"]], NULL)
doc.addParagraph("", NULL)
# -- Example 2: Invoice template --
doc.addHeading("Example 2 — Invoice Template", 2)
doc.addParagraph("", NULL)
doc.addParagraph("INVOICE", [:bold = true, :size = 20, :align = "center"])
doc.addParagraph("", NULL)
doc.addMergeFieldParagraph(["Invoice No: ", [:field="InvoiceNumber"]], [:bold = true])
doc.addMergeFieldParagraph(["Date: ", [:field="InvoiceDate"]], NULL)
doc.addMergeFieldParagraph(["Due Date: ", [:field="DueDate"]], NULL)
doc.addParagraph("", NULL)
doc.addMergeFieldParagraph(["Bill To: ", [:field="ClientName"]], [:bold = true])
doc.addMergeFieldParagraph([[:field="ClientAddress"]], NULL)
doc.addMergeFieldParagraph([[:field="ClientCity"], " — ", [:field="ClientCountry"]], NULL)
doc.addParagraph("", NULL)
doc.addTable(
[
["Description", "Qty", "Unit Price", "Total"],
["«ItemDescription»", "«Qty»", "«UnitPrice»", "«LineTotal»"],
["Subtotal", "", "", "«Subtotal»"],
["Tax («TaxRate»%)", "", "", "«TaxAmount»"],
["Total Due", "", "", "«TotalDue»"]
],
[
:headerRow = true, :borderStyle = "single",
:headerBgColor = "404040", :headerTextColor = "FFFFFF",
:evenRowBgColor = "F5F5F5", :colWidths = [7, 2, 3, 2.5]
]
)
doc.addParagraph("", NULL)
doc.addParagraph("To use this template:", [:bold = true])
doc.addParagraph("1. Open the document in Word.", NULL)
doc.addParagraph("2. Go to Mailings → Select Recipients → Use an Existing List and choose your data source (Excel or CSV).", NULL)
doc.addParagraph("3. Click Finish & Merge → Edit Individual Documents to generate one letter per record.", NULL)
# -------------------------------------------------------
# SAVE
# -------------------------------------------------------
filename = "demo_comments.docx"
if doc.save(filename)
? "OK - Saved: " + filename
else
? "ERROR - Failed to save"
okpart8_controls.ring#
samples/UsingDOCXLib/part8_controls.ring
/*
DOCXLib - Demo (Comments)
*/
load "docxlib.ring"
/*
Content Controls
Checkboxes, dropdowns, text inputs
*/
doc = new WordWriter()
doc.setTitle("Content Controls Demo")
doc.setAuthor("Mahmoud")
doc.setPageSize("a4")
doc.setHeader("DOCXLib — Content Controls")
doc.showPageNumbers("right")
doc.addHeading("Feature 1 — Content Controls", 1)
doc.addParagraph("Interactive form elements embedded directly in Word.", NULL)
doc.addParagraph("", NULL)
# -- Checkboxes --
doc.addHeading("Checkboxes", 2)
doc.addCheckbox("I have read and accept the Terms and Conditions", true)
doc.addCheckbox("Subscribe to the Ring language newsletter", false)
doc.addCheckbox("Enable two-factor authentication", true)
doc.addCheckbox("Receive promotional emails", false)
doc.addCheckbox("Allow anonymous usage statistics", true)
doc.addParagraph("", NULL)
# -- Dropdowns --
doc.addHeading("Dropdown Lists", 2)
doc.addDropdown("Country",
["Saudi Arabia", "Egypt", "UAE", "Kuwait", "Jordan", "Morocco", "Other"],
"Saudi Arabia")
doc.addParagraph("", NULL)
doc.addDropdown("Experience Level",
["Beginner", "Intermediate", "Advanced", "Expert"],
"Intermediate")
doc.addParagraph("", NULL)
doc.addDropdown("Preferred Format",
["DOCX", "PDF", "HTML", "Markdown"],
"DOCX")
doc.addParagraph("", NULL)
# -- Text Inputs --
doc.addHeading("Text Input Fields", 2)
doc.addTextInput("Full Name", "", "Enter your full name here")
doc.addParagraph("", NULL)
doc.addTextInput("Email Address", "", "name@example.com")
doc.addParagraph("", NULL)
doc.addTextInput("Organisation", "King Saud University", NULL)
doc.addParagraph("", NULL)
doc.addTextInput("Comments", "", "Type your comments here...")
filename = "demo_controls.docx"
if doc.save(filename)
? "OK - Saved: " + filename
else
? "ERROR - Failed to save"
okpart9_themes.ring#
samples/UsingDOCXLib/part9_themes.ring
/*
DOCXLib - Demo (themes)
*/
load "docxlib.ring"
/*
Document Themes
8 built-in colour themes affecting headings and theme1.xml
*/
doc = new WordWriter()
doc.setTitle("Document Themes Demo")
doc.setAuthor("Mahmoud")
doc.setPageSize("a4")
# Apply the Blue theme — headings and theme1.xml use this palette
doc.setTheme("Blue")
doc.setHeader("DOCXLib — Document Themes")
doc.showPageNumbers("right")
doc.addHeading("Document Themes", 1)
doc.addParagraph("setTheme() applies a named colour palette to the document. Heading colours change automatically. A word/theme/theme1.xml file is written into the DOCX package.", NULL)
doc.addParagraph("", NULL)
doc.addHeading("Heading 1 — accent1 colour", 1)
doc.addHeading("Heading 2 — accent1 colour", 2)
doc.addHeading("Heading 3 — accent2 colour", 3)
doc.addHeading("Heading 4 — accent2 colour", 4)
doc.addHeading("Heading 5 — dk2 colour", 5)
doc.addHeading("Heading 6 — dk2 colour", 6)
doc.addParagraph("", NULL)
doc.addParagraph("This document uses the Blue theme. All six heading levels above pick their colour automatically from the theme palette.", NULL)
doc.addParagraph("", NULL)
doc.addTable(
[
["Theme", "Accent 1", "Accent 2", "DK2"],
["Office", "#4472C4 Blue", "#ED7D31 Orange", "#44546A Slate"],
["Blue", "#1E6BB5 DeepBlue", "#2E75B6 MidBlue","#1F3864 Navy"],
["Dark", "#88C0D0 IceBlue", "#81A1C1 Steel", "#C8D0D8 Silver"],
["Green", "#375623 Forest", "#70AD47 Lime", "#375623 Forest"],
["Red", "#C00000 DarkRed", "#FF0000 Red", "#7B0000 Maroon"],
["Purple", "#7030A0 Purple", "#9B59B6 Violet", "#3B0764 DeepPurple"],
["Teal", "#00796B Teal", "#009688 MedTeal","#004D40 DarkTeal"],
["Warm", "#E65100 DeepOrange","#F57C00 Orange","#6D3B00 Brown"]
],
[
:headerRow = true, :borderStyle = "single",
:headerBgColor = "1E6BB5", :headerTextColor = "FFFFFF",
:evenRowBgColor = "DEE9F7", :colWidths = [2.5, 4.5, 4.5, 4.5]
]
)
filename = "demo_themes.docx"
if doc.save(filename)
? "OK - Saved: " + filename
else
? "ERROR - Failed to save"
okpart10_bookmarks.ring#
samples/UsingDOCXLib/part10_bookmarks.ring
/*
DOCXLib - Demo (Bookmarks)
*/
load "docxlib.ring"
/*
Demonstrates three new features:
1. Bookmarks and cross-references
2. Tab stops (with leaders)
3. Line numbers
*/
doc = new WordWriter()
doc.setTitle("DOCXLib - Features Demo")
doc.setAuthor("Mahmoud")
doc.setPageSize("a4")
doc.setHeader("DOCXLib - Features Demo")
doc.showPageNumbers("right")
# -------------------------------------------------------
# PAGE 1 — Cover / Overview
# -------------------------------------------------------
doc.addHeading("DOCXLib", 1)
doc.addParagraph("Three features were demonstrated in this sample.", NULL)
doc.addParagraph("", NULL)
doc.addTable(
[
["#", "Feature", "Key Methods"],
["1", "Bookmarks + cross-references", "addBookmarkedParagraph() / addCrossRef()"],
["2", "Tab stops with leaders", "addTabbedParagraph() with :tabStops"],
["3", "Line numbers", "enableLineNumbers() / :suppressLineNumbers"]
],
[
:headerRow = true, :borderStyle = "single",
:headerBgColor = "1F4E79", :headerTextColor = "FFFFFF",
:evenRowBgColor = "EEF3F8", :colWidths = [1, 5.5, 8]
]
)
doc.addPageBreak()
# -------------------------------------------------------
# PAGE 2 — Feature 1: Bookmarks + Cross-References
# -------------------------------------------------------
doc.addBookmarkedParagraph("bm_feature1", "Feature 1 — Bookmarks and Cross-References", [:style = "Heading1"])
doc.addParagraph("A bookmark marks a named location in the document. A cross-reference inserts a field that automatically shows the page number where the bookmark lives — updating whenever Word recalculates fields (F9).", NULL)
doc.addParagraph("", NULL)
doc.addBorderedParagraph(
"API: addBookmarkedParagraph(name, text, options) wraps a paragraph in a bookmark. addCrossRef(name, prefix) inserts a REF field that resolves to the bookmark's page.",
[:borderStyle = "single", :borderColor = "2E75B6", :bgColor = "DEEAF1",
:spaceBefore = 80, :spaceAfter = 80, :indent = 240]
)
doc.addParagraph("", NULL)
# Section 1.1 — bookmark it
doc.addBookmarkedParagraph("bm_sec1_1", "1.1 Placing a Bookmark", [:style = "Heading2"])
doc.addParagraph("Use addBookmarkedParagraph() to mark any paragraph. The bookmark name must be unique across the document. Names may contain letters, digits and underscores — no spaces.", NULL)
doc.addParagraph("", NULL)
# Section 1.2 — bookmark it
doc.addBookmarkedParagraph("bm_sec1_2", "1.2 Inserting a Cross-Reference", [:style = "Heading2"])
doc.addParagraph("Use addCrossRef(bookmarkName, prefixText) anywhere after (or before) the bookmark. Word replaces the field with the live page number when you press F9 or print.", NULL)
doc.addParagraph("", NULL)
# Section 1.3 — cross-references back to earlier sections
doc.addBookmarkedParagraph("bm_sec1_3", "1.3 Live Examples", [:style = "Heading2"])
doc.addParagraph("The lines below are cross-references pointing back to sections on this page:", NULL)
doc.addParagraph("", NULL)
doc.addCrossRef("bm_sec1_1", "Section 1.1 starts")
doc.addCrossRef("bm_sec1_2", "Section 1.2 starts")
doc.addCrossRef("bm_feature2", "Feature 2 (Tab Stops) starts")
doc.addCrossRef("bm_feature3", "Feature 3 (Line Numbers) starts")
doc.addParagraph("", NULL)
doc.addParagraph("Press F9 in Word (or Ctrl+A then F9) to update all cross-reference fields to their live page numbers.", [:italic = true, :color = "595959"])
doc.addPageBreak()
# -------------------------------------------------------
# PAGE 3 — Feature 2: Tab Stops
# -------------------------------------------------------
doc.addBookmarkedParagraph("bm_feature2", "Feature 2 — Tab Stops with Leaders", [:style = "Heading1"])
doc.addParagraph("Tab stops position text at precise horizontal locations within a paragraph. The optional leader fills the gap between the previous text and the tab stop with a repeated character (dots, dashes, underscores).", NULL)
doc.addParagraph("", NULL)
doc.addBorderedParagraph(
"API: addTabbedParagraph(segments, options). Each item in segments is one column of text. Define :tabStops in options as a list of [:pos, :align, :leader].",
[:borderStyle = "single", :borderColor = "375623", :bgColor = "E2EFDA",
:spaceBefore = 80, :spaceAfter = 80, :indent = 240]
)
doc.addParagraph("", NULL)
doc.addHeading("Example 1 — Table of Contents style (dot leader)", 2)
doc.addParagraph("Right-aligned page number with dot leader — classic TOC look:", NULL)
doc.addParagraph("", NULL)
# TOC-style entries: title on left, page number right-aligned with dots
tocTabs = [:tabStops = [[:pos = 8500, :align = "right", :leader = "dot"]]]
doc.addTabbedParagraph(["Introduction", "1"], tocTabs)
doc.addTabbedParagraph(["Feature 1 — Bookmarks", "2"], tocTabs)
doc.addTabbedParagraph(["Feature 2 — Tab Stops", "3"], tocTabs)
doc.addTabbedParagraph(["Feature 3 — Line Numbers", "4"], tocTabs)
doc.addTabbedParagraph(["Conclusion", "5"], tocTabs)
doc.addParagraph("", NULL)
doc.addHeading("Example 2 — Price list (dot leader)", 2)
doc.addParagraph("Product names on the left, prices right-aligned:", NULL)
doc.addParagraph("", NULL)
priceTabs = [:tabStops = [[:pos = 8500, :align = "right", :leader = "dot"]]]
doc.addTabbedParagraph(["Ring Language License", "$0.00 (Open Source)"], priceTabs)
doc.addTabbedParagraph(["DOCXLib Library", "$0.00 (Open Source)"], priceTabs)
doc.addTabbedParagraph(["PWCT2 Visual IDE", "$0.00 (Open Source)"], priceTabs)
doc.addTabbedParagraph(["Supernova Language", "$0.00 (Open Source)"], priceTabs)
doc.addParagraph("", NULL)
doc.addHeading("Example 3 — Multi-column layout (no leader)", 2)
doc.addParagraph("Three columns using left tab stops — simulates a simple table without borders:", NULL)
doc.addParagraph("", NULL)
# Header row (bold)
colTabs = [
:bold = true,
:tabStops = [
[:pos = 3600, :align = "left", :leader = "none"],
[:pos = 6800, :align = "left", :leader = "none"]
]
]
doc.addTabbedParagraph(["Country", "Capital", "Population"], colTabs)
# Data rows
colTabsNormal = [
:tabStops = [
[:pos = 3600, :align = "left", :leader = "none"],
[:pos = 6800, :align = "left", :leader = "none"]
]
]
doc.addTabbedParagraph(["Saudi Arabia", "Riyadh", "35 million"], colTabsNormal)
doc.addTabbedParagraph(["Egypt", "Cairo", "104 million"], colTabsNormal)
doc.addTabbedParagraph(["UAE", "Abu Dhabi","10 million"], colTabsNormal)
doc.addTabbedParagraph(["Kuwait", "Kuwait City","4.7 million"], colTabsNormal)
doc.addParagraph("", NULL)
doc.addHeading("Example 4 — Underscore leader (signature lines)", 2)
doc.addParagraph("Common in forms and certificates:", NULL)
doc.addParagraph("", NULL)
sigTabs = [:tabStops = [[:pos = 7200, :align = "left", :leader = "underscore"]]]
doc.addTabbedParagraph(["Name: ", ""], sigTabs)
doc.addTabbedParagraph(["Signature: ", ""], sigTabs)
doc.addTabbedParagraph(["Date: ", ""], sigTabs)
doc.addPageBreak()
# -------------------------------------------------------
# PAGE 4 — Feature 3: Line Numbers
# -------------------------------------------------------
doc.addBookmarkedParagraph("bm_feature3", "Feature 3 — Line Numbers", [:style = "Heading1"])
doc.addParagraph("Line numbers are printed in the left margin beside each line of text. They are required by legal document standards and many academic journals.", NULL)
doc.addParagraph("", NULL)
doc.addBorderedParagraph(
"API: enableLineNumbers(options) activates line numbering. Options: :start (first number), :step (show every N lines), :distance (gap from text in twips), :restart (newPage | newSection | continuous). Use [:suppressLineNumbers = true] on a paragraph to exclude it from numbering.",
[:borderStyle = "single", :borderColor = "7030A0", :bgColor = "EDE7F6",
:spaceBefore = 80, :spaceAfter = 80, :indent = 240]
)
doc.addParagraph("", NULL)
# Enable line numbers from here — step 5 so numbers show every 5 lines
doc.enableLineNumbers([:start = 1, :step = 5, :restart = "newPage"])
doc.addHeading("Numbered Section", 2)
doc.addParagraph("This paragraph has a line number. The document was configured with enableLineNumbers() using step:5, so numbers appear every 5 lines. This lets readers quickly locate specific passages without cluttering the margin with a number on every line.", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("Legal contracts, academic papers, court submissions, legislative drafts, and source code printouts all benefit from line numbers. The Ring programming language itself is often presented with numbered listings.", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("Cross-references in legal documents say things like 'see line 42' rather than 'see page 3, paragraph 2' — far more precise when the document may be reformatted. This is the primary reason courts and journals mandate line numbers.", NULL)
doc.addParagraph("", NULL)
# This paragraph suppresses its own line number (e.g. a caption or note)
doc.addParagraph("(This paragraph has suppressLineNumbers:true — it does not count toward line numbering and shows no line number in the margin.)",
[:italic = true, :color = "595959", :suppressLineNumbers = true])
doc.addParagraph("", NULL)
doc.addParagraph("Numbering resumes on the next paragraph after the suppressed one. The count continues from where it left off before the suppressed line.", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("The distance between the line number and the text body is controlled by :distance in twips (default 360 twips = 0.25 inch). Increase this if you need wider line numbers or if the document has a very narrow left margin.", NULL)
doc.addParagraph("", NULL)
doc.addHeading("Configuration Reference", 2)
doc.addTable(
[
["Option", "Type", "Default", "Description"],
[":start", "integer", "1", "Line number of the first line"],
[":step", "integer", "1", "Print number every N lines (5 = every 5th)"],
[":distance", "integer", "360", "Gap from left text edge in twips (720 = 0.5in)"],
[":restart", "string", "newPage", "newPage | newSection | continuous"]
],
[
:headerRow = true, :borderStyle = "single",
:headerBgColor = "4B0082", :headerTextColor = "FFFFFF",
:evenRowBgColor = "F3E5F5", :colWidths = [3, 2.5, 2.5, 6.5]
]
)
# -------------------------------------------------------
# SAVE
# -------------------------------------------------------
filename = "demo_bookmarks.docx"
if doc.save(filename)
? "OK - Saved: " + filename
else
? "ERROR - Failed to save"
okpart11_tableofcontents.ring#
samples/UsingDOCXLib/part11_tableofcontents.ring
/*
DOCXLib - Demo (Table of Contents)
*/
load "docxlib.ring"
/*
Demonstrates:
* addTableOfFigures(title) - collects all Figure N captions
* addTableOfTables(title) - collects all Table N captions
* addTableOfSeq(label, title) - generic version for any SEQ label
* Both lists live-update in Word with F9 / Update Fields
*/
doc = new WordWriter()
doc.setTitle("DOCXLib - Table of Figures & Tables Demo")
doc.setAuthor("Mahmoud")
doc.setPageSize("a4")
doc.setTheme("Blue")
doc.setHeader("DOCXLib - Table of Figures & Tables")
doc.showPageNumbers("right")
# -----------------------------------------------------------
# PAGE 1 - Table of Figures + Table of Tables (front matter)
# -----------------------------------------------------------
doc.addHeading("Document Overview", 1)
doc.addParagraph("This document demonstrates the Table of Figures and Table of Tables feature. The lists below are live Word fields - press F9 or right-click and choose Update Field to populate page numbers.", NULL)
doc.addParagraph("", NULL)
# --- Table of Figures ---
doc.addTableOfFigures("List of Figures")
doc.addParagraph("", NULL)
# --- Table of Tables ---
doc.addTableOfTables("List of Tables")
doc.addParagraph("", NULL)
doc.addPageBreak()
# -----------------------------------------------------------
# PAGE 2 - Figures with captions
# -----------------------------------------------------------
doc.addHeading("Chapter 1 - Ring Language Architecture", 1)
doc.addParagraph("This chapter provides an overview of the Ring language runtime and its major components.", NULL)
doc.addParagraph("", NULL)
doc.addHeading("1.1 Virtual Machine", 2)
doc.addParagraph("The Ring VM is a stack-based bytecode interpreter written in C. It processes compiled Ring bytecode and manages the execution stack, variable scopes, and garbage collection.", NULL)
doc.addParagraph("", NULL)
# Figure 1 - placeholder box (grey rect)
doc.addRect([:width=12, :height=4, :fillColor="E8E8E8", :lineColor="AAAAAA",
:text="[ Figure Placeholder: Ring VM Architecture Diagram ]",
:textColor="555555", :textBold=false])
doc.addFigureCaption("Ring Virtual Machine architecture overview")
doc.addParagraph("", NULL)
doc.addHeading("1.2 Compiler Pipeline", 2)
doc.addParagraph("Ring source code passes through a multi-stage compiler pipeline before execution. Each stage transforms the representation closer to executable bytecode.", NULL)
doc.addParagraph("", NULL)
doc.addRect([:width=12, :height=3.5, :fillColor="E8F4E8", :lineColor="88AA88",
:text="[ Figure Placeholder: Compiler Pipeline Stages ]",
:textColor="336633", :textBold=false])
doc.addFigureCaption("Multi-stage Ring compiler pipeline: Lexer → Parser → Code Generation")
doc.addParagraph("", NULL)
doc.addPageBreak()
# -----------------------------------------------------------
# PAGE 3 - More figures + tables
# -----------------------------------------------------------
doc.addHeading("Chapter 2 - DOCXLib Feature Coverage", 1)
doc.addParagraph("DOCXLib provides comprehensive Word document generation from Ring code. The following tables and figures summarise its capabilities.", NULL)
doc.addParagraph("", NULL)
# Table 1
doc.addTableCaption("DOCXLib version history and major milestones")
doc.addTable(
[
["Version", "Release Focus", "Key Features Added"],
["0.1–0.5", "Core document elements","Paragraphs, tables, images, lists, styles"],
["0.6", "Layout & formatting", "Text boxes, watermarks, multi-column, RTL"],
["0.7", "Headers & structure", "Odd/even headers, page background, page borders"],
["0.8", "Reference features", "Bookmarks, cross-refs, tab stops, line numbers"],
["0.9", "Review & automation", "Comments, SEQ captions, mail merge fields"],
["0.95", "Rich content", "Content controls, drawing shapes, themes"],
["1.0", "Navigation lists", "Table of Figures, Table of Tables"]
],
[
:headerRow = true, :borderStyle = "single",
:headerBgColor = "1E6BB5", :headerTextColor = "FFFFFF",
:evenRowBgColor = "DEE9F7", :colWidths = [2, 4, 9.5]
]
)
doc.addParagraph("", NULL)
doc.addHeading("2.1 Feature Distribution", 2)
doc.addParagraph("The chart below illustrates how library features are distributed across functional categories.", NULL)
doc.addParagraph("", NULL)
doc.addRect([:width=12, :height=4.5, :fillColor="F0F4FF", :lineColor="4472C4",
:text="[ Figure Placeholder: Feature Distribution Chart ]",
:textColor="1E6BB5", :textBold=false])
doc.addFigureCaption("DOCXLib feature distribution by category")
doc.addParagraph("", NULL)
# Table 2
doc.addTableCaption("Feature count by category in DOCXLib")
doc.addTable(
[
["Category", "Feature Count", "Example Methods"],
["Text & Paragraphs", "12", "addParagraph, addHeading, addHyperlink"],
["Tables", "8", "addTable, addTableCaption"],
["Images & Shapes", "10", "addImage, addShape, addRect, addEllipse"],
["Headers & Footers", "8", "setHeader, setFooter, showPageNumbers"],
["Lists", "6", "addBulletList, addNumberedList"],
["References", "8", "addBookmark, addCrossRef, addTOC, addTableOfFigures"],
["Form Controls", "3", "addCheckbox, addDropdown, addTextInput"],
["Document Settings", "10", "setTheme, setPageSize, setMargins"],
["Total", "65+", "-"]
],
[
:headerRow = true, :borderStyle = "single",
:headerBgColor = "375623", :headerTextColor = "FFFFFF",
:evenRowBgColor = "E2EFDA", :colWidths = [4.5, 3, 8]
]
)
doc.addParagraph("", NULL)
doc.addPageBreak()
# -----------------------------------------------------------
# PAGE 4 - More figures on a new page
# -----------------------------------------------------------
doc.addHeading("Chapter 3 - Usage Examples", 1)
doc.addParagraph("", NULL)
doc.addHeading("3.1 Document Generation Workflow", 2)
doc.addParagraph("The typical workflow for generating a Word document with DOCXLib:", NULL)
doc.addParagraph("", NULL)
doc.addRect([:width=12, :height=3, :fillColor="FFF3E0", :lineColor="E65100",
:text="[ Figure Placeholder: Document Generation Workflow Diagram ]",
:textColor="6D3B00", :textBold=false])
doc.addFigureCaption("Typical DOCXLib document generation workflow")
doc.addParagraph("", NULL)
doc.addHeading("3.2 Table of Figures API", 2)
doc.addParagraph("The three methods:", NULL)
doc.addParagraph("", NULL)
# Table 3
doc.addTableCaption("Methods for auto-generated caption lists")
doc.addTable(
[
["Method", "Purpose"],
["addTableOfFigures(title)", "Collects all Figure N captions"],
["addTableOfTables(title)", "Collects all Table N captions"],
["addTableOfSeq(seqLabel, title)", "Generic - any SEQ label (Equation, Chart, etc.)"]
],
[
:headerRow = true, :borderStyle = "single",
:headerBgColor = "7030A0", :headerTextColor = "FFFFFF",
:evenRowBgColor = "EDE7F6", :colWidths = [7, 8.5]
]
)
doc.addParagraph("", NULL)
doc.addBorderedParagraph(
"How it works: Word uses a TOC field with the \c switch: " +
' TOC \c "Figure" \h' + NL +
"This instructs Word to scan the document for all SEQ Figure fields, " +
"collect their caption text and page numbers, and render them as a " +
"dot-leader list - exactly what Insert > Table of Figures produces. " +
"Press F9 to update after document generation.",
[:borderStyle = "single", :borderColor = "7030A0", :bgColor = "EDE7F6",
:spaceBefore = 80, :spaceAfter = 80, :indent = 240]
)
# -----------------------------------------------------------
# SAVE
# -----------------------------------------------------------
filename = "demo_tableofcontents.docx"
if doc.save(filename)
? "OK - Saved: " + filename
else
? "ERROR - Failed to save"
okpart12_footnotes.ring#
samples/UsingDOCXLib/part12_footnotes.ring
/*
DOCXLib - Demo (Footnotes)
*/
load "docxlib.ring"
/*
Demonstrates:
1. Superscript and subscript
2. Line spacing (single, 1.5x, double, exact)
3. Nested / multi-level bullet and numbered lists
4. Footnotes and endnotes
*/
# ============================================================================
# Demo 1: Superscript & Subscript
# ============================================================================
doc1 = new WordWriter()
doc1.setTitle("Demo 1 – Superscript & Subscript")
doc1.setAuthor("DOCXLib Demo")
doc1.addHeading("Superscript & Subscript Demo", 1)
doc1.addParagraph("Superscript and subscript are enabled via run options in any paragraph or rich paragraph.", NULL)
doc1.addHeading("Scientific Formulas", 2)
# Chemical formula using subscript
doc1.addRichParagraph([
["Water: H", NULL],
["2", [:subscript = true]],
["O", NULL]
], NULL)
doc1.addRichParagraph([
["Carbon Dioxide: CO", NULL],
["2", [:subscript = true]]
], NULL)
doc1.addRichParagraph([
["Sulfuric Acid: H", NULL],
["2", [:subscript = true]],
["SO", NULL],
["4", [:subscript = true]]
], NULL)
doc1.addHeading("Mathematical Expressions", 2)
# Powers using superscript
doc1.addRichParagraph([
["Area of a circle: A = ", [:bold = true]],
["π", NULL],
["r", NULL],
["2", [:superscript = true]]
], NULL)
doc1.addRichParagraph([
["Einstein's equation: E = mc", [:bold = true]],
["2", [:superscript = true]]
], NULL)
doc1.addRichParagraph([
["Pythagorean theorem: a", NULL],
["2", [:superscript = true]],
[" + b", NULL],
["2", [:superscript = true]],
[" = c", NULL],
["2", [:superscript = true]]
], NULL)
doc1.addHeading("Ordinal Numbers", 2)
doc1.addRichParagraph([
["1", NULL],
["st", [:superscript = true]],
[" place, 2", NULL],
["nd", [:superscript = true]],
[" place, 3", NULL],
["rd", [:superscript = true]],
[" place", NULL]
], NULL)
doc1.addHeading("Mixed Styling", 2)
doc1.addRichParagraph([
["Bold", [:bold = true]],
[" normal ", NULL],
["italic", [:italic = true]],
[" normal X", NULL],
["n+1", [:superscript = true, :color = "red"]],
[" and log", NULL],
["10", [:subscript = true]],
["(x)", NULL]
], NULL)
if doc1.save("demo_superscript_subscript.docx")
? "Created: demo_superscript_subscript.docx"
else
? "Error creating demo_superscript_subscript.docx"
ok
# ============================================================================
# Demo 2: Line Spacing
# ============================================================================
doc2 = new WordWriter()
doc2.setTitle("Demo 2 – Line Spacing")
doc2.setAuthor("DOCXLib Demo")
doc2.addHeading("Line Spacing Demo", 1)
doc2.addParagraph("Line spacing is controlled via :lineSpacing (multiplier) or :lineSpacingPt (exact points), with an optional :lineRule key.", NULL)
sampleText = "This paragraph demonstrates the configured line spacing. " +
"Reading it carefully, you should notice the vertical gap between lines " +
"is different from a standard single-spaced paragraph."
doc2.addHeading("Single Spacing (1.0×)", 2)
doc2.addParagraph(sampleText, [:lineSpacing = 1.0])
doc2.addHeading("One-and-a-Half Spacing (1.5×)", 2)
doc2.addParagraph(sampleText, [:lineSpacing = 1.5])
doc2.addHeading("Double Spacing (2.0×)", 2)
doc2.addParagraph(sampleText, [:lineSpacing = 2.0])
doc2.addHeading("Exact 18pt Spacing", 2)
doc2.addParagraph(sampleText, [:lineSpacingPt = 18, :lineRule = "exact"])
doc2.addHeading("At-Least 20pt Spacing", 2)
doc2.addParagraph(sampleText, [:lineSpacingPt = 20, :lineRule = "atLeast"])
doc2.addHeading("Combined: double-spaced, centered, blue", 2)
doc2.addParagraph("This paragraph is double-spaced, centred, and coloured blue.",
[:lineSpacing = 2.0, :align = "center", :color = "0000FF", :italic = true])
doc2.addHeading("Space Before & After + Line Spacing", 2)
doc2.addParagraph("Paragraph A – 240 twips before, 120 after, 1.5× line spacing.",
[:spaceBefore = 240, :spaceAfter = 120, :lineSpacing = 1.5])
doc2.addParagraph("Paragraph B – same settings, demonstrating the gap above and below.",
[:spaceBefore = 240, :spaceAfter = 120, :lineSpacing = 1.5])
if doc2.save("demo_line_spacing.docx")
? "Created: demo_line_spacing.docx"
else
? "Error creating demo_line_spacing.docx"
ok
# ============================================================================
# Demo 3: Nested / Multi-level Lists
# ============================================================================
doc3 = new WordWriter()
doc3.setTitle("Demo 3 – Nested Lists")
doc3.setAuthor("DOCXLib Demo")
doc3.addHeading("Nested Lists Demo", 1)
doc3.addParagraph("Multi-level lists use [text, level] pairs. Level 0 is the top, higher numbers indent further.", NULL)
doc3.addHeading("Nested Bullet List", 2)
doc3.addNestedBulletList([
["Fruits", 0],
["Tropical fruits", 1],
["Mango", 2],
["Papaya", 2],
["Dragonfruit", 2],
["Citrus fruits", 1],
["Orange", 2],
["Lemon", 2],
["Grapefruit", 2],
["Berries", 1],
["Strawberry", 2],
["Blueberry", 2],
["Vegetables", 0],
["Root vegetables", 1],
["Carrot", 2],
["Potato", 2],
["Leafy greens", 1],
["Spinach", 2],
["Kale", 2]
])
doc3.addPageBreak()
doc3.addHeading("Nested Numbered List", 2)
doc3.addNestedNumberedList([
["Project Phases", 0],
["Planning", 1],
["Define requirements", 2],
["Create project plan", 2],
["Assign resources", 2],
["Development", 1],
["Backend implementation", 2],
["Frontend implementation", 2],
["Database setup", 2],
["Testing", 1],
["Unit tests", 2],
["Integration tests", 2],
["User acceptance testing", 2],
["Deployment", 0],
["Staging environment", 1],
["Deploy to staging", 2],
["Smoke testing", 2],
["Production environment", 1],
["Final deployment", 2],
["Post-deployment monitoring", 2]
])
doc3.addHeading("Three-Level Mixed Nesting", 2)
doc3.addNestedBulletList([
["Level 0 – Top", 0],
["Level 1 – Sub", 1],
["Level 2 – Sub-sub", 2],
["Level 2 – another sub-sub", 2],
["Level 1 – another sub", 1],
["Level 0 – another top", 0]
])
if doc3.save("demo_nested_lists.docx")
? "Created: demo_nested_lists.docx"
else
? "Error creating demo_nested_lists.docx"
ok
# ============================================================================
# Demo 4: Footnotes & Endnotes
# ============================================================================
doc4 = new WordWriter()
doc4.setTitle("Demo 4 – Footnotes & Endnotes")
doc4.setAuthor("DOCXLib Demo")
doc4.showPageNumbers("center")
doc4.addHeading("Footnotes & Endnotes Demo", 1)
doc4.addParagraph("This document demonstrates footnotes (references at the bottom of each page) and endnotes (collected at the end of the document).", NULL)
doc4.addHeading("Basic Footnotes", 2)
doc4.addFootnote(
"The Ring programming language was created by Mahmoud Fayed.",
"Ring is a simple, yet powerful language for building applications. See https://ring-lang.net for details.",
NULL
)
doc4.addFootnote(
'Word documents use the Open XML format (OOXML), standardised as ISO/IEC 29500.',
"ISO/IEC 29500:2016 – Information technology – Document description and processing languages – Office Open XML File Formats.",
NULL
)
doc4.addFootnote(
"Footnote markers appear as superscript numbers in the body text.",
"The marker is placed immediately after the text it refers to, using the FootnoteReference character style.",
NULL
)
doc4.addHeading("Footnotes with Formatting", 2)
doc4.addFootnote(
"This sentence is bold and has a footnote attached.",
"The bold formatting applies only to the preceding text run; the footnote marker inherits the FootnoteReference style.",
[:bold = true]
)
doc4.addFootnote(
"Centered paragraph with footnote.",
"Alignment is a paragraph-level property and does not affect the footnote marker position.",
[:align = "center"]
)
doc4.addHeading("Rich Paragraph with Multiple Footnotes", 2)
doc4.addParagraph("You can also place footnote references anywhere within a rich paragraph by registering footnotes first, then embedding the reference runs:", NULL)
fnA = doc4.registerFootnote("First footnote registered manually – appears at position A in the paragraph.")
fnB = doc4.registerFootnote("Second footnote registered manually – appears at position B in the paragraph.")
fnC = doc4.registerFootnote("Third footnote registered manually – appears at position C in the paragraph.")
doc4.addRichParagraph([
["Beginning of sentence", NULL],
["", [:footnoteId = fnA]],
[", a middle part", NULL],
["", [:footnoteId = fnB]],
[", and the end of the sentence", NULL],
["", [:footnoteId = fnC]],
[".", NULL]
], NULL)
doc4.addPageBreak()
doc4.addHeading("Endnotes", 2)
doc4.addParagraph("Endnotes work the same way but their content appears at the very end of the document rather than at the bottom of each page.", NULL)
doc4.addEndnote(
"The word 'docx' is short for Document XML.",
"A .docx file is a ZIP archive containing a set of XML files that together describe the document structure, styles, and content.",
NULL
)
doc4.addEndnote(
"Endnotes are numbered independently from footnotes.",
"In standard Word documents, footnotes and endnotes each maintain their own sequential counter starting at 1.",
NULL
)
doc4.addHeading("Mixed Footnotes and Endnotes", 2)
en1 = doc4.registerEndnote("This is an endnote placed inside a rich paragraph using registerEndnote().")
fn4 = doc4.registerFootnote("This is a footnote placed alongside the endnote in the same paragraph.")
doc4.addRichParagraph([
["This sentence has both a footnote", NULL],
["", [:footnoteId = fn4]],
[" and an endnote", NULL],
["", [:endnoteId = en1]],
[" reference side by side.", NULL]
], NULL)
doc4.addHeading("Superscript Combined with Footnote", 2)
fn5 = doc4.registerFootnote("The formula E = mc² was published by Albert Einstein in 1905 in his paper on special relativity.")
doc4.addRichParagraph([
["The famous equation E = mc", NULL],
["2", [:superscript = true]],
["", [:footnoteId = fn5]],
[" changed our understanding of energy and mass.", NULL]
], NULL)
if doc4.save("demo_footnotes_endnotes.docx")
? "Created: demo_footnotes_endnotes.docx"
else
? "Error creating demo_footnotes_endnotes.docx"
ok
# ============================================================================
# Demo 5: All four features combined in one document
# ============================================================================
doc5 = new WordWriter()
doc5.setTitle("Research Paper Sample")
doc5.setAuthor("DOCXLib Demo")
doc5.showPageNumbers("center")
doc5.setWatermarkText("DRAFT")
doc5.addHeading("A Brief Study of the Ring Language", 1)
doc5.addParagraph("Department of Computer Science – Technical Report 2025", [:align = "center", :italic = true])
doc5.addLineBreak()
doc5.addHeading("Abstract", 2)
doc5.addParagraph(
"Ring is an open-source, multi-paradigm programming language that supports functional, " +
"object-oriented, and procedural styles. This report surveys its features and examines " +
"document-generation capabilities through the DOCXLib library.",
[:lineSpacing = 1.5, :align = "both"]
)
doc5.addHeading("1. Introduction", 2)
fnIntro = doc5.registerFootnote("Ring was first publicly released in 2016. See ring-lang.net for the official documentation.")
doc5.addRichParagraph([
["The Ring programming language", [:bold = true]],
["", [:footnoteId = fnIntro]],
[" was designed with simplicity in mind. Its syntax is straightforward, making it " +
"accessible to beginners while retaining the power required by expert developers.", NULL]
], [:lineSpacing = 1.5, :align = "both"])
doc5.addHeading("2. Key Formula Support", 2)
fnFormula = doc5.registerFootnote("OOXML specifies superscript/subscript via the w:vertAlign element in run properties.")
doc5.addRichParagraph([
["The library correctly renders expressions such as H", NULL],
["2", [:subscript = true]],
["O, E = mc", NULL],
["2", [:superscript = true]],
["", [:footnoteId = fnFormula]],
[", and x", NULL],
["n+1", [:superscript = true]],
[" inside any Word paragraph.", NULL]
], [:lineSpacing = 1.5])
doc5.addHeading("3. Document Structure", 2)
doc5.addParagraph("A well-structured technical document typically follows the outline below:", [:lineSpacing = 1.5])
doc5.addNestedNumberedList([
["Front Matter", 0],
["Title page", 1],
["Abstract", 1],
["Table of contents", 1],
["Body", 0],
["Introduction", 1],
["Background", 1],
["Methodology", 1],
["Results", 1],
["Conclusion", 1],
["Back Matter", 0],
["References", 1],
["Appendices", 1],
["Index", 1]
])
doc5.addHeading("4. Conclusion", 2)
enConclusion = doc5.registerEndnote("Full source code for DOCXLib is available under the MIT license.")
doc5.addRichParagraph([
["DOCXLib now covers the most important Word document features required by " +
"real-world applications, making it a solid foundation for document automation in Ring.", NULL],
["", [:endnoteId = enConclusion]]
], [:lineSpacing = 1.5, :align = "both"])
if doc5.save("demo_combined_research_paper.docx")
? "Created: demo_combined_research_paper.docx"
else
? "Error creating demo_combined_research_paper.docx"
ok
? ""
? "All demos created successfully."
? ""part13_paragraphshading.ring#
samples/UsingDOCXLib/part13_paragraphshading.ring
/*
DOCXLib - Demo (Paragraph Shading)
*/
load "docxlib.ring"
/*
Demonstrates the next features:
1. Table cell background color / shading (via addTable headerBgColor / evenRowBgColor)
2. Custom paragraph styles (defineStyle)
3. Repeating header rows (table option :repeatHeader)
4. Different first-page header/footer
5. Paragraph shading (addShadedParagraph / [:bgColor] option)
6. Floating text boxes (addTextBox)
*/
doc = new WordWriter()
doc.setTitle("DOCXLib - Features Demo")
doc.setAuthor("Mahmoud")
doc.setPageSize("a4")
# -------------------------------------------------
# Different first-page header/footer
# The cover page shows a bold title banner; all
# subsequent pages show the regular running header.
# -------------------------------------------------
doc.setFirstPageHeader("DOCXLib - Feature Showcase")
doc.setFirstPageFooter("Confidential - Do Not Distribute")
doc.setHeader("DOCXLib Documentation")
doc.showPageNumbers("right")
# -------------------------------------------------------
# COVER PAGE
# -------------------------------------------------------
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("DOCXLib", [:align = "center", :bold = true, :size = 36, :color = "1F4E79"])
doc.addParagraph("Version 1.0", [:align = "center", :bold = true, :size = 20, :color = "2F75B6"])
doc.addParagraph("", NULL)
doc.addParagraph("New Features Demo", [:align = "center", :italic = true, :size = 16, :color = "595959"])
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
# -------------------------------------------------
# Floating text box on cover page
# A styled announcement box placed in the center
# -------------------------------------------------
doc.addTextBox("New Features in This Sample",
[:x = 4, :y = 10, :width = 10, :height = 2,
:align = "center", :bold = true, :size = 14,
:color = "FFFFFF", :bgColor = "2E75B6",
:borderColor = "1F4E79", :borderSize = 12])
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("Created with Ring Programming Language", [:align = "center", :italic = true, :size = 10, :color = "7F7F7F"])
doc.addParagraph("https://ring-lang.github.io", [:align = "center", :size = 10, :color = "0563C1"])
doc.addPageBreak()
# -------------------------------------------------------
# TABLE OF NEW FEATURES
# -------------------------------------------------------
doc.addHeading("Overview of New Features", 1)
doc.addParagraph("The following features were added in this sample:", NULL)
doc.addParagraph("", NULL)
doc.addTable(
[
["#", "Feature", "Key API"],
["1", "Table cell background color / shading", "addTable + :headerBgColor / :evenRowBgColor / :bgColor"],
["2", "Custom paragraph styles", "defineStyle() + [:style = 'MyId']"],
["3", "Repeating table header rows", "addTable + :repeatHeader = true"],
["4", "Different first-page header/footer", "setFirstPageHeader() / setFirstPageFooter()"],
["5", "Paragraph shading", "addShadedParagraph() / [:bgColor = 'RRGGBB']"],
["6", "Floating text boxes", "addTextBox()"]
],
[
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "1F4E79",
:headerTextColor = "FFFFFF",
:evenRowBgColor = "D6E4F0",
:colWidths = [0.8, 6.5, 8.5]
]
)
# -------------------------------------------------------
# FEATURE 1 - TABLE CELL BACKGROUND COLOR
# -------------------------------------------------------
doc.addHeading("Feature 1 - Table Cell Background Color", 1)
doc.addParagraph("Tables now support per-cell background shading through three complementary options:", NULL)
doc.addParagraph("", NULL)
doc.addTable(
[
["Option", "Purpose", "Example Value"],
[":headerBgColor", "Fill color for the header row","2E75B6"],
[":evenRowBgColor", "Zebra-stripe color for even rows", "D9E2F3"],
[":bgColor on WordCell", "Per-cell individual fill", "FFD700"]
],
[
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "2E75B6",
:headerTextColor = "FFFFFF",
:evenRowBgColor = "DEEAF1",
:colWidths = [4.5, 6, 4]
]
)
doc.addParagraph("", NULL)
doc.addParagraph("Example - product catalogue with colored tiers:", [:bold = true])
doc.addParagraph("", NULL)
# Product catalogue demo with per-cell colors via WordCell
headerCells = [
new WordCell() { setText("Product", NULL) },
new WordCell() { setText("Tier", NULL) },
new WordCell() { setText("Price", NULL) },
new WordCell() { setText("Stock", NULL) }
]
row1 = [
new WordCell() { setText("Widget Pro X", NULL) },
new WordCell() { setText("Gold", NULL) .setBgColor("FFD700") },
new WordCell() { setText("$199.00", NULL) },
new WordCell() { setText("In Stock", NULL) .setBgColor("C6EFCE") }
]
row2 = [
new WordCell() { setText("Widget Standard", NULL) },
new WordCell() { setText("Silver", NULL) .setBgColor("BFBFBF") },
new WordCell() { setText("$99.00", NULL) },
new WordCell() { setText("In Stock", NULL) .setBgColor("C6EFCE") }
]
row3 = [
new WordCell() { setText("Widget Basic", NULL) },
new WordCell() { setText("Bronze", [:color = "FFFFFF"]) .setBgColor("ED7D31") },
new WordCell() { setText("$49.00", NULL) },
new WordCell() { setText("Low Stock", NULL) .setBgColor("FFEB9C") }
]
row4 = [
new WordCell() { setText("Widget Lite", NULL) },
new WordCell() { setText("Basic", NULL) },
new WordCell() { setText("$19.00", NULL) },
new WordCell() { setText("Out of Stock", NULL) .setBgColor("FFC7CE") }
]
doc.addTable(
[headerCells, row1, row2, row3, row4],
[
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "404040",
:headerTextColor = "FFFFFF",
:colWidths = [5, 3, 3, 3]
]
)
doc.addPageBreak()
doc.addPageBreak()
# -------------------------------------------------------
# FEATURE 2 - CUSTOM PARAGRAPH STYLES
# -------------------------------------------------------
doc.addHeading("Feature 2 - Custom Paragraph Styles", 1)
doc.addParagraph("Use defineStyle() to declare reusable named styles. Apply them with [:style = 'StyleId'].", NULL)
doc.addParagraph("", NULL)
# Define styles
doc.defineStyle("CalloutNote",
[:name = "Callout Note", :bold = false, :italic = true,
:size = 11, :color = "1F4E79", :bgColor = "DEEAF1",
:align = "both", :spaceBefore = 120, :spaceAfter = 120,
:indent = 360, :keepLines = true])
doc.defineStyle("WarningBox",
[:name = "Warning Box", :bold = true,
:size = 11, :color = "7B2C2C", :bgColor = "FCE4E4",
:align = "left", :spaceBefore = 120, :spaceAfter = 120,
:indent = 360])
doc.defineStyle("SectionSummary",
[:name = "Section Summary", :bold = false, :italic = false,
:size = 12, :color = "375623", :bgColor = "E2EFDA",
:align = "both", :spaceBefore = 80, :spaceAfter = 80,
:lineSpacing = 1.4])
doc.defineStyle("TipBox",
[:name = "Tip Box", :bold = false, :italic = false,
:size = 11, :color = "375623",
:align = "left", :spaceBefore = 80, :spaceAfter = 80,
:indent = 360])
# Demo usage
doc.addParagraph("The following paragraphs each use a different custom style:", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("CalloutNote style - Used for informational callouts inside documentation. The background and italic formatting draw the reader's eye without disrupting document flow.",
[:style = "CalloutNote"])
doc.addParagraph("", NULL)
doc.addParagraph("WarningBox style - IMPORTANT: This style highlights critical warnings. The red background immediately signals the reader to pay attention to this content.",
[:style = "WarningBox"])
doc.addParagraph("", NULL)
doc.addParagraph("SectionSummary style - This green-tinted summary style is ideal for end-of-section recaps, concluding remarks, or key takeaway paragraphs in long reports.",
[:style = "SectionSummary"])
doc.addParagraph("", NULL)
doc.addParagraph("TipBox style - Tip: Custom styles are defined once at the top of your script and can be reused across any number of paragraphs throughout the entire document.",
[:style = "TipBox"])
doc.addPageBreak()
# -------------------------------------------------------
# FEATURE 3 - REPEATING HEADER ROWS
# -------------------------------------------------------
doc.addHeading("Feature 3 - Repeating Table Header Rows", 1)
doc.addParagraph("When a table spans multiple pages, adding :repeatHeader = true causes Word to repeat the first (header) row at the top of every page automatically.", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("The 30-row table below will overflow to the next page. Open the document in Word and scroll to verify the blue header row repeats.", [:italic = true, :color = "595959"])
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("", NULL)
# Build a 30-row table that overflows a page
tableData = [["#", "Country", "Capital City", "Population (M)", "Area (km²)"]]
countries = [
["1", "China", "Beijing", "1,412", "9,597,000"],
["2", "India", "New Delhi", "1,380", "3,287,000"],
["3", "USA", "Washington D.C.", "331", "9,834,000"],
["4", "Indonesia", "Jakarta", "274", "1,905,000"],
["5", "Pakistan", "Islamabad", "221", "881,000"],
["6", "Brazil", "Brasília", "213", "8,516,000"],
["7", "Nigeria", "Abuja", "211", "924,000"],
["8", "Bangladesh", "Dhaka", "166", "147,000"],
["9", "Russia", "Moscow", "146", "17,098,000"],
["10", "Ethiopia", "Addis Ababa", "122", "1,104,000"],
["11", "Mexico", "Mexico City", "129", "1,964,000"],
["12", "Japan", "Tokyo", "125", "378,000"],
["13", "Philippines", "Manila", "113", "300,000"],
["14", "Egypt", "Cairo", "102", "1,002,000"],
["15", "DR Congo", "Kinshasa", "100", "2,345,000"],
["16", "Vietnam", "Hanoi", "97", "331,000"],
["17", "Iran", "Tehran", "84", "1,648,000"],
["18", "Turkey", "Ankara", "84", "784,000"],
["19", "Germany", "Berlin", "83", "357,000"],
["20", "Thailand", "Bangkok", "70", "513,000"],
["21", "UK", "London", "67", "244,000"],
["22", "France", "Paris", "67", "551,000"],
["23", "Tanzania", "Dodoma", "60", "945,000"],
["24", "South Africa", "Pretoria", "60", "1,219,000"],
["25", "Myanmar", "Naypyidaw", "54", "677,000"],
["26", "Kenya", "Nairobi", "54", "580,000"],
["27", "South Korea", "Seoul", "52", "100,000"],
["28", "Colombia", "Bogotá", "51", "1,142,000"],
["29", "Spain", "Madrid", "47", "506,000"],
["30", "Argentina", "Buenos Aires", "45", "2,780,000"]
]
countriesLen = len(countries)
for ci = 1 to countriesLen
tableData + countries[ci]
next
doc.addTable(tableData,
[
:headerRow = true,
:repeatHeader = true,
:borderStyle = "single",
:headerBgColor = "1F4E79",
:headerTextColor = "FFFFFF",
:evenRowBgColor = "EEF3F8",
:colWidths = [0.8, 4, 4, 3.5, 3.5]
]
)
doc.addPageBreak()
# -------------------------------------------------------
# FEATURE 4 - FIRST-PAGE DIFFERENT HEADER/FOOTER
# -------------------------------------------------------
doc.addHeading("Feature 4 - Different First-Page Header and Footer", 1)
doc.addParagraph("This document itself demonstrates Feature 4. Look at the header and footer areas:", NULL)
doc.addParagraph("", NULL)
# Use addTable with bold rows to explain what to look for
doc.addTable(
[
["Page", "Header shows", "Footer shows"],
["Page 1 (cover)", "DOCXLib v1.6.0 - Feature Showcase", "Confidential - Do Not Distribute"],
["Pages 2+", "DOCXLib v1.6.0 Documentation", "Page N of M (right-aligned)"]
],
[
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "404040",
:headerTextColor = "FFFFFF",
:colWidths = [3, 7, 5]
]
)
doc.addParagraph("", NULL)
doc.addParagraph("API used in this document:", [:bold = true])
doc.addParagraph("", NULL)
codeLines = [
'doc.setFirstPageHeader("DOCXLib v1.6.0 - Feature Showcase")',
'doc.setFirstPageFooter("Confidential - Do Not Distribute")',
'doc.setHeader("DOCXLib v1.6.0 Documentation")',
'doc.showPageNumbers("right")'
]
codeLinesLen = len(codeLines)
for ci = 1 to codeLinesLen
doc.addParagraph(codeLines[ci],
[:font = "Courier New", :size = 10, :bgColor = "F2F2F2",
:spaceAfter = 40, :spaceBefore = 40, :indent = 360])
next
doc.addParagraph("", NULL)
doc.addParagraph("You can also call setFirstPageDifferent(true) without providing any first-page text to simply suppress the header/footer on page 1 (common for title pages).", [:italic = true, :color = "595959"])
doc.addPageBreak()
# -------------------------------------------------------
# FEATURE 5 - PARAGRAPH SHADING
# -------------------------------------------------------
doc.addHeading("Feature 5 - Paragraph Shading", 1)
doc.addParagraph("Individual paragraphs can now have a background fill color. There are two ways to apply it:", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("Method 1 - addShadedParagraph(text, color, options)", [:bold = true])
doc.addParagraph("", NULL)
doc.addShadedParagraph("This paragraph uses addShadedParagraph() with color '1F4E79'. The background fills the full width of the paragraph text block.", "1F4E79",
[:color = "FFFFFF", :bold = true, :spaceBefore = 60, :spaceAfter = 60, :indent = 360])
doc.addShadedParagraph("Warning: This is a yellow-highlighted paragraph. Great for callout boxes, tips, notes, and other highlighted content.", "FFF2CC",
[:color = "7E6000", :spaceBefore = 60, :spaceAfter = 60, :indent = 360])
doc.addShadedParagraph("Success: This green shading works well for confirming positive actions, status indicators, or checklist completion messages.", "E2EFDA",
[:color = "375623", :spaceBefore = 60, :spaceAfter = 60, :indent = 360])
doc.addShadedParagraph("Error: This red-shaded paragraph immediately draws attention to errors, failures, or critical missing information.", "FCE4E4",
[:color = "7B2C2C", :bold = true, :spaceBefore = 60, :spaceAfter = 60, :indent = 360])
doc.addParagraph("", NULL)
doc.addParagraph("Method 2 - [:bgColor] option in addParagraph()", [:bold = true])
doc.addParagraph("", NULL)
doc.addParagraph("This paragraph uses the :bgColor key in a standard addParagraph() options list.",
[:bgColor = "E9F5FB", :color = "1F4E79", :italic = true, :spaceBefore = 60, :spaceAfter = 60, :indent = 360])
doc.addParagraph("", NULL)
doc.addParagraph("Shading also works seamlessly with custom styles (Feature 2) by setting :bgColor in defineStyle().", [:italic = true, :color = "595959"])
doc.addPageBreak()
# -------------------------------------------------------
# FEATURE 6 - FLOATING TEXT BOXES
# -------------------------------------------------------
doc.addHeading("Feature 6 - Floating Text Boxes", 1)
doc.addParagraph("Text boxes are absolutely-positioned floating containers. They can appear anywhere on the page, overlapping or alongside regular content.", NULL)
doc.addParagraph("", NULL)
doc.addParagraph("The boxes shown on this page are live - open in Word to see their exact positions.", [:italic = true, :color = "595959"])
doc.addParagraph("", NULL)
# Several demo text boxes at different positions
doc.addTextBox("SIDEBAR This is a sidebar text box floating to the right of the main content area. Text boxes can hold any text content.",
[:x = 11.5, :y = 5.5, :width = 5.5, :height = 5,
:align = "left", :size = 10,
:bgColor = "EEF3F8", :borderColor = "2E75B6", :borderSize = 8])
doc.addTextBox("NOTE",
[:x = 0.5, :y = 6, :width = 2.5, :height = 1,
:align = "center", :bold = true, :size = 12,
:color = "FFFFFF", :bgColor = "ED7D31",
:borderColor = "C55A11", :borderSize = 8])
doc.addParagraph("Option reference for addTextBox():", [:bold = true])
doc.addParagraph("", NULL)
doc.addTable(
[
["Option", "Default", "Description"],
[":x", "2.0", "Horizontal position from left margin (cm)"],
[":y", "5.0", "Vertical position from top margin (cm)"],
[":width", "6.0", "Box width in cm"],
[":height", "3.0", "Box height in cm"],
[":align", "center", "Text alignment inside box: left/center/right"],
[":bold", "false", "Bold text inside the box"],
[":italic", "false", "Italic text inside the box"],
[":font", "(default)", "Font family name"],
[":size", "(default)", "Font size in points"],
[":color", "(default)", "Text color (name or hex)"],
[":bgColor", "FFFFFF", "Box fill color"],
[":borderColor", "4472C4", "Border color"],
[":borderSize", "8", "Border width in eighths of a point (8 = 1pt)"],
[":noFill", "false", "Transparent background"],
[":noBorder", "false", "No visible border"]
],
[
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "404040",
:headerTextColor = "FFFFFF",
:evenRowBgColor = "F2F2F2",
:colWidths = [3, 2.5, 10]
]
)
doc.addParagraph("", NULL)
# A no-fill bordered text box
doc.addTextBox("This text box has no fill (transparent background) but keeps its border.",
[:x = 1, :y = 19, :width = 9, :height = 1.5,
:align = "center", :italic = true, :size = 11,
:noFill = true, :borderColor = "7030A0", :borderSize = 16])
# -------------------------------------------------------
# SAVE
# -------------------------------------------------------
filename = "demo_paragraphshading.docx"
result = doc.save(filename)
if result
? "OK - Document saved: " + filename
else
? "ERROR - Failed to save document"
okpart14_pagebackground.ring#
samples/UsingDOCXLib/part14_pagebackground.ring
/*
DOCXLib - Demo (Page Background)
*/
load "docxlib.ring"
/*
Demonstrates four features:
A. Odd/Even page headers and footers
B. Paragraph borders
C. Section breaks with orientation change
D. Page background color
*/
doc = new WordWriter()
doc.setTitle("DOCXLib - New Features Demo")
doc.setAuthor("Mahmoud")
doc.setPageSize("a4")
# -------------------------------------------------
# Feature A: Odd/Even page headers/footers
# Odd pages (right-hand): chapter/section title on the right
# Even pages (left-hand): document title on the left
# -------------------------------------------------
doc.setHeader("Chapter 1 - DOCXLib Features") # odd pages
doc.setEvenPageHeader("DOCXLib Documentation") # even pages
doc.showPageNumbers("right")
doc.setEvenPageFooter("Page - DOCXLib")
# -------------------------------------------------
# Feature D: Page background color
# A very light blue tint - visible in Word when
# "Print Background Colors" is on
# -------------------------------------------------
doc.setPageBackground("EBF3FB")
# -------------------------------------------------------
# PAGE 1 - Intro
# -------------------------------------------------------
doc.addHeading("DOCXLib - New Features", 1)
doc.addParagraph("This document demonstrates four features. Each feature section is clearly labeled and includes live examples.", NULL)
doc.addParagraph("", NULL)
# Overview table
doc.addTable(
[
["Feature", "API"],
["A: Odd/Even page headers/footers", "setEvenPageHeader() / setEvenPageFooter()"],
["B: Paragraph borders", "addBorderedParagraph() / [:_hasBorder]"],
["C: Section breaks + orientation", "startLandscapeSection() / endLandscapeSection()"],
["D: Page background color", "setPageBackground()"]
],
[
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "1F4E79",
:headerTextColor = "FFFFFF",
:evenRowBgColor = "D9E8F5",
:colWidths = [7, 9]
]
)
doc.addPageBreak()
# -------------------------------------------------------
# PAGE 2 - Feature A
# -------------------------------------------------------
doc.addHeading("Feature A - Odd/Even Page Headers and Footers", 1)
doc.addParagraph("In books and formal reports, right-hand (odd) pages typically show the chapter title while left-hand (even) pages show the document or book title. Word calls this Even and Odd Headers.", NULL)
doc.addParagraph("", NULL)
doc.addBorderedParagraph("How to use: call setHeader() for odd pages and setEvenPageHeader() for even pages. Calling either method automatically enables even/odd mode.",
[:borderStyle = "single", :borderColor = "2E75B6", :borderSize = 6,
:bgColor = "DEEAF1", :spaceBefore = 80, :spaceAfter = 80, :indent = 240])
doc.addParagraph("", NULL)
doc.addParagraph("This document itself uses Feature A. Check the headers above as you page through it - odd pages show the chapter name on the right, even pages show the document title.", [:italic = true, :color = "595959"])
doc.addParagraph("", NULL)
doc.addTable(
[
["Page type", "Header", "Footer"],
["Odd pages", "Chapter 1 - DOCXLib Features", "Page N (right-aligned)"],
["Even pages", "DOCXLib Documentation", "Page - DOCXLib (center)"]
],
[
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "2E75B6",
:headerTextColor = "FFFFFF",
:colWidths = [3, 7, 6]
]
)
doc.addPageBreak()
# -------------------------------------------------------
# PAGE 3 - Feature B
# -------------------------------------------------------
doc.addHeading("Feature B - Paragraph Borders", 1)
doc.addParagraph("Paragraph borders draw a rule on one or more sides of a paragraph. They are widely used for callout boxes, notes, warnings, and visual separators - without using a floating text box.", NULL)
doc.addParagraph("", NULL)
# Full box with default single border
doc.addBorderedParagraph("Default box border - all four sides, single style, 0.75pt, black. This is the simplest way to frame a paragraph.",
[:spaceBefore = 80, :spaceAfter = 80, :indent = 240])
doc.addParagraph("", NULL)
# Colored thick box
doc.addBorderedParagraph("Thick blue border - borderStyle:thick, borderColor:2E75B6, borderSize:18 (2.25pt). Good for important callouts.",
[:borderStyle = "thick", :borderColor = "2E75B6", :borderSize = 18,
:bgColor = "EBF3FB", :spaceBefore = 80, :spaceAfter = 80, :indent = 240,
:bold = true])
doc.addParagraph("", NULL)
# Top and bottom only (horizontal rules)
doc.addBorderedParagraph("Top and bottom borders only - sides:['top','bottom'], creates a horizontal rule effect above and below the text without side lines.",
[:sides = ["top", "bottom"], :borderColor = "595959", :borderSize = 8,
:spaceBefore = 80, :spaceAfter = 80, :indent = 240, :align = "center", :italic = true])
doc.addParagraph("", NULL)
# Left side only (blockquote style)
doc.addBorderedParagraph("Left border only - sides:['left'], borderColor:ED7D31, borderSize:24. Creates a classic blockquote-style sidebar rule.",
[:sides = ["left"], :borderColor = "ED7D31", :borderSize = 24,
:bgColor = "FFF2CC", :spaceBefore = 80, :spaceAfter = 80, :indent = 360])
doc.addParagraph("", NULL)
# Wave border
doc.addBorderedParagraph("Wave border - borderStyle:wave, all sides. Decorative border useful for certificates, titles, or creative documents.",
[:borderStyle = "wave", :borderColor = "7030A0", :borderSize = 10,
:spaceBefore = 80, :spaceAfter = 80, :indent = 240,
:align = "center", :color = "7030A0", :bold = true])
doc.addParagraph("", NULL)
# Double border
doc.addBorderedParagraph("Double border - borderStyle:double, borderColor:1F4E79, borderSize:6. Traditional formal styling.",
[:borderStyle = "double", :borderColor = "1F4E79", :borderSize = 6,
:bgColor = "E2EFDA", :spaceBefore = 80, :spaceAfter = 80, :indent = 240])
doc.addParagraph("", NULL)
doc.addParagraph("API reference:", [:bold = true])
doc.addParagraph("addBorderedParagraph(text, options) accepts: :borderStyle, :borderColor, :borderSize, :borderSpace, :sides (list), plus all standard paragraph options.", [:size = 10, :color = "595959"])
doc.addPageBreak()
# -------------------------------------------------------
# PAGES 4-5 - Feature C (portrait → landscape → portrait)
# -------------------------------------------------------
doc.addHeading("Feature C - Section Breaks with Orientation Change", 1)
doc.addParagraph("Documents often need a single landscape page for a wide table or diagram, surrounded by portrait pages. DOCXLib v1.7.0 adds startLandscapeSection() and endLandscapeSection() to make this seamless.", NULL)
doc.addParagraph("", NULL)
doc.addBorderedParagraph("The next page is landscape. After the wide table, the document returns to portrait automatically.",
[:borderStyle = "single", :borderColor = "375623", :bgColor = "E2EFDA",
:spaceBefore = 80, :spaceAfter = 80, :indent = 240])
# -- switch to landscape --
doc.addLandscapeStart()
doc.addHeading("Wide Data Table - Landscape Page", 2)
doc.addParagraph("This entire page is landscape. The table below would not fit on a portrait page.", [:italic = true, :color = "595959"])
doc.addParagraph("", NULL)
# Wide table with many columns - only fits on landscape
doc.addTable(
[
["Country", "Region", "Q1 Sales", "Q2 Sales", "Q3 Sales", "Q4 Sales", "Annual", "Growth", "Rank"],
["Saudi Arabia", "Middle East", "12,450", "14,200", "13,800", "15,600", "56,050", "+12.4%", "1"],
["UAE", "Middle East", "9,800", "11,200", "10,900", "12,400", "44,300", "+9.8%", "2"],
["Egypt", "North Africa", "7,200", "8,100", "7,900", "8,800", "32,000", "+8.2%", "3"],
["Kuwait", "Middle East", "5,600", "6,300", "6,100", "6,900", "24,900", "+7.5%", "4"],
["Jordan", "Middle East", "4,100", "4,700", "4,500", "5,100", "18,400", "+6.9%", "5"],
["Morocco", "North Africa", "3,800", "4,200", "4,100", "4,600", "16,700", "+5.8%", "6"],
["Tunisia", "North Africa", "2,900", "3,300", "3,200", "3,600", "13,000", "+4.9%", "7"],
["Lebanon", "Middle East", "2,400", "2,700", "2,600", "2,900", "10,600", "+3.2%", "8"]
],
[
:headerRow = true,
:repeatHeader = true,
:borderStyle = "single",
:headerBgColor = "1F4E79",
:headerTextColor = "FFFFFF",
:evenRowBgColor = "EEF3F8",
:colWidths = [3.5, 3.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 1.8]
]
)
# -- return to portrait --
doc.addLandscapeEnd()
doc.addHeading("Back to Portrait", 2)
doc.addParagraph("This page is portrait again. The document automatically resumed its original page dimensions after endLandscapeSection().", NULL)
doc.addParagraph("", NULL)
doc.addBorderedParagraph("Key API: startLandscapeSection() inserts a section break that switches to landscape. endLandscapeSection() inserts a break that returns to portrait. All content between the two calls is rendered on landscape pages.",
[:borderStyle = "single", :borderColor = "2E75B6", :bgColor = "DEEAF1",
:spaceBefore = 80, :spaceAfter = 80, :indent = 240])
doc.addPageBreak()
# -------------------------------------------------------
# LAST PAGE - Feature D
# -------------------------------------------------------
doc.addHeading("Feature D - Page Background Color", 1)
doc.addParagraph("The entire document has a light blue background (color EBF3FB) applied via setPageBackground(). This is visible in Word when View > Print Layout is active and print background colors is enabled.", NULL)
doc.addParagraph("", NULL)
doc.addBorderedParagraph("setPageBackground() adds <w:background w:color='...'/> before <w:body> and sets <w:displayBackgroundShape/> in settings.xml so Word shows it on screen without any manual steps.",
[:borderStyle = "single", :borderColor = "2E75B6", :bgColor = "D9E8F5",
:spaceBefore = 80, :spaceAfter = 80, :indent = 240])
doc.addParagraph("", NULL)
doc.addParagraph("Common use cases:", [:bold = true])
doc.addParagraph("", NULL)
doc.addTable(
[
["Use case", "Suggested color", "Hex"],
["Light parchment", "Warm off-white", "FFF8DC"],
["Legal / formal", "Pale grey", "F2F2F2"],
["Technical docs", "Light blue", "EBF3FB"],
["Warning / alert", "Light yellow", "FFFDE7"],
["Ecological theme", "Light green", "F1F8E9"],
["Premium / dark mode", "Dark navy", "1F3864"]
],
[
:headerRow = true,
:borderStyle = "single",
:headerBgColor = "404040",
:headerTextColor = "FFFFFF",
:evenRowBgColor = "F0F6FB",
:colWidths = [5, 4.5, 3.5]
]
)
doc.addParagraph("", NULL)
doc.addParagraph("Note: passing NULL or an empty string to setPageBackground() removes the background color.", [:italic = true, :color = "595959"])
# -------------------------------------------------------
# SAVE
# -------------------------------------------------------
filename = "demo_pagebackground.docx"
result = doc.save(filename)
if result
? "OK - Saved: " + filename
else
? "ERROR - Failed to save"
okpart15_mailmerge.ring#
samples/UsingDOCXLib/part15_mailmerge.ring
/*
DOCXLib - Demo (MailMerge)
*/
load "docxlib.ring"
/*
Feature 1 -- Mail Merge Template Engine
doc.setMergeTemplate(template) register a template once
doc.mergeRecord(data) render template for one record
doc.mergeAll(dataList, sep) render template for every record
doc.clearMergeTemplate() remove the registered template
Template items:
"Plain text with {{FIELD}} tokens"
[:type = "heading", :level = N, :text = "{{FIELD}} Report"]
[:type = "paragraph", :text = "...", :options = [:bold = true]]
[:type = "table", :data = [...], :options = [...]]
[:type = "pagebreak"]
[:type = "emptyline"]
Feature 2 -- Chart Data Tables
:showDataTable = true show data table below the chart
:dataTableShowKeys = true include colour legend keys in the table
Supported on: column, bar, line, area charts
Not applicable to: pie, doughnut, scatter, bubble
*/
? "==================================================="
? " DOCXLib -- Merge & Data Table Demo"
? "==================================================="
? ""
doc = new WordWriter()
doc.setTitle("DOCXLib -- Mail Merge and Chart Data Tables")
doc.setAuthor("DOCXLib Demo")
doc.setPageSize("a4")
doc.setTheme("Blue")
doc.setHeader("DOCXLib -- Merge and Data Table Demo")
doc.setFooter("Generated by DOCXLib")
# =============================================================================
# PART 1 -- CHART DATA TABLES
# =============================================================================
doc.addHeading("Part 1: Chart Data Tables", 1)
doc.addParagraph(
"The :showDataTable = true option renders the chart source data in a " +
"compact table directly beneath the plot area. This is especially useful " +
"in printed reports where the reader should be able to verify exact values " +
"without hunting for a separate appendix. Use :dataTableShowKeys = false " +
"to omit the colour-legend column.", NULL)
doc.addEmptyParagraph()
quarters = ["Q1", "Q2", "Q3", "Q4"]
# ---- 1a. Column chart with data table (keys on) ----------------------------
doc.addHeading("1a. Column Chart + Data Table (with legend keys)", 2)
doc.addParagraph(
"The table below the chart shows the exact values for every series and " +
"category. Legend colour keys are included in the leftmost column.", NULL)
doc.addEmptyParagraph()
doc.addColumnChart(
"Quarterly Revenue by Product",
quarters,
[
[:name = "Ring", :values = [320000, 410000, 380000, 490000], :color = "4472C4"],
[:name = "PWCT", :values = [210000, 265000, 245000, 305000], :color = "ED7D31"],
[:name = "Supernova", :values = [145000, 180000, 162000, 215000], :color = "70AD47"]
],
[:widthCm = 15, :heightCm = 8,
:legendPos = "b", :yAxisMin = 0,
:yAxisFormat = "$#,##0", :showGridlines = false,
:showDataTable = true, :dataTableShowKeys = true])
doc.addCaption("Figure 1 -- Column chart with data table and legend keys")
doc.addEmptyParagraph()
doc.addPageBreak()
# ---- 1b. Line chart with data table (keys off) -----------------------------
doc.addHeading("1b. Line Chart + Data Table (keys hidden)", 2)
doc.addParagraph(
"Same option, but :dataTableShowKeys = false removes the colour column " +
"from the data table. Useful when colour coding is already clear from the lines.", NULL)
doc.addEmptyParagraph()
doc.addLineChart(
"Monthly Active Users (thousands)",
["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
[
[:name = "Web", :values = [142, 158, 171, 185, 201, 218], :color = "4472C4"],
[:name = "Mobile", :values = [89, 104, 118, 135, 152, 171], :color = "ED7D31"],
[:name = "Desktop", :values = [67, 69, 72, 71, 74, 76], :color = "70AD47"]
],
[:widthCm = 15, :heightCm = 8,
:legendPos = "b", :yAxisMin = 0,
:yAxisFormat = "#,##0", :yAxisTitle = "Users (thousands)",
:smooth = true,
:showDataTable = true, :dataTableShowKeys = false])
doc.addCaption("Figure 2 -- Line chart with data table (no legend keys)")
doc.addEmptyParagraph()
doc.addPageBreak()
# ---- 1c. Stacked bar with data table ----------------------------------------
doc.addHeading("1c. Stacked Bar Chart + Data Table", 2)
doc.addParagraph(
"Data tables work with all grouping modes. Here a 100% stacked bar " +
"uses :yAxisFormat = " + char(34) + "0%" + char(34) + " so the table values match the axis labels.", NULL)
doc.addEmptyParagraph()
doc.addBarChart(
"Market Share by Region",
["North", "South", "East", "West"],
[
[:name = "Ring", :values = [0.42, 0.35, 0.38, 0.45], :color = "4472C4"],
[:name = "PWCT", :values = [0.31, 0.38, 0.29, 0.27], :color = "ED7D31"],
[:name = "Others", :values = [0.27, 0.27, 0.33, 0.28], :color = "A9A9A9"]
],
[:widthCm = 15, :heightCm = 8,
:grouping = "percentStacked", :legendPos = "b",
:yAxisFormat = "0%",
:showDataTable = true, :dataTableShowKeys = true])
doc.addCaption("Figure 3 -- 100%% stacked bar with data table")
doc.addEmptyParagraph()
doc.addPageBreak()
# ---- 1d. Area chart with data table -----------------------------------------
doc.addHeading("1d. Stacked Area Chart + Data Table", 2)
doc.addEmptyParagraph()
doc.addAreaChart(
"Cumulative Downloads",
["2019", "2020", "2021", "2022", "2023", "2024"],
[
[:name = "Ring", :values = [12000, 28000, 51000, 89000, 142000, 215000], :color = "4472C4"],
[:name = "PWCT", :values = [8000, 16000, 28000, 47000, 74000, 108000], :color = "ED7D31"],
[:name = "Supernova", :values = [3000, 8000, 18000, 34000, 58000, 91000], :color = "70AD47"]
],
[:widthCm = 15, :heightCm = 8,
:grouping = "stacked", :legendPos = "b",
:yAxisMin = 0, :yAxisFormat = "#,##0",
:yAxisTitle = "Downloads",
:showDataTable = true, :dataTableShowKeys = true])
doc.addCaption("Figure 4 -- Stacked area chart with data table")
doc.addEmptyParagraph()
doc.addPageBreak()
# =============================================================================
# PART 2 -- MAIL MERGE TEMPLATE ENGINE
# =============================================================================
doc.addHeading("Part 2: Mail Merge Template Engine", 1)
doc.addParagraph(
"setMergeTemplate() registers a template once. mergeRecord() fills it " +
"for a single record. mergeAll() fills it for every record in a list, " +
"inserting a separator between records. Template items can be plain " +
"strings, headings, paragraphs with formatting options, tables, page " +
"breaks, and empty lines. All text fields support {{FIELDNAME}} tokens.", NULL)
doc.addEmptyParagraph()
doc.addPageBreak()
# ---- 2a. Simple letter template ---------------------------------------------
doc.addHeading("2a. Personalised Letter", 2)
doc.addParagraph(
"A letter template used with three recipient records. " +
"Separator between records is a page break.", NULL)
doc.addEmptyParagraph()
doc.setMergeTemplate([
[:type = "paragraph", :text = "{{Date}}", :options = [:align = "right"]],
[:type = "emptyline"],
[:type = "paragraph", :text = "{{RecipientName}}"],
[:type = "paragraph", :text = "{{CompanyName}}"],
[:type = "paragraph", :text = "{{Address}}"],
[:type = "emptyline"],
"Dear {{Salutation}} {{LastName}},",
[:type = "emptyline"],
[:type = "paragraph",
:text = "We are pleased to inform you that your application to the " +
"{{ProgramName}} has been successful. Your enrolment number is " +
"{{EnrolmentNumber}} and your start date is {{StartDate}}."],
[:type = "emptyline"],
[:type = "paragraph",
:text = "Your assigned track is {{Track}} and your faculty advisor is " +
"{{Advisor}}. Please report to {{Room}} at 09:00 on your start date."],
[:type = "emptyline"],
"We look forward to welcoming you.",
[:type = "emptyline"],
[:type = "paragraph", :text = "Yours sincerely,"],
[:type = "emptyline"],
[:type = "paragraph", :text = "Mahmoud",
:options = [:bold = true]],
[:type = "paragraph", :text = "Director, {{ProgramName}}"]
])
letterRecipients = [
[:Date = "1 March 2025",
:RecipientName = "Ms Alice Benali",
:CompanyName = "",
:Address = "14 Riyadh Street, Riyadh 11451, Saudi Arabia",
:Salutation = "Ms", :LastName = "Benali",
:ProgramName = "Ring Language MSc Programme",
:EnrolmentNumber = "MSC-2025-001",
:StartDate = "15 September 2025",
:Track = "Compiler Design",
:Advisor = "Dr. Sara Al-Ghamdi",
:Room = "Building 3, Room 204"],
[:Date = "1 March 2025",
:RecipientName = "Mr Mendes",
:CompanyName = "",
:Address = "Av. Paulista 1001, Sao Paulo, Brazil",
:Salutation = "Mr", :LastName = "Mendes",
:ProgramName = "Ring Language MSc Programme",
:EnrolmentNumber = "MSC-2025-002",
:StartDate = "15 September 2025",
:Track = "Visual Programming",
:Advisor = "Dr. Khalid",
:Room = "Building 3, Room 204"],
[:Date = "1 March 2025",
:RecipientName = "Dr. Yuki",
:CompanyName = "Osaka University",
:Address = "1-1 Yamadaoka, Suita, Osaka 565-0871, Japan",
:Salutation = "Dr", :LastName = "Tanaka",
:ProgramName = "Ring Language MSc Programme",
:EnrolmentNumber = "MSC-2025-003",
:StartDate = "15 September 2025",
:Track = "Language Internals and VM Optimisation",
:Advisor = "Prof. Ali",
:Room = "Building 3, Room 204"]
]
doc.mergeAll(letterRecipients, "pagebreak")
doc.clearMergeTemplate()
doc.addPageBreak()
# ---- 2b. Invoice template ---------------------------------------------------
doc.addHeading("2b. Invoice Template with Table", 2)
doc.addParagraph(
"Templates can contain tables with {{FIELD}} tokens in cells. " +
"Here an invoice header table and a line-items summary are merged " +
"for each client record. Separator between invoices is a page break.", NULL)
doc.addEmptyParagraph()
doc.setMergeTemplate([
[:type = "heading", :level = 1, :text = "INVOICE"],
[:type = "emptyline"],
# Header block as a table
[:type = "table",
:data = [
["Invoice Number", "{{InvoiceNum}}", "Date", "{{InvoiceDate}}"],
["Bill To", "{{ClientName}}", "Due Date", "{{DueDate}}"],
["Address", "{{ClientAddress}}","Payment", "{{PaymentTerms}}"]
],
:options = [
:borderStyle = "single", :borderColor = "CCCCCC",
:colWidths = [3.5, 5.0, 3.0, 5.0]
]],
[:type = "emptyline"],
[:type = "paragraph", :text = "Project: {{ProjectName}}", :options = [:bold = true]],
[:type = "emptyline"],
# Line items
[:type = "table",
:data = [
["Description", "Hours", "Rate", "Amount"],
["{{Item1Desc}}", "{{Item1Hours}}", "{{Item1Rate}}", "{{Item1Amount}}"],
["{{Item2Desc}}", "{{Item2Hours}}", "{{Item2Rate}}", "{{Item2Amount}}"],
["{{Item3Desc}}", "{{Item3Hours}}", "{{Item3Rate}}", "{{Item3Amount}}"],
["", "", "Subtotal", "{{Subtotal}}"],
["", "", "Tax (15%)", "{{Tax}}"],
["", "", "TOTAL DUE", "{{Total}}"]
],
:options = [
:headerRow = true, :headerBgColor = "1F3864",
:borderStyle = "single", :borderColor = "CCCCCC",
:colWidths = [8.0, 2.5, 3.0, 3.5],
:conditionalRules = [
[:col = 4, :condition = "contains", :value = "{{Total}}",
:bgColor = "E2EFDA", :bold = true]
]
]],
[:type = "emptyline"],
[:type = "paragraph",
:text = "Please transfer payment to Account: {{BankAccount}} " +
"using reference {{InvoiceNum}} by {{DueDate}}."],
[:type = "paragraph",
:text = "Thank you for your business, {{ClientName}}.",
:options = [:italic = true]]
])
invoices = [
[:InvoiceNum = "INV-2025-0041",
:InvoiceDate = "1 March 2025",
:DueDate = "31 March 2025",
:ClientName = "TechStart Ltd",
:ClientAddress = "88 Innovation Way, Dubai, UAE",
:PaymentTerms = "Net 30",
:ProjectName = "Ring Integration Suite",
:Item1Desc = "Backend API development",
:Item1Hours = "40", :Item1Rate = "$120", :Item1Amount = "$4,800",
:Item2Desc = "Testing and QA",
:Item2Hours = "16", :Item2Rate = "$90", :Item2Amount = "$1,440",
:Item3Desc = "Documentation",
:Item3Hours = "8", :Item3Rate = "$80", :Item3Amount = "$640",
:Subtotal = "$6,880",
:Tax = "$1,032",
:Total = "$7,912",
:BankAccount = "SA44 2000 0001 2345 6789 1234"],
[:InvoiceNum = "INV-2025-0042",
:InvoiceDate = "1 March 2025",
:DueDate = "31 March 2025",
:ClientName = "Global Analytics Corp",
:ClientAddress = "200 Data Blvd, Cairo, Egypt",
:PaymentTerms = "Net 30",
:ProjectName = "PWCT Visual Dashboard",
:Item1Desc = "UI component design",
:Item1Hours = "32", :Item1Rate = "$110", :Item1Amount = "$3,520",
:Item2Desc = "Data visualisation module",
:Item2Hours = "24", :Item2Rate = "$120", :Item2Amount = "$2,880",
:Item3Desc = "Client training session",
:Item3Hours = "4", :Item3Rate = "$200", :Item3Amount = "$800",
:Subtotal = "$7,200",
:Tax = "$1,080",
:Total = "$8,280",
:BankAccount = "SA44 2000 0001 2345 6789 1234"]
]
doc.mergeAll(invoices, "pagebreak")
doc.clearMergeTemplate()
doc.addPageBreak()
# ---- 2c. Certificate template -----------------------------------------------
doc.addHeading("2c. Completion Certificate", 2)
doc.addParagraph(
"A certificate template for course completions. " +
"Separator is a horizontal line so all certificates stay in one page flow.", NULL)
doc.addEmptyParagraph()
doc.setMergeTemplate([
[:type = "paragraph",
:text = "CERTIFICATE OF COMPLETION",
:options = [:bold = true, :align = "center", :fontSize = 18]],
[:type = "emptyline"],
[:type = "paragraph",
:text = "This is to certify that",
:options = [:align = "center", :italic = true]],
[:type = "paragraph",
:text = "{{FullName}}",
:options = [:bold = true, :align = "center", :fontSize = 16]],
[:type = "paragraph",
:text = "has successfully completed the course",
:options = [:align = "center", :italic = true]],
[:type = "paragraph",
:text = "{{CourseName}}",
:options = [:bold = true, :align = "center"]],
[:type = "paragraph",
:text = "with a final grade of {{Grade}} ({{Score}}%)",
:options = [:align = "center"]],
[:type = "emptyline"],
[:type = "paragraph",
:text = "Awarded on {{AwardDate}} | Certificate ID: {{CertID}}",
:options = [:align = "center", :italic = true]],
[:type = "emptyline"]
])
certRecipients = [
[:FullName = "Alice Benali",
:CourseName = "Ring Language Fundamentals",
:Grade = "Distinction", :Score = "94",
:AwardDate = "28 February 2025", :CertID = "CERT-2025-0101"],
[:FullName = "Carlos Mendes",
:CourseName = "PWCT Visual Programming",
:Grade = "Merit", :Score = "82",
:AwardDate = "28 February 2025", :CertID = "CERT-2025-0102"],
[:FullName = "Yuki Tanaka",
:CourseName = "Ring Language Fundamentals",
:Grade = "Distinction", :Score = "97",
:AwardDate = "28 February 2025", :CertID = "CERT-2025-0103"],
[:FullName = "Amina Diallo",
:CourseName = "Supernova Systems Programming",
:Grade = "Pass", :Score = "71",
:AwardDate = "28 February 2025", :CertID = "CERT-2025-0104"],
[:FullName = "Ravi Sharma",
:CourseName = "Ring Language Fundamentals",
:Grade = "Merit", :Score = "85",
:AwardDate = "28 February 2025", :CertID = "CERT-2025-0105"]
]
doc.mergeAll(certRecipients, "line")
doc.clearMergeTemplate()
doc.addPageBreak()
# ---- 2d. Report section template with chart presets -------------------------
doc.addHeading("2d. Product Report Template (Merge + Chart Presets)", 2)
doc.addParagraph(
"Demonstrates combining mergeRecord() with chart style presets. " +
"The template adds a text block and a data table per product; " +
"charts are added manually in the loop using a shared preset.", NULL)
doc.addEmptyParagraph()
# Set a shared chart preset for all product charts
doc.setChartDefaults([
:widthCm = 14,
:heightCm = 6,
:legendPos = "b",
:yAxisMin = 0,
:yAxisFormat = "#,##0",
:showGridlines = false,
:showDataTable = true,
:dataTableShowKeys = true
])
doc.setMergeTemplate([
[:type = "heading", :level = 2, :text = "{{ProductName}} -- Performance Summary"],
[:type = "paragraph",
:text = "Category: {{Category}} | Launch Year: {{LaunchYear}} | " +
"Current Version: {{Version}}"],
[:type = "emptyline"],
[:type = "paragraph", :text = "{{Description}}"],
[:type = "emptyline"],
[:type = "table",
:data = [
["Metric", "2022", "2023", "2024"],
["Downloads", "{{DL22}}", "{{DL23}}", "{{DL24}}"],
["Active Users", "{{AU22}}", "{{AU23}}", "{{AU24}}"],
["Github Stars", "{{Stars22}}", "{{Stars23}}", "{{Stars24}}"],
["Issues Closed", "{{Issues22}}", "{{Issues23}}", "{{Issues24}}"]
],
:options = [
:headerRow = true, :headerBgColor = "1F3864",
:evenRowBgColor = "F5F8FF",
:borderStyle = "single",
:colWidths = [4.0, 3.0, 3.0, 3.0]
]],
[:type = "emptyline"]
])
products = [
[:ProductName = "Ring",
:Category = "General-Purpose Language", :LaunchYear = "2016",
:Version = "1.26",
:Description = "Ring is a multi-paradigm language with a focus on natural " +
"language programming, visual programming, and a batteries-included " +
"standard library. It runs on Windows, Linux, macOS, and Android.",
:DL22 = "51,000", :DL23 = "89,000", :DL24 = "142,000",
:AU22 = "12,400", :AU23 = "22,800", :AU24 = "38,500",
:Stars22 = "920", :Stars23 = "1,240", :Stars24 = "1,680",
:Issues22 = "184", :Issues23 = "231", :Issues24 = "298"],
[:ProductName = "PWCT",
:Category = "Visual Programming Environment", :LaunchYear = "2005",
:Version = "1.9",
:Description = "Programming Without Coding Technology is a visual " +
"programming environment that enables developers to create " +
"programs through a drag-and-drop component model.",
:DL22 = "28,000", :DL23 = "47,000", :DL24 = "74,000",
:AU22 = "6,800", :AU23 = "11,400", :AU24 = "19,200",
:Stars22 = "480", :Stars23 = "640", :Stars24 = "850",
:Issues22 = "94", :Issues23 = "118", :Issues24 = "147"]
]
years = ["2022", "2023", "2024"]
# Manually loop so we can add a chart per product after the merge block
productLen = len(products)
for pi = 1 to productLen
pdata = products[pi]
doc.mergeRecord(pdata)
# Parse download numbers for chart (strip commas)
dl22 = number(substr(pdata[:DL22], ",", ""))
dl23 = number(substr(pdata[:DL23], ",", ""))
dl24 = number(substr(pdata[:DL24], ",", ""))
au22 = number(substr(pdata[:AU22], ",", ""))
au23 = number(substr(pdata[:AU23], ",", ""))
au24 = number(substr(pdata[:AU24], ",", ""))
doc.addColumnChart(
pdata[:ProductName] + " -- Downloads vs Active Users",
years,
[
[:name = "Downloads", :values = [dl22, dl23, dl24], :color = "4472C4"],
[:name = "Active Users", :values = [au22, au23, au24], :color = "ED7D31"]
],
[]) # all from setChartDefaults
doc.addCaption("Figure " + (4 + pi) + " -- " + pdata[:ProductName] + " growth (data table from :showDataTable)")
doc.addEmptyParagraph()
if pi < productLen
doc.addPageBreak()
ok
next
doc.clearMergeTemplate()
doc.clearChartDefaults()
# ---- Save -------------------------------------------------------------------
? "Building document ..."
doc.save("demo_mailmerge_datatable_output.docx")
? "Done -- demo_mailmerge_datatable_output.docx"part15_mailmerge2.ring#
samples/UsingDOCXLib/part15_mailmerge2.ring
/*
DOCXLib - Demo (MailMerge2)
*/
load "docxlib.ring"
/*
Rich Table Cells in Mail Merge Templates
mergeCell(runs, cellOptions)
Create a WordCell with multiple styled runs for use inside merge
templates. {{FIELD}} tokens in run text are filled automatically
when mergeRecord() / mergeAll() is called.
mergeFillWordCell(cellObj, data) [internal, used automatically]
Clones a WordCell, filling {{FIELD}} tokens in every run while
preserving all run-level formatting (bold, color, italic, size, etc.)
mergeFillTable() upgraded
Now detects WordCell objects in table data and routes them through
mergeFillWordCell() instead of plain string coercion.
This means a merge table cell can have:
- Multiple runs with independent formatting
- Bold labels + regular values in the same cell
- Colour-coded values
- Mixed font sizes
- Any combination of run properties
...all driven by {{FIELD}} tokens that are filled per record.
*/
? "==================================================="
? " DOCXLib -- Rich Merge Cells Demo"
? "==================================================="
? ""
doc = new WordWriter()
doc.setTitle("DOCXLib -- Rich Table Cells in Merge Templates")
doc.setAuthor("DOCXLib Demo")
doc.setPageSize("a4")
doc.setTheme("Blue")
doc.setHeader("DOCXLib -- Rich Merge Cells")
doc.setFooter("Generated by DOCXLib")
# =============================================================================
# SECTION 1 -- THE PROBLEM: plain strings lose formatting
# =============================================================================
doc.addHeading("Section 1: Why Rich Merge Cells Are Needed", 1)
doc.addParagraph(
"In early stage of development, every cell in a merge table template had to be a plain " +
"string. That meant you could not have, for example, a bold label followed " +
"by a regular value inside the same cell, or a colour-coded numeric result. " +
"The entire cell was either styled or unstyled -- you could not mix.", NULL)
doc.addEmptyParagraph()
doc.addParagraph(
"During development we provided an update that solves this with mergeCell(runs, cellOptions). Pass a list of " +
"run definitions -- each with its own :text, :bold, :color, :italic, " +
":size etc. -- and {{FIELD}} tokens inside any run are filled " +
"automatically when the template is merged.", NULL)
doc.addEmptyParagraph()
doc.addPageBreak()
# =============================================================================
# SECTION 2 -- EMPLOYEE PROFILE CARDS
# Each card: header cell spanning columns, then label+value pairs where
# the label is bold/dark and the value is regular, all in one cell.
# =============================================================================
doc.addHeading("Section 2: Employee Profile Cards", 1)
doc.addParagraph(
"Each card uses mergeCell() to put a bold label and a regular value " +
"in the same cell. The Status cell is colour-coded: green for Active, " +
"amber for On Leave, red for Terminated -- the colour comes from a " +
":bgColor field in the data record.", NULL)
doc.addEmptyParagraph()
doc.setMergeTemplate([
# Full-width header row: Name + title on one bold run, department on a smaller run
[:type = "table",
:data = [
[
mergeCell([
[:text = "{{FullName}}", :bold = true, :size = 28, :color = "FFFFFF"],
[:text = " -- ", :bold = false, :size = 20, :color = "BDD7EE"],
[:text = "{{Title}}", :italic = true, :size = 20, :color = "BDD7EE"]
], [:bgColor = "1F3864", :colspan = 4, :verticalAlign = "center"])
],
# Row 2: Employee ID | Department
[
mergeCell([
[:text = "Employee ID: ", :bold = true, :color = "1F3864"],
[:text = "{{EmployeeID}}", :bold = false, :color = "000000"]
], []),
mergeCell([
[:text = "Department: ", :bold = true, :color = "1F3864"],
[:text = "{{Department}}", :bold = false, :color = "000000"]
], []),
mergeCell([
[:text = "Location: ", :bold = true, :color = "1F3864"],
[:text = "{{Location}}", :bold = false, :color = "000000"]
], []),
mergeCell([
[:text = "Start Date: ", :bold = true, :color = "1F3864"],
[:text = "{{StartDate}}", :bold = false, :color = "000000"]
], [])
],
# Row 3: Email | Phone | Salary | Status (colour-coded)
[
mergeCell([
[:text = "Email: ", :bold = true, :color = "1F3864"],
[:text = "{{Email}}", :bold = false, :color = "000000"]
], []),
mergeCell([
[:text = "Phone: ", :bold = true, :color = "1F3864"],
[:text = "{{Phone}}", :bold = false, :color = "000000"]
], []),
mergeCell([
[:text = "Salary: ", :bold = true, :color = "1F3864"],
[:text = "{{Salary}}", :bold = false, :color = "375623"]
], []),
mergeCell([
[:text = "Status: ", :bold = true, :color = "FFFFFF"],
[:text = "{{Status}}", :bold = true, :color = "FFFFFF"]
], [:bgColor = "{{StatusBg}}", :align = "center"])
]
],
:options = [
:borderStyle = "single", :borderColor = "CCCCCC",
:colWidths = [4.0, 4.0, 4.0, 4.0],
:repeatHeader = false
]],
[:type = "emptyline"]
])
employees = [
[:FullName = "Alice Benali",
:Title = "Senior Ring Developer",
:EmployeeID = "EMP-1001",
:Department = "Engineering",
:Location = "Riyadh, SA",
:StartDate = "15 Jan 2020",
:Email = "alice@ringdemo.com",
:Phone = "+966 50 111 2233",
:Salary = "$95,000",
:Status = "Active",
:StatusBg = "375623"],
[:FullName = "Carlos Mendes",
:Title = "PWCT Specialist",
:EmployeeID = "EMP-1002",
:Department = "Product",
:Location = "Sao Paulo, BR",
:StartDate = "3 Mar 2021",
:Email = "carlos@ringdemo.com",
:Phone = "+55 11 9876 5432",
:Salary = "$78,000",
:Status = "On Leave",
:StatusBg = "7F4F00"],
[:FullName = "Yuki Tanaka",
:Title = "Language Internals Engineer",
:EmployeeID = "EMP-1003",
:Department = "Research",
:Location = "Osaka, JP",
:StartDate = "10 Sep 2019",
:Email = "yuki@ringdemo.com",
:Phone = "+81 6 1234 5678",
:Salary = "$102,000",
:Status = "Active",
:StatusBg = "375623"],
[:FullName = "Amina Diallo",
:Title = "Visual Programming Researcher",
:EmployeeID = "EMP-1004",
:Department = "Research",
:Location = "Dakar, SN",
:StartDate = "20 Jun 2022",
:Email = "amina@ringdemo.com",
:Phone = "+221 77 555 6677",
:Salary = "$71,000",
:Status = "Active",
:StatusBg = "375623"],
[:FullName = "David Park",
:Title = "Systems Architect",
:EmployeeID = "EMP-1005",
:Department = "Infrastructure",
:Location = "Seoul, KR",
:StartDate = "1 Feb 2018",
:Email = "david@ringdemo.com",
:Phone = "+82 2 3456 7890",
:Salary = "$115,000",
:Status = "Terminated",
:StatusBg = "C00000"]
]
doc.mergeAll(employees, "emptyline")
doc.clearMergeTemplate()
doc.addPageBreak()
# =============================================================================
# SECTION 3 -- INVOICE LINE ITEMS with rich totals row
# Bold labels on header cells, colour-coded total row, mixed sizes
# =============================================================================
doc.addHeading("Section 3: Invoices with Rich Line-Item Tables", 1)
doc.addParagraph(
"The invoice header uses mergeCell() for bold label + value pairs. " +
"The totals row uses large bold text with a dark background. " +
"Individual line-item description cells contain a bold product name " +
"followed by a smaller italic description on a second run.", NULL)
doc.addEmptyParagraph()
doc.setMergeTemplate([
# Invoice title bar
[:type = "table",
:data = [
[
mergeCell([
[:text = "INVOICE", :bold = true, :size = 36, :color = "FFFFFF"]
], [:bgColor = "1F3864", :colspan = 2, :align = "left", :verticalAlign = "center"]),
mergeCell([
[:text = "{{CompanyName}}", :bold = true, :size = 22, :color = "FFFFFF"],
[:text = +"{{CompanyTag}}", :italic = true, :size = 18, :color = "BDD7EE"]
], [:bgColor = "1F3864", :colspan = 2, :align = "right", :verticalAlign = "center"])
],
# Invoice metadata row
[
mergeCell([
[:text = "Invoice No: ", :bold = true, :color = "1F3864"],
[:text = "{{InvNum}}", :bold = false, :color = "000000"]
], []),
mergeCell([
[:text = "Date: ", :bold = true, :color = "1F3864"],
[:text = "{{InvDate}}",:bold = false, :color = "000000"]
], []),
mergeCell([
[:text = "Due Date: ", :bold = true, :color = "1F3864"],
[:text = "{{DueDate}}", :bold = false, :color = "000000"]
], []),
mergeCell([
[:text = "Bill To: ", :bold = true, :color = "1F3864"],
[:text = "{{ClientName}}", :bold = false, :color = "000000"]
], [])
]
],
:options = [:borderStyle = "single", :borderColor = "CCCCCC",
:colWidths = [4.0, 4.0, 4.0, 4.0]]],
[:type = "emptyline"],
# Line items table
[:type = "table",
:data = [
# Header row (plain strings are fine for static labels)
["Description", "Qty", "Unit Price", "Amount"],
# Line items with rich description cells
[
mergeCell([
[:text = "{{L1Name}}", :bold = true, :color = "000000"],
[:text = " -- {{L1Desc}}", :italic = true, :size = 18, :color = "666666"]
], []),
"{{L1Qty}}", "{{L1Price}}", "{{L1Amount}}"
],
[
mergeCell([
[:text = "{{L2Name}}", :bold = true, :color = "000000"],
[:text = " -- {{L2Desc}}", :italic = true, :size = 18, :color = "666666"]
], []),
"{{L2Qty}}", "{{L2Price}}", "{{L2Amount}}"
],
[
mergeCell([
[:text = "{{L3Name}}", :bold = true, :color = "000000"],
[:text = " -- {{L3Desc}}", :italic = true, :size = 18, :color = "666666"]
], []),
"{{L3Qty}}", "{{L3Price}}", "{{L3Amount}}"
],
# Subtotal / tax rows
["", "", mergeCell([[:text = "Subtotal:", :bold = true]], [:align = "right"]),
mergeCell([[:text = "{{Subtotal}}",:bold = false]], [])],
["", "", mergeCell([[:text = "Tax (15%):", :bold = true]], [:align = "right"]),
mergeCell([[:text = "{{Tax}}",:bold = false]], [])],
# Total row: large bold white on dark background
[
mergeCell([
[:text = "TOTAL DUE", :bold = true, :size = 26, :color = "FFFFFF"]
], [:bgColor = "1F3864", :colspan = 3, :align = "right", :verticalAlign = "center"]),
mergeCell([
[:text = "{{Total}}", :bold = true, :size = 26, :color = "FFFFFF"]
], [:bgColor = "1F3864", :align = "center", :verticalAlign = "center"])
]
],
:options = [
:headerRow = true, :headerBgColor = "2E75B6",
:borderStyle = "single", :borderColor = "CCCCCC",
:colWidths = [8.5, 1.5, 3.0, 3.0]
]],
[:type = "emptyline"]
])
invoices = [
[:CompanyName = "Ring Tech Ltd",
:CompanyTag = "Enterprise Software Solutions",
:InvNum = "INV-2025-0081", :InvDate = "1 Mar 2025", :DueDate = "31 Mar 2025",
:ClientName = "Global Analytics Corp",
:L1Name = "Ring Enterprise Licence",
:L1Desc = "Annual seat licence, 50 users",
:L1Qty = "1", :L1Price = "$12,000", :L1Amount = "$12,000",
:L2Name = "PWCT Visual Studio Plugin",
:L2Desc = "Per-user licence x10",
:L2Qty = "10", :L2Price = "$450", :L2Amount = "$4,500",
:L3Name = "Implementation Consulting",
:L3Desc = "On-site setup and training, 3 days",
:L3Qty = "3", :L3Price = "$1,800", :L3Amount = "$5,400",
:Subtotal = "$21,900", :Tax = "$3,285", :Total = "$25,185"],
[:CompanyName = "Ring Tech Ltd",
:CompanyTag = "Enterprise Software Solutions",
:InvNum = "INV-2025-0082", :InvDate = "1 Mar 2025", :DueDate = "31 Mar 2025",
:ClientName = "StartHub Ventures",
:L1Name = "Supernova Cloud Starter",
:L1Desc = "Monthly subscription, 12 months",
:L1Qty = "12", :L1Price = "$299", :L1Amount = "$3,588",
:L2Name = "API Integration Package",
:L2Desc = "REST connector setup",
:L2Qty = "1", :L2Price = "$1,200", :L2Amount = "$1,200",
:L3Name = "Priority Support",
:L3Desc = "12-month SLA coverage",
:L3Qty = "1", :L3Price = "$600", :L3Amount = "$600",
:Subtotal = "$5,388", :Tax = "$808", :Total = "$6,196"]
]
doc.mergeAll(invoices, "pagebreak")
doc.clearMergeTemplate()
doc.addPageBreak()
# =============================================================================
# SECTION 4 -- STUDENT REPORT CARDS
# Grade cells: bold grade letter + italic descriptor, colour by grade band
# =============================================================================
doc.addHeading("Section 4: Student Report Cards", 1)
doc.addParagraph(
"Each subject cell contains a bold grade letter + italic descriptor in the " +
"same cell. The overall result cell is large, bold, and colour-coded by grade. " +
"The comment cell uses three runs: label bold, body regular, signed italic.", NULL)
doc.addEmptyParagraph()
doc.setMergeTemplate([
[:type = "heading", :level = 2, :text = "{{StudentName}} -- {{Programme}}"],
[:type = "table",
:data = [
# Header row
["Subject", "Grade", "Mark", "Comments"],
# Subject rows -- grade cell has two runs
[
"Mathematics",
mergeCell([
[:text = "{{MathGrade}}", :bold = true, :size = 26, :color = "{{MathGradeColor}}"],
[:text = " {{MathDesc}}", :italic = true, :size = 18, :color = "444444"]
], [:align = "center"]),
mergeCell([[:text = "{{MathMark}}%", :bold = true, :color = "{{MathGradeColor}}"]], [:align = "center"]),
"{{MathComment}}"
],
[
"Ring Programming",
mergeCell([
[:text = "{{RingGrade}}", :bold = true, :size = 26, :color = "{{RingGradeColor}}"],
[:text = " {{RingDesc}}", :italic = true, :size = 18, :color = "444444"]
], [:align = "center"]),
mergeCell([[:text = "{{RingMark}}%", :bold = true, :color = "{{RingGradeColor}}"]], [:align = "center"]),
"{{RingComment}}"
],
[
"Compiler Design",
mergeCell([
[:text = "{{CompGrade}}", :bold = true, :size = 26, :color = "{{CompGradeColor}}"],
[:text = " {{CompDesc}}", :italic = true, :size = 18, :color = "444444"]
], [:align = "center"]),
mergeCell([[:text = "{{CompMark}}%", :bold = true, :color = "{{CompGradeColor}}"]], [:align = "center"]),
"{{CompComment}}"
],
[
"Visual Programming",
mergeCell([
[:text = "{{VisPGrade}}", :bold = true, :size = 26, :color = "{{VisPGradeColor}}"],
[:text = " {{VisPDesc}}", :italic = true, :size = 18, :color = "444444"]
], [:align = "center"]),
mergeCell([[:text = "{{VisPMark}}%", :bold = true, :color = "{{VisPGradeColor}}"]], [:align = "center"]),
"{{VisPComment}}"
],
# Overall result row
[
mergeCell([[:text = "Overall Result", :bold = true, :color = "FFFFFF"]], [:bgColor = "1F3864", :colspan = 2]),
mergeCell([
[:text = "{{OverallGrade}}", :bold = true, :size = 30, :color = "{{OverallColor}}"],
[:text = " {{OverallDesc}}", :italic = true, :size = 18, :color = "FFFFFF"]
], [:bgColor = "1F3864", :align = "center"]),
mergeCell([[:text = "{{OverallAvg}}%", :bold = true, :size = 26, :color = "{{OverallColor}}"]], [:bgColor = "1F3864", :align = "center"])
],
# Tutor comment row
[
mergeCell([
[:text = "Tutor Comment: ", :bold = true, :color = "1F3864"],
[:text = "{{TutorComment}}", :bold = false, :color = "000000"],
[:text = " -- {{TutorName}}", :italic = true, :size = 18, :color = "666666"]
], [:colspan = 4])
]
],
:options = [
:headerRow = true, :headerBgColor = "2E75B6",
:borderStyle = "single", :borderColor = "CCCCCC",
:colWidths = [3.5, 2.5, 2.0, 8.0]
]],
[:type = "emptyline"]
])
students = [
[:StudentName = "Alice Benali",
:Programme = "Ring Language MSc -- Year 1",
:MathGrade = "A", :MathDesc = "Distinction", :MathMark = "92",
:MathGradeColor = "375623",
:MathComment = "Excellent analytical work throughout the semester.",
:RingGrade = "A+", :RingDesc = "Distinction", :RingMark = "97",
:RingGradeColor = "375623",
:RingComment = "Outstanding language design project.",
:CompGrade = "B", :CompDesc = "Merit", :CompMark = "81",
:CompGradeColor = "2E75B6",
:CompComment = "Strong theoretical foundations, solid implementation.",
:VisPGrade = "A", :VisPDesc = "Distinction", :VisPMark = "90",
:VisPGradeColor = "375623",
:VisPComment = "Creative PWCT extension project impressed the panel.",
:OverallGrade = "A", :OverallDesc = "Distinction", :OverallAvg = "90",
:OverallColor = "375623",
:TutorComment = "Alice is one of our strongest students. Recommended for PhD track.",
:TutorName = "Prof. Ali"],
[:StudentName = "Carlos Mendes",
:Programme = "Ring Language MSc -- Year 1",
:MathGrade = "B", :MathDesc = "Merit", :MathMark = "78",
:MathGradeColor = "2E75B6",
:MathComment = "Good performance; proof-writing could be more rigorous.",
:RingGrade = "B+", :RingDesc = "Merit", :RingMark = "84",
:RingGradeColor = "2E75B6",
:RingComment = "Solid Ring project with good test coverage.",
:CompGrade = "C", :CompDesc = "Pass", :CompMark = "64",
:CompGradeColor = "7F4F00",
:CompComment = "Passed but needs to strengthen optimisation knowledge.",
:VisPGrade = "B", :VisPDesc = "Merit", :VisPMark = "80",
:VisPGradeColor = "2E75B6",
:VisPComment = "Good use of PWCT components; needs more documentation.",
:OverallGrade = "B", :OverallDesc = "Merit", :OverallAvg = "77",
:OverallColor = "BDD7EE",
:TutorComment = "Carlos shows real-world focus. Encourage deeper theoretical study.",
:TutorName = "Prof. Ali"],
[:StudentName = "Amina Diallo",
:Programme = "Ring Language MSc -- Year 1",
:MathGrade = "D", :MathDesc = "Marginal", :MathMark = "52",
:MathGradeColor = "C00000",
:MathComment = "Supplementary exam recommended for this module.",
:RingGrade = "B", :RingDesc = "Merit", :RingMark = "76",
:RingGradeColor = "2E75B6",
:RingComment = "Ring coursework was well-structured and functional.",
:CompGrade = "C", :CompDesc = "Pass", :CompMark = "63",
:CompGradeColor = "7F4F00",
:CompComment = "Adequate understanding; exam preparation needed.",
:VisPGrade = "A", :VisPDesc = "Distinction", :VisPMark = "91",
:VisPGradeColor = "375623",
:VisPComment = "Exceptional PWCT2 visual language design project.",
:OverallGrade = "C", :OverallDesc = "Pass", :OverallAvg = "71",
:OverallColor = "FFC000",
:TutorComment = "Amina excels in visual programming. Mathematics requires urgent attention.",
:TutorName = "Prof. Ali"]
]
doc.mergeAll(students, "pagebreak")
doc.clearMergeTemplate()
doc.addPageBreak()
# =============================================================================
# SECTION 5 -- API REFERENCE CARDS (mixed font sizes + token fills)
# Demonstrates mixing plain cells and rich cells in the same table
# =============================================================================
doc.addHeading("Section 5: API Reference Cards", 1)
doc.addParagraph(
"Each card documents one function. The function signature cell uses " +
"a monospace bold run for the name and a regular run for the parameters. " +
"The returns cell has a bold type prefix followed by a description. " +
"Plain string cells are used for fields that need no mixed formatting.", NULL)
doc.addEmptyParagraph()
doc.setMergeTemplate([
[:type = "table",
:data = [
# Function signature header -- full-width
[
mergeCell([
[:text = "{{FuncName}}", :bold = true, :font = "Courier New", :size = 26, :color = "FFFFFF"],
[:text = "( {{Params}} )", :bold = false, :font = "Courier New", :size = 22, :color = "BDD7EE"]
], [:bgColor = "1F3864", :colspan = 2, :verticalAlign = "center"])
],
# Module + Added in
[
mergeCell([
[:text = "Module: ", :bold = true, :color = "1F3864"],
[:text = "{{Module}}", :bold = false, :color = "000000"]
], []),
mergeCell([
[:text = "Added in: ", :bold = true, :color = "1F3864"],
[:text = "v{{AddedIn}}", :bold = false, :color = "000000"]
], [])
],
# Description -- full width, plain
[
mergeCell([
[:text = "Description: ", :bold = true, :color = "1F3864"],
[:text = "{{Description}}", :bold = false, :color = "000000"]
], [:colspan = 2])
],
# Parameters
[
mergeCell([
[:text = "Parameters:", :bold = true, :color = "1F3864"]
], [:colspan = 2, :bgColor = "EEF3FA"])
],
[
mergeCell([
[:text = "{{P1Name}}", :bold = true, :font = "Courier New", :color = "C00000"],
[:text = " -- ", :bold = false, :color = "888888"],
[:text = "{{P1Desc}}", :bold = false, :color = "000000"]
], [:colspan = 2])
],
[
mergeCell([
[:text = "{{P2Name}}", :bold = true, :font = "Courier New", :color = "C00000"],
[:text = " -- ", :bold = false, :color = "888888"],
[:text = "{{P2Desc}}", :bold = false, :color = "000000"]
], [:colspan = 2])
],
# Returns
[
mergeCell([
[:text = "Returns: ", :bold = true, :color = "1F3864"],
[:text = "{{RetType}}", :bold = true, :font = "Courier New", :color = "7F3F00"],
[:text = " -- {{RetDesc}}", :bold = false, :color = "000000"]
], [:colspan = 2])
],
# Example -- full width code cell
[
mergeCell([
[:text = "Example: ", :bold = true, :color = "1F3864"]
], [:colspan = 2, :bgColor = "EEF3FA"])
],
[
mergeCell([
[:text = "{{Example}}", :font = "Courier New", :size = 18, :color = "1A1A2E"]
], [:colspan = 2, :bgColor = "EEF3FA"])
]
],
:options = [
:borderStyle = "single", :borderColor = "CCCCCC",
:colWidths = [8.0, 8.0]
]],
[:type = "emptyline"]
])
apiFunctions = [
[:FuncName = "setMergeTemplate",
:Params = "templateDef",
:Module = "WordWriter (mail merge)",
:AddedIn = "1.12.4",
:Description = "Register a document template for repeated mail-merge output. " +
"The template is a list of items; each item is a plain string or " +
"an associative list describing a heading, paragraph, table, etc.",
:P1Name = "templateDef",
:P1Desc = "List of template items. Strings are paragraphs; lists must have :type key.",
:P2Name = "(none)",
:P2Desc = "This function takes only one parameter.",
:RetType = "self",
:RetDesc = "Returns the WordWriter instance for method chaining.",
:Example = "doc.setMergeTemplate([" +
" " + char(34) + "Dear {{Name}}," + char(34) + "," +
" [:type=" + char(34) + "paragraph" + char(34) + ", :text=" + char(34) + "Your score is {{Score}}." + char(34) + "]" +
"])"],
[:FuncName = "mergeCell",
:Params = "runs, cellOptions",
:Module = "Global helper (mail merge)",
:AddedIn = "1.12.5",
:Description = "Create a WordCell with multiple styled text runs for use inside " +
"mail-merge table templates. {{FIELD}} tokens in any run are filled " +
"automatically when mergeRecord() or mergeAll() is called.",
:P1Name = "runs",
:P1Desc = "List of run definitions. Each: [:text=, :bold=, :italic=, :color=, :size=, :font=, ...]",
:P2Name = "cellOptions",
:P2Desc = "Cell-level options: [:align=, :bgColor=, :verticalAlign=, :colspan=, :rowspan=]",
:RetType = "WordCell",
:RetDesc = "A fully configured WordCell ready for use in a table data array.",
:Example = "mergeCell([" +
" [:text=" + char(34) + "Score: " + char(34) + ", :bold=true, :color=" + char(34) + "1F3864" + char(34) + "]," +
" [:text=" + char(34) + "{{Score}}" + char(34) + ", :bold=true, :color=" + char(34) + "375623" + char(34) + "]" +
"], [:align=" + char(34) + "center" + char(34) + "])"],
[:FuncName = "mergeAll",
:Params = "dataList, separator",
:Module = "WordWriter (mail merge)",
:AddedIn = "1.12.4",
:Description = "Render the registered template once per record in dataList, " +
"inserting a separator between records. The most efficient way " +
"to produce batch personalised documents.",
:P1Name = "dataList",
:P1Desc = "List of associative lists. Each list is one merge record.",
:P2Name = "separator",
:P2Desc = char(34) + "pagebreak" + char(34) + " (default) | " +
char(34) + "emptyline" + char(34) + " | " +
char(34) + "line" + char(34) + " | " +
char(34) + "none" + char(34),
:RetType = "self",
:RetDesc = "Returns the WordWriter instance for method chaining.",
:Example = "doc.mergeAll([" +
" [:Name=" + char(34) + "Alice" + char(34) + ", :Score=" + char(34) + "94" + char(34) + "]," +
" [:Name=" + char(34) + "Bob" + char(34) + ", :Score=" + char(34) + "78" + char(34) + "]" +
"], " + char(34) + "pagebreak" + char(34) + ")"]
]
doc.mergeAll(apiFunctions, "emptyline")
doc.clearMergeTemplate()
# ---- Save -------------------------------------------------------------------
? "Building document ..."
doc.save("demo_mailmerge2_cells_output.docx")
? "Done -- demo_mailmerge2_cells_output.docx"part16_wordreader.ring#
samples/UsingDOCXLib/part16_wordreader.ring
/*
DOCXLib - Demo (WordReader)
*/
load "docxlib.ring"
/*
Demonstrates the complete read -> inspect -> modify -> save workflow.
The demo is fully self-contained:
Step 1 Generate a rich source document (product catalogue + report)
Step 2 Open it with WordReader and print a structural summary
Step 3 Inspect headings, paragraphs, tables programmatically
Step 4 Perform modifications:
a) Global find/replace (year update)
b) Table cell edits (price/status updates)
c) Heading rename
d) Paragraph rewrite
e) Append a new summary section
Step 5 Export the modified document via toWriter() + save()
Step 6 Open the saved file, verify the changes round-tripped
*/
? "======================================================="
? " DOCXLib -- WordReader Demo"
? "======================================================="
? ""
# =============================================================================
# STEP 1 -- Generate the source document
# =============================================================================
? "STEP 1: Generating source document (demo_wordreader_source.docx) ..."
src = new WordWriter()
src.setTitle("Ring Technology -- Product Catalogue 2024")
src.setAuthor("Ring Documentation Team")
src.setDefaultFont("Calibri", 11)
src.setTheme("Blue")
src.setHeader("Ring Technology -- Confidential -- 2024")
src.setFooter("Page | Ring Technology Ltd")
# Cover section
src.addHeading("Ring Technology", 1)
src.addHeading("Product Catalogue 2024", 2)
src.addParagraph(
"This catalogue provides an overview of all Ring Technology products " +
"available in the 2024 financial year. Pricing reflects the standard " +
"enterprise tier. Volume discounts are available on request.", NULL)
src.addEmptyParagraph()
# Products section
src.addHeading("1. Core Products", 1)
src.addHeading("1.1 Ring Language Platform", 2)
src.addParagraph(
"The Ring Language Platform is a multi-paradigm programming environment " +
"featuring natural language syntax, built-in visual programming support, " +
"and a comprehensive standard library. Version 1.26 is the current release.", NULL)
src.addTable([
["Product", "Version", "Licence", "Unit Price"],
["Ring Language IDE", "1.26", "Annual", "$1,200"],
["Ring Enterprise Licence", "1.26", "Perpetual", "$8,500"],
["Ring Developer Starter", "1.26", "Annual", "$450"],
["Ring Education Bundle", "1.26", "Per-Seat/Year", "$150"]
], [:headerRow = true, :borderStyle = "single",
:colWidths = [5.5, 2.0, 2.5, 2.5]])
src.addEmptyParagraph()
src.addHeading("1.2 PWCT Visual Programming Suite", 2)
src.addParagraph(
"PWCT (Programming Without Coding Technology) is a visual programming " +
"environment that generates Ring source code from graphical flowcharts. " +
"Suitable for education, rapid prototyping, and non-developer audiences.", NULL)
src.addTable([
["Product", "Version", "Licence", "Unit Price"],
["PWCT Desktop", "2.0", "Perpetual", "$950"],
["PWCT Team Edition", "2.0", "Annual/5", "$3,200"],
["PWCT2 Visual Studio", "2.0", "Annual", "$750"],
["PWCT Mobile SDK", "1.5", "Annual", "$600"]
], [:headerRow = true, :borderStyle = "single",
:colWidths = [5.5, 2.0, 2.5, 2.5]])
src.addEmptyParagraph()
src.addHeading("1.3 RingStar Cloud Platform", 2)
src.addParagraph(
"RingStar is Ring Technology's cloud-native application platform. " +
"It provides managed infrastructure, auto-scaling, and a REST API gateway " +
"optimised for Ring applications.", NULL)
src.addTable([
["Plan", "Instances", "Storage", "Support", "Monthly"],
["Starter", "2", "50 GB", "Community","$99"],
["Professional", "10", "500 GB", "Email", "$499"],
["Business", "50", "2 TB", "Phone", "$1,999"],
["Enterprise", "Unlimited", "10 TB", "Dedicated","$7,500"]
], [:headerRow = true, :borderStyle = "single",
:colWidths = [3.0, 2.5, 2.0, 2.5, 2.5]])
src.addEmptyParagraph()
# Financial section
src.addHeading("2. Financial Summary", 1)
src.addParagraph(
"The following table summarises annual revenue by product line for the " +
"2024 fiscal year. All figures in USD thousands.", NULL)
src.addTable([
["Product Line", "Q1 2024", "Q2 2024", "Q3 2024", "Q4 2024", "Total 2024"],
["Ring Platform", "320", "415", "389", "502", "1,626"],
["PWCT Suite", "210", "268", "241", "315", "1,034"],
["RingStar", "185", "240", "312", "418", "1,155"],
["Services", "125", "138", "149", "171", "583"],
["TOTAL", "840", "1,061", "1,091", "1,406", "4,398"]
], [:headerRow = true, :borderStyle = "single",
:colWidths = [3.5, 2.0, 2.0, 2.0, 2.0, 2.5]])
src.addEmptyParagraph()
# Status section
src.addHeading("3. Product Status", 1)
src.addParagraph(
"Current development and release status for all major products as of " +
"the 2024 catalogue publication date.", NULL)
src.addTable([
["Product", "Status", "Next Release", "Notes"],
["Ring Language", "RELEASED", "Q2 2025", "v1.27 in development"],
["PWCT Visual Suite", "RELEASED", "Q3 2025", "Mobile beta Q1 2025"],
["RingStar Cloud", "BETA", "Q1 2025", "GA expected March 2025"],
["Ring AI Toolkit", "IN DEVELOPMENT","Q4 2025", "LLM integration"],
["Ring Enterprise IDE", "PLANNING", "Q1 2026", "Roadmap confirmed"]
], [:headerRow = true, :borderStyle = "single",
:colWidths = [4.0, 3.0, 2.5, 5.0]])
src.addEmptyParagraph()
# Notes
src.addHeading("4. Important Notes", 1)
src.addParagraph(
"All pricing shown is exclusive of applicable taxes. Enterprise customers " +
"should contact their account manager for volume pricing. Ring Technology " +
"reserves the right to revise pricing at any time with 30 days notice.", NULL)
src.addParagraph(
"This document is confidential and intended for internal distribution only. " +
"Do not distribute outside Ring Technology without written authorisation.", NULL)
src.save("demo_wordreader_source.docx")
? " Source document saved."
? ""
# =============================================================================
# STEP 2 -- Open with WordReader and print summary
# =============================================================================
? "STEP 2: Opening with WordReader ..."
wr = new WordReader("demo_wordreader_source.docx")
? wr.summary()
# =============================================================================
# STEP 3 -- Inspect structure programmatically
# =============================================================================
? "STEP 3: Inspecting document structure ..."
? ""
? "--- Block index ---"
wr.listBlocks()
? ""
? "--- All headings ---"
blocks = wr.getBlocks()
bLen = len(blocks)
for i = 1 to bLen
b = blocks[i]
if b[:type] = "heading"
? " H" + string(b[:level]) + ": " + b[:text]
ok
next
? ""
? "--- Table 5 contents (Product Status) ---"
tblIdx4 = wr.getTableBlockIndex(5)
if tblIdx4 > 0
tbl = wr.getBlock(tblIdx4)
rows = tbl[:rows]
rowLen = len(rows)
for ri = 1 to rowLen
row = rows[ri]
line = " Row " + string(ri) + ": "
cLen = len(row)
for ci = 1 to cLen
cell = row[ci]
ct = ""
if isList(cell) ct = cell[:text]
else ct = "" + cell
ok
line += ct + " | "
next
? line
next
ok
? ""
? "--- Find blocks containing BETA ---"
found = wr.findBlocks("BETA")
if len(found) > 0
for idx in found
b = wr.getBlock(idx)
? " Block " + string(idx) + " (" + b[:type] + ")"
next
else
? " Not found."
ok
? ""
? "--- Specific cells ---"
? " Table 1, Row 3, Col 1: " + wr.getCell(wr.getTableBlockIndex(1), 3, 1)
? " Table 1, Row 3, Col 4: " + wr.getCell(wr.getTableBlockIndex(1), 3, 4)
? " Table 5, Row 4, Col 2: " + wr.getCell(tblIdx4, 4, 2)
? ""
# =============================================================================
# STEP 4 -- Modify the document
# =============================================================================
? "STEP 4: Applying modifications ..."
? ""
wr.cTitle = substr(wr.cTitle,"2024","2025")
wr.cHeaderText = substr(wr.cHeaderText,"2024","2025")
# a) Global find/replace: update year throughout
? " a) Global find/replace: 2024 -> 2025 ..."
wr.replaceText("2024", "2025")
? " Verifying title heading: " + wr.getBlock(1)[:text]
? ""
# b) Table cell edits -- update prices in the Ring Platform table (table 1)
? " b) Updating Ring Platform prices (table 1) ..."
t1 = wr.getTableBlockIndex(1)
wr.setCell(t1, 2, 4, "$1,400") # Ring Language IDE
wr.setCell(t1, 3, 4, "$9,800") # Ring Enterprise Licence
wr.setCell(t1, 4, 4, "$520") # Ring Developer Starter
wr.setCell(t1, 5, 4, "$175") # Ring Education Bundle
? " New price for Ring Enterprise: " + wr.getCell(t1, 3, 4)
? ""
# c) Update status for RingStar (table 5, row 4: BETA -> RELEASED)
? " c) Updating RingStar status: BETA -> RELEASED ..."
wr.setTableCell(5, 4, 2, "RELEASED")
wr.setTableCell(5, 4, 3, "Q1 2025")
wr.setTableCell(5, 4, 4, "GA released January 2025")
? " New status: " + wr.getCell(wr.getTableBlockIndex(5), 4, 2)
? ""
# d) Rename a heading
? " d) Updating catalogue title heading ..."
wr.setHeadingText(2, "Product Catalogue 2025 (Revised Edition)")
? " New heading: " + wr.getBlock(2)[:text]
? ""
# e) Rewrite the intro paragraph
? " e) Rewriting introduction paragraph ..."
introIdx = 0
for i = 1 to bLen
if blocks[i][:type] = "paragraph" and len(blocks[i][:text]) > 50
introIdx = i
break
ok
next
if introIdx > 0
wr.setBlockText(introIdx,
"This catalogue provides an updated overview of all Ring Technology " +
"products available in the 2025 financial year. Pricing has been " +
"revised to reflect current market conditions. Volume discounts " +
"remain available on request and have been expanded for education.")
? " Paragraph rewritten."
ok
? ""
# f) Append a new summary section
? " f) Appending 2025 update summary section ..."
# Get a writer from the reader - all reader mutations above are already in aBlocks.
# The writer receives the full modified document and we add new content to it.
w = wr.toWriter()
w.addPageBreak()
w.addHeading("5. 2025 Edition -- Change Summary", 1)
w.addParagraph(
"This section documents all changes made to the catalogue in the 2025 " +
"revised edition compared to the original 2024 publication.", NULL)
w.addTable([
["Change", "Section", "Detail"],
["Year references updated", "Throughout", "All 2024 references changed to 2025"],
["Ring Platform pricing", "Section 1.1", "Prices increased by ~15%"],
["RingStar status", "Section 3", "BETA -> RELEASED; GA confirmed Jan 2025"],
["RingStar notes", "Section 3", "Updated to reflect GA release"],
["Introduction rewritten", "Cover", "Updated to reflect 2025 pricing policy"],
["Title updated", "Cover", "Revised Edition designation added"]
], [:colWidths=[5.5, 3.0, 6.5], :headerRow=true])
w.addEmptyParagraph()
w.addParagraph(
"Document revision prepared by the Ring Documentation Team. " +
"For queries contact: docs@ringtech.example.com", NULL)
? " Section appended."
? ""
# =============================================================================
# STEP 5 -- Save the modified document
# =============================================================================
? "STEP 5: Saving modified document (demo_wordreader_modified.docx) ..."
w.save("demo_wordreader_modified.docx")
wr.cleanup()
? " Saved and temp files cleaned up."
? ""
# =============================================================================
# STEP 6 -- Re-read the saved file to verify round-trip
# =============================================================================
? "STEP 6: Re-reading modified document to verify round-trip ..."
wr2 = new WordReader("demo_wordreader_modified.docx")
? wr2.summary()
? "--- Verification checks ---"
checkTitle = wr2.getTitle()
? " Title metadata : " + checkTitle
# Find the title heading
blocks2 = wr2.getBlocks()
b2Len = len(blocks2)
titleHeadingText = ""
for i = 1 to b2Len
if blocks2[i][:type] = "heading" and blocks2[i][:level] = 2
titleHeadingText = blocks2[i][:text]
break
ok
next
? " Title heading : " + titleHeadingText
# Verify RingStar status changed
t4b2 = wr2.getTableBlockIndex(5)
? " RingStar status: " + wr2.getCell(t4b2, 4, 2)
# Verify price change
t1b2 = wr2.getTableBlockIndex(1)
? " Enterprise price: " + wr2.getCell(t1b2, 3, 4)
# Check 2025 section heading exists
foundH5 = false
for i = 1 to b2Len
b = blocks2[i]
if b[:type] = "heading" and substr(b[:text], "2025 Edition") > 0
foundH5 = true
ok
next
? " Change summary section present: " + foundH5
# Check no stray 2024 references remain in headings
stray2024 = false
for i = 1 to b2Len
b = blocks2[i]
bTxt = b[:text]
if bTxt = NULL bTxt = "" ok
if substr(bTxt, "2024") > 0 and b[:type] = "heading"
? " WARNING: 2024 still in heading " + string(i) + ": " + bTxt
stray2024 = true
ok
next
if !stray2024
? " No 2024 references in headings: true"
ok
wr2.cleanup()
? ""
? "======================================================="
? " Demo complete."
? " Files: demo_wordreader_source.docx"
? " demo_wordreader_modified.docx"
? "======================================================="