### Install unhwp Source: https://github.com/iyulab/unhwp/blob/main/bindings/python/README.md Install the unhwp library using pip. ```bash pip install unhwp ``` -------------------------------- ### Basic HWP Conversion Example Source: https://github.com/iyulab/unhwp/blob/main/README.md A simple example demonstrating the basic conversion of an HWP file named 'report.hwp'. By default, this produces Markdown and extracts images. ```bash # Basic conversion unhwp report.hwp ``` -------------------------------- ### Quick Start C# - Parse File and Get Markdown Source: https://github.com/iyulab/unhwp/blob/main/README.md Demonstrates basic usage of the UnhwpDocument class in C#. It parses an HWP file, converts it to Markdown, and saves the output to a file. The `using` statement ensures proper disposal of native resources. ```csharp using Unhwp; // Parse document — always use `using` to release native memory using var doc = UnhwpDocument.ParseFile("document.hwp"); // Get Markdown string markdown = doc.ToMarkdown(); File.WriteAllText("output.md", markdown); // Get plain text string text = doc.ToText(); // Get full structured JSON string json = doc.ToJson(); // With frontmatter var opts = new MarkdownOptions { IncludeFrontmatter = true }; string mdWithFm = doc.ToMarkdown(opts); // Document statistics Console.WriteLine($"Sections: {doc.SectionCount}"); Console.WriteLine($"Resources: {doc.ResourceCount}"); Console.WriteLine($"Title: {doc.Title}"); Console.WriteLine($"Author: {doc.Author}"); ``` -------------------------------- ### Install unhwp CLI and library via Cargo Source: https://github.com/iyulab/unhwp/blob/main/README.md Shows how to install the unhwp command-line interface and add the unhwp library to a Rust project using Cargo. ```bash # Install CLI cargo install unhwp-cli # Add library to your project cargo add unhwp ``` -------------------------------- ### Install unhwp on Linux (x64) Source: https://github.com/iyulab/unhwp/blob/main/README.md Downloads and extracts the latest unhwp release for Linux. Provides options for installing to system-wide or user-specific directories. ```bash # Auto-detect latest version and download VERSION=$(curl -s "https://api.github.com/repos/iyulab/unhwp/releases/latest" | grep '"tag_name"' | cut -d'"' -f4) curl -LO "https://github.com/iyulab/unhwp/releases/latest/download/unhwp-linux-x86_64-${VERSION}.tar.gz" tar -xzf "unhwp-linux-x86_64-${VERSION}.tar.gz" # Install to /usr/local/bin (requires sudo) sudo mv unhwp /usr/local/bin/ # Or install to user directory mkdir -p ~/.local/bin mv unhwp ~/.local/bin/ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc source ~/.bashrc # Verify installation unhwp --version ``` -------------------------------- ### Rust Quick Start: Text Extraction and Markdown Conversion Source: https://github.com/iyulab/unhwp/blob/main/README.md A basic example of using the Unhwp Rust library to extract plain text from an HWP file and convert another HWP file to Markdown, writing the output to a file. ```rust use unhwp::{parse_file, to_markdown}; fn main() -> unhwp::Result<()> { // Simple text extraction let text = unhwp::extract_text("document.hwp")?; println!("{}", text); // Convert to Markdown let markdown = to_markdown("document.hwp")?; std::fs::write("output.md", markdown)?; Ok(()) } ``` -------------------------------- ### Install Unhwp WASM Package Source: https://github.com/iyulab/unhwp/blob/main/unhwp-wasm/README.md Install the @iyulab/unhwp package using npm. This command is used for setting up the library in your project. ```bash npm install @iyulab/unhwp ``` -------------------------------- ### Quick Start: Basic HWP to Markdown Conversion Source: https://github.com/iyulab/unhwp/blob/main/bindings/python/README.md Demonstrates simple conversion of an HWP document to Markdown and extraction of plain text. ```python import unhwp # Simple conversion markdown = unhwp.to_markdown("document.hwp") print(markdown) # Extract plain text text = unhwp.extract_text("document.hwp") ``` -------------------------------- ### Quick Start: Convert HWP to Markdown and Extract Text Source: https://github.com/iyulab/unhwp/blob/main/bindings/csharp/Unhwp/README.md Demonstrates basic usage of UnhwpConverter for converting a document to Markdown and extracting plain text. ```csharp using Unhwp; // Simple conversion string markdown = UnhwpConverter.ToMarkdown("document.hwp"); Console.WriteLine(markdown); // Extract plain text string text = UnhwpConverter.ExtractText("document.hwp"); ``` -------------------------------- ### Install Unhwp via NuGet Package Manager Source: https://github.com/iyulab/unhwp/blob/main/bindings/csharp/Unhwp/README.md Alternatively, install the Unhwp package using the NuGet Package Manager in Visual Studio. ```powershell Install-Package Unhwp ``` -------------------------------- ### Install unhwp on macOS Source: https://github.com/iyulab/unhwp/blob/main/README.md Downloads and extracts the latest unhwp release for macOS, supporting both Intel and Apple Silicon architectures. Installs the executable to /usr/local/bin. ```bash VERSION=$(curl -s "https://api.github.com/repos/iyulab/unhwp/releases/latest" | grep '"tag_name"' | cut -d'"' -f4) # Intel Mac curl -LO "https://github.com/iyulab/unhwp/releases/latest/download/unhwp-macos-x86_64-${VERSION}.tar.gz" tar -xzf "unhwp-macos-x86_64-${VERSION}.tar.gz" # Apple Silicon (M1/M2/M3/M4) curl -LO "https://github.com/iyulab/unhwp/releases/latest/download/unhwp-macos-aarch64-${VERSION}.tar.gz" tar -xzf "unhwp-macos-aarch64-${VERSION}.tar.gz" # Install sudo mv unhwp /usr/local/bin/ # Verify unhwp --version ``` -------------------------------- ### Install Unhwp Package Source: https://github.com/iyulab/unhwp/blob/main/bindings/csharp/Unhwp/README.md Add the Unhwp NuGet package to your .NET project using the dotnet CLI. ```bash dotnet add package Unhwp ``` -------------------------------- ### Quick Start: Full Parsing with Image Extraction Source: https://github.com/iyulab/unhwp/blob/main/bindings/python/README.md Shows how to parse an HWP document for full content, including Markdown, section/paragraph counts, and saving images. ```python import unhwp # Full parsing with images with unhwp.parse("document.hwp") as result: print(result.markdown) print(f"Sections: {result.section_count}") print(f"Paragraphs: {result.paragraph_count}") # Save images for img in result.images: img.save(f"output/{img.name}") ``` -------------------------------- ### Quick Start: Full Parsing with Image Extraction Source: https://github.com/iyulab/unhwp/blob/main/bindings/csharp/Unhwp/README.md Shows how to parse an HWP document for full content, including Markdown, section/paragraph counts, and saving extracted images. ```csharp using var result = UnhwpConverter.Parse("document.hwp"); Console.WriteLine(result.Markdown); Console.WriteLine($ ``` -------------------------------- ### Basic HWP Conversion using Legacy API (C#) Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Provides examples of using the legacy Unhwp API for basic operations like checking the library version, detecting file format, and converting HWP to Markdown. Suitable for simple, direct conversions. ```csharp using Unhwp; // Check library version Console.WriteLine($"unhwp version: {HwpConverter.Version}"); // Detect file format var format = HwpConverter.DetectFormat("document.hwp"); Console.WriteLine($"Format: {format}"); // Convert to Markdown (simple) string markdown = HwpConverter.ToMarkdown("document.hwp"); File.WriteAllText("output.md", markdown); // Convert with cleanup enabled (for LLM training data) string cleanMarkdown = HwpConverter.ToMarkdown("document.hwp", enableCleanup: true); ``` -------------------------------- ### Install unhwp on Windows (x64) Source: https://github.com/iyulab/unhwp/blob/main/README.md Automates downloading and extracting the latest unhwp release for Windows. Optionally moves the executable to a system-wide accessible directory. ```powershell # Auto-detect latest version and download $VERSION = (Invoke-RestMethod "https://api.github.com/repos/iyulab/unhwp/releases/latest").tag_name Invoke-WebRequest -Uri "https://github.com/iyulab/unhwp/releases/latest/download/unhwp-windows-x86_64-${VERSION}.zip" -OutFile "unhwp.zip" Expand-Archive -Path "unhwp.zip" -DestinationPath "." # Move to a directory in PATH (optional) Move-Item -Path "unhwp.exe" -Destination "$env:LOCALAPPDATA\Microsoft\WindowsApps\" # Verify installation unhwp --version ``` -------------------------------- ### HwpConverter.Version Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Gets the current version of the Unhwp library. ```APIDOC ## HwpConverter.Version ### Description Gets the library version. ### Method `static string Version` ### Parameters None ### Response - **Version** (string) - The library version string. ``` -------------------------------- ### ASP.NET Core API for HWP Conversion Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Provides an example of an ASP.NET Core controller endpoint to receive HWP files via upload and convert them to Markdown. Includes error handling for bad requests. ```csharp // Controller example [ApiController] [Route("api/[controller]")] public class DocumentController : ControllerBase { [HttpPost("convert")] public async Task ConvertHwp(IFormFile file) { if (file == null || file.Length == 0) return BadRequest("No file uploaded"); using var stream = file.OpenReadStream(); using var ms = new MemoryStream(); await stream.CopyToAsync(ms); try { var options = new ConversionOptions { EnableCleanup = true, TableFallback = TableFallback.Html }; var markdown = HwpConverter.BytesToMarkdown(ms.ToArray(), true); return Ok(new { markdown }); } catch (HwpException ex) { return BadRequest(new { error = ex.Message }); } } } ``` -------------------------------- ### Get Raw Structured Content Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Provides access to the full, raw structured content of the HWP document as JSON. This includes metadata, styles, formatting, tables, images, and links. ```csharp /// /// Gets the raw structured content as JSON. /// This provides access to the full document structure including: /// - Document metadata (title, author, dates) /// - Paragraph styles (heading level, alignment, list type) /// - Text formatting (bold, italic, underline, font, color, etc.) /// - Table structure (rows, cells, colspan, rowspan) /// - Equations, images, and links /// ``` -------------------------------- ### Display Help Information Source: https://github.com/iyulab/unhwp/blob/main/README.md Shows the help message for the Unhwp CLI, listing available commands and options. ```bash unhwp --help # Show help ``` -------------------------------- ### Convert HWP to Markdown with Custom Options (Legacy API C#) Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Illustrates converting an HWP document to Markdown using the legacy API with a specific set of custom options, including frontmatter inclusion, table fallback to HTML, and aggressive cleanup. Useful for fine-tuning conversion output. ```csharp using Unhwp; var options = new ConversionOptions { IncludeFrontmatter = true, TableFallback = TableFallback.Html, EnableCleanup = true, CleanupPreset = CleanupPreset.Aggressive, DetectMojibake = true }; string markdown = HwpConverter.ToMarkdown("document.hwp", options); ``` -------------------------------- ### Get Error Message Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves an error message if an error occurred during parsing. ```APIDOC ## unhwp_result_get_error ### Description Retrieves an error message if the parsing operation resulted in an error. ### Method Extern function (P/Invoke) ### Endpoint N/A ### Parameters #### Path Parameters - **result** (IntPtr) - Required - The pointer to the result object. ### Response #### Success Response - **return value** (IntPtr) - A pointer to a null-terminated UTF-8 string containing the error message, or IntPtr.Zero if no error occurred. This pointer must be freed using `unhwp_free_string`. ``` -------------------------------- ### Get Raw Content Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves the raw, unprocessed content of the parsed document. ```APIDOC ## unhwp_result_get_raw_content ### Description Extracts the raw, unprocessed content of the document from the result object. ### Method Extern function (P/Invoke) ### Endpoint N/A ### Parameters #### Path Parameters - **result** (IntPtr) - Required - The pointer to the result object. ### Response #### Success Response - **return value** (IntPtr) - A pointer to a null-terminated UTF-8 string containing the raw content. This pointer must be freed using `unhwp_free_string`. ``` -------------------------------- ### Get Paragraph Count Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves the number of paragraphs within the parsed document. ```APIDOC ## unhwp_result_get_paragraph_count ### Description Counts the number of paragraphs found within the parsed document. ### Method Extern function (P/Invoke) ### Endpoint N/A ### Parameters #### Path Parameters - **result** (IntPtr) - Required - The pointer to the result object. ### Response #### Success Response - **return value** (int) - The total number of paragraphs in the document. ``` -------------------------------- ### Quiet Batch Conversion (Shell) Source: https://github.com/iyulab/unhwp/blob/main/README.md Demonstrates how to perform a quiet batch conversion of multiple HWP files in a directory using a shell loop. The `-q` flag suppresses output for each conversion. ```bash # Quiet batch conversion (shell) — -q is on the `convert` subcommand for f in *.hwp; do unhwp convert "$f" -q; done ``` -------------------------------- ### Get Section Count Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves the number of sections within the parsed document. ```APIDOC ## unhwp_result_get_section_count ### Description Counts the number of sections found within the parsed document. ### Method Extern function (P/Invoke) ### Endpoint N/A ### Parameters #### Path Parameters - **result** (IntPtr) - Required - The pointer to the result object. ### Response #### Success Response - **return value** (int) - The total number of sections in the document. ``` -------------------------------- ### Get Text Result Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves the parsed document content as plain text. ```APIDOC ## unhwp_result_get_text ### Description Extracts the document content as plain text from the result object. ### Method Extern function (P/Invoke) ### Endpoint N/A ### Parameters #### Path Parameters - **result** (IntPtr) - Required - The pointer to the result object obtained from a parse function. ### Response #### Success Response - **return value** (IntPtr) - A pointer to a null-terminated UTF-8 string containing the plain text content. This pointer must be freed using `unhwp_free_string`. ``` -------------------------------- ### Convert HWP/HWPX to Markdown using CLI Source: https://github.com/iyulab/unhwp/blob/main/README.md Basic usage of the unhwp CLI for document conversion. Specifies input file and optionally an output directory. ```bash # Convert HWP/HWPX to Markdown (creates _output/ directory) unhwp document.hwp # Specify output directory unhwp document.hwp ./output # Using subcommand unhwp convert document.hwp -o ./output ``` -------------------------------- ### Get Markdown Result Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves the parsed document content as a Markdown string. ```APIDOC ## unhwp_result_get_markdown ### Description Extracts the document content formatted as Markdown from the result object. ### Method Extern function (P/Invoke) ### Endpoint N/A ### Parameters #### Path Parameters - **result** (IntPtr) - Required - The pointer to the result object obtained from a parse function. ### Response #### Success Response - **return value** (IntPtr) - A pointer to a null-terminated UTF-8 string containing the Markdown content. This pointer must be freed using `unhwp_free_string`. ``` -------------------------------- ### Build Native Library for Windows Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Builds the unhwp library in release mode for Windows x64. The output is unhwp.dll. ```bash # Windows cargo build --release # Output: target/release/unhwp.dll ``` -------------------------------- ### Getting Paragraph Count Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves the total number of paragraphs within the HWP document. ```csharp public int ParagraphCount { get { ThrowIfDisposed(); return UnhwpNative.unhwp_result_get_paragraph_count(_handle); } } ``` -------------------------------- ### Run Benchmarks Source: https://github.com/iyulab/unhwp/blob/main/README.md Execute the project's performance benchmarks using Cargo. ```bash cargo bench ``` -------------------------------- ### Getting Section Count Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves the total number of sections within the HWP document. ```csharp public int SectionCount { get { ThrowIfDisposed(); return UnhwpNative.unhwp_result_get_section_count(_handle); } } ``` -------------------------------- ### Get Image Data Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves specific image data from the parsed document by its index. ```APIDOC ## unhwp_result_get_image ### Description Retrieves the data for a specific image from the parsed document based on its index. ### Method Extern function (P/Invoke) ### Endpoint N/A ### Parameters #### Path Parameters - **result** (IntPtr) - Required - The pointer to the result object. - **index** (int) - Required - The zero-based index of the image to retrieve. - **outImage** (out ImageData) - Required - An output parameter to receive the image data structure. ### Response #### Success Response - **return value** (int) - 0 on success, non-zero on failure. The `outImage` parameter will be populated with image details if successful. ``` -------------------------------- ### Rust: Convert to Markdown with Section Markers Source: https://github.com/iyulab/unhwp/blob/main/README.md Shows how to use the `to_markdown_with_options` function in the Unhwp Rust library to convert an HWP file to Markdown, specifically enabling section markers (e.g., ``) for better structure. ```rust use unhwp::{to_markdown_with_options, RenderOptions, SectionMarkerStyle}; let options = RenderOptions::default() .with_section_markers(SectionMarkerStyle::Comment); let markdown = to_markdown_with_options("document.hwp", &options)?; // Each section preceded by ``` -------------------------------- ### Get Image Count Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves the number of images embedded within the parsed document. ```APIDOC ## unhwp_result_get_image_count ### Description Counts the number of images found within the parsed document. ### Method Extern function (P/Invoke) ### Endpoint N/A ### Parameters #### Path Parameters - **result** (IntPtr) - Required - The pointer to the result object. ### Response #### Success Response - **return value** (int) - The total number of images in the document. ``` -------------------------------- ### Getting Last Error Message Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves the last error message from the HWP native library. ```csharp private string? GetError() { var ptr = UnhwpNative.unhwp_result_get_error(_handle); return ptr != IntPtr.Zero ? Marshal.PtrToStringUTF8(ptr) : null; } ``` -------------------------------- ### Build Native Library for Linux Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Builds the unhwp library in release mode for Linux x64. The output is libunhwp.so. ```bash # Linux cargo build --release # Output: target/release/libunhwp.so ``` -------------------------------- ### HwpDocument.RawText Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Gets the plain text content of the HWP document. The content is loaded lazily and cached after the first access. ```APIDOC ## HwpDocument.RawText ### Description Gets the plain text content of the HWP document. The content is loaded lazily and cached after the first access. ### Method `string RawText { get; }` ### Parameters None ### Request Example ```csharp var document = HwpDocument.Parse("path/to/document.hwp"); string plainText = document.RawText; ``` ### Response #### Success Response (string) Returns the document content as plain text. #### Response Example ```text Document Title This is the content in plain text format. ``` ### Error Handling Throws `HwpException` if the document content cannot be extracted or if the document has been disposed. Throws `ObjectDisposedException` if the document object is disposed. ``` -------------------------------- ### Parse HWP Document with Conversion Options (C#) Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Demonstrates parsing an HWP document using custom conversion options, such as enabling cleanup with an aggressive preset and detecting mojibake. Useful for preparing documents for specific downstream processes like LLM training. ```csharp using Unhwp; var options = new ConversionOptions { EnableCleanup = true, CleanupPreset = CleanupPreset.Aggressive, DetectMojibake = true, IncludeFrontmatter = true }; using var doc = HwpDocument.Parse("document.hwp", options); // Write markdown to file File.WriteAllText("output.md", doc.Markdown); // Get plain text for processing string text = doc.RawText; Console.WriteLine($"Word count: ~{text.Split(' ').Length}"); ``` -------------------------------- ### HwpDocument.Markdown Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Gets the rendered Markdown content of the HWP document. The content is loaded lazily and cached after the first access. ```APIDOC ## HwpDocument.Markdown ### Description Gets the rendered Markdown content of the HWP document. The content is loaded lazily and cached after the first access. ### Method `string Markdown { get; }` ### Parameters None ### Request Example ```csharp var document = HwpDocument.Parse("path/to/document.hwp"); string markdownContent = document.Markdown; ``` ### Response #### Success Response (string) Returns the document content as a Markdown formatted string. #### Response Example ```json "# Document Title\n\nThis is the content in Markdown format." ``` ### Error Handling Throws `HwpException` if the document content cannot be rendered or if the document has been disposed. Throws `ObjectDisposedException` if the document object is disposed. ``` -------------------------------- ### Basic Usage in Browser (ES Module) Source: https://github.com/iyulab/unhwp/blob/main/unhwp-wasm/README.md Demonstrates how to initialize the WASM module and parse an HWP document fetched from a URL. It shows how to convert the parsed document to Markdown, plain text, and retrieve section and paragraph counts. ```javascript import init, { parse } from '@iyulab/unhwp'; await init(); const response = await fetch('document.hwp'); const data = new Uint8Array(await response.arrayBuffer()); const doc = parse(data); console.log(doc.toMarkdown()); console.log(doc.toText()); console.log(doc.sectionCount(), doc.paragraphCount()); ``` -------------------------------- ### Convert HWP to Markdown with Custom Render Options Source: https://github.com/iyulab/unhwp/blob/main/README.md Converts an HWP file to Markdown using `to_markdown_with_options`, allowing fine-grained control over rendering. Options include frontmatter, table fallback, heading levels, image directories, and section marker styles. ```rust use unhwp::{to_markdown_with_options, RenderOptions, SectionMarkerStyle, TableFallback}; let options = RenderOptions::default() .with_frontmatter() .with_table_fallback(TableFallback::Html) .with_max_heading_level(3) .with_image_dir("./images") .with_image_prefix("images/") .with_cleanup() // Standard cleanup .with_section_markers(SectionMarkerStyle::Comment); // let markdown = to_markdown_with_options("document.hwp", &options)?; ``` -------------------------------- ### API: Extract Plain Text from HWP Source: https://github.com/iyulab/unhwp/blob/main/bindings/python/README.md Use the `extract_text` function to get only the plain text content from an HWP/HWPX document. ```python text = unhwp.extract_text("document.hwp") ``` -------------------------------- ### Get Plain Text Content Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves the plain text content of the parsed HWP document. The text is cached after the first retrieval. ```csharp /// /// Gets the plain text content. /// public string RawText { get { ThrowIfDisposed(); if (_cachedText == null) { var ptr = UnhwpNative.unhwp_result_get_text(_handle); _cachedText = ptr != IntPtr.Zero ? Marshal.PtrToStringUTF8(ptr) ?? string.Empty : throw new HwpException(-3, GetError() ?? "Failed to extract text"); } return _cachedText; } } ``` -------------------------------- ### Build NuGet Package for C# Source: https://github.com/iyulab/unhwp/blob/main/bindings/README.md Builds the NuGet package for the C# bindings. This includes copying native libraries to the appropriate runtime directory. ```bash cd bindings/csharp # Copy native libraries mkdir -p Unhwp/runtimes/win-x64/native cp ../../target/release/unhwp.dll Unhwp/runtimes/win-x64/native/ # Build package dotnet pack Unhwp/Unhwp.csproj -c Release ``` -------------------------------- ### Get Rendered Markdown Content Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves the Markdown representation of the parsed HWP document. The content is cached after the first retrieval for performance. ```csharp /// /// Gets the rendered Markdown content. /// public string Markdown { get { ThrowIfDisposed(); if (_cachedMarkdown == null) { var ptr = UnhwpNative.unhwp_result_get_markdown(_handle); _cachedMarkdown = ptr != IntPtr.Zero ? Marshal.PtrToStringUTF8(ptr) ?? string.Empty : throw new HwpException(-3, GetError() ?? "Failed to render markdown"); } return _cachedMarkdown; } } ``` -------------------------------- ### Configure Unhwp NuGet Package in .csproj Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Specifies the necessary .NET target framework and includes native libraries for different runtimes within the project file for NuGet packaging. ```xml net10.0 enable true runtimes\win-x64\native PreserveNewest true runtimes\linux-x64\native PreserveNewest true runtimes\osx-x64\native PreserveNewest ``` -------------------------------- ### Get Unhwp Library Version Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Retrieves the current version of the Unhwp native library. This is a static method and does not require an instance of HwpConverter. ```csharp using System; namespace Unhwp { public class HwpConverter : IDisposable { // ... other methods ... /// /// Gets the library version. /// public static string Version => UnhwpNative.GetVersion(); // ... other methods ... } } ``` -------------------------------- ### Trigger Manual Publishing Workflow Source: https://github.com/iyulab/unhwp/blob/main/bindings/README.md Manually triggers the GitHub Actions workflow for publishing bindings. Requires the 'gh' CLI to be installed and authenticated. ```bash # Trigger workflow manually gh workflow run bindings.yml -f publish=true ``` -------------------------------- ### Build Native Library from Source Source: https://github.com/iyulab/unhwp/blob/main/README.md Builds the native Unhwp library from source using Cargo, enabling the `ffi` feature which is required for C# and .NET integration. This command is typically run in a Rust development environment. ```bash # Build native library from source (requires ffi feature) cargo build --release --features ffi ``` -------------------------------- ### Build Native Library for macOS Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Builds the unhwp library in release mode for macOS (Intel and Apple Silicon). The output is libunhwp.dylib. ```bash # macOS cargo build --release # Output: target/release/libunhwp.dylib ``` -------------------------------- ### API: Custom CleanupOptions Source: https://github.com/iyulab/unhwp/blob/main/bindings/python/README.md Create custom cleanup configurations by specifying options like `enabled`, `preset`, and `detect_mojibake`. ```python opts = unhwp.CleanupOptions( enabled=True, preset=1, detect_mojibake=True, ) ``` -------------------------------- ### Declare UNHWP Library Functions Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Declares external functions from the UNHWP library using P/Invoke. These include functions for getting the library version and supported formats. ```csharp [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr unhwp_version(); [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern int unhwp_supported_formats(); ``` -------------------------------- ### Build Native Library with Cargo Source: https://github.com/iyulab/unhwp/blob/main/bindings/README.md Builds the unhwp Rust library in release mode. The output location depends on the operating system. ```bash # From repository root cargo build --release # Output locations: # Windows: target/release/unhwp.dll # Linux: target/release/libunhwp.so # macOS: target/release/libunhwp.dylib ``` -------------------------------- ### Advanced Conversion for AI Training Source: https://github.com/iyulab/unhwp/blob/main/README.md Performs a comprehensive conversion of an HWP file, outputting all formats and applying aggressive cleanup suitable for AI training data preparation. ```bash # All formats + cleanup for AI training unhwp convert report.hwp --all --cleanup aggressive ``` -------------------------------- ### Convert HWP/HWPX to Markdown (Basic) Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Converts an HWP/HWPX file to Markdown format. An optional parameter `enableCleanup` can be used to perform basic cleanup during conversion. ```csharp using System; using System.IO; namespace Unhwp { public class HwpConverter : IDisposable { // ... other methods ... /// /// Converts an HWP/HWPX file to Markdown. /// public static string ToMarkdown(string path, bool enableCleanup = false) { int result; IntPtr markdownPtr, errorPtr; if (enableCleanup) { result = UnhwpNative.unhwp_to_markdown_with_cleanup( path, out markdownPtr, out errorPtr); } else { result = UnhwpNative.unhwp_to_markdown( path, out markdownPtr, out errorPtr); } if (result != UnhwpNative.UNHWP_OK) { var error = UnhwpNative.PtrToStringAndFree(errorPtr); throw new HwpException(result, error ?? "Unknown error"); } return UnhwpNative.PtrToStringAndFree(markdownPtr) ?? throw new HwpException(result, "Empty result"); } // ... other methods ... } } ``` -------------------------------- ### Implement GetVersion Helper Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Provides a helper method to retrieve the UNHWP library version as a C# string. Returns 'unknown' if the version cannot be determined. ```csharp /// /// Gets the library version. /// public static string GetVersion() { var ptr = unhwp_version(); return Marshal.PtrToStringUTF8(ptr) ?? "unknown"; } ``` -------------------------------- ### Display Version Information Source: https://github.com/iyulab/unhwp/blob/main/README.md Displays the version of the Unhwp tool. Use `--version` for the main version and `version` for detailed version information. ```bash unhwp --version # Show version unhwp version # Show detailed version info ``` -------------------------------- ### Get Raw Document Content as JSON Source: https://github.com/iyulab/unhwp/blob/main/README.md Parses an HWP file and retrieves its complete structure, including metadata, sections, styles, and tables, in JSON format. This is useful for detailed analysis or programmatic manipulation of document content. ```rust let doc = unhwp::parse_file("document.hwp")?; let json = doc.raw_content(); // JSON includes: // - metadata: title, author, created, modified // - sections: paragraphs, tables // - styles: bold, italic, underline, font, color // - tables: rows, cells, colspan, rowspan // - images, equations, links ``` -------------------------------- ### Batch Process HWP Files in a Directory Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Converts all .hwp and .hwpx files in a specified directory to Markdown, saving them to an output directory. Handles file not found and parse errors. ```csharp using Unhwp; using System.IO; using System.Threading.Tasks; async Task ProcessDirectory(string inputDir, string outputDir) { var files = Directory.GetFiles(inputDir, "*.hwp") .Concat(Directory.GetFiles(inputDir, "*.hwpx")); await Parallel.ForEachAsync(files, async (file, ct) => { try { var markdown = HwpConverter.ToMarkdown(file, enableCleanup: true); var outputPath = Path.Combine( outputDir, Path.GetFileNameWithoutExtension(file) + ".md"); await File.WriteAllTextAsync(outputPath, markdown, ct); Console.WriteLine($"Converted: {file}"); } catch (HwpException ex) { Console.WriteLine($"Error processing {file}: {ex.Message}"); } }); } ``` -------------------------------- ### API: CleanupOptions Presets Source: https://github.com/iyulab/unhwp/blob/main/bindings/python/README.md Utilize predefined presets for output cleanup: minimal, default, aggressive, or disabled. ```python # Presets opts = unhwp.CleanupOptions.minimal() opts = unhwp.CleanupOptions.default() opts = unhwp.CleanupOptions.aggressive() opts = unhwp.CleanupOptions.disabled() ``` -------------------------------- ### ConversionOptions Class Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Configuration options for converting HWP documents. ```APIDOC ## Class ConversionOptions ### Description Contains options that can be specified during the conversion of HWP documents. ### Properties #### IncludeFrontmatter - **Type**: bool - **Description**: Determines whether to include frontmatter in the conversion. Defaults to true. ``` -------------------------------- ### Convert HWP File to Directory (Default) Source: https://github.com/iyulab/unhwp/blob/main/README.md The default command for converting an HWP file. It outputs extracted content and resources into a directory. ```bash unhwp convert FILE [OPTIONS] # Convert to directory (default command) ``` -------------------------------- ### In-Memory HWP to Markdown Conversion Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Demonstrates converting HWP data from a byte array or a stream directly to Markdown format. Supports cleanup options. ```csharp using Unhwp; // From byte array byte[] hwpData = File.ReadAllBytes("document.hwp"); string markdown = HwpConverter.BytesToMarkdown(hwpData, enableCleanup: true); // From stream using var stream = File.OpenRead("document.hwp"); string markdownFromStream = HwpConverter.StreamToMarkdown(stream); ``` -------------------------------- ### UnhwpNative.unhwp_to_markdown_with_cleanup Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Converts an HWP/HWPX file to Markdown with default cleanup options applied. Includes error reporting. ```APIDOC ## unhwp_to_markdown_with_cleanup ### Description Converts the HWP/HWPX document at the specified path into Markdown format, applying default cleanup options. The output Markdown and any error messages are returned via output pointers. ### Method `unhwp_to_markdown_with_cleanup` ### Parameters #### Path Parameters - **path** (string) - Required - The file path to the HWP/HWPX document. #### Output Parameters - **outMarkdown** (IntPtr) - Output - A pointer to a null-terminated UTF-8 string containing the Markdown content. - **outError** (IntPtr) - Output - A pointer to a null-terminated UTF-8 string containing error information if the operation fails. ### Return Value - **int** - Returns UNHWP_OK on success, or an error code on failure. ``` -------------------------------- ### Convert to All Formats Source: https://github.com/iyulab/unhwp/blob/main/README.md Converts an HWP file to all available formats (Markdown, text, JSON, and images). Useful for comprehensive data extraction. ```bash unhwp convert document.hwp --all # → document_output/extract.md # → document_output/extract.txt # → document_output/content.json # → document_output/images/ ``` -------------------------------- ### Convert HWP/HWPX to Markdown (Advanced Options) Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Converts an HWP/HWPX file to Markdown using advanced conversion and cleanup options. This method allows fine-grained control over the output. ```csharp using System; using System.IO; namespace Unhwp { public class HwpConverter : IDisposable { // ... other methods ... /// /// Converts an HWP/HWPX file to Markdown with custom options. /// public static string ToMarkdown(string path, ConversionOptions options) { var renderOpts = new UnhwpNative.RenderOptions { IncludeFrontmatter = options.IncludeFrontmatter ? 1 : 0, ImagePathPrefix = IntPtr.Zero, TableFallback = (int)options.TableFallback, PreserveLineBreaks = options.PreserveLineBreaks ? 1 : 0, EscapeSpecialChars = options.EscapeSpecialChars ? 1 : 0 }; var cleanupOpts = new UnhwpNative.CleanupOptions { Enabled = options.EnableCleanup ? 1 : 0, Preset = (int)options.CleanupPreset, DetectMojibake = options.DetectMojibake ? 1 : 0, PreserveFrontmatter = options.PreserveFrontmatter ? 1 : 0 }; var result = UnhwpNative.unhwp_to_markdown_ex( path, ref renderOpts, ref cleanupOpts, out var markdownPtr, out var errorPtr); if (result != UnhwpNative.UNHWP_OK) { var error = UnhwpNative.PtrToStringAndFree(errorPtr); throw new HwpException(result, error ?? "Unknown error"); } return UnhwpNative.PtrToStringAndFree(markdownPtr) ?? throw new HwpException(result, "Empty result"); } // ... other methods ... } } ``` -------------------------------- ### Update unhwp using built-in mechanism Source: https://github.com/iyulab/unhwp/blob/main/README.md Demonstrates commands for checking for, applying, and forcing the update of the unhwp tool. The update process is automated and platform-aware. ```bash # Check for updates unhwp update --check # Update to latest version unhwp update # Force reinstall (even if on latest) unhwp update --force ``` -------------------------------- ### API: RenderOptions for Markdown Source: https://github.com/iyulab/unhwp/blob/main/bindings/python/README.md Configure Markdown rendering options like frontmatter inclusion, image path prefixes, and line break preservation. ```python opts = unhwp.RenderOptions( include_frontmatter=True, image_path_prefix="images/", preserve_line_breaks=False, ) ``` -------------------------------- ### ConversionOptions Class Definition Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Configuration options for converting HWP documents to Markdown. ```csharp /// /// Conversion options for HWP to Markdown. /// public class ConversionOptions { public bool IncludeFrontmatter { get; set; } = true; } ``` -------------------------------- ### HwpConverter.ToMarkdown (Basic) Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Converts an HWP/HWPX file to Markdown. ```APIDOC ## HwpConverter.ToMarkdown (Basic) ### Description Converts an HWP/HWPX file to Markdown. ### Method `static string ToMarkdown(string path, bool enableCleanup = false)` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the HWP/HWPX file. - **enableCleanup** (bool) - Optional - Whether to enable cleanup of the output Markdown. Defaults to false. ### Response - **Markdown** (string) - The converted Markdown content. ### Error Handling Throws `HwpException` if the conversion fails. ``` -------------------------------- ### Show Document Metadata Source: https://github.com/iyulab/unhwp/blob/main/README.md Displays metadata information about an HWP file, such as author, title, and creation date. ```bash unhwp info FILE # Show document metadata ``` -------------------------------- ### UnhwpNative.unhwp_to_markdown_ex Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Converts an HWP/HWPX file to Markdown with custom rendering and cleanup options. Provides detailed control over the conversion process. ```APIDOC ## unhwp_to_markdown_ex ### Description Converts the HWP/HWPX document at the specified path into Markdown format using extended options for rendering and cleanup. This function allows for fine-grained control over the conversion process. ### Method `unhwp_to_markdown_ex` ### Parameters #### Path Parameters - **path** (string) - Required - The file path to the HWP/HWPX document. #### Input Parameters - **renderOptions** (ref RenderOptions) - Required - Structure containing rendering options. - **cleanupOptions** (ref CleanupOptions) - Required - Structure containing cleanup options. #### Output Parameters - **outMarkdown** (IntPtr) - Output - A pointer to a null-terminated UTF-8 string containing the Markdown content. - **outError** (IntPtr) - Output - A pointer to a null-terminated UTF-8 string containing error information if the operation fails. ### Return Value - **int** - Returns UNHWP_OK on success, or an error code on failure. ``` -------------------------------- ### Parse HWP Document and Access Properties (C#) Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Demonstrates parsing an HWP document once and accessing various properties like Markdown, RawText, Images, and document structure. Useful for quick access to common document elements. ```csharp using Unhwp; // Parse document once, access multiple properties using var doc = HwpDocument.Parse("document.hwp"); // Access properties like result.Markdown, result.RawText, result.RawContent, result.Images Console.WriteLine($"Markdown length: {doc.Markdown.Length}"); Console.WriteLine($"Raw text preview: {doc.RawText[..100]}..."); Console.WriteLine($"Image count: {doc.Images.Count}"); Console.WriteLine($"Sections: {doc.SectionCount}, Paragraphs: {doc.ParagraphCount}"); // Access structured JSON with full metadata (formatting, styles, etc.) string jsonContent = doc.RawContent; Console.WriteLine($"JSON content length: {jsonContent.Length}"); // Save all images foreach (var image in doc.Images) { image.SaveTo($"./images/{image.Name}"); Console.WriteLine($"Saved: {image.Name} ({image.Size} bytes)"); } ``` -------------------------------- ### Build Python Wheel Package Source: https://github.com/iyulab/unhwp/blob/main/bindings/README.md Builds the Python wheel package for the unhwp library. This involves copying the native library and using the 'build' tool. ```bash cd bindings/python # Copy native library mkdir -p src/unhwp/lib/win-x64 cp ../../target/release/unhwp.dll src/unhwp/lib/win-x64/ # Build wheel pip install build python -m build ``` -------------------------------- ### Convert HWP to Markdown (stdout or file) Source: https://github.com/iyulab/unhwp/blob/main/README.md Converts an HWP file to Markdown format. Output can be directed to standard output or a specified file using the -o option. ```bash unhwp md FILE [-o OUTPUT] # Convert to Markdown (stdout or file) ``` -------------------------------- ### Convert to Specific Formats Source: https://github.com/iyulab/unhwp/blob/main/README.md Converts an HWP file to specified formats, in this case, Markdown and plain text. ```bash unhwp convert document.hwp --formats md,txt ``` -------------------------------- ### API: Convert HWP to Markdown with Cleanup Source: https://github.com/iyulab/unhwp/blob/main/bindings/python/README.md Converts HWP documents to Markdown with optional cleanup using `to_markdown_with_cleanup` and `CleanupOptions`. ```python markdown = unhwp.to_markdown_with_cleanup( "document.hwp", cleanup_options=unhwp.CleanupOptions.aggressive() ) ``` -------------------------------- ### Access and Parse Raw JSON Content (C#) Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Shows how to retrieve the full structured content of an HWP document as JSON and then parse it using System.Text.Json for programmatic access to metadata, sections, paragraphs, and text formatting. ```csharp using Unhwp; using System.Text.Json; using var doc = HwpDocument.Parse("document.hwp"); // Get full structured content as JSON // Includes: metadata, sections, paragraphs, text runs with formatting, // tables, images, equations, hyperlinks, styles, and more string jsonContent = doc.RawContent; // Parse JSON for programmatic access using var jsonDoc = JsonDocument.Parse(jsonContent); var root = jsonDoc.RootElement; // Access metadata if (root.TryGetProperty("metadata", out var metadata)) { var title = metadata.GetProperty("title").GetString(); var author = metadata.GetProperty("author").GetString(); Console.WriteLine($"Title: {title}, Author: {author}"); } // Iterate through sections and paragraphs if (root.TryGetProperty("sections", out var sections)) { foreach (var section in sections.EnumerateArray()) { var content = section.GetProperty("content"); foreach (var block in content.EnumerateArray()) { if (block.TryGetProperty("Paragraph", out var para)) { // Access paragraph style (heading level, alignment, etc.) var style = para.GetProperty("style"); var headingLevel = style.GetProperty("heading_level").GetInt32(); // Access text runs with formatting var runs = para.GetProperty("content"); foreach (var run in runs.EnumerateArray()) { if (run.TryGetProperty("Text", out var textRun)) { var text = textRun.GetProperty("text").GetString(); var runStyle = textRun.GetProperty("style"); var isBold = runStyle.GetProperty("bold").GetBoolean(); var isItalic = runStyle.GetProperty("italic").GetBoolean(); Console.WriteLine($"Text: {text} (bold={isBold}, italic={isItalic})"); } } } } } } // Save JSON to file for external processing File.WriteAllText("document.json", jsonContent); ``` -------------------------------- ### Conversion Options Class Source: https://github.com/iyulab/unhwp/blob/main/docs/csharp-integration.md Defines configurable options for HWP conversion, including fallback behavior, line break preservation, character escaping, and cleanup settings. ```csharp public TableFallback TableFallback { get; set; } = TableFallback.SimplifiedMarkdown; public bool PreserveLineBreaks { get; set; } = false; public bool EscapeSpecialChars { get; set; } = true; public bool EnableCleanup { get; set; } = false; public CleanupPreset CleanupPreset { get; set; } = CleanupPreset.Default; public bool DetectMojibake { get; set; } = true; public bool PreserveFrontmatter { get; set; } = true; public static ConversionOptions Default => new ConversionOptions(); public static ConversionOptions WithCleanup => new ConversionOptions { EnableCleanup = true, CleanupPreset = CleanupPreset.Default }; public static ConversionOptions AggressiveCleanup => new ConversionOptions { EnableCleanup = true, CleanupPreset = CleanupPreset.Aggressive }; } ```