<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by StackDepth on Medium]]></title>
        <description><![CDATA[Stories by StackDepth on Medium]]></description>
        <link>https://medium.com/@stackdepth?source=rss-6a5c8573369a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5l7P1kjrAFXfTJYjczohLQ.jpeg</url>
            <title>Stories by StackDepth on Medium</title>
            <link>https://medium.com/@stackdepth?source=rss-6a5c8573369a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 00:49:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stackdepth/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Convert Word to RTF in the Browser Using JavaScript]]></title>
            <link>https://medium.com/@stackdepth/how-to-convert-word-to-rtf-in-the-browser-using-javascript-9221b78e3576?source=rss-6a5c8573369a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9221b78e3576</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[StackDepth]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 02:29:40 GMT</pubDate>
            <atom:updated>2026-11-17T02:29:40.414Z</atom:updated>
            <content:encoded><![CDATA[<p>Converting Word to RTF directly in the browser using JavaScript and WASM eliminates the need to upload sensitive documents to a backend server. This approach is ideal for offline-first applications, privacy-sensitive workflows, and scenarios where files must never leave the user’s device. RTF remains a highly compatible rich-text format supported by legacy systems, desktop editors, and many content import pipelines.</p><h3>Prerequisites and Dependencies</h3><p>Before diving into the code, ensure you have:</p><ul><li>A modern browser that supports WebAssembly.</li><li>Spire.Doc for JavaScript — a library that compiles document processing logic to WASM and runs entirely in the browser.</li><li>Font files (e.g., Arial regular and bold) and a sample DOCX file placed in your project’s static assets.</li></ul><blockquote><strong><em>Dependency note</em></strong><em>: The example uses Spire.Doc for JavaScript. The library handles DOCX parsing and RTF export in a virtual file system (VFS) without any server-side processing.</em></blockquote><h3>Step-by-Step Conversion Process</h3><p>The conversion pipeline consists of six core steps:</p><ol><li>Wait for WASM initialization and obtain the document module instance.</li><li>Fetch fonts and the source DOCX into the WASM virtual file system (VFS).</li><li>Load the DOCX document from the VFS.</li><li>Export to RTF by calling the save API with FileFormat.Rtf.</li><li>Read the binary result from the VFS and wrap it in a Blob to trigger a browser download.</li><li>Dispose of the document object to prevent memory leaks.</li></ol><h3>Complete Code Example (React)</h3><pre>function App() {<br>  const wordToRtf = async () =&gt; {<br>    const docModule = window.wasmModule?.spiredoc;<br>    if (!docModule) {<br>      alert(&#39;Spire.Doc is not ready yet&#39;);<br>      return;<br>    }<br><br>// Load fonts and source document into the WASM VFS<br>    await window.spire.FetchFileToVFS(&#39;arial.ttf&#39;, &#39;/Library/Fonts/&#39;, `${process.env.PUBLIC_URL}/font/`);<br>    await window.spire.FetchFileToVFS(&#39;arialbd.ttf&#39;, &#39;/Library/Fonts/&#39;, `${process.env.PUBLIC_URL}/font/`);<br>    await window.spire.FetchFileToVFS(&#39;WordToRtf.docx&#39;, &#39;&#39;, `${process.env.PUBLIC_URL}/data/`);<br>    const doc = new docModule.Document();<br>    doc.LoadFromFile(&#39;WordToRtf.docx&#39;);<br>    const outputFileName = &#39;WordToRtf.rtf&#39;;<br>    doc.SaveToFile({<br>      fileName: outputFileName,<br>      fileFormat: docModule.FileFormat.Rtf<br>    });<br>    doc.Dispose();<br>    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);<br>    const blob = new Blob([fileArray], { type: &#39;application/rtf&#39; });<br>    const url = URL.createObjectURL(blob);<br>    const a = document.createElement(&#39;a&#39;);<br>    a.href = url;<br>    a.download = outputFileName;<br>    a.click();<br>    URL.revokeObjectURL(url);<br>  };<br>  return (<br>    &lt;div style={{ textAlign: &#39;center&#39;, height: &#39;300px&#39; }}&gt;<br>      &lt;h1&gt;Word to RTF&lt;/h1&gt;<br>      &lt;button onClick={wordToRtf}&gt;Generate&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><h3>Key Implementation Details</h3><h4>1. Module Readiness Check</h4><p>WASM modules are large and take time to load. Always verify that window.wasmModule?.spiredoc exists before proceeding. In production, replace the simple alert with a loading indicator to improve user experience.</p><h4>2. Virtual File System (VFS) and Font Loading</h4><p>The WASM runtime uses a virtual file system because browsers do not expose a native file system to WebAssembly. FetchFileToVFS copies static assets (fonts and documents) into this VFS. Missing fonts cause layout corruption—preload every font used in your documents. The three arguments are: (1) file name, (2) target VFS path, and (3) base URL for static assets.</p><h4>3. Document Loading and RTF Export</h4><pre>const doc = new docModule.Document();<br>doc.LoadFromFile(&#39;WordToRtf.docx&#39;);<br>doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Rtf });<br>doc.Dispose();</pre><p>The FileFormat.Rtf enum controls the output format. Other formats (PDF, HTML) can be produced by changing the enum. Always call Dispose() —WASM objects are not garbage-collected automatically, and unreleased document instances will exhaust browser memory in repeated conversions.</p><h4>4. Reading the Result and Triggering Download</h4><p>After conversion, the RTF file remains inside the WASM VFS. Use FS.readFile to obtain the binary array, create a Blob with the MIME type application/rtf, and generate a temporary object URL for download. Finally, call URL.revokeObjectURL to release the memory reference.</p><h3>Deployment and Resource Preparation</h3><p>Place the required assets in your project’s static directory:</p><pre>public/<br>├── font/<br>│   ├── arial.ttf<br>│   └── arialbd.ttf<br>└── data/<br>    └── WordToRtf.docx</pre><p>For user-uploaded files, write the uploaded File object&#39;s bytes directly into the VFS instead of using FetchFileToVFS. This adapts the same pattern to dynamic Word to RTF conversion workflows.</p><h3>Limitations and Optimization Tips</h3><ul><li><strong>Large WASM bundle</strong>: Load the module on demand and split chunks to avoid slowing down the first screen.</li><li><strong>Font dependency</strong>: Preload all fonts used by your documents into the VFS; otherwise, styles will be lost.</li><li><strong>Large DOCX files (tens of MB)</strong>: Browser memory and CPU limits make frontend conversion impractical — use a backend service for such cases.</li><li><strong>Browser compatibility</strong>: WebAssembly is supported by all modern browsers but not by legacy browsers.</li><li><strong>Error handling</strong>: Wrap conversions in try/catch and handle missing files, corrupted formats, and conversion failures gracefully.</li></ul><h3>Summary</h3><p>With a WASM document library, you can perform Word to RTF conversion entirely in the browser — no backend, no file uploads. The core workflow is: initialize the WASM module, load fonts and the DOCX into a virtual file system, export using the RTF format enum, read the binary result from the VFS, and trigger a download. This pattern can be adapted to other document format conversions by changing the loading logic and output format enum.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9221b78e3576" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set Word Document Editing Restrictions with Python]]></title>
            <link>https://medium.com/@stackdepth/set-word-document-editing-restrictions-with-python-6a6b16e9089c?source=rss-6a5c8573369a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a6b16e9089c</guid>
            <category><![CDATA[ms-word]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[StackDepth]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 06:57:39 GMT</pubDate>
            <atom:updated>2026-11-09T06:57:39.365Z</atom:updated>
            <content:encoded><![CDATA[<p>If you need to protect Word documents with Python, setting Word document editing restrictions is a practical way to prevent unwanted changes while still allowing limited collaboration. With Python, you can make a DOCX file read-only, allow only comments, allow only form fields, track revisions, or remove protection entirely.</p><p>This guide shows how to use Free Spire.Doc for Python to apply editing restrictions to Word documents, protect specific editable areas, and batch process multiple DOCX files.</p><blockquote><em>Note: The examples use Free Spire.Doc for Python. It provides basic document reading/writing and protection APIs, but it has a page limit. Evaluate whether it fits your project before using it in production.</em></blockquote><h3>Common Use Cases for Word Editing Restrictions</h3><p>In many business scenarios, you do not want recipients to freely modify the main content of a Word document, but you may still need to allow limited input:</p><ul><li><strong>Contract drafts</strong>: Allow users to fill in only designated fields.</li><li><strong>Review documents</strong>: Allow reviewers to add comments without changing the original text.</li><li><strong>Generated reports</strong>: Prevent downstream users from accidentally modifying fixed template content.</li><li><strong>Batch document delivery</strong>: Apply a consistent protection policy to many files without manually opening each one in Word.</li></ul><p>Manually opening each document, setting protection, and entering a password is slow when the document volume is large. Python can load documents in batches, configure protection rules, and save the protected files, making it suitable for automated export pipelines.</p><h3>Word Editing Restriction Types in Python</h3><p>Word editing restrictions usually fall into the following categories:</p><ul><li>AllowOnlyReading: The document is read-only and cannot be modified.</li><li>AllowOnlyComments: Users can insert comments but cannot edit the main content.</li><li>AllowOnlyFormFields: Users can only operate form fields.</li><li>AllowOnlyRevisions: All changes are retained as tracked revisions.</li><li>NoProtection: Removes document protection.</li></ul><p>You can also set a protection password. The password restricts editing only; it is not file encryption and is separate from saving an encrypted Word document.</p><h3>Install Free Spire.Doc for Python</h3><p>Install the dependency with pip:</p><pre>pip install spire.doc.free</pre><h3>How to Protect a Word Document with Python</h3><p>The following example wraps common operations: applying protection, removing protection, and saving the result.</p><pre>from spire.doc import Document, ProtectionType<br><br>def set_word_protection(<br>    input_path: str,<br>    output_path: str,<br>    protection_type: ProtectionType,<br>    password: str = &quot;&quot;<br>):<br>    &quot;&quot;&quot;<br>    Add editing restrictions to a Word document<br>    :param input_path: Path to the source document<br>    :param output_path: Output path after protection<br>    :param protection_type: Protection type<br>    :param password: Protection password; leave empty for no password<br>    &quot;&quot;&quot;<br>    doc = Document()<br>    doc.LoadFromFile(input_path)<br>    # Set document protection<br>    doc.Protect(protection_type, password)<br>    # Save<br>    doc.SaveToFile(output_path)<br>    doc.Close()<br><br>def remove_word_protection(input_path: str, output_path: str, password: str = &quot;&quot;):<br>    &quot;&quot;&quot;Remove editing protection from the document; if a password is set, the correct password must be provided&quot;&quot;&quot;<br>    doc = Document()<br>    doc.LoadFromFile(input_path)<br>    doc.Unprotect(password)<br>    doc.SaveToFile(output_path)<br>    doc.Close()<br><br>if __name__ == &quot;__main__&quot;:<br>    # Scenario 1: Set to [Allow Only Comments] with a protection password<br>    set_word_protection(<br>        input_path=&quot;template.docx&quot;,<br>        output_path=&quot;protected_comments.docx&quot;,<br>        protection_type=ProtectionType.AllowOnlyComments,<br>        password=&quot;Demo@2026&quot;<br>    )<br>    # Scenario 2: Set to [Read Only] without password protection<br>    # Users can still manually remove this restriction<br>    set_word_protection(<br>        input_path=&quot;template.docx&quot;,<br>        output_path=&quot;protected_readonly.docx&quot;,<br>        protection_type=ProtectionType.AllowOnlyReading<br>    )<br>    # Scenario 3: Remove protection<br>    # remove_word_protection(&quot;protected_comments.docx&quot;, &quot;unprotected.docx&quot;, password=&quot;Demo@2026&quot;)</pre><h3>Advanced: Allow Specific Editable Areas in a Protected Word Document</h3><p>Many requirements are not about locking the entire document. Instead, most content should be read-only while specific paragraphs or fragments remain editable.</p><p>The library provides PermissionStart and PermissionEnd permission markers. Insert a pair of markers with the same identifier into the document. After enabling AllowOnlyReading protection, the content between the start and end tags with the same ID becomes an editable region.</p><p>Markers can be placed in a paragraph’s child object collection to wrap an entire paragraph or local content within a paragraph.</p><p><strong>Example: </strong>mark the second paragraph as editable while the rest of the document is read-only.</p><pre>from spire.doc import *<br>from spire.doc.common import *<br><br># Load document<br>doc = Document()<br>doc.LoadFromFile(&quot;Sample.docx&quot;)<br><br># Get the first section<br>section = doc.Sections.get_Item(0)<br><br># Create a pair of permission markers using the same identifier, exception1<br>start_tag = PermissionStart(doc, &quot;exception1&quot;)<br>end_tag = PermissionEnd(doc, &quot;exception1&quot;)<br><br># Get the target paragraph (index starts from 0; here the second paragraph is selected)<br>target_paragraph = section.Paragraphs.get_Item(1)<br><br># Insert the start marker at the beginning of the paragraph and the end marker at the end<br>target_paragraph.ChildObjects.Insert(0, start_tag)<br>target_paragraph.ChildObjects.Add(end_tag)<br><br># Enable read-only protection for the whole document<br>doc.Protect(ProtectionType.AllowOnlyReading, &quot;password&quot;)<br><br># Save the result<br>doc.SaveToFile(&quot;output/RestrictionException.docx&quot;)<br>doc.Close()</pre><h3>Common Issues and Best Practices</h3><h4>1. A protection password is not strong encryption</h4><p>A Word editing protection password is an Office protection lock. Its security strength is much lower than a file-open password, and mature tools can remove it. For highly sensitive documents, do not rely solely on this mechanism. Use permission systems, watermarks, auditing, PDF conversion, and other controls as needed.</p><h4>2. Check DOCX compatibility first</h4><p>The protection behavior of .doc and .docx is not completely consistent. Prefer .docx for modern automation workflows. Some older versions of Word or WPS may display different prompts when opening protected documents.</p><h4>3. Prepare fonts on Linux servers</h4><p>When Chinese fonts are missing in a Linux environment, documents may display garbled text when opened. Preinstall the required fonts or use containers to fix the font environment.</p><h4>4. Test protection with tracked changes</h4><p>If a document already has Track Changes enabled and protection is added on top, some Office versions may change the interaction logic. Test the workflow before deploying it to production.</p><h3>Conclusion</h3><p>With a few lines of Python, you can automate Word document editing restrictions such as read-only protection, comments-only mode, form-field-only editing, and revision tracking. This approach is well suited to template export, batch document delivery, and automated contract workflows.</p><p>When implementing document protection, distinguish between editing protection and security protection. Editing protection only constrains modification behavior. If your goal is to prevent leakage or copying, combine it with file encryption, watermarks, permission management, PDF conversion, and other controls. Do not treat Word document protection as a complete security defense line.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a6b16e9089c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Automate PowerPoint Slides in C#: Add, Delete, Copy & Hide]]></title>
            <link>https://medium.com/@stackdepth/how-to-automate-powerpoint-slides-in-c-add-delete-copy-hide-7d9198ce6c04?source=rss-6a5c8573369a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d9198ce6c04</guid>
            <category><![CDATA[powerpoint]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[slides]]></category>
            <dc:creator><![CDATA[StackDepth]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 06:01:03 GMT</pubDate>
            <atom:updated>2026-11-03T06:01:03.681Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are building dynamic reports, automating branded decks, or batch-cleaning a PPT template, you need to programmatically control the slides themselves: add them, delete them, clone them, and toggle visibility. This tutorial shows exactly how to do that in C# using Free Spire.Presentation for .NET — a managed library that works without any Microsoft Office or Interop dependency.</p><blockquote><strong><em>Free edition note:</em></strong><em> The free version enforces a 10-slide limit per document during read/write. It is suitable for small-to-medium automation tasks.</em></blockquote><h3>Quick API Overview</h3><p>Before the step-by-step walkthrough, here is the core API surface you will use for every C# PowerPoint slide operation:</p><ul><li><strong>Append blank slide</strong>: Slides.Append() — adds at the end.</li><li><strong>Insert blank slide</strong>: Slides.Insert(index) — uses a zero-based index.</li><li><strong>Copy a slide</strong>: Slides.Append(sourceSlide) or Slides.Insert(index, sourceSlide) — preserves layout and formatting.</li><li><strong>Delete by index</strong>: Slides.RemoveAt(index) — validate Count &gt; index first.</li><li><strong>Delete by referenc</strong>e: Slides.Remove(slideObject).</li><li><strong>Hide / unhide</strong>: slide.Hidden = true / false — does not alter the collection.</li></ul><p>The two core types are Presentation (the deck) and ISlide (an individual slide). Presentation implements IDisposable—always wrap it in a using statement when file I/O is involved.</p><h3>Setup: Install via NuGet</h3><pre>dotnet add package FreeSpire.Presentation</pre><p>All slide operations flow through Presentation.Slides. When you instantiate a new Presentation, the library adds one default blank slide. To start from zero, remove it first:</p><pre>using var ppt = new Presentation();<br>ppt.Slides.RemoveAt(0);</pre><h3>How to Add Slides in C#</h3><p>There are two entry points for adding blank slides:</p><pre>ppt.Slides.Append();    // blank slide at the end<br>ppt.Slides.Insert(1);   // blank slide at index 1 (second position)</pre><p>Neither overload carries over content from an existing slide. If you need content, use the copy overloads in the next section.</p><h3>How to Delete Slides in C# (and Avoid the Index-Shift Bug)</h3><p>You can delete by index or by object reference:</p><pre>ppt.Slides.RemoveAt(0);           // by index<br>ISlide target = ppt.Slides[2];<br>ppt.Slides.Remove(target);        // by reference</pre><p>Critical for batch deletion: iterate in reverse order. A forward loop calls RemoveAt, which shifts the indices of all remaining elements—causing skipped slides or ArgumentOutOfRangeException.</p><pre>for (int i = ppt.Slides.Count - 1; i &gt;= 0; i--)<br>{<br>    if (ShouldDelete(ppt.Slides[i]))<br>        ppt.Slides.RemoveAt(i);<br>}</pre><p>Always check ppt.Slides.Count &gt; index before any index-based removal.</p><h3>How to Copy Slides in C# (Same Document or Cross-Document)</h3><p>Copying is achieved by passing an existing ISlide into Append or Insert. Layout, images, and formatting are retained.</p><p>Within the same presentation:</p><pre>ISlide source = ppt.Slides[0];<br>ppt.Slides.Append(source);      // clone at the end<br>ppt.Slides.Insert(2, source);   // clone at index 2</pre><p>Across presentations: no conversion step is needed. Pass the source ISlide directly into the target collection.</p><pre>using var sourcePpt = new Presentation();<br>sourcePpt.LoadFromFile(&quot;source.pptx&quot;);<br><br>using var targetPpt = new Presentation();<br>targetPpt.LoadFromFile(&quot;target.pptx&quot;);<br>ISlide toCopy = sourcePpt.Slides[0];<br>targetPpt.Slides.Insert(0, toCopy);</pre><p>From a code-shape perspective, “copy” and “insert blank” differ only by whether the second argument is an ISlide.</p><h3>How to Hide Slides in C#</h3><p>ISlide exposes a Hidden Boolean property. It behaves exactly like PowerPoint’s “Hide Slide” feature: the slide is skipped during the slideshow but remains visible and editable in the editor. Because it does not change the Slides collection structure, no reverse iteration is required for batch hiding.</p><pre>ppt.Slides[1].Hidden = true;   // hide slide 2<br>ppt.Slides[1].Hidden = false;  // unhide</pre><h3>Summary</h3><p>This covers the four slide-level operations you will need in most C# PowerPoint automation pipelines: add, delete, copy, and hide, all without an Office installation. Use the API cheat sheet for quick reference, remember the reverse-iteration rule for deletion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d9198ce6c04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Change PDF Page Size: Resize, Scale & Set Custom Dimensions]]></title>
            <link>https://medium.com/@stackdepth/python-change-pdf-page-size-resize-scale-set-custom-dimensions-2377bf1f2360?source=rss-6a5c8573369a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2377bf1f2360</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[StackDepth]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 06:51:31 GMT</pubDate>
            <atom:updated>2026-10-30T06:51:31.132Z</atom:updated>
            <content:encoded><![CDATA[<p>In real-world document workflows, a PDF’s page size often determines whether it can be printed, archived, or embedded into another system. A report designed for A3 may need to be reduced to A4 for distribution, or scanned documents may need to be standardized to a custom dimension. Manually adjusting pages one by one is time-consuming and error-prone, making batch processing with a Python script the more reliable choice.</p><p>Free Spire.PDF for Python is a lightweight, practical tool for this job. It has a small footprint and a straightforward API, making it well-suited for page-level restructuring. This guide walks through several common approaches to modifying PDF page size with Python, from the underlying logic to working code.</p><h3>Prerequisites</h3><p>Install the library via pip</p><pre>pip install spire.pdf.free</pre><blockquote><strong><em>Note:</em></strong><em> The free version has a page limit (usually 10 pages per document), making it suitable for small-scale processing or proof-of-concept validation. For larger documents, consider the commercial edition.</em></blockquote><h3>Core Concept: Why You Cannot “Directly Change” the Page Size</h3><p>Although the PDF page size (MediaBox) is technically an editable property, changing it directly causes text and images originally laid out for the old size to become misaligned or clipped. A more reliable approach is to rebuild the document:</p><ol><li>Load the original document and create a page template for each page, capturing all content as a snapshot.</li><li>Create a new document with blank pages at the target size.</li><li>Draw the template onto the new page, adapting the content via drawing coordinates and scaling layout.</li><li>Save the new document and release resources.</li></ol><p>Free Spire.PDF’s PdfPageBase.CreateTemplate() and PdfTemplate.Draw() are designed precisely for this workflow. Whether the target size is larger, smaller, or has a different aspect ratio, the same logic applies.</p><h3>Scenario 1: Change to a Standard Paper Size (A3, B4, Letter, etc.)</h3><p>Free Spire.PDF includes built-in enums for common standard paper sizes — PdfPageSize.A3(), PdfPageSize.B4(), PdfPageSize.Letter(), and others including A0, A1, A2, A4, B0–B3, and Legal. The following code converts every page of a PDF to B4:</p><pre>from spire.pdf.common import *<br>from spire.pdf import *<br><br>input_file = &quot;source.pdf&quot;<br>output_file = &quot;resized_b4.pdf&quot;<br>original_pdf = PdfDocument()<br>original_pdf.LoadFromFile(input_file)<br>new_pdf = PdfDocument()<br>for i in range(original_pdf.Pages.Count):<br>    page = original_pdf.Pages.get_Item(i)<br>    # Create a new B4-sized page with zero margins to avoid extra whitespace<br>    new_page = new_pdf.Pages.Add(PdfPageSize.B4(), PdfMargins(0.0))<br>    # KEY: Set the text layout to OnePage to scale the original content as a whole<br>    layout = PdfTextLayout()<br>    layout.Layout = PdfLayoutType.OnePage<br>    template = page.CreateTemplate()<br>    template.Draw(new_page, PointF.Empty(), layout)<br>new_pdf.SaveToFile(output_file)<br>new_pdf.Close()<br>original_pdf.Close()</pre><p>The critical setting is PdfLayoutType.OnePage. Without it, content is drawn at its original scale, and anything exceeding the new page size is clipped—not scaled. With it, the template scales as a whole to fit the available area of the new page, ensuring all content remains visible.</p><h3>Scenario 2: Custom Dimensions (Millimeters, Inches, or Any Unit)</h3><p>In practice, the target size is rarely a standard paper size. A print product might require 200 mm × 280 mm, or a system might mandate 6 × 9 inches. Free Spire.PDF’s base unit is the point (1 point = 1/72 inch). Use PdfUnitConvertor to convert physical units to points, then create a SizeF:</p><pre>from spire.pdf.common import *<br>from spire.pdf import *<br><br>input_file = &quot;source.pdf&quot;<br>output_file = &quot;custom_size.pdf&quot;<br># Target size: 200 mm × 280 mm<br>converter = PdfUnitConvertor()<br>width_pt = converter.ConvertUnits(200, PdfGraphicsUnit.Millimeter, PdfGraphicsUnit.Point)<br>height_pt = converter.ConvertUnits(280, PdfGraphicsUnit.Millimeter, PdfGraphicsUnit.Point)<br>original_pdf = PdfDocument()<br>original_pdf.LoadFromFile(input_file)<br>new_pdf = PdfDocument()<br>for i in range(original_pdf.Pages.Count):<br>    page = original_pdf.Pages.get_Item(i)<br>    new_page = new_pdf.Pages.Add(SizeF(width_pt, height_pt), PdfMargins(0.0))<br>    layout = PdfTextLayout()<br>    layout.Layout = PdfLayoutType.OnePage<br>    template = page.CreateTemplate()<br>    template.Draw(new_page, PointF.Empty(), layout)<br>new_pdf.SaveToFile(output_file)<br>new_pdf.Close()<br>original_pdf.Close()</pre><p>ConvertUnits takes three arguments: the value, the source unit, and the target unit. Supported units include Millimeter, Inch, Pixel, and Point. If you are unsure of the original page size, read it first for reference:</p><pre>page = original_pdf.Pages[0]<br>print(f&quot;Original page size: {page.Size.Width} × {page.Size.Height} points&quot;)</pre><p>The PdfPageBase.Size.Width and PdfPageBase.Size.Height properties return the dimensions in points.</p><h3>Scenario 3: Proportional Scaling (Enlarge or Shrink)</h3><p>Sometimes the goal is not a fixed physical size, but “scale up by 1.2×” or “shrink to 80%.” This requires only multiplying the original dimensions by a factor, making the logic simpler than the previous scenarios:</p><pre>from spire.pdf.common import *<br>from spire.pdf import *<br><br>input_file = &quot;source.pdf&quot;<br>output_file = &quot;scaled_120.pdf&quot;<br>scale = 1.2<br>original_pdf = PdfDocument()<br>original_pdf.LoadFromFile(input_file)<br>new_pdf = PdfDocument()<br>for i in range(original_pdf.Pages.Count):<br>    page = original_pdf.Pages.get_Item(i)<br>    new_width = float(page.Size.Width * scale)<br>    new_height = float(page.Size.Height * scale)<br>    new_page = new_pdf.Pages.Add(SizeF(new_width, new_height), PdfMargins(0.0))<br>    layout = PdfTextLayout()<br>    layout.Layout = PdfLayoutType.OnePage<br>    template = page.CreateTemplate()<br>    template.Draw(new_page, PointF.Empty(), layout)<br>new_pdf.SaveToFile(output_file)<br>new_pdf.Close()<br>original_pdf.Close()</pre><p>When scaling proportionally, the aspect ratio of every page remains unchanged, preventing distortion from stretching. PdfLayoutType.OnePage serves as a safeguard here: even if a page&#39;s original dimensions differ slightly from the others, the content will still fit fully into the new page.</p><h3>Summary</h3><p>Adjusting PDF page size by redrawing through page templates is a stable, reliable method for automating document page normalization. The core workflow consists of four steps: read the original page → create a template → open a new page → draw the template onto it. In production, you can adjust the scaling logic, margins, and alignment to meet your specific business requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2377bf1f2360" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python JSON to Word: How to Convert JSON Data into DOCX Documents]]></title>
            <link>https://medium.com/@stackdepth/python-json-to-word-how-to-convert-json-data-into-docx-documents-8e8071f8a191?source=rss-6a5c8573369a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e8071f8a191</guid>
            <category><![CDATA[docx]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[StackDepth]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 03:55:27 GMT</pubDate>
            <atom:updated>2026-10-23T03:55:27.908Z</atom:updated>
            <content:encoded><![CDATA[<p>Python JSON to Word conversion is not a file-format switch. JSON is a machine-readable data structure; a Word document is a human-readable artifact. The real work is structural mapping: deciding whether each JSON layer should become a paragraph, a table, a heading, or an image. This guide shows exactly how to do that mapping in Python using the free library Free Spire.Doc for Python, with runnable code for flat objects, object arrays, nested structures, and image fields.</p><p>What you will learn:</p><ul><li>How to install and set up Free Spire.Doc for Python</li><li>How to map JSON objects, arrays, and nesting to Word paragraphs, tables, and headings</li><li>How to handle missing keys in real-world API data without breaking the script</li><li>How to compare Free Spire.Doc with other Python JSON-to-Word approaches</li></ul><h3>Why Python JSON to Word Is a Mapping Problem, Not a Format Conversion</h3><p>The same JSON payload can produce very different Word documents depending on the mapping you choose. A flat object with five fields might become five paragraphs; the same data as an array of 500 records should become a table, not 2,500 paragraphs. Getting the mapping right first makes the code almost mechanical.</p><p>The core object model in Free Spire.Doc is:</p><pre>Document → Section → Paragraph → TextRange<br>                  ↘ Table → Row → Cell → Paragraph</pre><p>Document is the root, Section holds page-level settings, Paragraph is the text container, and TextRange controls character-level formatting (font, size, bold) inside a paragraph. Table cells expose the same paragraph model, so formatting knowledge transfers directly from body text to tables.</p><h3>How to Install Free Spire.Doc for Python</h3><p>Install from PyPI:</p><pre>pip install Spire.Doc.Free</pre><p>Free Spire.Doc does not require Microsoft Word on the development or target machine. Before relying on it in production, know the hard free-tier caps: a single document is limited to 500 paragraphs and 25 tables, and content beyond that is truncated during write.</p><p>For report generation, API snapshots, and small-to-medium ledgers this is usually enough; if your output regularly exceeds that scale, plan for data sharding or a commercial license.</p><h3>JSON-to-Word Mapping Reference</h3><ul><li>Flat object key-value pairs → Paragraph (Key: Value)</li><li>Array of objects → Table (keys → headers, objects → rows)</li><li>Nested object → Heading + indented paragraphs (recursive)</li><li>Image path field → Inline image</li></ul><h3>How to Convert a Flat JSON Object to Word Paragraphs</h3><p>This is the simplest mapping: one paragraph per key-value pair. It works well when the schema is fixed and the field count is small.</p><pre>import json<br>from spire.doc import Document, FileFormat, HorizontalAlignment<br>from spire.doc.common import *<br><br>json_str = &#39;{&quot;Project&quot;: &quot;Data Pipeline&quot;, &quot;Owner&quot;: &quot;Zhang Wei&quot;, &quot;Status&quot;: &quot;In Progress&quot;, &quot;Start Date&quot;: &quot;2025-03-01&quot;}&#39;<br>data = json.loads(json_str)<br>doc = Document()<br>section = doc.AddSection()<br>title = section.AddParagraph()<br>title.AppendText(&quot;Project Information&quot;).CharacterFormat.Bold = True<br>title.Format.HorizontalAlignment = HorizontalAlignment.Center<br>for key, value in data.items():<br>    para = section.AddParagraph()<br>    para.AppendText(f&quot;{key}: {value}&quot;).CharacterFormat.FontSize = 12<br>    para.Format.AfterSpacing = 6<br>doc.SaveToFile(&quot;flat_object.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>AppendText returns a TextRange, which is where character formatting such as bold, font size, and font name is applied. Paragraph-level settings—alignment and spacing—live on paragraph.Format.</p><h3>How to Convert a JSON Array to a Word Table</h3><p>An array of objects maps to table rows, with column headers derived from the records. The critical production detail: do not assume every record shares the same keys. Real API responses omit optional fields, and a single missing key should not kill the entire batch.</p><p>Scan all records first and collect the union of keys as headers:</p><pre>import json<br>from spire.doc import (<br>    Document, FileFormat, HorizontalAlignment, VerticalAlignment,<br>    TableRowHeightType, Color<br>)<br>from spire.doc.common import *<br><br>records = [<br>    {&quot;Product&quot;: &quot;Laptop&quot;, &quot;Unit Price&quot;: 6999, &quot;Stock&quot;: 45},<br>    {&quot;Product&quot;: &quot;Wireless Mouse&quot;, &quot;Unit Price&quot;: 199, &quot;Stock&quot;: 200},<br>    {&quot;Product&quot;: &quot;Mechanical Keyboard&quot;, &quot;Unit Price&quot;: 549, &quot;Stock&quot;: 120},<br>]<br># Dynamic headers: tolerate records with inconsistent keys<br>all_keys = []<br>for record in records:<br>    for key in record:<br>        if key not in all_keys:<br>            all_keys.append(key)<br>doc = Document()<br>section = doc.AddSection()<br>table = section.AddTable(True)<br>table.ResetCells(len(records) + 1, len(all_keys))<br># Header row (one extra row beyond the record count)<br>header_row = table.Rows[0]<br>header_row.IsHeader = True<br>header_row.Height = 24<br>header_row.HeightType = TableRowHeightType.Exactly<br>for col, key in enumerate(all_keys):<br>    cell = header_row.Cells[col]<br>    cell.CellFormat.BackColor = Color.get_Gray()<br>    cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle<br>    p = cell.AddParagraph()<br>    p.Format.HorizontalAlignment = HorizontalAlignment.Center<br>    tr = p.AppendText(key)<br>    tr.CharacterFormat.Bold = True<br>    tr.CharacterFormat.FontSize = 11<br># Data rows<br>for row_idx, record in enumerate(records, start=1):<br>    row = table.Rows[row_idx]<br>    row.Height = 22<br>    row.HeightType = TableRowHeightType.Exactly<br>    for col, key in enumerate(all_keys):<br>        cell = row.Cells[col]<br>        cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle<br>        p = cell.AddParagraph()<br>        p.Format.HorizontalAlignment = HorizontalAlignment.Center<br>        p.AppendText(str(record.get(key, &quot;-&quot;)))<br>doc.SaveToFile(&quot;array_table.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>Two non-negotiables: ResetCells uses len(records) + 1 because the header occupies a row; and record.get(key, &quot;—&quot;) instead of subscript access keeps the column count consistent while preventing a KeyError from aborting the whole document.</p><h3>How to Render Nested JSON as a Recursive Heading Structure</h3><p>Nested JSON encodes hierarchy and does not fit a two-dimensional table. A recursive walker with a level parameter controls indentation and font size, producing a visual outline:</p><pre>from spire.doc import Document, FileFormat<br>from spire.doc.common import *<br><br>def add_nested(section, obj, level=0):<br>    if isinstance(obj, dict):<br>        for key, value in obj.items():<br>            if isinstance(value, (dict, list)):<br>                heading = section.AddParagraph()<br>                tr = heading.AppendText(str(key))<br>                tr.CharacterFormat.Bold = True<br>                tr.CharacterFormat.FontSize = max(14 - level * 2, 10)<br>                heading.Format.SetLeftIndent(level * 18)<br>                add_nested(section, value, level + 1)<br>            else:<br>                para = section.AddParagraph()<br>                para.Format.SetLeftIndent(level * 18)<br>                tr = para.AppendText(f&quot;{key}: {value}&quot;)<br>                tr.CharacterFormat.FontSize = max(12 - level, 10)<br>    elif isinstance(obj, list):<br>        for item in obj:<br>            add_nested(section, item, level)<br>nested = {<br>    &quot;Report&quot;: {<br>        &quot;Title&quot;: &quot;Quarterly Operations Summary&quot;,<br>        &quot;Period&quot;: &quot;2025 Q2&quot;,<br>        &quot;Metrics&quot;: {&quot;Revenue&quot;: &quot;5.8 million&quot;, &quot;YoY&quot;: &quot;+12%&quot;},<br>        &quot;Notes&quot;: &quot;All regions achieved positive growth&quot;<br>    }<br>}<br>doc = Document()<br>section = doc.AddSection()<br>add_nested(section, nested)<br>doc.SaveToFile(&quot;nested_report.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>The recursion is depth-agnostic — two levels or five levels follow the same logic. Watch the 500-paragraph cap here: deeply nested or large datasets consume the free quota quickly, so estimate output size before committing to this approach in production.</p><h3>How to Insert Images from JSON Path Fields into Word</h3><p>If the JSON includes an image path such as &quot;logo&quot;: &quot;images/logo.png&quot;, insert it with AppendPicture and set display dimensions in points:</p><pre>para = section.AddParagraph()<br>pic = para.AppendPicture(&quot;images/logo.png&quot;)<br>pic.Width = 80<br>pic.Height = 50</pre><p>The same call works inside a table cell by attaching it to the paragraph returned from cell.AddParagraph().</p><h3>Conclusion</h3><p>The core of Python JSON to Word conversion is not the library API but the mapping decision: key-value pairs become paragraphs, record collections become tables, and nested relationships become recursive headings.</p><p>Once that mapping is fixed, Free Spire.Doc’s Document → Section → Paragraph / Table model applies it to DOCX directly. Start with the flat-object snippet, move to the array-to-table pattern for records, and reach for recursion only when the data actually has hierarchy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e8071f8a191" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Merge Multiple CSV Files into One Workbook with Python]]></title>
            <link>https://medium.com/@stackdepth/merge-multiple-csv-files-into-one-workbook-with-python-ddaa276036ea?source=rss-6a5c8573369a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddaa276036ea</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[csv]]></category>
            <dc:creator><![CDATA[StackDepth]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 07:27:19 GMT</pubDate>
            <atom:updated>2026-10-15T07:27:19.190Z</atom:updated>
            <content:encoded><![CDATA[<p>If you need to batch import CSV files to Excel using Python, this tutorial will show you how to merge multiple CSV files into one Excel workbook — with each CSV stored on its own worksheet. This is a common data processing task when you want to consolidate scattered CSV reports into a single .xlsx file for easier viewing and distribution.</p><p>Python’s built-in csv module can read CSV data, but writing each file to a separate Excel sheet requires extra logic. With Free Spire.XLS for Python, you can load a CSV directly as a workbook object and copy its worksheet into a target workbook with just a few lines of code.</p><h3>Key Takeaways</h3><ul><li>Use Workbook.LoadFromFile() to load a CSV file.</li><li>Use Worksheets.AddCopy() to copy CSV data into a new Excel worksheet.</li><li>Save the final workbook as .xlsx to avoid free-version worksheet limits.</li><li>Free Spire.XLS for Python works without Microsoft Excel installed.</li><li>The script handles comma, tab, and semicolon delimiters.</li></ul><h3>Why Merge Multiple CSV Files into One Excel Workbook?</h3><p>In everyday data processing, CSV files often arrive as separate exports — one per department, region, or time period. Combining them into a single Excel workbook with multiple sheets makes it easier to:</p><ul><li>Review all data in one place.</li><li>Share a single file instead of dozens of CSVs.</li><li>Preserve each dataset on its own worksheet.</li><li>Automate repetitive reporting tasks.</li></ul><p>Python is ideal for this kind of CSV to Excel automation, especially when you need to process files in bulk.</p><h3>Prerequisites: Install Free Spire.XLS for Python</h3><p>Install the free library via pip. It supports Python 3.6+ and runs on Windows, macOS, and Linux:</p><pre>pip install Spire.Xls.Free</pre><p>Free Spire.XLS for Python does not require Microsoft Excel, so it works on servers and in headless environments.</p><blockquote><strong>Free version limitation</strong>: The free edition limits .xls files to 5 worksheets per workbook and 200 rows per worksheet. If you save as .xlsx, this limitation is not triggered. For workbooks with many sheets or large row counts, always output .xlsx.</blockquote><h3>How to Batch Import CSV Files to Excel in Python (Step-by-Step)</h3><p>The core idea is simple:</p><ol><li>Create a target Workbook.</li><li>Loop through all CSV files in a directory.</li><li>Load each CSV file individually.</li><li>Copy its worksheet into the target workbook.</li><li>Rename the copied worksheet.</li><li>Save the target workbook as .xlsx.</li></ol><p>The AddCopy method copies both data and formatting. Use WorksheetCopyType.CopyAll to ensure the entire worksheet is preserved.</p><h4>Step 1: Load Each CSV File</h4><p>Use Workbook.LoadFromFile() to load a CSV. The data appears in the first worksheet (index 0).</p><h4>Step 2: Create a Target Excel Workbook</h4><p>Create a new Workbook() object that will hold all imported CSV sheets.</p><h4>Step 3: Copy CSV Data to a New Worksheet</h4><p>Call target_book.Worksheets.AddCopy(source_sheet, WorksheetCopyType.CopyAll) to add the CSV data as a new sheet.</p><h4>Step 4: Rename the Worksheet</h4><p>Excel worksheet names are limited to 31 characters. Use the CSV file name (without extension) and truncate if necessary.</p><h4>Step 5: Save the Merged Workbook as .xlsx</h4><p>Save with SaveToFile(output_path, FileFormat.Version2016) to produce an .xlsx file.</p><h3>Complete Python Script: Merge All CSV Files into One Excel File</h3><p>The following script merges every CSV in a directory into a single Excel workbook, with one worksheet per CSV:</p><pre>import os<br>import glob<br>from spire.xls import *<br>from spire.xls.common import *<br><br>def merge_csv_to_excel(csv_dir, output_path, delimiter=&quot;,&quot;):<br>    &quot;&quot;&quot;<br>    Merge all CSV files in a directory into one Excel file.<br>    Each CSV becomes a separate worksheet named after the file (without extension).<br>    Args:<br>        csv_dir: Directory containing CSV files<br>        output_path: Output Excel file path (recommended: .xlsx)<br>        delimiter: CSV delimiter, default comma<br>    &quot;&quot;&quot;<br>    csv_files = glob.glob(os.path.join(csv_dir, &quot;*.csv&quot;))<br>    if not csv_files:<br>        print(&quot;No CSV files found&quot;)<br>        return<br>    # Create target workbook<br>    target_book = Workbook()<br>    # Note: Workbook() creates 3 default blank sheets; they are removed later.<br>    for idx, file_path in enumerate(csv_files):<br>        file_name = os.path.splitext(os.path.basename(file_path))[0]<br>        # Load a single CSV file<br>        source_book = Workbook()<br>        source_book.LoadFromFile(file_path, delimiter, 1, 1)<br>        # Get the parsed CSV worksheet<br>        source_sheet = source_book.Worksheets[0]<br>        # Copy into target workbook<br>        target_book.Worksheets.AddCopy(source_sheet, WorksheetCopyType.CopyAll)<br>        # Rename the newly copied worksheet<br>        new_sheet = target_book.Worksheets[target_book.Worksheets.Count - 1]<br>        new_sheet.Name = file_name[:31]  # Excel sheet names max 31 characters<br>        source_book.Dispose()<br>        print(f&quot;Imported: {file_name}&quot;)<br>    # Remove default blank worksheets (Sheet1/Sheet2/Sheet3)<br>    for i in range(target_book.Worksheets.Count - 1, -1, -1):<br>        sheet = target_book.Worksheets[i]<br>        if sheet.Name in [&quot;Sheet1&quot;, &quot;Sheet2&quot;, &quot;Sheet3&quot;]:<br>            target_book.Worksheets.RemoveAt(i)<br>    # Save as .xlsx<br>    target_book.SaveToFile(output_path, FileFormat.Version2016)<br>    target_book.Dispose()<br>    print(f&quot;\nMerge completed: {output_path}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    merge_csv_to_excel(<br>        csv_dir=&quot;./csv_files&quot;,<br>        output_path=&quot;./merged_output.xlsx&quot;,<br>        delimiter=&quot;,&quot;<br>    )<br></pre><h3>Conclusion</h3><p>This Python script is ideal for lightweight automation: it collects scattered CSV files into one Excel workbook, with each file on its own sheet. Free Spire.XLS for Python makes batch CSV to Excel import simple because it runs without an Office environment and provides a clean API for loading CSV data and copying worksheets.</p><p>Whether you are consolidating reports, merging exports, or building a data pipeline, this approach helps you merge multiple CSV files into one Excel workbook quickly and reliably.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddaa276036ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React & JavaScript: Merge Excel XLSX Files Without a Server]]></title>
            <link>https://medium.com/@stackdepth/react-javascript-merge-excel-xlsx-files-without-a-server-f43136ac6549?source=rss-6a5c8573369a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f43136ac6549</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[webassembly]]></category>
            <dc:creator><![CDATA[StackDepth]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 05:55:54 GMT</pubDate>
            <atom:updated>2026-08-28T05:55:54.276Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern web application development, merging Excel files is a frequent and often tedious requirement. Traditional approaches rely heavily on backend servers to process these files — increasing server costs, network bandwidth, and latency.</p><p>This article presents a robust JavaScript Excel merging solution powered by WebAssembly (WASM). By leveraging a React frontend and a WASM-based Excel engine, we perform all read/write operations directly in the browser. This purely client-side approach guarantees data privacy, eliminates server load, and delivers near-native processing speeds.</p><h3>Excel Merging with JavaScript: Technical Overview</h3><h4>Core Architecture (Virtual File System)</h4><p>Our strategy revolves around building a Virtual File System (VFS) directly inside the browser’s memory. The user-selected Excel files are written to this VFS, enabling the WASM module to access them instantly. The module reads each file sequentially, copies <em>all</em> worksheets into a single destination workbook, and exports the final merged file for download.</p><h4>Technology Stack</h4><ul><li><strong>Frontend Framework</strong>: React (functional components with Hooks for state management).</li><li><strong>Excel Processing Engine</strong>: <a href="https://www.e-iceblue.com/Introduce/xls-for-javascript.html">Spire.XLS for JavaScript</a> (or its <a href="https://www.e-iceblue.com/Introduce/free-xls-for-javascript.html">free version</a>), compiled to WebAssembly.</li><li>Virtual File System (VFS): The native FS module provided by the WASM runtime.</li><li>Font Support: TrueType fonts (like Arial) are loaded into the VFS to ensure correct rendering of Chinese and special characters.</li></ul><blockquote>💡 <a href="https://www.e-iceblue.com/Tutorials/XLS-Javascript/Getting-Started/How-to-Integrate-Spire.XLS-for-JavaScript-in-a-React-Project.html">Check out the complete installation guide for the JavaScript library in a React project.</a></blockquote><h3>Step-by-Step Implementation Guide</h3><h4>1. Loading the WASM Module (The Foundation)</h4><p>The WASM module must be loaded when the React component mounts. We use the useEffect hook to dynamically import the JavaScript &quot;glue&quot; code and instantiate the WASM binary.</p><p>Why this matters for performance: Dynamic imports (webpackIgnore: true) prevent Webpack from bundling the large WASM files, allowing them to load asynchronously from the public directory.</p><pre>useEffect(() =&gt; {<br>  let mounted = true;<br>  (async () =&gt; {<br>    try {<br>      const publicUrl = process.env.PUBLIC_URL || &#39;&#39;;<br>      const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.js`);<br>      const rawModule = spireModule.default || spireModule;<br>      const module = typeof rawModule === &#39;function&#39;<br>        ? await rawModule({ locateFile: p =&gt; p.endsWith(&#39;.wasm&#39;) ? `${publicUrl}/${p}` : p })<br>        : rawModule;<br>      if (mounted) {<br>        window.wasmModule = module;<br>        setWasmModule(module);<br>      }<br>    } catch (err) {<br>      console.error(&#39;WASM loading failed:&#39;, err);<br>    }<br>  })();<br>  return () =&gt; { mounted = false; };<br>}, []);</pre><h4>2. Managing the Virtual File System (VFS)</h4><p>Writing files to the VFS bridges the gap between the browser’s native File API and the WASM runtime.</p><h4>Loading Fonts for Rendering</h4><p>Excel documents require system fonts for accurate text rendering. We fetch Arial.ttf from a static folder and inject it into the VFS&#39;s /Library/Fonts/ directory on the first run.</p><pre>if (!fontLoadedRef.current) {<br>  await window.spire.FetchFileToVFS(<br>    &#39;Arial.ttf&#39;,<br>    &#39;/Library/Fonts/&#39;,<br>    `${process.env.PUBLIC_URL}/static/font/`<br>  );<br>  fontLoadedRef.current = true;<br>}</pre><h4>Injecting User Files</h4><p>Every selected Excel file is converted to binary and written directly to the VFS root.</p><pre>for (const file of selectedFiles) {<br>  const arrayBuffer = await file.arrayBuffer();<br>  const uint8 = new Uint8Array(arrayBuffer);<br>  window.dotnetRuntime.Module.FS.writeFile(file.name, uint8);<br>}</pre><h4>3. Core Logic: Merging Excel Files in the Browser</h4><p>This section contains the heart of the client-side Excel merging process.</p><p>The Workflow:</p><ol><li>Initialize a destination Workbook (set to Excel 2016) and clear its default sheets.</li><li>Iterate over every selected file.</li><li>Load the file into a temporary Workbook.</li><li>Copy all worksheets using XlsWorksheetsCollection.Convert(...).AddCopy with CopyAll flags.</li><li>Save the merged result back to the VFS.</li></ol><pre>// Create the target workbook<br>newbook = new mod.Workbook();<br>newbook.Version = mod.ExcelVersion.Version2016;<br>newbook.Worksheets.Clear();<br><br>tempbook = new mod.Workbook();<br>for (const file of selectedFiles) {<br>  tempbook.LoadFromFile(file.name);<br>  const count = tempbook.Worksheets.Count;<br>  for (let i = 0; i &lt; count; i++) {<br>    const sheet = tempbook.Worksheets.get(i);<br>    mod.XlsWorksheetsCollection.Convert(newbook.Worksheets).AddCopy({<br>      sheet: sheet,<br>      flags: mod.WorksheetCopyType.CopyAll,<br>    });<br>  }<br>  tempbook.Worksheets.Clear();<br>}</pre><h4>4. Exporting and Downloading the Merged File</h4><p>Once the merge is complete, we read the output binary from the VFS, construct a Blob, and trigger an automatic browser download.</p><pre>const outputFileName = &#39;Merged_Result.xlsx&#39;;<br>newbook.SaveToFile({ fileName: outputFileName, version: mod.ExcelVersion.Version2016 });<br><br>const bytes = window.dotnetRuntime.Module.FS.readFile(outputFileName);<br>const blob = new Blob([bytes], {<br>  type: &#39;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&#39;,<br>});<br>// Create a download link...</pre><h4>5. Best Practices: Memory Management with WASM</h4><p>WASM objects (like Workbook) occupy linear memory outside the JavaScript garbage collector&#39;s reach. Always call .Dispose() in a finally block to prevent memory leaks—especially when merging large files.</p><pre>finally {<br>  try { newbook?.Dispose(); } catch (_) {}<br>  try { tempbook?.Dispose(); } catch (_) {}<br>  setIsMerging(false);<br>}</pre><h3>Complete React Component Code (Merge .xls / .xlsx)</h3><p>Below is the full, production-ready React component. It includes loading states, file selection validation, and error handling for a seamless user experience.</p><pre>import React, { useState, useEffect, useRef } from &#39;react&#39;;<br><br>function App() {<br>  const [wasmModule, setWasmModule] = useState(null);<br>  const [selectedFiles, setSelectedFiles] = useState([]);<br>  const [isMerging, setIsMerging] = useState(false);<br>  const fileInputRef = useRef(null);<br>  const fontLoadedRef = useRef(false);<br><br>  useEffect(() =&gt; {<br>    let mounted = true;<br>    (async () =&gt; {<br>      try {<br>        const publicUrl = process.env.PUBLIC_URL || &#39;&#39;;<br>        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.js`);<br>        const rawModule = spireModule.default || spireModule;<br>        const module = typeof rawModule === &#39;function&#39;<br>          ? await rawModule({ locateFile: p =&gt; p.endsWith(&#39;.wasm&#39;) ? `${publicUrl}/${p}` : p })<br>          : rawModule;<br>        if (mounted) {<br>          window.wasmModule = module;<br>          setWasmModule(module);<br>        }<br>      } catch (err) {<br>        console.error(&#39;WASM loading failed:&#39;, err);<br>      }<br>    })();<br>    return () =&gt; { mounted = false; };<br>  }, []);<br><br>  const mergeUploadedExcel = async () =&gt; {<br>    const mod = window.wasmModule?.spirexls;<br>    if (!mod || selectedFiles.length === 0) {<br>      console.warn(&#39;Module not ready or no files selected&#39;);<br>      return;<br>    }<br>    if (!window.dotnetRuntime?.Module?.FS) {<br>      console.warn(&#39;WASM runtime not ready&#39;);<br>      return;<br>    }<br><br>    setIsMerging(true);<br>    let newbook = null;<br>    let tempbook = null;<br><br>    try {<br>      if (!fontLoadedRef.current) {<br>        await window.spire.FetchFileToVFS(<br>          &#39;Arial.ttf&#39;,<br>          &#39;/Library/Fonts/&#39;,<br>          `${process.env.PUBLIC_URL}/static/font/`<br>        );<br>        fontLoadedRef.current = true;<br>      }<br><br>      for (const file of selectedFiles) {<br>        const arrayBuffer = await file.arrayBuffer();<br>        const uint8 = new Uint8Array(arrayBuffer);<br>        window.dotnetRuntime.Module.FS.writeFile(file.name, uint8);<br>      }<br><br>      newbook = new mod.Workbook();<br>      newbook.Version = mod.ExcelVersion.Version2016;<br>      newbook.Worksheets.Clear();<br><br>      tempbook = new mod.Workbook();<br><br>      for (const file of selectedFiles) {<br>        tempbook.LoadFromFile(file.name);<br>        const count = tempbook.Worksheets.Count;<br>        for (let i = 0; i &lt; count; i++) {<br>          const sheet = tempbook.Worksheets.get(i);<br>          mod.XlsWorksheetsCollection.Convert(newbook.Worksheets).AddCopy({<br>            sheet: sheet,<br>            flags: mod.WorksheetCopyType.CopyAll,<br>          });<br>        }<br>        tempbook.Worksheets.Clear();<br>      }<br><br>      const outputFileName = &#39;Merged_Result.xlsx&#39;;<br>      newbook.SaveToFile({ fileName: outputFileName, version: mod.ExcelVersion.Version2013 });<br><br>      const bytes = window.dotnetRuntime.Module.FS.readFile(outputFileName);<br>      const blob = new Blob([bytes], {<br>        type: &#39;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&#39;,<br>      });<br>      const url = URL.createObjectURL(blob);<br>      const a = document.createElement(&#39;a&#39;);<br>      a.href = url;<br>      a.download = outputFileName;<br>      document.body.appendChild(a);<br>      a.click();<br>      document.body.removeChild(a);<br>      URL.revokeObjectURL(url);<br><br>    } catch (err) {<br>      console.error(&#39;Merge failed:&#39;, err);<br>    } finally {<br>      try { newbook?.Dispose(); } catch (_) {}<br>      try { tempbook?.Dispose(); } catch (_) {}<br>      setIsMerging(false);<br>    }<br>  };<br><br>  return (<br>    &lt;div style={{ textAlign: &#39;center&#39;, padding: &#39;40px 20px&#39;, maxWidth: &#39;600px&#39;, margin: &#39;0 auto&#39; }}&gt;<br>      &lt;h1&gt;📂 Merge Local Excel Files (Client-Side)&lt;/h1&gt;<br><br>      &lt;div style={{ margin: &#39;20px 0&#39; }}&gt;<br>        &lt;input<br>          ref={fileInputRef}<br>          type=&quot;file&quot;<br>          multiple<br>          accept=&quot;.xlsx,.xls&quot;<br>          onChange={(e) =&gt; {<br>            const fileList = Array.from(e.target.files);<br>            const excelFiles = fileList.filter(f =&gt;<br>              f.name.toLowerCase().endsWith(&#39;.xlsx&#39;) || f.name.toLowerCase().endsWith(&#39;.xls&#39;)<br>            );<br>            setSelectedFiles(excelFiles);<br>          }}<br>          style={{ display: &#39;none&#39; }}<br>        /&gt;<br>        &lt;button<br>          onClick={() =&gt; fileInputRef.current?.click()}<br>          style={{ padding: &#39;10px 24px&#39;, fontSize: &#39;16px&#39;, cursor: &#39;pointer&#39; }}<br>          disabled={!wasmModule}<br>        &gt;<br>          {wasmModule ? &#39;Select Excel Files&#39; : &#39;Loading WASM...&#39;}<br>        &lt;/button&gt;<br>        &lt;div style={{ marginTop: 12, fontSize: &#39;14px&#39;, color: &#39;#555&#39; }}&gt;<br>          {selectedFiles.length &gt; 0 ? (<br>            &lt;&gt;<br>              &lt;span&gt;&lt;strong&gt;{selectedFiles.length}&lt;/strong&gt; file(s) selected:&lt;/span&gt;<br>              &lt;ul style={{ listStyle: &#39;none&#39;, padding: 0, margin: &#39;8px 0&#39; }}&gt;<br>                {selectedFiles.map((f, idx) =&gt; (<br>                  &lt;li key={idx} style={{ background: &#39;#f0f0f0&#39;, margin: &#39;4px 0&#39;, padding: &#39;4px 8px&#39;, borderRadius: &#39;4px&#39; }}&gt;<br>                    {f.name} ({(f.size / 1024).toFixed(1)} KB)<br>                  &lt;/li&gt;<br>                ))}<br>              &lt;/ul&gt;<br>            &lt;/&gt;<br>          ) : (<br>            &#39;Click the button above to choose .xlsx or .xls files.&#39;<br>          )}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br><br>      &lt;button<br>        onClick={mergeUploadedExcel}<br>        disabled={!wasmModule || selectedFiles.length === 0 || isMerging}<br>        style={{<br>          padding: &#39;10px 32px&#39;,<br>          fontSize: &#39;16px&#39;,<br>          cursor: (!wasmModule || selectedFiles.length === 0 || isMerging) ? &#39;not-allowed&#39; : &#39;pointer&#39;,<br>          backgroundColor: &#39;#1976d2&#39;,<br>          color: &#39;#fff&#39;,<br>          border: &#39;none&#39;,<br>          borderRadius: &#39;4px&#39;,<br>          transition: &#39;background 0.2s&#39;,<br>        }}<br>      &gt;<br>        {isMerging ? &#39;⏳ Merging...&#39; : &#39;🚀 Start Merge &amp; Download&#39;}<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p><strong>How to run:</strong><br>Start your React dev server with npm start. After the WASM module loads:</p><ol><li>Click “Select Excel Files” (hold Ctrl/Cmd to pick multiple).</li><li>Click “Start Merge &amp; Download” — the browser will automatically download Merged_Result.xlsx.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*cEEfhR1jIWPX21ufmNrn1g.png" /></figure><h3>Advanced Extension Ideas</h3><p>Once your base JavaScript Excel merge is functional, consider these scalable upgrades:</p><ol><li><strong>Selective Merging</strong>: Allow users to choose specific worksheets (instead of all) via a checkbox UI.</li><li><strong>Single-Sheet Consolidation</strong>: Offer an option to append all data into one active sheet rather than multiple tabs.</li><li><strong>Real-Time Progress</strong>: Integrate a progress bar (using setInterval or event emitters) for large file feedback.</li><li><strong>Cloud Export</strong>: Connect the output blob to AWS S3 or Google Drive APIs for direct cloud saving.</li><li><strong>Format Conversion</strong>: Add a toggle to save the merged result as .xls (legacy) or .xlsx (modern).</li></ol><h3>Conclusion</h3><p>This article demonstrated a modern, high-performance approach to merging multiple Excel files in JavaScript using WebAssembly and React. By offloading the processing entirely to the client, this architecture enhances data security, drastically reduces infrastructure costs, and delivers a smooth user experience.</p><p>As WebAssembly continues to mature, complex document manipulation — traditionally reserved for desktop software — is now feasible in the browser. You can easily embed this complete component into your existing React projects and customize it to fit your enterprise needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f43136ac6549" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>