htmltoword Ruby Gem

repository·master·Indexed 41 days ago

https://github.com/karnov/htmltoword

A Ruby gem that converts HTML documents into Microsoft Word (.docx) files, designed for generating dynamic reports and forms. It includes a Rails integration providing an action controller renderer for .docx formats, support for custom .docx templates, and XSLT configuration. Features include support for page breaks, text highlighting, text alignment, and table formatting with customizable cell borders and fills.

Tokens
3.8K
Snippets
16
Records
20
Agent score
51%

What's inside htmltoword

  1. Integrate htmltoword with Rails

    master

    For htmltoword version >= 0.2, an action controller renderer is provided. You can respond to the .docx format directly. The gem will look for views with the .docx.erb extension.

    Using View Templates

    Create a view file named my_view.docx.erb. This file contains the HTML structure that will be converted into the Word document.

    Example my_view.docx.erb:

    <h1 class="custom-title"> My custom template </h1>
    <%= render partial: 'my_partial', collection: @objects, as: :item %>

    Controller Implementation

    You can use respond_with or the render docx: syntax.

    Using respond_with:

    def my_action
      respond_with(@object, filename: 'my_file.docx', word_template: 'my_template.docx')
    end

    Using render docx::

    def my_action2
      respond_to do |format|
        format.docx do
          render docx: 'my_view', filename: 'my_file.docx'
        end
      end
    end

    Direct HTML Content: If you don't want to use a .docx.erb template, you can pass the HTML string directly via the content key:

    render docx: 'my_file.docx', content: '<html><body><h1>Hello</h1></body></html>'
    def my_action
      respond_to :docx
      # ...
      respond_with(@object, filename: 'my_file.docx', word_template: 'my_template.docx')
    end
  2. Apply page breaks and text highlighting

    master

    You can control document flow and text emphasis using specific HTML elements and classes:

    Page Breaks

    Insert a page break by using a div with the -page-break class:

    <div class="-page-break"></div>

    Text Highlighting

    To highlight text, use a span with the class h and provide a color via the data-style attribute.

    Valid color values: black, blue, cyan, green, magenta, red, yellow, white, darkBlue, darkCyan, darkGreen, darkMagenta, darkRed, darkYellow, darkGray, lightGray, or none.

    <span class="h" data-style="yellow">Highlighted Text Here</span>
    <div class="-page-break"></div>
    <span class="h" data-style="yellow">Highlighted Text Here</span>
  3. Format tables and cell borders

    master

    The gem provides basic support for tables using standard tags (thead, tbody, tr, th, td, h1...h6).

    Table Borders

    Use the class table-bordered to apply a default black, single-line border (weight of 6).

    Cell Borders

    Customize individual cell borders using the class pattern: ms-border-[location]-[value]-[color]-[size].

    [location]

    Specifies where the border is applied:

    • top
    • bottom
    • start (left in LTR)
    • end (right in LTR)
    • insideH (interior horizontal edges)
    • insideV (interior vertical edges)
    • tl2br (top-left to bottom-right diagonal)
    • tr2bl (top-right to bottom-left diagonal)

    [value]

    Specifies the border style (e.g., single, dashed, dotted, double, thick, doubleWave, wave, etc.).

    [color]

    Hex values in RRGGBB format (do not include the # prefix). Example: FFFF00. The value auto is also permitted.

    [size]

    Specifies the width. Note that the gem multiplies the supplied value by 6. If 0 or nothing is provided, it defaults to 6.

    Cell Fill

    Use the class ms-fill-[color] to set the background color of a cell.

    <!-- Example: A thick, red, bottom border on a cell -->
    <td class="ms-border-bottom-thick-FF0000-1">Cell Content</td>
    
    <!-- Example: Cell with yellow fill -->
    <td class="ms-fill-FFFF00">Filled Cell</td>
  4. How Htmltoword::Document handles images

    master

    The Htmltoword::Document class automatically processes images found in the HTML content to embed them into the resulting .docx file.

    Image Processing Logic:

    1. Detection: The library scans <img> tags in the provided HTML.
    2. Source: It uses the src attribute of the image tag. If a data-filename attribute is present, it is used to determine the filename; otherwise, it extracts the filename from the src URL.
    3. Embedding: Images are streamed into the word/media/ directory of the .docx zip structure using open-uri.
    4. Content Types: The library automatically updates the [Content_Types].xml file within the .docx structure to ensure the new image extensions (e.g., .jpg, .png) are recognized by Word.
  5. Configure custom templates path

    master

    If you want to use your own .docx files as templates (to define custom styles for h1, h2, etc.), you must configure the custom_templates_path in the Htmltoword configuration.

    require 'htmltoword'
    
    # Configure the location of your custom templates
    Htmltoword.config.custom_templates_path = 'some_path'
    
    my_html = '<html><head></head><body><p>Hello</p></body></html>'
    
    # Use the custom template
    file = Htmltoword::Document.create_and_save(my_html, 'output.docx', 'my_custom_template.docx')
  6. Configure global template and XSLT paths

    master

    From version 2.0, you can use a configuration block to set paths for default and custom templates and XSLT files.

    • custom_templates_path: Path for your custom .docx templates.
    • default_templates_path: Path for default templates (must contain a default.docx file).
    • default_xslt_path: Path for the html_to_wordml.xslt file.
    • custom_xslt_path: Path for additional custom XSLT files.
    Htmltoword.configure do |config|
      config.custom_templates_path = 'path_for_custom_templates'
      config.default_templates_path = 'path_for_default_template'
      config.default_xslt_path = 'some_path'
      config.custom_xslt_path = 'some_path'
    end
  7. Render DOCX files in Rails controllers

    master

    After integration, you can trigger a Word document download from a controller action in two ways:

    1. Using render :docx

    You can use the standard render method. By default, it uses the current action name as the filename and the gem's default template.

    render docx: 'custom_filename'

    2. Using to_docx

    If ActionController::Responder is present, you can call to_docx directly on the responder. This is a shorthand for rendering the current action as a docx file.

    # Inside a controller action
    # This will render the current action name as the filename
    to_docx
    
    # Or with custom options
    to_docx filename: 'my_report', word_template: 'templates/report.docx.erb'
    # Using render
    render docx: 'custom_filename'
    
    # Using the to_docx responder
    to_docx
    
    # Using to_docx with options
    to_docx filename: 'my_report', word_template: 'templates/report.docx.erb'
  8. Integrate htmltoword with Rails

    master

    The htmltoword gem provides a Railtie that automatically registers the :docx MIME type and adds a renderer to ActionController.

    Once the gem is included in your Rails application, you can render .docx files directly from your controllers using the render :docx syntax or the to_docx responder method.

  9. Use Htmltoword::Document to create and save files

    master

    The Htmltoword::Document class provides two primary methods for converting HTML to Word documents:

    1. create(html_string, [template_name]): Returns the document contents as a string. Use this if you want to handle the raw file data manually.
    2. create_and_save(html_string, file_path, [template_name]): Creates the .docx file and saves it directly to the specified file_path.

    Note: Since version 0.4.0, create returns a string. If you need to save the file to disk, you must use create_and_save.

    require 'htmltoword'
    
    my_html = '<html><head></head><body><p>Hello</p></body></html>'
    
    # Returns a string containing the file contents
    document = Htmltoword::Document.create(my_html)
    
    # Saves the file to the specified path
    file = Htmltoword::Document.create_and_save(my_html, 'path/to/output.docx')
  10. Configure template and XSLT paths in Htmltoword

    master

    The Htmltoword::Configuration class allows you to define where the gem looks for default and custom templates and XSLT files. You can set the following attributes using their accessors:

    • default_templates_path: The directory containing the gem's built-in templates.
    • custom_templates_path: The directory where your application's custom .docx.erb templates are located.
    • default_xslt_path: The directory containing the gem's built-in XSLT files.
    • custom_xslt_path: The directory where your application's custom XSLT files are located.

    By default, both custom and default paths are initialized to the gem's internal templates and xslt directories.

    config = Htmltoword::Configuration.new
    config.custom_templates_path = '/path/to/your/templates'
    config.custom_xslt_path = '/path/to/your/xslt'