<?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 Andrew Wilson on Medium]]></title>
        <description><![CDATA[Stories by Andrew Wilson on Medium]]></description>
        <link>https://medium.com/@andrewwil?source=rss-b31d5d80d9b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dCSBfij-J7YkzZf0JC-XNg.jpeg</url>
            <title>Stories by Andrew Wilson on Medium</title>
            <link>https://medium.com/@andrewwil?source=rss-b31d5d80d9b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 10:56:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrewwil/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 Add and Remove Excel Slicers in C# (Tables and PivotTables)]]></title>
            <link>https://medium.com/@andrewwil/how-to-add-and-remove-excel-slicers-in-c-tables-and-pivottables-cfb2651da8db?source=rss-b31d5d80d9b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfb2651da8db</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Andrew Wilson]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 02:21:34 GMT</pubDate>
            <atom:updated>2026-11-16T02:21:34.097Z</atom:updated>
            <content:encoded><![CDATA[<p>Excel slicers are visual filtering controls for PivotTables and structured tables. Compared with traditional PivotTable filters, slicers support multi-select filtering, intuitive interaction, and linked filtering across multiple PivotTables. They are especially useful for automated reports, batch template export, and dashboard generation.</p><p>When generating or modifying Excel files with slicers on a .NET server, you typically need to handle PivotTables, cache fields, slicer object layout, and selected filter items. This article provides reproducible C# examples for common Excel slicer automation tasks.</p><h3>Quick Answer</h3><p>Use Worksheet.Slicers.Add(...) to create a slicer:</p><ul><li>For an Excel table: sheet.Slicers.Add(table, &quot;E3&quot;, 0)</li><li>For a PivotTable: sheet.Slicers.Add(pivot, &quot;G7&quot;, 0)</li></ul><p>Use RemoveAt(index) to remove one slicer, or Clear() to remove all slicers in a worksheet. Slicers require .xlsx output; legacy .xls files are not supported.</p><h3>What Is an Excel Slicer?</h3><p>A slicer is a visual filtering component in Excel. It cannot exist independently; it must be bound to one of these data sources:</p><ul><li>Excel structured table: ListObject</li><li>PivotTable: PivotTable</li></ul><p>At the OpenXML level, a slicer maintains a separate cache called a Slicer Cache. The cache is associated with the data source field, while the Slicer View controls the UI position, size, title, and selected items.</p><blockquote><strong><em>Key constraint</em></strong><em>: Legacy binary Excel files (97–2003, </em><em>.xls) do not support slicers. The output format must be Office Open XML, such as </em><em>.xlsx.</em></blockquote><h3>Prerequisites</h3><p>Install the Free Spire.XLS package via NuGet:</p><pre>Install-Package FreeSpire.XLS</pre><p>Add the required namespaces:</p><pre>using Spire.Xls;<br>using Spire.Xls.Core;</pre><h3>How to Add a Slicer to an Excel Table (ListObject) in C#</h3><p>A structured table is the most direct data carrier for an Excel slicer. The API entry point is:</p><pre>int Worksheet.Slicers.Add(IListObject table, string destCellName, int index)</pre><p>The parameters specify:</p><ul><li>table: the target ListObject table</li><li>destCellName: the cell where the slicer’s upper-left corner is placed</li><li>index: the zero-based column index used for slicer filtering</li></ul><p>The following example creates an Excel table and adds a slicer bound to its first column:</p><pre>using Spire.Xls;<br>using Spire.Xls.Core;<br><br>Workbook workbook = new Workbook();<br>Worksheet sheet = workbook.Worksheets[0];<br>// Fill headers and data<br>sheet.Range[&quot;A1&quot;].Value = &quot;Region&quot;;<br>sheet.Range[&quot;B1&quot;].Value = &quot;Product&quot;;<br>sheet.Range[&quot;C1&quot;].Value = &quot;Sales&quot;;<br>string[,] data = {<br>    { &quot;East&quot;,  &quot;Laptop&quot;,  &quot;8200&quot; },<br>    { &quot;East&quot;,  &quot;Monitor&quot;, &quot;3600&quot; },<br>    { &quot;South&quot;, &quot;Laptop&quot;,  &quot;7500&quot; }<br>};<br>for (int r = 0; r &lt; data.GetLength(0); r++)<br>    for (int c = 0; c &lt; data.GetLength(1); c++)<br>        sheet.Range[r + 2, c + 1].Value = data[r, c];<br>// Create a ListObject table<br>IListObject table = sheet.ListObjects.Create(&quot;SalesTable&quot;, sheet.Range[&quot;A1:C4&quot;]);<br>// Add a slicer at E3, bound to column 0 (Region)<br>int slicerIndex = sheet.Slicers.Add(table, &quot;E3&quot;, 0);<br>workbook.SaveToFile(&quot;SlicerOnTable.xlsx&quot;, ExcelVersion.Version2016);</pre><p>The return value of Slicers.Add is the index of the new slicer in the collection. You can reuse it later when modifying or deleting the slicer. You do not need to clear the destination cell area in advance; the library places the slicer at the specified position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*sYqUwVrDaMU_A1U3nh9SaQ.png" /></figure><h3>How to Add a Slicer to an Excel PivotTable in C#</h3><p>When the data source is a PivotTable, the slicer is bound to an IPivotTable and its fields are IPivotField objects. The method signature changes to:</p><pre>int Worksheet.Slicers.Add(IPivotTable pivot, string destCellName, int baseFieldIndex)</pre><p>The following example constructs the data source, creates a PivotCache, creates a PivotTable, configures row and value fields, and then adds a slicer:</p><pre>using Spire.Xls;<br>using Spire.Xls.Core;<br><br>public class Program<br>{<br>    static void Main(string[] args)<br>    {<br>        Workbook workbook = new Workbook();<br>        Worksheet sheet = workbook.Worksheets[0];<br>        sheet.Name = &quot;Data&quot;;<br>        // 1. Source data<br>        sheet.Range[&quot;A1&quot;].Value = &quot;Region&quot;;<br>        sheet.Range[&quot;B1&quot;].Value = &quot;Product&quot;;<br>        sheet.Range[&quot;C1&quot;].Value = &quot;Amount&quot;;<br>        string[,] rows = {<br>            { &quot;North&quot;, &quot;Product A&quot;, &quot;1200&quot; },<br>            { &quot;South&quot;, &quot;Product B&quot;, &quot;850&quot;  },<br>            { &quot;North&quot;, &quot;Product C&quot;, &quot;2100&quot; },<br>            { &quot;East&quot;,  &quot;Product A&quot;, &quot;640&quot;  },<br>            { &quot;South&quot;, &quot;Product C&quot;, &quot;930&quot;  },<br>            { &quot;East&quot;,  &quot;Product B&quot;, &quot;1100&quot; },<br>            { &quot;North&quot;, &quot;Product A&quot;, &quot;780&quot;  },<br>            { &quot;South&quot;, &quot;Product B&quot;, &quot;560&quot;  }<br>        };<br>        for (int r = 0; r &lt; rows.GetLength(0); r++)<br>            for (int c = 0; c &lt; rows.GetLength(1); c++)<br>                sheet.Range[r + 2, c + 1].Value = rows[r, c];<br>        // 2. Create PivotCache<br>        PivotCache cache = workbook.PivotCaches.Add(sheet.Range[&quot;A1:C9&quot;]);<br>        // 3. Create PivotTable<br>        PivotTable pivot = sheet.PivotTables.Add(&quot;SalesPivot&quot;, sheet.Range[&quot;E3&quot;], cache);<br>        // 4. Add row fields<br>        pivot.PivotFields[&quot;Region&quot;].Axis = AxisTypes.Row;<br>        pivot.PivotFields[&quot;Product&quot;].Axis = AxisTypes.Row;<br>        // 5. Add value field<br>        pivot.DataFields.Add(pivot.PivotFields[&quot;Amount&quot;], &quot;Sum of Amount&quot;, SubtotalTypes.Sum);<br>        pivot.BuiltInStyle = PivotBuiltInStyles.PivotStyleLight16;<br>        // 6. Add slicer<br>        int slicerIndex = sheet.Slicers.Add(pivot, &quot;G7&quot;, 0);<br>        XlsSlicer slicer = sheet.Slicers[slicerIndex];<br>        slicer.Name = &quot;RegionSlicer&quot;;<br>        slicer.Caption = &quot;Sales Region&quot;;<br>        slicer.StyleType = SlicerStyleType.SlicerStyleLight2;<br>        slicer.Width = 160;<br>        slicer.Height = 120;<br>        workbook.SaveToFile(&quot;PivotTableWithSlicer.xlsx&quot;, ExcelVersion.Version2016);<br>        workbook.Dispose();<br>    }<br>}</pre><p>The connection between the slicer and the PivotTable is written into the workbook’s slicer XML cache by the library. The generated .xlsx file can be opened in Excel and used interactively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*TsjccMj1GP0l5rnl6Nl_aA.png" /></figure><h3>How to Remove Excel Slicers in C#</h3><p>You can remove slicers at two levels of granularity.</p><p>Remove a single slicer by index:</p><pre>sheet.Slicers.RemoveAt(0)</pre><p>Remove all slicers from the current worksheet:</p><pre>sheet.Slicers.Clear();</pre><p>RemoveAt and Clear only affect the slicer objects themselves. They do not delete the table or PivotTable data to which the slicer is attached. If a slicer was connected to a PivotTable on another worksheet, that connection is removed, but the PivotTable itself remains unchanged.</p><h3>Conclusion</h3><p>Adding and removing Excel slicers in C# is straightforward with Free Spire.XLS for .NET. Use Slicers.Add with a ListObject or PivotTable, configure slicer captions and dimensions, and use RemoveAt or Clear when slicers are no longer needed. For automated reporting and template export, remember to save files as .xlsx because slicers are not supported in legacy .xls files.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfb2651da8db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Convert PowerPoint to Videos (MP4/WMV) in C#]]></title>
            <link>https://medium.com/@andrewwil/how-to-convert-powerpoint-to-videos-mp4-wmv-in-c-0a4ade066ff0?source=rss-b31d5d80d9b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a4ade066ff0</guid>
            <category><![CDATA[powerpoint]]></category>
            <category><![CDATA[videos]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Andrew Wilson]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 03:13:19 GMT</pubDate>
            <atom:updated>2026-11-05T03:13:19.862Z</atom:updated>
            <content:encoded><![CDATA[<p>In backend automation, batch-exporting PowerPoint presentations to video is a recurring requirement — for generating courseware clips, product demo videos, automated reporting assets, and more.</p><p>Two common approaches exist, but both carry trade-offs:</p><ol><li><strong>Microsoft PowerPoint COM automation</strong>: High animation fidelity, but the server must have Office installed; permission control, concurrency, and containerized deployment become difficult to manage.</li><li><strong>Frame-by-frame screenshots + FFmpeg composition</strong>: Controllable, but requires custom parsing of animations, frame-sequence management, and timeline handling — high development and maintenance overhead.</li></ol><p>This article presents a more balanced solution: Spire.Presentation for .NET handles PPT/PPTX parsing, slide rendering, and frame timing, while FFmpeg is reused underneath for video encoding. No Microsoft PowerPoint installation is required, making it suitable for server-side batch export of standard presentation videos.</p><h3>Prerequisites: Two Components You Cannot Skip</h3><p>This conversion pipeline relies on two core dependencies. Neither is optional.</p><ol><li><strong>Spire.Presentation for .NET (</strong><em>version 11.4.5 above)</em>: responsible for loading PPT/PPTX, parsing slide content, animation transitions, and generating frame sequences;</li><li><strong>FFmpeg</strong>: responsible for receiving rendered frames and encoding output MP4/WMV video files. The library itself does not bundle the FFmpeg binary package; developers need to prepare it separately and specify the path.</li></ol><h4>Project Import</h4><p>Install Spire.Presentation through the NuGet Package Manager.</p><pre>Install-Package Spire.Presentation</pre><blockquote><em>⚠️ </em><strong><em>Evaluation warning</em></strong><em>: In evaluation mode, output videos contain a red watermark and include only the first 10 slides. For full validation, </em><a href="https://www.e-iceblue.com/TemLicense.html"><em>apply for a one-month temporary license</em></a><em>.</em></blockquote><h4>FFmpeg Preparation</h4><p>On Windows 🖥️: Download the essentials build from the <a href="https://www.gyan.dev/ffmpeg/builds/">official FFmpeg download page</a>, extract it, and locate the bin folder.</p><p>Example path:</p><pre>G:\ffmpeg\bin</pre><p>In the code below, the SaveToVideoOption constructor expects the bin directory path, not the full path to ffmpeg.exe.</p><h3>Complete C# Example: PPTX to MP4/WMV</h3><p>The conversion workflow has four steps: load → specify FFmpeg path → configure options → export.</p><pre>using System;<br>using Spire.Presentation;<br><br>namespace PptToVideoDemo<br>{<br>    internal class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            // Input PPT path, output video path<br>            string inputPptPath = @&quot;F:\Report.pptx&quot;;<br>            string outputMp4Path = @&quot;F:\Output\output.mp4&quot;;<br>            // Directory containing the FFmpeg binaries<br>            string ffmpegBinFolder = @&quot;G:\ffmpeg\bin&quot;;<br>            try<br>            {<br>                using (Presentation ppt = new Presentation())<br>                {<br>                    // Load the presentation<br>                    ppt.LoadFromFile(inputPptPath);<br>                    // Configure video export settings<br>                    var videoOption = new SaveToVideoOption(ffmpegBinFolder)<br>                    {<br>                        // Default dwell time per slide (seconds)<br>                        DurationForEachSlide = 3,<br>                        // Frame rate<br>                        Fps = 24,<br>                    };<br>                    ppt.SaveToVideoOption = videoOption;<br>                    // Export to MP4; FileFormat.WMV is also supported<br>                    ppt.SaveToFile(outputMp4Path, FileFormat.MP4);<br>                    Console.WriteLine(&quot;Conversion completed: &quot; + outputMp4Path);<br>                }<br>            }<br>            catch (Exception ex)<br>            {<br>                Console.WriteLine(&quot;Conversion failed: &quot; + ex.Message);<br>            }<br>        }<br>    }<br>}</pre><h4>Key Parameters:</h4><ul><li>DurationForEachSlide: the base dwell time for a slide. If the PPT already has slide transition timing or narration timing set, the library will prioritize the document&#39;s own timing;</li><li>Fps: frame rate. 24/30fps is sufficient for regular presentation videos;</li><li>FileFormat.MP4 / FileFormat.WMV: the two supported output container formats.</li></ul><p><strong>✅ Result preview:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*O5PnHX42u2oYJwUOvD1qrA.png" /><figcaption>ppt to video</figcaption></figure><h3>Batch Conversion: Processing an Entire Directory</h3><p>For bulk workflows, wrap the single-file conversion logic in a loop. In concurrent environments, isolate FFmpeg processes carefully — multiple tasks competing for the binary and disk I/O can cause failures. Use a queue to limit concurrency.</p><pre>static void BatchConvert(string sourceDir, string outputDir, string ffmpegPath)<br>{<br>    foreach (var file in System.IO.Directory.GetFiles(sourceDir, &quot;*.pptx&quot;))<br>    {<br>        var outFile = System.IO.Path.Combine(outputDir,<br>            System.IO.Path.GetFileNameWithoutExtension(file) + &quot;.mp4&quot;);<br>        ConvertSinglePpt(file, outFile, ffmpegPath);<br>    }<br>}</pre><h3>Practical Notes</h3><p>This part is important so that you can assess risks in advance:</p><h4>1. FFmpeg Is a Hard Requirement</h4><p>In Linux and Docker environments, you must package FFmpeg for the target platform yourself. The container image must install or bundle the binary in advance — otherwise, conversion fails immediately.</p><h4>2. Animation and Multimedia Boundaries</h4><p>Simple fade in/out and basic shape animations render reliably. Complex path animations, some 3D transition effects, OLE-embedded objects, and certain embedded audio streams may not be fully reproduced. Validate with a small representative PPT before batch processing if the deck contains heavy multimedia.</p><h4>3. Time and Resource Overhead</h4><p>Conversion is not instantaneous. More slides, higher resolution, and higher frame rates all increase CPU usage and wall-clock time. The library launches an FFmpeg subprocess — monitor process reclamation on production servers.</p><h4>4. Missing Fonts</h4><p>If the server lacks fonts used in the PPT, text fallback and layout disruption can occur. Solutions: preinstall the fonts in the deployment environment, or embed fonts during preprocessing.</p><h3>Summary</h3><p>This approach is designed for backend automation of standard presentation videos — courseware, explainer clips, and automated reporting assets. It separates concerns cleanly: the library handles document parsing and rendering, while FFmpeg handles encoding. The result is a workable balance between development effort and deployment complexity, provided FFmpeg is correctly provisioned and multimedia expectations are set realistically.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a4ade066ff0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Export Python Code to Word Documents (.py to .docx)]]></title>
            <link>https://medium.com/@andrewwil/export-python-code-to-word-documents-py-to-docx-fd7a4d1cea08?source=rss-b31d5d80d9b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd7a4d1cea08</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docx]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Andrew Wilson]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 03:44:17 GMT</pubDate>
            <atom:updated>2026-10-23T03:44:17.140Z</atom:updated>
            <content:encoded><![CDATA[<p>In daily technical work, teams often need to export code to Word documents. Common use cases include writing technical proposals, delivering test reports, organizing study notes, and archiving script source code. Copying and pasting code directly into Word often causes formatting problems, lost indentation, missing code styles, and inefficient batch processing.</p><p>With Python document automation libraries, you can automate the process of writing code into Word, preserving indentation, applying code styles, and generating documents in batches. This guide shows how to export Python code to Word using the free library Free Spire.Doc for Python, with several methods for turning .py files into readable Word documents.</p><h3>Environment Setup</h3><p>Install the free version via pip:</p><pre>pip install Spire.Doc.Free</pre><p>When importing, you usually need both the core module and common types:</p><pre>from spire.doc import *<br>from spire.doc.common import *</pre><p>⚠️ <strong>Important free-version limit</strong>: each document can contain at most 500 paragraphs and 25 tables. It is therefore suitable for small-to-medium code files or code snippets, not very large source archives.</p><p>Below is the minimal Word document creation template. It is also the basic structure used by the code formatting methods in this article:</p><pre>doc = Document()<br>section = doc.AddSection()<br>paragraph = section.AddParagraph()<br>paragraph.AppendText(&quot;Hello&quot;)<br>doc.SaveToFile(&quot;output.docx&quot;, FileFormat.Docx2019)<br>doc.Dispose()</pre><h3>Method 1: Write Code as Plain Text Line by Line</h3><p>The simplest approach is to read the code file line by line, append each line to the same paragraph, and insert line breaks with BreakType.LineBreak. The key requirement is to use a <strong>monospace font</strong> such as Courier New or Consolas. Without a monospace font, indentation and alignment will break.</p><pre>with open(&quot;demo.py&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>    lines = f.read().split(&quot;\n&quot;)<br><br>doc = Document()<br>section = doc.AddSection()<br>para = section.AddParagraph()<br>for i, line in enumerate(lines):<br>    run = para.AppendText(line)<br>    run.CharacterFormat.FontName = &quot;Courier New&quot;<br>    run.CharacterFormat.FontSize = 10.5<br>    if i &lt; len(lines) - 1:<br>        para.AppendBreak(BreakType.LineBreak)</pre><p>You can improve readability further by setting a light gray paragraph background with Color.get_WhiteSmoke(), configuring multiple line spacing with LineSpacingRule.Multiple, or enabling line numbers through section.PageSetup for easier reading and printing.</p><ul><li>✅ <strong>Advantages</strong>: Simple to implement; preserves the source structure completely</li><li>❌ <strong>Disadvantages</strong>: No syntax highlighting; long code is only moderately readable</li></ul><p>If you want centralized style management, define a code style with ParagraphStyle and apply it using ApplyStyle:</p><pre>style = ParagraphStyle(doc)<br>style.Name = &quot;code&quot;<br>style.CharacterFormat.FontName = &quot;Consolas&quot;<br>style.CharacterFormat.FontSize = 10<br>doc.Styles.Add(style)<br>para.ApplyStyle(&quot;code&quot;)</pre><p>Output preview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*g7MkK4pvCRKDCLFvlxfRgw.png" /></figure><h3>Method 2: Add Syntax Highlighting with Pygments</h3><p>Plain text is reliable, but keywords, strings, and comments have no color distinction. Pygments can parse Python code into a styled intermediate format and pass it to Free Spire.Doc for rendering. There are two practical options.</p><blockquote><em>Install the dependency first: </em><em>pip install Pygments</em></blockquote><h4>Option A: Insert RTF to Keep Code Editable</h4><p>RTF is a rich text format supported natively by Word. Pygments’ RtfFormatter generates an RTF string with color and font control words. Insert it with paragraph.AppendRTF(). The output remains selectable and editable text in Word while preserving syntax highlighting.</p><pre>from spire.doc import *<br>from pygments import highlight<br>from pygments.lexers import PythonLexer<br>from pygments.formatters import RtfFormatter<br><br>code = open(&quot;demo.py&quot;, encoding=&quot;utf-8&quot;).read()<br>formatter = RtfFormatter(fontface=&quot;Consolas&quot;)<br>rtf_text = highlight(code, PythonLexer(), formatter)<br>rtf_text = rtf_text.replace(r&quot;\f0&quot;, r&quot;\f0\fs24&quot;)  # Set font size to about 12 pt<br>doc = Document()<br>section = doc.AddSection()<br>para = section.AddParagraph()<br>para.AppendRTF(rtf_text)<br>doc.SaveToFile(&quot;code_highlighted.docx&quot;, FileFormat.Docx2019)</pre><p>One detail: RtfFormatter font size control depends on modifying the RTF control word \fs. For example, \fs24 roughly corresponds to a 12-point font.</p><p>Output preview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*p7I49YhPFCuaej_9wJcz0g.png" /></figure><h3>Option B: Insert HTML for Automatic Wrapping</h3><p>If the code comes from web content, or if rendering quality matters more than editability, generate HTML with inline styles using HtmlFormatter, then insert it with paragraph.AppendHTML(). Free Spire.Doc maps HTML elements to Word formatting, and long lines wrap automatically.</p><pre>from spire.doc import *<br>from pathlib import Path<br>from pygments import highlight<br>from pygments.lexers import PythonLexer<br>from pygments.formatters import HtmlFormatter<br><br>code = Path(&quot;demo.py&quot;).read_text(encoding=&quot;utf-8&quot;)<br>html_text = highlight(code, PythonLexer(), HtmlFormatter(full=True))<br>doc = Document()<br>section = doc.AddSection()<br>section.PageSetup.Margins.All = 60<br>para = section.AddParagraph()<br>para.AppendHTML(html_text)<br>doc.SaveToFile(&quot;code_html.docx&quot;, FileFormat.Docx2019)<br>doc.Dispose()</pre><p>💡 Selection tips:</p><ul><li>If you need to edit the code later in Word, prefer <strong>RTF</strong>.</li><li>If visual presentation and automatic line wrapping matter most, prefer <strong>HTML</strong>.</li></ul><h3>Method 3: Render Code as an Image and Insert It into Word</h3><p>When format consistency matters more than editability, render syntax-highlighted code as an image and insert it into the document. Use Pygments’ ImageFormatter with paragraph.AppendPicture().</p><blockquote><em>ImageFormatter relies on Pillow for drawing. Install the dependency first: </em><em>pip install pillow</em></blockquote><pre>import textwrap<br>from pygments import highlight<br>from pygments.lexers import PythonLexer<br>from pygments.formatters import ImageFormatter<br>from spire.doc import *<br><br># 1. Read the Python source code<br>with open(&quot;demo.py&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>    code = f.read()<br># 2. Manually wrap long lines<br>def wrap_code_lines(code_text, max_width=75):<br>    wrapped_lines = []<br>    for line in code_text.splitlines():<br>        if len(line) &gt; max_width:<br>            wrapped_lines.extend(textwrap.wrap(<br>                line,<br>                width=max_width,<br>                replace_whitespace=False,<br>                drop_whitespace=False<br>            ))<br>        else:<br>            wrapped_lines.append(line)<br>    return &quot;\n&quot;.join(wrapped_lines)<br>code = wrap_code_lines(code, max_width=75)<br># 3. Generate the image<br>formatter = ImageFormatter(<br>    font_name=&quot;Consolas&quot;,<br>    font_size=18,<br>    scale=2,<br>    image_pad=10,<br>    line_pad=2,<br>    background_color=&quot;#ffffff&quot;<br>)<br>img_bytes = highlight(code, PythonLexer(), formatter)<br>with open(&quot;code.png&quot;, &quot;wb&quot;) as f:<br>    f.write(img_bytes)<br># 4. Create the Word document<br>doc = Document()<br>section = doc.AddSection()<br>section.PageSetup.Margins.All = 60<br># 5. Insert the image<br>paragraph = section.AddParagraph()<br>picture = paragraph.AppendPicture(&quot;code.png&quot;)<br># 6. Set the image width to fit the page<br>page_width = (<br>    section.PageSetup.PageSize.Width<br>    - section.PageSetup.Margins.Left<br>    - section.PageSetup.Margins.Right<br>)<br>picture.Width = page_width<br># 7. Save the Word document<br>doc.SaveToFile(&quot;code_image.docx&quot;, FileFormat.Docx2019)<br>doc.Dispose()</pre><ul><li>✅ <strong>Advantages</strong>: Independent of Word version and local fonts; visually stable and consistent</li><li>❌ Disadvantages: Code cannot be searched, copied, or edited; long code requires manual wrapping; best for finalized documents and short snippets</li></ul><p>Output preview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*I2JwiuatyOHLIgxqLE3Yww.png" /></figure><h3>📊 Comparison and Summary</h3><p>The methods differ in syntax highlighting, editability, line wrapping, and best-fit scenarios.</p><ul><li><strong>Plain text line-by-line writin</strong>g: No syntax highlighting; fully editable; manual line wrapping; best for quick archiving and low-complexity scenarios.</li><li><strong>Pygments + RTF</strong>: Syntax highlighting included; editable; manual line wrapping; best when highlighting must be preserved and code may be modified later.</li><li><strong>Pygments + HTML</strong>: Syntax highlighting included; partially editable; automatic line wrapping; best when rendering quality and wrapping are priorities.</li><li><strong>Pygments + image</strong>: Syntax highlighting included; not editable; requires soft wrapping; best for short snippets, finalized documents, and strict format consistency.</li></ul><p>🔍 When choosing a method, consider three main factors: whether the code size is close to the free version’s paragraph limit, whether the code content must be edited later, and whether long lines or Chinese characters need special handling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd7a4d1cea08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Remove Duplicate Rows in Excel Using C#]]></title>
            <link>https://medium.com/@andrewwil/how-to-remove-duplicate-rows-in-excel-using-c-00e6557746fd?source=rss-b31d5d80d9b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/00e6557746fd</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Andrew Wilson]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 06:14:01 GMT</pubDate>
            <atom:updated>2026-10-21T06:14:01.485Z</atom:updated>
            <content:encoded><![CDATA[<p>Data cleaning is a common requirement in C# development, and removing duplicate rows in Excel is one of the most frequent tasks. In the C# ecosystem, Spire.XLS for .NET is an Excel manipulation library that does not require Microsoft Office to be installed. It provides multiple ways to remove duplicate rows in Excel, from a native API to manual LINQ-based control.</p><p>This guide compares two practical approaches:</p><ol><li>Using the native RemoveDuplicates() method in Spire.XLS</li><li>Using LINQ to identify duplicates and DeleteRow() to remove them manually</li></ol><p>Before discussing the implementation, install Spire.XLS via NuGet:</p><pre>Install-Package Spire.XLS</pre><h3>Method 1: Use Native RemoveDuplicates() in C# (Recommended)</h3><p>Starting with Spire.XLS 15.5.2, the Worksheet class provides a native RemoveDuplicates() method. Its behavior aligns with Excel’s Remove Duplicates feature. It offers three overloads for common Excel deduplication scenarios.</p><h4>1. Remove Duplicate Rows from the Entire Worksheet</h4><p>This is the simplest way to remove duplicate rows in Excel using C#. It scans all used areas in the worksheet and keeps only the first occurrence of identical rows.</p><pre>using Spire.Xls;<br><br>namespace RemoveDuplicateRows<br>{<br>    internal class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            // Open the Excel file<br>            Workbook workbook = new Workbook();<br>            workbook.LoadFromFile(&quot;duplicates.xlsx&quot;);<br><br>            // Get the desired worksheet<br>            Worksheet sheet = workbook.Worksheets[0];<br><br>            // Remove duplicates<br>            sheet.RemoveDuplicates();<br><br>            // Save the modified file<br>            workbook.SaveToFile(&quot;RemoveDuplicates.xlsx&quot;, ExcelVersion.Version2016);<br>            workbook.Dispose();<br>        }<br>    }<br>}</pre><h4>2. Remove Duplicates from a Specified Excel Range</h4><p>You can limit duplicate detection to a specific range. This helps avoid including headers, notes, or formula areas by mistake.</p><pre>// Parameters: start row, start column, end row, end column (1-based)<br>sheet.RemoveDuplicates(2, 1, sheet.LastRow, sheet.LastColumn);</pre><h4>3. Remove Duplicates Based on Specific Columns and Header Settings</h4><p>This is the most practical option for real business data. For example, you may want to identify duplicates only by Order Number and Customer ID, while ignoring columns such as Update Time that naturally differ.</p><pre>// hasHeaders: true means the first row is a header and is excluded from duplicate detection<br>// columnOffsets: offsets from the starting column; 0 = column A, 1 = column B<br>sheet.RemoveDuplicates(1, 1, sheet.LastRow, sheet.LastColumn, true, new[] { 0, 1 });</pre><h4>Benefits of the Native RemoveDuplicates() Method</h4><ul><li>Handles grouping, comparison, and row shifting internally</li><li>Requires minimal C# code</li><li>Avoids manual row-index offset errors</li><li>Matches Excel’s built-in deduplication behavior</li></ul><blockquote><em>Note: The native </em><em>RemoveDuplicates() API requires Spire.XLS 15.5.2 or later. If your project uses an older version or the free edition, use Method 2 below.</em></blockquote><h3>Method 2: Use LINQ and DeleteRow() to Remove Duplicate Rows in C#</h3><p>If you cannot use the native RemoveDuplicates() method, or if you need custom logic for which duplicate row to keep, the manual LINQ approach is a reliable alternative.</p><p>The process has three steps:</p><ol><li>Group rows and identify duplicate row numbers</li><li>Build a list of rows to delete</li><li>Delete rows from bottom to top, or dynamically correct row indexes</li></ol><h4>Choose the Right Grouping Key</h4><p>For Excel deduplication in C#, use the cell’s DisplayedText instead of Value or Text. DisplayedText returns the text users see in Excel and considers number formats, date formats, and formula results. Using Value may miss duplicates when values look the same but are stored differently.</p><pre>using Spire.Xls;<br>using System.Linq;<br><br>using var workbook = new Workbook();<br>workbook.LoadFromFile(&quot;input.xlsx&quot;);<br>Worksheet sheet = workbook.Worksheets[0];<br><br>// Assume data starts at row 2; row 1 is the header.<br>// This example detects duplicates based only on column A.<br>int startRow = 2;<br>var range = sheet.Range[startRow, 1, sheet.LastRow, sheet.LastColumn];<br>var duplicateRowIndexes = range.Rows<br>    .GroupBy(row =&gt; row.Columns[0].DisplayedText)<br>    .Where(g =&gt; g.Count() &gt; 1)<br>    .SelectMany(g =&gt; g.Skip(1))       // Keep the first row in each group<br>    .Select(row =&gt; row.Columns[0].Row)<br>    .OrderBy(r =&gt; r)<br>    .ToList();</pre><h4>Handle Row Index Shifts When Deleting Duplicate Rows</h4><p>Excel row numbers change after each deletion. For example, after deleting row 3, the original row 4 becomes the new row 3. If you call DeleteRow() using the original row numbers in ascending order, later deletions will target the wrong rows.</p><p>A common solution is to correct the index using the number of deletions already performed:</p><pre>for (int i = 0; i &lt; duplicateRowIndexes.Count; i++)<br>{<br>    sheet.DeleteRow(duplicateRowIndexes[i] - i);<br>}</pre><p>Because duplicateRowIndexes is sorted in ascending order, each deleted row shifts subsequent rows up by one. Subtracting i gives the correct current row index.</p><p>Alternatively, you can delete rows from bottom to top. This is logically equivalent and avoids index correction.</p><h3>Best Practices for Excel Deduplication in C#</h3><h4>Handle Headers Explicitly</h4><p>Both methods require careful header handling. With the native API, use the hasHeaders parameter. With the manual LINQ approach, start from row 2 so the header is excluded from grouping and deletion.</p><h4>Dispose Workbook Resources</h4><p>Workbook implements IDisposable. When processing large Excel files, use a using declaration or explicitly call Dispose(). Otherwise, file handles and memory may not be released promptly, which can cause issues in long-running server-side applications.</p><h4>Use DisplayedText for Manual Comparisons</h4><p>When using LINQ-based Excel deduplication, DisplayedText is usually safer than Value because it reflects formatted values as users see them in Excel.</p><h3>Conclusion</h3><p>To remove duplicate rows in Excel using C#, Spire.XLS for .NET provides two practical approaches. The native RemoveDuplicates() method is the simplest and most reliable choice for standard Excel deduplication because it handles grouping and row shifting internally. The LINQ + DeleteRow() approach offers more control and works with older library versions, but requires careful handling of row-index offsets.</p><p>Choose the native API for simplicity and Excel-aligned behavior. Choose the manual LINQ approach when you need custom deduplication rules or version compatibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00e6557746fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# HTML to PDF: Generate PDFs from HTML Templates]]></title>
            <link>https://medium.com/@andrewwil/c-html-to-pdf-generate-pdfs-from-html-templates-0836744fdd46?source=rss-b31d5d80d9b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0836744fdd46</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Andrew Wilson]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 09:20:19 GMT</pubDate>
            <atom:updated>2026-10-16T09:20:19.099Z</atom:updated>
            <content:encoded><![CDATA[<p>In enterprise applications, generating PDF reports, invoices, certificates, and other documents is a common requirement. The traditional approach is to draw PDF content line by line in code — creating pages, calculating coordinates, and drawing text and tables. This has low development efficiency and makes style adjustments difficult. Once the design changes, a large amount of code must be modified.</p><p>The HTML template approach solves this problem. The core idea is simple:</p><ol><li>Design the document appearance with HTML + CSS.</li><li>At runtime, fill dynamic data into template placeholders.</li><li>Convert the rendered HTML into PDF.</li></ol><p>This C# HTML to PDF workflow offers several key advantages:</p><ul><li><strong>Flexible design</strong>: HTML + CSS easily implements complex layouts and refined styles without writing complex PDF drawing code.</li><li><strong>Template reuse</strong>: The same template can be used in multiple scenarios, requiring only data replacement.</li><li><strong>Low maintenance cost</strong>: Style adjustments only require changing the HTML template, not the C# business code.</li><li><strong>Front-end/back-end collaboration</strong>: HTML templates can be created by front-end developers, while the back end only handles data filling and conversion.</li></ul><p>This article uses <a href="https://www.e-iceblue.com/Introduce/pdf-for-net-introduce.html"><strong>Spire.PDF for .NET</strong></a> as the PDF generation library. It provides multiple ways to convert HTML to PDF: fast conversion through the Qt plugin, or high-fidelity output using ChromeHtmlConverter — ideal for enterprise document generation.</p><h3>Install Spire.PDF via NuGet</h3><p>Install Spire.PDF through NuGet:</p><pre>Install-Package Spire.PDF</pre><p>Or use the .NET CLI:</p><pre>dotnet add package Spire.PDF</pre><p>This article uses Qt WebEngine as an example. You need to <a href="https://www.e-iceblue.cn/conversion/convert-html-into-pdf.html">download the QT plugin package for your operating system from the official site and extract it</a>, and ensure that the plugin directory contains HTMLConverter.dll and its dependency files.</p><p>⚠️ It is recommended to set the project’s target platform to x86 or x64, consistent with the plugin version.</p><h3>Design an HTML Template for PDF Invoices and Reports</h3><p>Template design principle: fix the unchanging parts (layout, styles, brand elements) with HTML + CSS, and mark the changing parts with placeholders in the {{PLACEHOLDER}} format.</p><p>Below is an example of an invoice HTML template for PDF generation:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;style&gt;<br>        body { font-family: &quot;Microsoft YaHei&quot;, &quot;SimSun&quot;, Arial, sans-serif; padding: 40px; color: #333; }<br>        .header { display: flex; justify-content: space-between; margin-bottom: 30px; }<br>        .header h1 { color: #2c3e50; margin: 0; }<br>        .meta { text-align: right; font-size: 13px; color: #666; }<br>        .biller { margin-bottom: 20px; }<br>        .biller strong { display: block; margin-bottom: 5px; }<br>        table { width: 100%; border-collapse: collapse; margin-top: 20px; }<br>        th { background: #2c3e50; color: #fff; padding: 10px; text-align: left; }<br>        td { padding: 10px; border-bottom: 1px solid #e0e0e0; }<br>        .summary { margin-top: 20px; text-align: right; }<br>        .summary .total { font-size: 18px; font-weight: bold; color: #e74c3c; }<br>        .footer { margin-top: 40px; font-size: 12px; color: #999; border-top: 1px solid #eee; padding-top: 15px; }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;header&quot;&gt;<br>        &lt;h1&gt;INVOICE&lt;/h1&gt;<br>        &lt;div class=&quot;meta&quot;&gt;<br>            &lt;p&gt;Invoice No: {{INVOICE_NUMBER}}&lt;/p&gt;<br>            &lt;p&gt;Date: {{INVOICE_DATE}}&lt;/p&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;biller&quot;&gt;<br>        &lt;strong&gt;{{BILLER_NAME}}&lt;/strong&gt;<br>        &lt;p&gt;{{BILLER_ADDRESS}}&lt;/p&gt;<br>        &lt;p&gt;{{BILLER_EMAIL}}&lt;/p&gt;<br>    &lt;/div&gt;<br><br>    &lt;table&gt;<br>        &lt;thead&gt;<br>            &lt;tr&gt;<br>                &lt;th&gt;Description&lt;/th&gt;<br>                &lt;th&gt;Quantity&lt;/th&gt;<br>                &lt;th&gt;Unit Price&lt;/th&gt;<br>                &lt;th&gt;Total&lt;/th&gt;<br>            &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>            {{ITEMS_ROWS}}<br>        &lt;/tbody&gt;<br>    &lt;/table&gt;<br><br>    &lt;div class=&quot;summary&quot;&gt;<br>        &lt;p&gt;Subtotal: {{SUBTOTAL}}&lt;/p&gt;<br>        &lt;p&gt;Tax ({{TAX_RATE}}%): {{TAX}}&lt;/p&gt;<br>        &lt;p class=&quot;total&quot;&gt;Total: {{TOTAL}}&lt;/p&gt;<br>    &lt;/div&gt;<br><br>    &lt;div class=&quot;footer&quot;&gt;<br>        &lt;p&gt;Thank you for your business.&lt;/p&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Here {{ITEMS_ROWS}} is a special placeholder used to generate the table&#39;s loop rows. Other placeholders correspond to simple value replacements.</p><p>🖼️ Template preview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*Qivb0hGWFRYq-_K9THQQFA.png" /></figure><h3>C# Code: Fill HTML Template and Convert to PDF</h3><p>The following complete console program covers template reading, placeholder replacement, table row generation, and calling Spire.PDF to convert to PDF.</p><h4>1️⃣ Namespace References</h4><pre>using System;<br>using System.Collections.Generic;<br>using System.Drawing;<br>using System.IO;<br>using System.Text;<br>using Spire.Additions.Qt;          // Namespace containing HtmlConverter<br>using Spire.Pdf.Graphics;           // Namespace containing PdfMargins</pre><blockquote><em>📌 The </em><em>HtmlConverter class is located in the </em><em>Spire.Additions.Qt namespace, and the assembly is Spire.Pdf.dll. </em><em>PdfMargins is under </em><em>Spire.Pdf.Graphics.</em></blockquote><h4>2️⃣ Complete C# Example Code</h4><pre>namespace HtmlToPdfDemo<br>{<br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            // ========== 1. Read the HTML template ==========<br>            string templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &quot;template.html&quot;);<br>            if (!File.Exists(templatePath))<br>            {<br>                Console.WriteLine($&quot;Template file not found: {templatePath}&quot;);<br>                return;<br>            }<br>            string html = File.ReadAllText(templatePath, Encoding.UTF8);<br><br>            // ========== 2. Simple placeholder data ==========<br>            var data = new Dictionary&lt;string, string&gt;<br>            {<br>                { &quot;INVOICE_NUMBER&quot;, &quot;INV-2025-001&quot; },<br>                { &quot;INVOICE_DATE&quot;,   DateTime.Now.ToString(&quot;MM/dd/yyyy&quot;) },<br>                { &quot;BILLER_NAME&quot;,    &quot;Acme Corporation&quot; },<br>                { &quot;BILLER_ADDRESS&quot;, &quot;1234 Market Street, San Francisco, CA 94103&quot; },<br>                { &quot;BILLER_EMAIL&quot;,   &quot;billing@acmecorp.com&quot; },<br>                { &quot;SUBTOTAL&quot;,       &quot;$10,000.00&quot; },<br>                { &quot;TAX_RATE&quot;,       &quot;6&quot; },<br>                { &quot;TAX&quot;,            &quot;$600.00&quot; },<br>                { &quot;TOTAL&quot;,          &quot;$10,600.00&quot; }<br>            };<br><br>            // ========== 3. Table row data ==========<br>            var items = new List&lt;Dictionary&lt;string, string&gt;&gt;<br>            {<br>                new Dictionary&lt;string, string&gt;<br>                {<br>                    { &quot;DESCRIPTION&quot;, &quot;Consulting services&quot; },<br>                    { &quot;QUANTITY&quot;,    &quot;10&quot; },<br>                    { &quot;UNIT_PRICE&quot;,  &quot;$500.00&quot; },<br>                    { &quot;TOTAL_PRICE&quot;, &quot;$5,000.00&quot; }<br>                },<br>                <br>                new Dictionary&lt;string, string&gt;<br>                {<br>                    { &quot;DESCRIPTION&quot;, &quot;Development services&quot; },<br>                    { &quot;QUANTITY&quot;,    &quot;5&quot; },<br>                    { &quot;UNIT_PRICE&quot;,  &quot;$1,000.00&quot; },<br>                    { &quot;TOTAL_PRICE&quot;, &quot;$5,000.00&quot; }<br>                }<br>            };<br><br>            // ========== 4. Replace simple placeholders ==========<br>            foreach (var kv in data)<br>            {<br>                html = html.Replace(&quot;{{&quot; + kv.Key + &quot;}}&quot;, kv.Value);<br>            }<br><br>            // ========== 5. Generate table rows and replace {{ITEMS_ROWS}} ==========<br>            var rowsBuilder = new StringBuilder();<br>            foreach (var item in items)<br>            {<br>                string row = $@&quot;<br>                    &lt;tr&gt;<br>                        &lt;td&gt;{item[&quot;DESCRIPTION&quot;]}&lt;/td&gt;<br>                        &lt;td&gt;{item[&quot;QUANTITY&quot;]}&lt;/td&gt;<br>                        &lt;td&gt;{item[&quot;UNIT_PRICE&quot;]}&lt;/td&gt;<br>                        &lt;td&gt;{item[&quot;TOTAL_PRICE&quot;]}&lt;/td&gt;<br>                    &lt;/tr&gt;&quot;;<br>                rowsBuilder.Append(row);<br>            }<br>            html = html.Replace(&quot;{{ITEMS_ROWS}}&quot;, rowsBuilder.ToString());<br><br>            // ========== 6. Call Free Spire.PDF to convert HTML to PDF ==========<br>            string outputPdf = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &quot;InvoiceOutput.pdf&quot;);<br><br>            // TODO: Change this to the Qt plugin directory after extraction on your machine<br>            string pluginPath = @&quot;G:\Plugin\plugins-windows-x64\plugins&quot;;<br><br>            try<br>            {<br>                HtmlConverter.PluginPath = pluginPath;<br><br>                HtmlConverter.Convert(<br>                    html,<br>                    outputPdf,<br>                    true,                                       // Enable JavaScript<br>                    100000,                                     // Timeout 100 seconds<br>                    new SizeF(595, 842),                        // A4 size (unit: points)<br>                    new PdfMargins(20),                         // Page margins<br>                    LoadHtmlType.SourceCode                     // Pass in HTML string<br>                );<br><br>                Console.WriteLine($&quot;PDF generated successfully: {outputPdf}&quot;);<br>            }<br>            catch (Exception ex)<br>            {<br>                Console.WriteLine($&quot;Failed to generate PDF: {ex.Message}&quot;);<br>                Console.WriteLine(ex.StackTrace);<br>            }<br>        }<br>    }<br>}</pre><h4>3️⃣ Key Code Explanation</h4><ul><li><strong>Placeholder replacement</strong>: Iterate through the business data dictionary and replace the {{KEY}} placeholders in the HTML template one by one to fill in the basic document information.</li><li><strong>Table row generation</strong>: Read the detail list data, concatenate HTML table row fragments in a loop, assemble the detail row content, and embed it into the table area of the template.</li><li><strong>HTML-to-PDF conversion</strong>: Call HtmlConverter.Convert to perform document conversion, specifying the input type as an HTML source string. Enable JavaScript rendering, set a 100-second timeout, A4 standard page size, and uniform page margins.</li><li><strong>Plugin path configuration</strong>: Set HtmlConverter.PluginPath to point to the local Qt plugin directory so that the rendering engine can load the required dependency components.</li><li><strong>Output file handling</strong>: The generated PDF file is saved to the program’s running directory.</li></ul><p>🖼️ Generated PDF preview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*IuTrCHKtXcWHxgwi1iAC1A.png" /></figure><h3>Qt vs Chrome: Choose the Right HTML Rendering Engine</h3><p>Spire.PDF provides two HTML rendering solutions for C# HTML to PDF conversion.</p><h4>1. Qt Plugin Solution</h4><p>Best for: Fast, simple, and efficient conversion.</p><p><strong>Key features:</strong></p><ul><li>Supports login sessions.</li><li>Concise code.</li><li>Fast conversion.</li><li>Lightweight and easy to deploy.</li></ul><pre>using Spire.Additions.Qt;<br><br>HtmlConverter.PluginPath = @&quot;F:\Libraries\Plugin\plugins-windows-x64\plugins&quot;;<br>HtmlConverter.Convert(<br>    htmlString,<br>    fileName,<br>    true,               // Enable JavaScript<br>    100000,             // Timeout 100 seconds<br>    new SizeF(595, 842), // A4 size<br>    new PdfMargins(20),  // Page margins<br>    LoadHtmlType.SourceCode<br>);</pre><blockquote><em>💡 The default timeout is 30 seconds, JavaScript is enabled by default, the default page size is A4, left and right margins are 90, and top and bottom margins are 72.</em></blockquote><h4>2. ChromeHtmlConverter Solution</h4><p>Best for: High-fidelity conversion with logging.</p><p><strong>Key features:</strong></p><ul><li>Renders dynamic content like a browser.</li><li>Provides detailed logs.</li><li>Better for complex pages and pixel-perfect output.</li><li>⚠️ Requires Google Chrome to be installed.</li></ul><pre>using Spire.Pdf.HtmlConverter;<br><br>string chromeLocation = @&quot;C:\Program Files\Google\Chrome\Application\chrome.exe&quot;;<br>ChromeHtmlConverter converter = new ChromeHtmlConverter(chromeLocation);<br>ConvertOptions options = new ConvertOptions<br>{<br>    Timeout = 10 * 1000,<br>    PageSettings = new PageSettings<br>    {<br>        PaperWidth = 8.27,    // A4 width (inches)<br>        PaperHeight = 11.69,  // A4 height (inches)<br>        MarginTop = 0.4,<br>        MarginBottom = 0.4,<br>        MarginLeft = 0.4,<br>        MarginRight = 0.4<br>    }<br>};<br>converter.Convert(htmlContent, outputPdf, options);</pre><blockquote><em>📖 For details, see: </em><a href="https://medium.com/@andrewwil/convert-html-web-pages-to-pdf-in-c-chrome-method-a5a170f3b41e">Convert HTML Web Pages to PDF in C# (Chrome Method)</a></blockquote><h3>Conclusion</h3><p>Spire.PDF for .NET’s HTML to PDF solution is suitable for enterprise production environments. The whole process can be summarized in four steps:</p><p>🎨 Template design → 🧩 Data filling → ⚙️ Plugin rendering → 📄 PDF output</p><p>The amount of code is small. The core complexity lies in debugging CSS compatibility, handling Chinese fonts, and configuring the deployment environment.</p><ul><li>Qt plugin is ideal for fast and simple conversion.</li><li>ChromeHtmlConverter is ideal for high-fidelity output.</li></ul><p>If your project needs to handle long documents or has high requirements for rendering quality, Spire.PDF for .NET is a choice worth considering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0836744fdd46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Draw Lines, Rectangles, and Curves on PDF Pages with C#]]></title>
            <link>https://medium.com/@andrewwil/draw-lines-rectangles-and-curves-on-pdf-pages-with-c-4bf2386f5b40?source=rss-b31d5d80d9b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bf2386f5b40</guid>
            <category><![CDATA[shapes]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Andrew Wilson]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 08:41:54 GMT</pubDate>
            <atom:updated>2026-10-15T08:41:54.697Z</atom:updated>
            <content:encoded><![CDATA[<p>Drawing shapes in PDFs is a common task when generating reports, diagrams, or data visualization documents. This article shows how to use Free Spire.PDF for .NET to draw lines, rectangles, ellipses, polygons, arcs, Bézier curves, and custom paths in C#. It also covers the coordinate system, pens and brushes, transparency, and graphics state management.</p><h3>Prerequisites</h3><p>Install Free Spire.PDF via NuGet in Visual Studio:</p><p>powershell</p><pre>Install-Package FreeSpire.PDF</pre><p>Then import the required namespaces:</p><pre>using Spire.Pdf;<br>using Spire.Pdf.Graphics;<br>using System.Drawing;</pre><h3>Coordinate System</h3><p>Spire.PDF uses a coordinate system that differs from the Adobe PDF specification:</p><ul><li>The origin is at the top-left corner of the page.</li><li>The X-axis extends to the right.</li><li>The Y-axis extends downward.</li><li>The unit is the point.</li></ul><p>An A4 page has a bottom-right coordinate of (595, 842). This top-down layout is convenient for positioning content.</p><p>By default, a new page includes 40-point margins, and the coordinate origin is placed at the top-left inside the margins. To draw in the edge area, create the page with zero margins:</p><pre>PdfDocument doc = new PdfDocument();<br>PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(0));</pre><h3>Pens and Brushes</h3><p>Use PdfPen for stroking and PdfBrush for filling.</p><pre>PdfPen pen = new PdfPen(Color.ForestGreen, 0.1f);<br>PdfPen penThick = new PdfPen(Color.Red, 3f);<br><br>PdfBrush brush = new PdfSolidBrush(Color.DeepSkyBlue);</pre><ul><li>PdfPen defines stroke color and line width.</li><li>PdfSolidBrush creates a solid fill.</li></ul><h3>Drawing Basic Shapes</h3><p>All drawing operations are performed through PdfPageBase.Canvas. Save the graphics state before drawing to avoid affecting later operations.</p><pre>PdfDocument doc = new PdfDocument();<br>PdfPageBase page = doc.Pages.Add();<br>PdfGraphicsState state = page.Canvas.Save();<br><br>// Rectangle (stroke)<br>page.Canvas.DrawRectangle(pen,<br>    new RectangleF(new PointF(2, 22), new SizeF(120, 120)));<br>// Pie / circle (a 360° pie is a full circle)<br>page.Canvas.DrawPie(penThick, 150, 30, 100, 90, 360, 360);<br>// Ellipse (fill)<br>page.Canvas.DrawEllipse(brush, 350, 40, 20, 60);<br>page.Canvas.Restore(state);<br>doc.SaveToFile(&quot;Shapes.pdf&quot;);</pre><p><strong>Notes:</strong></p><ul><li>DrawRectangle accepts a PdfPen and a RectangleF.</li><li>DrawPie uses start and sweep angles in degrees. A 360° sweep produces a full circle.</li><li>DrawEllipse can be filled with a brush or stroked with a pen.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*Dw_GwiSeJ-Mc_q8LCa6tWA.png" /></figure><h3>Drawing Lines and Polygons</h3><p>Use DrawLine for lines and DrawPolygon for polygons.</p><pre>// Line<br>page.Canvas.DrawLine(pen, new PointF(50, 200), new PointF(300, 200));<br><br>// Triangle<br>PointF[] trianglePoints = {<br>    new PointF(100, 250),<br>    new PointF(200, 350),<br>    new PointF(0, 350)<br>};<br>page.Canvas.DrawPolygon(pen, brush, trianglePoints);</pre><p>DrawPolygon accepts a PdfPen, a PdfBrush, and a PointF[]. Pass null for either the pen or brush to stroke-only or fill-only.</p><h3>Drawing Arcs and Bézier Curves</h3><p>Arcs and Bézier curves can be combined to create more complex shapes.</p><pre>// Arc<br>page.Canvas.DrawArc(pen, new RectangleF(50, 400, 100, 80), 0, 180);<br><br>// Bézier curve<br>page.Canvas.DrawBezier(pen,<br>    200, 400,   // start point<br>    250, 350,   // control point 1<br>    350, 450,   // control point 2<br>    400, 400    // end point<br>);</pre><ul><li>DrawArc takes a start angle and a sweep angle.</li><li>DrawBezier requires four points: start, two control points, and end.</li></ul><h3>Building Custom Paths with PdfPath</h3><p>Use PdfPath when you need to combine multiple shape elements into a single path. The Add methods append elements to the path; nothing is drawn until DrawPath is called.</p><pre>PdfPath path = new PdfPath();<br>path.AddLine(50, 500, 150, 500);<br>path.AddRectangle(new RectangleF(180, 500, 60, 60));<br>path.AddPolygon(new PointF[] {<br>    new PointF(280, 500),<br>    new PointF(330, 560),<br>    new PointF(230, 560)<br>});<br>path.AddBezier(400, 500, 430, 480, 470, 520, 500, 500);<br><br>page.Canvas.DrawPath(pen, path);</pre><h3>Applying Transparency</h3><p>Use SetTransparency to control opacity. Values range from 0 (fully transparent) to 1 (opaque).</p><pre>PdfGraphicsState state = page.Canvas.Save();<br><br>page.Canvas.SetTransparency(0.5f);<br>PdfBrush semiBrush = new PdfSolidBrush(Color.Blue);<br>page.Canvas.DrawRectangle(semiBrush, new RectangleF(50, 600, 200, 80));<br>page.Canvas.Restore(state);</pre><p>Transparency affects the canvas state. Always pair it with Save and Restore so later drawing is not unintentionally affected.</p><h3>Managing Graphics State</h3><p>Save and Restore are used as a pair. They push and pop the current graphics state, including pen color, line width, transparency, and coordinate transformations.</p><pre>PdfGraphicsState state = page.Canvas.Save();<br>// Drawing operations that may change pens, transparency, or coordinates<br>page.Canvas.Restore(state);<br>// Drawing returns to the state captured at Save</pre><p>If you translate, rotate, or scale the coordinate system before drawing, place those operations between Save and Restore as well. This prevents side effects on the rest of the page.</p><h3>Complete Example</h3><p>The following example draws several shapes on a single PDF page.</p><pre>using Spire.Pdf;<br>using Spire.Pdf.Graphics;<br>using System.Drawing;<br><br>namespace PdfShapeDemo<br>{<br>    class Program<br>    {<br>        static void Main()<br>        {<br>            PdfDocument doc = new PdfDocument();<br>            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(20));<br>            PdfGraphicsState state = page.Canvas.Save();<br>            PdfPen greenPen = new PdfPen(Color.ForestGreen, 1.5f);<br>            PdfPen redPen = new PdfPen(Color.Red, 2f);<br>            PdfBrush blueBrush = new PdfSolidBrush(Color.DeepSkyBlue);<br>            PdfBrush orangeBrush = new PdfSolidBrush(Color.Orange);<br>            // Rectangle<br>            page.Canvas.DrawRectangle(greenPen,<br>                new RectangleF(30, 40, 100, 60));<br>            // Circle<br>            page.Canvas.DrawPie(redPen, 160, 40, 60, 60, 360, 360);<br>            // Filled ellipse<br>            page.Canvas.DrawEllipse(blueBrush, 250, 40, 80, 50);<br>            // Line<br>            page.Canvas.DrawLine(greenPen,<br>                new PointF(30, 130), new PointF(350, 130));<br>            // Triangle<br>            page.Canvas.DrawPolygon(redPen, orangeBrush, new PointF[] {<br>                new PointF(30, 160),<br>                new PointF(90, 250),<br>                new PointF(30, 250)<br>            });<br>            // Arc<br>            page.Canvas.DrawArc(greenPen,<br>                new RectangleF(180, 160, 100, 80), 0, 180);<br>            // Semi-transparent rectangle<br>            page.Canvas.SetTransparency(0.4f);<br>            page.Canvas.DrawRectangle(new PdfSolidBrush(Color.Purple),<br>                new RectangleF(30, 300, 200, 80));<br>            page.Canvas.Restore(state);<br>            doc.SaveToFile(&quot;Output.pdf&quot;);<br>            doc.Close();<br>        }<br>    }<br>}</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*-rKNNxeddYx-CClqYHZ26A.png" /></figure><h3>Best Practices and Notes</h3><ul><li>Polygon point order matters. Arrange vertices consistently clockwise or counterclockwise to get the intended shape.</li><li>RectangleF uses the top-left corner and size, not the bottom-right corner.</li><li>A4 content area is about 595 × 842 points. Shapes drawn outside this range will not appear on the page.</li><li>Transparency persists in the canvas state. Reset it to 1 or restore a saved state when it is no longer needed.</li><li>Use Save/Restore around state changes such as transparency, pen changes, and coordinate transformations.</li><li>Coordinates are in points, not pixels. Convert from pixels if your layout uses screen dimensions.</li></ul><p>With these techniques, you can build precise vector graphics directly into PDF documents using C# and Free Spire.PDF for .NET.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bf2386f5b40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Transpose Excel Rows and Columns in Python]]></title>
            <link>https://medium.com/@andrewwil/how-to-transpose-excel-rows-and-columns-in-python-17514ff3ebfd?source=rss-b31d5d80d9b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/17514ff3ebfd</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Andrew Wilson]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 07:00:14 GMT</pubDate>
            <atom:updated>2026-10-10T07:00:14.765Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In data processing, you often need to swap rows and columns in a spreadsheet: turning a horizontal table into a vertical one, or converting a vertical metrics table into a horizontal summary. Manual copy-paste transposition is inefficient when the data is large or when the process needs to be repeated automatically.</p><p>Python offers several ways to work with Excel. This article shows how to transpose rows and columns using Free Spire.XLS for Python. It does not require Microsoft Excel to be installed, can read and write .xlsx/.xls files directly, and preserves cell styles and formatting—not just plain text.</p><blockquote><strong><em>⚠️ Note:</em></strong><em> The free version is generally suitable for small-to-medium report automation. </em><a href="https://www.e-iceblue.com/Introduce/free-xls-for-python.html"><em>Review its limitations</em></a><em> before using it in large-scale production scenarios.</em></blockquote><h3>Prerequisites</h3><ul><li>Python 3.6+</li><li>Install the free package:</li></ul><pre>pip install Spire.Xls.Free</pre><ul><li>Import the required modules:</li></ul><pre>from spire.xls import Workbook, FileFormat</pre><h3>Step-by-Step Logic to Transpose Data in Excel</h3><p>The core idea is simple: matrix transposition. Data at row i, column j in the original sheet is written to row j, column i in the target area.</p><ol><li>Load the Excel workbook.</li><li>Read the first worksheet.</li><li>Get the used data range.</li><li>Loop through each cell and cache its value and style.</li><li>Write transposed values into a blank area.</li><li>Copy cell styles to the new cells.</li><li>Save the output file and release resources.</li></ol><p><strong>You can either:</strong></p><ul><li>Write the transposed result to a blank area on the same worksheet, or</li><li>Write it to a new worksheet.</li></ul><p>The example below uses the same worksheet. This avoids switching sheets for viewing and makes it easy to reference the original range with formulas.</p><h3>Full Example: Convert Rows and Columns While Preserving Styles</h3><pre>from spire.xls import Workbook, FileFormat<br><br>def transpose_excel(file_path: str, output_path: str):<br>    # Load workbook<br>    wb = Workbook()<br>    wb.LoadFromFile(file_path)<br>    sheet = wb.Worksheets[0]<br>    # Get the used range of the current worksheet<br>    used_range = sheet.AllocatedRange<br>    row_count = used_range.Rows.Count<br>    col_count = used_range.Columns.Count<br>    # Starting position of the target blank area<br>    start_row = row_count + 2<br>    start_col = col_count + 2<br>    # Iterate over the original range, transpose, and copy cell styles<br>    for r in range(1, row_count + 1):<br>        for c in range(1, col_count + 1):<br>            src_cell = sheet.Range[r, c]<br>            # Transpose: original (r, c) -&gt; target (start_row + c - 1, start_col + r - 1)<br>            dest_row = start_row + c - 1<br>            dest_col = start_col + r - 1<br>            dest_cell = sheet.Range[dest_row, dest_col]<br>            dest_cell.Value = src_cell.Value<br>            # Copy cell style (font, border, background color, etc.)<br>            dest_cell.Style = src_cell.Style<br>    # Save output file<br>    wb.SaveToFile(output_path, FileFormat.Version2016)<br>    # Release resources<br>    wb.Dispose()<br>    print(f&quot;Transposition completed. File saved to: {output_path}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    transpose_excel(&quot;source.xlsx&quot;, &quot;transposed_result.xlsx&quot;)</pre><h4>Key Code Explanation</h4><ul><li>AllocatedRange: Gets the cell range actually occupied by the worksheet, avoiding iteration over large numbers of blank cells and improving performance.</li><li>Cell style copying: dest_cell.Style = src_cell.Style. This is a capability many lightweight libraries lack; it preserves the original table’s borders, background colors, and font formatting.</li><li>Resource release with wb.Dispose(): The library uses unmanaged resources underneath. It is recommended to release them explicitly at the end of the script to avoid holding file handles.</li></ul><h4>Result</h4><p>After running the script, the result file transposed_result.xlsx is generated. Preview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*6BJciZNj0OAspeVrW14TRg.png" /></figure><h3>Fast Alternative: Transpose Excel Values Only</h3><pre>from spire.xls import Workbook, FileFormat<br><br>def transpose_excel_data_only(file_path: str, output_path: str):<br>    wb = Workbook()<br>    wb.LoadFromFile(file_path)<br>    sheet = wb.Worksheets[0]<br>    used_range = sheet.AllocatedRange<br>    row_count = used_range.Rows.Count<br>    col_count = used_range.Columns.Count<br>    # Read into a 2D array<br>    data = []<br>    for r in range(1, row_count + 1):<br>        row_data = []<br>        for c in range(1, col_count + 1):<br>            row_data.append(sheet.Range[r, c].Value)<br>        data.append(row_data)<br>    # Matrix transpose<br>    transposed_data = list(zip(*data))<br>    # Write to the blank area directly below the original range<br>    start_row = row_count + 2<br>    for tr, row in enumerate(transposed_data, start=start_row):<br>        for tc, val in enumerate(row, start=1):<br>            sheet.Range[tr, tc].Value = val<br>    wb.SaveToFile(output_path, FileFormat.Version2016)<br>    wb.Dispose()</pre><h3>Free Spire.XLS vs pandas for Excel Transpose</h3><h4><strong>1. pandas</strong></h4><p>Transposing data is simple (df.T), but the output process rebuilds the worksheet. Original formatting—such as cell colors, borders, and column widths—cannot be preserved. This is suitable for pure data analysis, not for document-format fidelity.</p><h4>2. Free Spire.XLS</h4><p>A standalone component that does not require Office and natively supports copying cell styles. When reports contain complex formatting, borders, and background colors that must be preserved, this approach is more convenient.</p><h3>Conclusion</h3><p>Transposing Excel rows and columns in Python is essentially matrix transposition. With Free Spire.XLS for Python, you can automate the process and preserve cell styles, borders, and background colors without installing Microsoft Excel.</p><p>If you only need raw data transposition, pandas may be sufficient. For style-preserving Excel row column transpose in Python, Free Spire.XLS is a practical and lightweight option.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17514ff3ebfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Compare Two Columns in Excel: VBA vs Python]]></title>
            <link>https://medium.com/@andrewwil/how-to-compare-two-columns-in-excel-vba-vs-python-c2fb81fe1165?source=rss-b31d5d80d9b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2fb81fe1165</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[vba]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Andrew Wilson]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 07:52:27 GMT</pubDate>
            <atom:updated>2026-09-24T07:52:27.987Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Comparing two columns in Excel is a common data-cleaning and validation task. Whether you need to find differences, matches, or unique values, Excel offers several ways to do it. Two popular approaches are VBA macros and Python scripts.</p><p>VBA is built into Excel and works well for manual, one-off comparisons. Python, on the other hand, is ideal for automation, batch processing, and server-side workflows. In this guide, you will learn how to compare two columns in Excel using both VBA and Python, with complete code examples and a comparison section to help you choose the right method.</p><blockquote><strong><em>Note</em></strong><em>: The Python example uses </em><a href="https://www.e-iceblue.com/Introduce/xls-for-python.html"><em>Free Spire.XLS for Python</em></a><em>, a free library that can read and write Excel files without requiring Microsoft Office.</em></blockquote><h3>📝 Requirement: Compare Two Columns in Excel</h3><p>Read an Excel worksheet, compare data in Column A and Column B, and output two types of results:</p><ol><li><strong>Differences</strong> — Items where Column A and Column B are different. This includes values that exist in A but not B, and values that exist in B but not A.</li><li><strong>Matches </strong>— Items where Column A and Column B are the same. These can be highlighted.</li></ol><p>Write the results to Column C so differences are easy to review.</p><blockquote><em>Convention: Data starts from row 2 (row 1 is the header). Only valid, non-empty cells are compared.</em></blockquote><h3>Method 1: Compare Two Columns in Excel with VBA</h3><p>VBA is embedded in Excel and uses the Excel application object directly. It is a good choice if you are already working in Excel, prefer manual macro execution, and do not want to install extra software. The main drawback is that it depends on Office and is less convenient for cross-platform or remote batch execution.</p><h4>VBA Code to Compare Two Columns</h4><pre>Sub CompareRowByRow()<br>    Dim ws As Worksheet<br>    Set ws = ActiveSheet<br>    <br>    Dim lastRowA As Long, lastRowB As Long, maxRow As Long<br>    lastRowA = ws.Cells(ws.Rows.Count, &quot;A&quot;).End(xlUp).Row<br>    lastRowB = ws.Cells(ws.Rows.Count, &quot;B&quot;).End(xlUp).Row<br>    maxRow = Application.WorksheetFunction.Max(lastRowA, lastRowB)<br>    <br>    &#39; Clear results in column C<br>    ws.Columns(&quot;C&quot;).ClearContents<br>    ws.Columns(&quot;C&quot;).Interior.ColorIndex = xlNone<br>    ws.Cells(1, 3).Value = &quot;Comparison Result&quot;<br>    <br>    Dim i As Long<br>    Dim valA As String, valB As String<br>    <br>    For i = 2 To maxRow<br>        valA = Trim(CStr(ws.Cells(i, 1).Value))<br>        valB = Trim(CStr(ws.Cells(i, 2).Value))<br>        <br>        &#39; Skip rows where both columns are empty<br>        If valA = &quot;&quot; And valB = &quot;&quot; Then GoTo NextRow<br>        <br>        If valA = valB Then<br>            &#39; Match: A and B are the same (and non-empty)<br>            ws.Cells(i, 3).Value = &quot;Match&quot;<br>            ws.Cells(i, 3).Interior.Color = RGB(200, 255, 200) &#39; Light green highlight<br>        Else<br>            &#39; Difference: includes one side empty, or both non-empty but unequal<br>            ws.Cells(i, 3).Value = &quot;Difference&quot;<br>        End If<br>        <br>NextRow:<br>    Next i<br>    <br>    MsgBox &quot;Row-by-row comparison complete. Results have been written to column C.&quot;<br>End Sub</pre><h4>How the VBA Code Works</h4><ul><li>Reads values from Column A and Column B row by row.</li><li>Uses Trim(CStr(...)) to ignore leading and trailing spaces and to unify numbers and text.</li><li>Skips rows where both columns are empty.</li><li>Writes “Match” and applies a light green background when values are equal and non-empty.</li><li>Writes “Difference” for all other cases, including when one side is empty or both sides are non-empty but unequal.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*3HBrfOmMrI0xrem_lkvOyQ.png" /></figure><h3>Advanced VBA: Show Specific Differences</h3><p>If you want Column C to display the actual difference values, replace the writing rules with this:</p><pre>If valA = valB Then<br>    &#39; Match: A and B are the same (and non-empty)<br>    ws.Cells(i, 3).Value = &quot;Match: &quot; &amp; valA<br>    ws.Cells(i, 3).Interior.Color = RGB(200, 255, 200) &#39; Light green highlight<br>Else<br>    &#39; Difference<br>    If valA &lt;&gt; &quot;&quot; And valB = &quot;&quot; Then<br>        ws.Cells(i, 3).Value = &quot;Difference: A only - &quot; &amp; valA<br>    ElseIf valA = &quot;&quot; And valB &lt;&gt; &quot;&quot; Then<br>        ws.Cells(i, 3).Value = &quot;Difference: B only - &quot; &amp; valB<br>    Else<br>        ws.Cells(i, 3).Value = &quot;Difference: &quot; &amp; valA &amp; &quot; vs &quot; &amp; valB<br>    End If<br>End If</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*GtpZIAFIrwjuAcdQ8Ru8jw.png" /></figure><h3>Method 2: Compare Two Columns in Excel with Python</h3><p>Python can run independently of Office and is easy to schedule. This makes it a strong choice for batch files, cron jobs, and server-side automation. Free Spire.XLS for Python can load Excel files, traverse cells, and write results without starting Excel.</p><h4>Install Free Spire.XLS for Python</h4><pre>pip install spire.xls.free</pre><h4>Python Code to Compare Excel Columns</h4><pre>from spire.xls import *<br>from spire.xls.common import *<br><br># Load workbook<br>workbook = Workbook()<br>workbook.LoadFromFile(&quot;C:\\Users\\Administrator\\Desktop\\example.xlsx&quot;)<br>sheet = workbook.Worksheets[0]<br>max_row = sheet.LastRow<br>sheet.Range[1, 3].Value = &quot;Comparison Result&quot;<br>for row in range(2, max_row + 1):<br>    cell_a = sheet.Range[row, 1]<br>    cell_b = sheet.Range[row, 2]<br>    <br>    val_a = str(cell_a.Value).strip() if cell_a.Value is not None else &quot;&quot;<br>    val_b = str(cell_b.Value).strip() if cell_b.Value is not None else &quot;&quot;<br>    <br>    # Skip rows where both columns are empty<br>    if not val_a and not val_b:<br>        continue<br>    <br>    cell_c = sheet.Range[row, 3]<br>    <br>    if val_a == val_b:<br>        cell_c.Value = &quot;Match&quot;<br>        cell_c.Style.Color = Color.get_Yellow()<br>    else:<br>        cell_c.Value = &quot;Difference&quot;<br># Save result<br>workbook.SaveToFile(&quot;comparison_result.xlsx&quot;, ExcelVersion.Version2016)<br>workbook.Dispose()<br>print(&quot;Row-by-row comparison complete. Results have been written to column C.&quot;)</pre><h4>How the Python Code Works</h4><ul><li>Reads Column A and Column B row by row.</li><li>Uses str(...).strip() to convert values to strings and remove leading/trailing spaces.</li><li>Skips rows where both columns are empty.</li><li>Writes “Match” and applies a yellow highlight when values are equal.</li><li>Writes “Difference” when values are not equal.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*hYkEctUmDHAXxAO5tRDP5w.png" /></figure><h3>VBA vs Python: Which Should You Use?</h3><p>When deciding between VBA and Python for comparing Excel columns, consider the following factors.</p><ul><li><strong>Runtime environment</strong>: VBA depends on Office or WPS and runs inside Excel. Python with Free Spire.XLS runs in an independent Python environment and does not start Excel.</li><li><strong>Deployment</strong>: VBA is embedded in an .xlsm file. Python scripts plus dependencies can be packaged as an .exe.</li><li><strong>Batch processing</strong>: VBA can lag when processing many files, and stability depends on Excel. Python is good for batch traversal of folders, though you should check free version limits.</li><li><strong>Debugging</strong>: VBA offers breakpoints in the VBA editor, letting you see sheet changes immediately. Python relies on logs and output files.</li><li><strong>Best for</strong>: VBA is best for one-off, manual comparisons inside Excel. Python + Free Spire.XLS is best for automated pipelines, scheduled jobs, and server-side processing.</li></ul><h3>Conclusion</h3><p>Comparing two columns in Excel is a classic data task, and both VBA and Python are valid solutions. VBA is a native Excel option that works well for manual, in-Excel comparisons. Python, especially with Free Spire.XLS for Python, gives you automation power without needing desktop Office.</p><p><strong>Choose VBA</strong> when you need a quick, interactive macro. <strong>Choose Python</strong> when you need batch processing, scheduled comparison, or server-side automation. By matching the tool to your environment, you can compare Excel columns faster and more reliably. ✅</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2fb81fe1165" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create and Export Excel Charts with Python]]></title>
            <link>https://medium.com/@andrewwil/how-to-create-and-export-excel-charts-with-python-ac27bf0f1736?source=rss-b31d5d80d9b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac27bf0f1736</guid>
            <dc:creator><![CDATA[Andrew Wilson]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 05:46:47 GMT</pubDate>
            <atom:updated>2026-09-15T05:46:47.898Z</atom:updated>
            <content:encoded><![CDATA[<p>In data processing and automated reporting, raw Excel tables are often hard to read. Excel charts make trends, proportions, and comparisons much easier to understand. However, many Python Excel libraries have limited chart support, complex configuration, or compatibility issues.</p><p>Free Spire.XLS for Python is a free library that lets you create Excel charts with concise Python code. It is ideal for automated reports, batch data visualization, and Python Excel automation workflows.</p><p>📚 This guide shows you how to:</p><ul><li>Install Free Spire.XLS for Python</li><li>Write data to Excel</li><li>Create column, line, pie, and combination charts</li><li>Export Excel charts as images</li><li>Avoid common charting pitfalls</li></ul><h3>Why Use Python to Create Excel Charts?</h3><p>Python is widely used for data analysis, automation, and reporting. When you combine Python with Excel charts, you can:</p><ul><li>Generate recurring reports automatically</li><li>Visualize large datasets without manual Excel work</li><li>Embed charts into dashboards, PDFs, or web pages</li><li>Reduce human error in reporting workflows</li></ul><p>Free Spire.XLS for Python supports common chart types and works well for small to medium-sized automation projects.</p><h3>Install Free Spire.XLS for Python</h3><p>Install the free library with pip:</p><pre>pip install spire.xls.free</pre><p>The core objects are Workbook and Worksheet. The following example creates a new workbook and writes sample sales data.</p><h3>Write Data to Excel with Python</h3><pre>from spire.xls import *<br>from spire.xls.common import *<br><br>workbook = Workbook()<br>sheet = workbook.Worksheets[0]<br>sheet.Name = &quot;Sales Data&quot;<br># Headers<br>sheet.Range[&quot;A1&quot;].Text = &quot;Month&quot;<br>sheet.Range[&quot;B1&quot;].Text = &quot;Sales&quot;<br>sheet.Range[&quot;C1&quot;].Text = &quot;Volume&quot;<br># Data rows<br>data = [<br>    (&quot;Jan&quot;, 12000, 300),<br>    (&quot;Feb&quot;, 18500, 420),<br>    (&quot;Mar&quot;, 15000, 360),<br>    (&quot;Apr&quot;, 21000, 500),<br>    (&quot;May&quot;, 19500, 460),<br>]<br>row = 2<br>for month, sales, volume in data:<br>    sheet.Range[f&quot;A{row}&quot;].Text = month<br>    sheet.Range[f&quot;B{row}&quot;].NumberValue = sales<br>    sheet.Range[f&quot;C{row}&quot;].NumberValue = volume<br>    row += 1</pre><p>⚠️ Important: Numeric values must be assigned with NumberValue, not Text. Otherwise, the chart engine may not recognize them as numbers, and the data series will be empty.</p><h3>Create a Column Chart in Excel with Python</h3><p>Column charts are useful for comparing categories, such as quarterly performance, product sales, or department metrics.</p><pre>chart = sheet.Charts.Add()<br>chart.ChartType = ExcelChartType.ColumnClustered<br>chart.DataRange = sheet.Range[&quot;A1:B6&quot;]<br>chart.SeriesDataFromRange = False   # Split data series by column<br><br># Position using cell coordinates<br>chart.LeftColumn = 5<br>chart.TopRow = 1<br>chart.RightColumn = 12<br>chart.BottomRow = 18<br>chart.ChartTitle = &quot;Monthly Sales&quot;<br>chart.ChartTitleArea.IsBold = True<br>chart.ChartTitleArea.Size = 12<br>chart.PrimaryCategoryAxis.Title = &quot;Month&quot;<br>chart.PrimaryValueAxis.Title = &quot;Sales&quot;<br>chart.PrimaryValueAxis.HasMajorGridLines = False<br>chart.Legend.Position = LegendPositionType.Bottom</pre><p>SeriesDataFromRange = False makes each column in the data range an independent series. This is necessary when headers are in the first row and data is arranged by column.</p><p>Save and release resources:</p><pre>workbook.SaveToFile(&quot;ColumnChart.xlsx&quot;, ExcelVersion.Version2016)<br>workbook.Dispose()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*iCAKwNPgcCd3QxFG4IJr5A.png" /></figure><h3>Create a Line Chart in Excel with Python</h3><p>Line charts are ideal for showing trends over time. The process is similar to column charts.</p><pre>chart = sheet.Charts.Add(ExcelChartType.Line)<br>chart.DataRange = sheet.Range[&quot;A1:C6&quot;]<br>chart.SeriesDataFromRange = False</pre><p>To display data labels for each line:</p><pre>for series in chart.Series:<br>    series.Format.Options.IsVaryColor = True<br>    series.DataPoints.DefaultDataPoint.DataLabels.HasValue = True</pre><p>IsVaryColor = True automatically assigns different colors to each series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*SEEAv3Pk9Y6kfK328iSvfg.png" /></figure><h3>Create a Combination Chart with Dual Y Axes</h3><p>When two metrics have very different scales — such as sales in thousands and volume in hundreds — a dual-axis combination chart is the standard solution.</p><pre>chart = sheet.Charts.Add()<br>chart.DataRange = sheet.AllocatedRange   # Automatically includes used range<br>chart.SeriesDataFromRange = False<br>chart.ChartType = ExcelChartType.CombinationChart<br><br># First series: sales, column chart, primary Y axis<br>sales = chart.Series.get_Item(0)<br>sales.SerieType = ExcelChartType.ColumnStacked<br>sales.Name = &quot;Sales ($)&quot;<br>sales.UsePrimaryAxis = True<br># Second series: volume, line chart, secondary Y axis<br>volume = chart.Series.get_Item(1)<br>volume.SerieType = ExcelChartType.LineMarkers<br>volume.Name = &quot;Volume (units)&quot;<br>volume.UsePrimaryAxis = False</pre><p>UsePrimaryAxis = False binds the series to the secondary axis on the right. This is the key to creating a dual-axis chart in Excel with Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*QPeMYMHcSlQE7m7UDaieZQ.png" /></figure><h3>Create a Pie Chart in Excel with Python</h3><p>Pie charts show proportions. The data range usually includes one category column and one value column.</p><pre>chart = sheet.Charts.Add(ExcelChartType.Pie)<br>chart.DataRange = sheet.Range[&quot;A1:B6&quot;]   # Category + values<br>chart.SeriesDataFromRange = False<br><br>series = chart.Series[0]<br># Data labels: show percentage and category name<br>data_labels = series.DataPoints.DefaultDataPoint.DataLabels<br>data_labels.HasPercentage = True<br>data_labels.HasCategoryName = True<br>data_labels.HasValue = False<br>data_labels.Position = DataLabelPositionType.Inside<br>data_labels.Font.Size = 10<br>data_labels.Font.Color = Color.get_Black()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*0OEbI5izEPuNWngSLKS16g.png" /></figure><h3>Export an Excel Chart as an Image with Python</h3><p>You can extract charts from Excel and save them as images for reports or web pages.</p><pre>workbook.LoadFromFile(&quot;ColumnChart.xlsx&quot;)<br>sheet = workbook.Worksheets[0]<br><br>image_stream = workbook.SaveChartAsImage(sheet, 0)  # First chart<br>image_stream.Save(&quot;chart_output.png&quot;)<br>workbook.Dispose()</pre><p>To export all charts in a worksheet, loop through sheet.Charts and call SaveChartAsImage with each index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*sPLxnOObiYxCpwWXdkWQiw.png" /></figure><h3>Best Practices and Common Pitfalls</h3><h4>1. Include Column Headers in DataRange</h4><p>When DataRange includes the header row, the chart engine automatically uses headers as series names and legend text. This saves you from manually setting Series.Name.</p><h4>2. Use Cell Styles for Cleaner Charts</h4><p>Charts do not inherit cell styles directly, but bold headers and background colors make the final chart look cleaner.</p><pre>sheet.Range[&quot;A1:C1&quot;].Style.Font.IsBold = True<br>sheet.Range[&quot;A1:C1&quot;].Style.Color = Color.get_DarkBlue()<br>sheet.Range[&quot;A1:C1&quot;].Style.Font.Color = Color.get_White()</pre><h4>3. Dispose Workbook Objects</h4><p>Always call Dispose() after using a Workbook, especially when processing multiple files in batch.</p><h3>Conclusion</h3><p>Excel charts make automated reports more readable and actionable. With Free Spire.XLS for Python, you can create column charts, line charts, pie charts, and dual-axis combination charts using simple code. You can also export charts as images for reports and web pages.</p><p>The core workflow is simple: set the data range, choose the chart type, and adjust properties. For small and medium-sized Python Excel automation projects, Free Spire.XLS provides a practical free solution. ✅</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac27bf0f1736" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Client-Side PDF Text Extraction with React & WASM]]></title>
            <link>https://medium.com/@andrewwil/client-side-pdf-text-extraction-with-react-wasm-b35a61b7f79e?source=rss-b31d5d80d9b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b35a61b7f79e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Andrew Wilson]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 03:39:29 GMT</pubDate>
            <atom:updated>2026-09-11T03:39:29.128Z</atom:updated>
            <content:encoded><![CDATA[<p>PDF text extraction comes up all the time in document automation. 📄 The usual approach is to have a backend service read the PDF and send back the text. But when you’re dealing with a lot of users or large PDF files, that can put a strain on your servers and burn through upload bandwidth.</p><p>With WASM, we can move PDF parsing into the browser. The file never has to leave the user’s machine, which is better for privacy and takes a lot of load off the backend.</p><p>In this post, we’ll use Spire.PDF for JavaScript (WASM) and React to build a local PDF text extractor. Users pick a PDF, the browser parses it, and they download the extracted text as a .txt file.</p><h3>1. Tech Stack and How It Works</h3><h4>📚 1.1 About the Library</h4><p><a href="https://www.e-iceblue.com/Introduce/pdf-for-javascript.html">Spire.PDF for JavaScript</a> is a browser-side PDF library. Its core is compiled to WebAssembly, and it exposes JavaScript APIs for loading, parsing, and manipulating PDF documents. It can extract text, images, form data, and more. In this post, we’ll only use its text extraction feature.</p><h4>⚙️ 1.2 How It Works</h4><pre>User selects a PDF<br>    ↓<br>Browser reads it into an ArrayBuffer<br>    ↓<br>WASM module loads the PDF<br>    ↓<br>Text is extracted page by page<br>    ↓<br>A TXT file is generated and downloaded</pre><p>✅ All of this happens on the client side. Nothing gets uploaded to a server.</p><h3>2. Project Setup and File Preparation</h3><h4>2.1 Dependency Files</h4><p>Run npm i spire.office to get the required resources. Then place the following files in your React project&#39;s public/ directory:</p><ul><li>spire.pdf.js</li><li>spire.pdf.wasm</li><li>spire.common.js</li><li>Spire.Common.Wasm.zip</li><li>_framework folder</li></ul><h4>2.2 React Environment</h4><p>You can use a project created with Create React App or Vite. The example below uses React function components and Hooks. ⚛️</p><h3>3. Core Implementation</h3><h4>3.1 Loading the WASM Module</h4><p>Since the WASM file loads asynchronously, we import it dynamically inside useEffect and store the module instance in state.</p><pre>useEffect(() =&gt; {<br>  (async () =&gt; {<br>    try {<br>      const publicUrl = process.env.PUBLIC_URL || &#39;&#39;;<br>      // Dynamically import the JS glue code; webpackIgnore prevents bundling<br>      const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.pdf.js`);<br>      const rawModule = spireModule.default || spireModule;<br>      // Load WASM; locateFile tells the loader where to find the .wasm file<br>      const loadedModule = typeof rawModule === &#39;function&#39;<br>        ? await rawModule({ locateFile: p =&gt; p.endsWith(&#39;.wasm&#39;) ? `${publicUrl}/${p}` : p })<br>        : rawModule;<br>      setPdfModule(loadedModule);<br>    } catch (error) {<br>      console.error(&#39;Failed to load spire.pdf.js:&#39;, error);<br>    }<br>  })();<br>}, []);</pre><p>💡 <strong>Key points:</strong></p><ul><li>webpackIgnore: true keeps Webpack from rewriting the dynamic import path.</li><li>locateFile tells the WASM loader where to find the .wasm file.</li></ul><blockquote>⚠️ Note: process.env.PUBLIC_URL works in Create React App. If you&#39;re using Vite, use import.meta.env.BASE_URL instead.</blockquote><h4>3.2 File Selection and State Management</h4><p>We hide the native &lt;input&gt; with useRef and trigger it from a custom button. This keeps the UI consistent across browsers.</p><pre>const fileInputRef = useRef(null);<br><br>const handleFileChange = (e) =&gt; {<br>  const file = e.target.files[0];<br>  if (file &amp;&amp; file.type === &#39;application/pdf&#39;) {<br>    setSelectedFile(file);<br>  } else {<br>    alert(&#39;Please select a valid PDF file&#39;);<br>    e.target.value = &#39;&#39;;<br>  }<br>};<br>const handleSelectFile = () =&gt; {<br>  fileInputRef.current.click();<br>};</pre><h4>3.3 Extracting Text</h4><p>The extraction logic lives in extractPdfText. Here&#39;s the flow:</p><pre>const extractPdfText = async () =&gt; {<br>  if (!selectedFile) return;<br>  const spirepdf = pdfModule?.spirepdf;<br>  if (!spirepdf) {<br>    alert(&#39;The module has not finished loading yet&#39;);<br>    return;<br>  }<br><br>setIsExtracting(true);<br>  try {<br>    // 1. Read the file as a byte array<br>    const arrayBuffer = await selectedFile.arrayBuffer();<br>    const uint8Array = new Uint8Array(arrayBuffer);<br>    // 2. Create and load the PDF document<br>    const pdf = new spirepdf.PdfDocument();<br>    pdf.LoadFromBytes(uint8Array);<br>    // 3. Set up extraction options (defaults are fine)<br>    const extractOptions = new spirepdf.PdfTextExtractOptions();<br>    let text = &#39;&#39;;<br>    // 4. Loop through every page<br>    for (let i = 0; i &lt; pdf.Pages.Count; i++) {<br>      const page = pdf.Pages.get_Item(i);<br>      const textExtractor = new spirepdf.PdfTextExtractor(page);<br>      text += textExtractor.ExtractText(extractOptions);<br>    }<br>    // 5. Generate a TXT file and trigger the download<br>    const outputFileName = selectedFile.name.replace(/\.pdf$/i, &#39;_extracted.txt&#39;);<br>    const blob = new Blob([text], { type: &#39;text/plain;charset=utf-8&#39; });<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>  } catch (error) {<br>    console.error(&#39;Extraction failed:&#39;, error);<br>    alert(&#39;An error occurred during extraction. Please check the console.&#39;);<br>  } finally {<br>    setIsExtracting(false);<br>  }<br>};</pre><p>📝 Notes:</p><ul><li>PdfDocument.LoadFromBytes expects a Uint8Array.</li><li>Page indices start at 0, so loop up to pdf.Pages.Count.</li><li>The download uses Blob and URL.createObjectURL, so there&#39;s no backend involved.</li></ul><h3>🎨 4. Polishing the UI</h3><p>To make the tool feel more polished, we add a loading state, disable the button while work is in progress, and show which file is selected.</p><h4>4.1 State</h4><ul><li>selectedFile: the currently selected file object</li><li>isExtracting: whether extraction is running; used to show the loading state and disable the button</li><li>pdfModule: whether the WASM module has finished loading</li></ul><h4>4.2 Button State</h4><pre>const isButtonDisabled = !selectedFile || isExtracting || !pdfModule;</pre><h4>4.3 Styling (Inline Styles)</h4><p>The layout centers a card on the page. The button uses the primary color #1a73e8, with hover and disabled styles.</p><p>The full style code is in the complete component below.</p><h3>5. Full Component Code</h3><p>Here’s the complete App.js file. You can copy it as is, but make sure spire.pdf.js and the .wasm files are in public/ first.</p><pre>import React, { useState, useEffect, useRef } from &#39;react&#39;;<br><br>function App() {<br>  const [pdfModule, setPdfModule] = useState(null);<br>  const [selectedFile, setSelectedFile] = useState(null);<br>  const [isExtracting, setIsExtracting] = useState(false);<br>  const fileInputRef = useRef(null);<br>  // Load the WASM module<br>  useEffect(() =&gt; {<br>    (async () =&gt; {<br>      try {<br>        const publicUrl = process.env.PUBLIC_URL || &#39;&#39;;<br>        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.pdf.js`);<br>        const rawModule = spireModule.default || spireModule;<br>        const loadedModule = typeof rawModule === &#39;function&#39;<br>          ? await rawModule({ locateFile: p =&gt; p.endsWith(&#39;.wasm&#39;) ? `${publicUrl}/${p}` : p })<br>          : rawModule;<br>        setPdfModule(loadedModule);<br>      } catch (error) {<br>        console.error(&#39;Failed to load spire.pdf.js:&#39;, error);<br>        alert(&#39;Failed to load the PDF library. Please refresh and try again.&#39;);<br>      }<br>    })();<br>  }, []);<br>  const handleSelectFile = () =&gt; {<br>    fileInputRef.current.click();<br>  };<br>  const handleFileChange = (e) =&gt; {<br>    const file = e.target.files[0];<br>    if (file &amp;&amp; file.type === &#39;application/pdf&#39;) {<br>      setSelectedFile(file);<br>    } else {<br>      alert(&#39;Please select a valid PDF file&#39;);<br>      e.target.value = &#39;&#39;;<br>    }<br>  };<br>  const extractPdfText = async () =&gt; {<br>    if (!selectedFile) {<br>      alert(&#39;Please select a PDF file first.&#39;);<br>      return;<br>    }<br>    const spirepdf = pdfModule?.spirepdf;<br>    if (!spirepdf) {<br>      alert(&#39;The WASM module has not finished loading. Please try again later.&#39;);<br>      return;<br>    }<br>    setIsExtracting(true);<br>    try {<br>      const arrayBuffer = await selectedFile.arrayBuffer();<br>      const uint8Array = new Uint8Array(arrayBuffer);<br>      const pdf = new spirepdf.PdfDocument();<br>      pdf.LoadFromBytes(uint8Array);<br>      const extractOptions = new spirepdf.PdfTextExtractOptions();<br>      let text = &#39;&#39;;<br>      for (let i = 0; i &lt; pdf.Pages.Count; i++) {<br>        const page = pdf.Pages.get_Item(i);<br>        const textExtractor = new spirepdf.PdfTextExtractor(page);<br>        text += textExtractor.ExtractText(extractOptions);<br>      }<br>      const outputFileName = selectedFile.name.replace(/\.pdf$/i, &#39;_extracted.txt&#39;);<br>      const blob = new Blob([text], { type: &#39;text/plain;charset=utf-8&#39; });<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>    } catch (error) {<br>      console.error(&#39;Failed to extract text:&#39;, error);<br>      alert(&#39;An error occurred while extracting text. Please check the console.&#39;);<br>    } finally {<br>      setIsExtracting(false);<br>    }<br>  };<br>  // Style object<br>  const styles = {<br>    container: {<br>      display: &#39;flex&#39;,<br>      justifyContent: &#39;center&#39;,<br>      alignItems: &#39;center&#39;,<br>      minHeight: &#39;100vh&#39;,<br>      backgroundColor: &#39;#f0f2f5&#39;,<br>      fontFamily: &#39;Arial, sans-serif&#39;,<br>      padding: &#39;20px&#39;,<br>    },<br>    card: {<br>      backgroundColor: &#39;#fff&#39;,<br>      padding: &#39;40px 50px&#39;,<br>      borderRadius: &#39;16px&#39;,<br>      boxShadow: &#39;0 8px 24px rgba(0,0,0,0.12)&#39;,<br>      maxWidth: &#39;600px&#39;,<br>      width: &#39;100%&#39;,<br>      textAlign: &#39;center&#39;,<br>    },<br>    title: {<br>      fontSize: &#39;28px&#39;,<br>      fontWeight: &#39;600&#39;,<br>      color: &#39;#1a1a2e&#39;,<br>      marginBottom: &#39;30px&#39;,<br>    },<br>    fileArea: {<br>      marginBottom: &#39;30px&#39;,<br>    },<br>    customFileButton: {<br>      display: &#39;inline-block&#39;,<br>      padding: &#39;10px 24px&#39;,<br>      backgroundColor: &#39;#e8f0fe&#39;,<br>      color: &#39;#1a73e8&#39;,<br>      borderRadius: &#39;30px&#39;,<br>      fontWeight: &#39;500&#39;,<br>      cursor: &#39;pointer&#39;,<br>      border: &#39;1px solid #d2e3fc&#39;,<br>      transition: &#39;background 0.2s&#39;,<br>    },<br>    fileName: {<br>      marginTop: &#39;12px&#39;,<br>      fontSize: &#39;16px&#39;,<br>      color: &#39;#333&#39;,<br>      wordBreak: &#39;break-all&#39;,<br>    },<br>    extractButton: {<br>      padding: &#39;12px 40px&#39;,<br>      fontSize: &#39;18px&#39;,<br>      fontWeight: &#39;500&#39;,<br>      color: &#39;#fff&#39;,<br>      backgroundColor: &#39;#1a73e8&#39;,<br>      border: &#39;none&#39;,<br>      borderRadius: &#39;30px&#39;,<br>      cursor: &#39;pointer&#39;,<br>      transition: &#39;background 0.3s, transform 0.1s&#39;,<br>      boxShadow: &#39;0 2px 8px rgba(26,115,232,0.3)&#39;,<br>    },<br>    extractButtonDisabled: {<br>      backgroundColor: &#39;#b0b0b0&#39;,<br>      cursor: &#39;not-allowed&#39;,<br>      boxShadow: &#39;none&#39;,<br>    },<br>    extractingText: {<br>      marginTop: &#39;15px&#39;,<br>      fontSize: &#39;16px&#39;,<br>      color: &#39;#1a73e8&#39;,<br>    },<br>  };<br>  const isButtonDisabled = !selectedFile || isExtracting || !pdfModule;<br>  return (<br>    &lt;div style={styles.container}&gt;<br>      &lt;div style={styles.card}&gt;<br>        &lt;h1 style={styles.title}&gt;📄 PDF Text Extractor&lt;/h1&gt;<br>        &lt;div style={styles.fileArea}&gt;<br>          &lt;input<br>            type=&quot;file&quot;<br>            accept=&quot;.pdf&quot;<br>            onChange={handleFileChange}<br>            ref={fileInputRef}<br>            style={{ display: &#39;none&#39; }}<br>          /&gt;<br>          &lt;div<br>            style={styles.customFileButton}<br>            onClick={handleSelectFile}<br>            onMouseEnter={(e) =&gt; (e.currentTarget.style.backgroundColor = &#39;#d2e3fc&#39;)}<br>            onMouseLeave={(e) =&gt; (e.currentTarget.style.backgroundColor = &#39;#e8f0fe&#39;)}<br>          &gt;<br>            📂 Select PDF File<br>          &lt;/div&gt;<br>          {selectedFile &amp;&amp; (<br>            &lt;div style={styles.fileName}&gt;<br>              ✅ Selected: &lt;strong&gt;{selectedFile.name}&lt;/strong&gt;<br>            &lt;/div&gt;<br>          )}<br>        &lt;/div&gt;<br>        &lt;button<br>          onClick={extractPdfText}<br>          disabled={isButtonDisabled}<br>          style={{<br>            ...styles.extractButton,<br>            ...(isButtonDisabled ? styles.extractButtonDisabled : {}),<br>          }}<br>          onMouseEnter={(e) =&gt; {<br>            if (!isButtonDisabled) {<br>              e.currentTarget.style.backgroundColor = &#39;#1558b0&#39;;<br>            }<br>          }}<br>          onMouseLeave={(e) =&gt; {<br>            if (!isButtonDisabled) {<br>              e.currentTarget.style.backgroundColor = &#39;#1a73e8&#39;;<br>            }<br>          }}<br>        &gt;<br>          {isExtracting ? &#39;⏳ Extracting...&#39; : &#39;🚀 Extract and Download Text&#39;}<br>        &lt;/button&gt;<br>        {isExtracting &amp;&amp; (<br>          &lt;div style={styles.extractingText}&gt;Processing, please wait...&lt;/div&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><h3>6. Running and Deploying</h3><ol><li>Start the dev server with npm start or yarn start.</li><li>The WASM module loads automatically when the page loads. Give it a moment, then it’s ready.</li><li>Select a PDF, click the button, and the browser downloads the extracted text file.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*fTDQiN0qU49KsiSbk92TJg.png" /></figure><h3>Final Thoughts</h3><p>This post walked through a JavaScript-based PDF text extraction setup, covering WASM loading, file reading, page-by-page extraction, and download handling. Everything runs in the browser, so there’s no backend dependency. That makes it a good fit for document preview, content search, data migration, and similar use cases.</p><p>You can adjust the extraction options, add error handling, or extend it to batch processing. The structure is clean and should drop into an existing React project without much friction. ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b35a61b7f79e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>