Export Plugin

  • Tags: report, xml, pdf, csv, rtf, grails2
  • Latest: 1.6
  • Last Updated: 14 May 2014
  • Grails version: 1.3 > *
42 votes

10% of Grails users

Dependency:
compile ":export:1.6"

 Documentation  Source  Issues

Summary

This plugin offers export functionality supporting different formats e.g. CSV, Excel, Open Document Spreadsheet, PDF and XML and can be extended to add additional formats.

Installation

grails install-plugin export

Description

Export Plugin

Author: Andreas Schmitt

Abstract

This plugin allows you to export domain objects to a variety of formats. Currently supported are CSV, Excel, ODS (Open Document Spreadsheets), PDF, RTF and XML. It can be easily extended to support further formats.

Installation

To install the plugin type:> grails install-plugin export

Add MimeTypes for CSV, Excel, ODS, PDF and RTF to grails-app/conf/Config.groovy so that it looks similar to:

grails.mime.types = [ html: ['text/html','application/xhtml+xml'],
                      xml: ['text/xml', 'application/xml'],
                      text: 'text-plain',
                      js: 'text/javascript',
                      rss: 'application/rss+xml',
                      atom: 'application/atom+xml',
                      css: 'text/css',
                      csv: 'text/csv',
                      pdf: 'application/pdf',
                      rtf: 'application/rtf',
                      excel: 'application/vnd.ms-excel',
                      ods: 'application/vnd.oasis.opendocument.spreadsheet',
                      all: '*/*',
                      json: ['application/json','text/json'],
                      form: 'application/x-www-form-urlencoded',
                      multipartForm: 'multipart/form-data'
                    ]

Usage

Export plugin uses resource plugin to provide resources (since version 1.1). Add the following markup to your GSP header:

<r:require module="export"/>

To use the export features in plugin versions up to 1.0 add the following markup to your GSP header:

<export:resource />

This will include the necessary CSS files for the export bar. The icons used for the export bar are from Mark James

http://www.famfamfam.com/lab/icons/silk/.

Add the export bar to your GSP page e.g. below the paginate buttons:

…
<div class="paginateButtons">
    <g:paginate total="${Book.count()}" />
</div>

<export:formats />

or

<export:formats formats="['csv', 'excel', 'ods', 'pdf', 'rtf', 'xml']" />

</div> ...

The formats tag supports the following attributes and allows you to pass through HTML attributes:

  • formats (Formats which should be displayed, List of Strings, e.g. ['csv', 'excel', 'ods', 'pdf', 'rtf', 'xml'])
  • params (Additional request parameters, Map, e.g. [sort: params?.sort, order: params?.order])
  • action (Action which should be called, defaults to current action)
  • controller (Controller which should be called, defaults to current controller)
You can customize the labels displayed on the export bar by adding the following lines to grails-app/i18n/messages.properties:

default.csv=CSV
default.excel=Excel
default.pdf=PDF
default.rtf=RTF
default.xml=XML
default.ods=ODS

To make the plugin work you need to add some code to your controller:

class BookController {

// Export service provided by Export plugin def exportService def grailsApplication //inject GrailsApplication ...

def list = { if(!params.max) params.max = 10

if(params?.format && params.format != "html"){ response.contentType = grailsApplication.config.grails.mime.types[params.format] response.setHeader("Content-disposition", "attachment; filename=books.${params.extension}")

exportService.export(params.format, response.outputStream,Book.list(params), [:], [:]) }

[ bookInstanceList: Book.list( params ) ] }

} ...

This will export all book objects with all attributes except version. You can also configure which attributes should be exported. The following example will rely on a simple domain class:

class Book {

String title String author }

And now for the controller code:

class BookController {

def exportService def grailsApplication //inject GrailsApplication ...

def list = { if(!params.max) params.max = 10

if(params?.format && params.format != "html"){ response.contentType = grailsApplication.config.grails.mime.types[params.format] response.setHeader("Content-disposition", "attachment; filename=books.${params.extension}")

List fields = ["author", "title"] Map labels = ["author": "Author", "title": "Title"]

/* Formatter closure in previous releases def upperCase = { value -> return value.toUpperCase() } */

// Formatter closure def upperCase = { domain, value -> return value.toUpperCase() }

Map formatters = [author: upperCase] Map parameters = [title: "Cool books", "column.widths": [0.2, 0.3, 0.5]]

exportService.export(params.format, response.outputStream, Book.list(params), fields, labels, formatters, parameters) }

[ bookInstanceList: Book.list( params ) ] }

} ...

You can see how the fields are now set explicitly. You can use labels to customize the output of the fields e.g. for i18n. Using formatters it is possible to customize how the resulting values are generated which can be used to specify a particular date format etc. by just mapping an attribute name to a closure. It is also possible to specify nonexistant fields and add formatters for those fields to produce static content like today's date.

Version 0.7 changes formatter closures. To upgrade from a previous release you need to add the domain argument to your closures as shown in the code sample below.

With the new formatter closure you can combine multiple attributes:

// Formatter closure
                        def title = { domain, value ->
				return domain?.author + ": " + domain?.title
			}

PDF export supports some additonal parameters which can be used just like the title attribute in the code sample above. The following parameters are supported:

  • pdf.encoding (specifies font encoding, defaults to "Cp1252" (=latin 1), allowed values: "Cp1250", "Cp1252" (=latin 2), "Cp1257", "Identity-H", "Identity-V", "MacRoman") see http://itextdocs.lowagie.com/tutorial/fonts/index.php for further information about encodings
  • title.encoding (same as pdf.encoding but for title font)
  • header.encoding (same as pdf.encoding but for header font)
  • text.encoding (same as pdf.encoding but for text font)
  • title.font.size (determines title font size, defaults to "10",allowed values: a number as String)
  • header.font.size (determines header font size, defaults to "10", allowed values: a number as String)
  • text.font.size (determines text font size, defaults to "10", allowed values: a number as String)
  • font.family (determines global font family, allowed values: constants defined in http://www.1t3xt.info/api/com/lowagie/text/FontFactory.html)
  • title.font.family (determines title font family, defaults to com.lowagie.text.FontFactory.HELVETICA, allowed values: constants defined in http://www.1t3xt.info/api/com/lowagie/text/FontFactory.html)
  • header.font.family (determines header font family, defaults to com.lowagie.text.FontFactory.HELVETICA, allowed values: constants defined in http://www.1t3xt.info/api/com/lowagie/text/FontFactory.html)
  • text.font.family (determines text font family, defaults to com.lowagie.text.FontFactory.HELVETICA, allowed values: constants defined in http://www.1t3xt.info/api/com/lowagie/text/FontFactory.html)
  • title.font.style (determines title font style, defaults to "bold", allowed values: "bold", "italic", "normal", "bolditalic")
  • header.font.style (determines header font style, defaults to "bold", allowed values: "bold", "italic", "normal", "bolditalic")
  • text.font.style (determines text font style, defaults to "normal", allowed values: "bold", "italic", "normal", "bolditalic")
  • border.color (determines table border color, defaults to: new Color(163, 163, 163), allowed values: a java.awt.Color object e.g. Color.RED)
  • separator.color (determines table row separator color, defaults to: new Color(238, 238, 238), allowed values: a java.awt.Color object e.g. new Color(100, 100, 100))
  • column.widths (specifies column widths in percent, defaults to equal size for all columns, allowed values: List of floats e.g.
    [0.2, 0.3, 0.5]
    for three columns)
  • header.rows (number of header rows, defaults to 1, allowed values: a number as String)
  • header (header fields, defaults to fields, allowed values: list of list of Strings e.g.
    [["Intended times"], ["Actual times", "Duration"]]
    )
  • header.parameters (header parameters currently supported colspan, defaults to no colspan, allowed values: list of maps e.g.
    [["colspan0": 3], ["colspan0": 1, "colspan1": 2]]
    )
  • pdf.orientation (page orientation, defaults to landscape, allowed values: "portrait")
  • header.enabled (enable/disable header output, boolean true or false, defaults to true)
For chinese characters in PDF use the following parameters:

...

Map parameters = ["pdf.encoding":"UniGB-UCS2-H", "font.family": "STSong-Light"]

...

CSV export also supports some additional parameters:

  • encoding (encoding, defaults to JVM default encoding, allowed values: http://java.sun.com/javase/6/docs/api/java/nio/charset/Charset.html e.g. "UTF-8")
  • separator (specifies the field separator char, defaults to ';', allowed values: a single character)
  • quoteCharacter (specifies the quote character, defaults to '"', use 'u0000' for no quote character and put a slash before the four 0s, allowed values: a single character)
  • lineEnd (specifies the line ending, defaults to the default platform line ending, allowed values: a String e.g. "rn")
  • header.enabled (enable/disable header output, boolean true or false, defaults to true)
Excel
  • column.widths (specifies column widths in percent, defaults to equal size for all columns, allowed values: List of floats e.g.
    [0.2, 0.3, 0.5]
    for three columns)
  • header.enabled (enable/disable header output, boolean true or false, defaults to true)
RTF
  • supports mainly the same parameters as PDF
  • rtf.encoding (specifies font encoding, defaults to "Cp1252" (=latin 1), allowed values: "Cp1250", "Cp1252" (=latin 2), "Cp1257", "Identity-H", "Identity-V", "MacRoman") see http://itextdocs.lowagie.com/tutorial/fonts/index.php for further information about encodings
  • title.encoding (same as rtf.encoding but for title font)
  • header.encoding (same as rtf.encoding but for header font)
  • text.encoding (same as rtf.encoding but for text font)
  • header.enabled (enable/disable header output, boolean true or false, defaults to true)
XML
  • encoding (encoding, defaults to JVM default encoding, allowed values: http://java.sun.com/javase/6/docs/api/java/nio/charset/Charset.html e.g. "UTF-8")
  • xml.root (specify root element name, defaults to object class name, a String)
  • depth (depth (as integer) for building tree affects how collections and relationships are exported, defaults to 1, 1 means only direct domain attributes 2 or more collection attributes as well)

Plugin version history ^

  • July, 18, 2012 (version 1.5)
    • more hidden internal domain attributes excluded
  • July, 18, 2012 (version 1.4)
    • Missing shadow.jpg file added
  • May, 18, 2012 (version 1.3)
    • Option to disable header output added (header.enabled)
  • May, 2, 2012 (version 1.2)
    • Exporter caching fields issue fixed
  • February, 11, 2012 (version 1.1)
    • Support for resources plugin added
    • ConfigurationHolder removed
  • July, 10, 2011 (version 1.0)
    • bug fixes
    • Excel now converts URLs to hyperlinks
  • March, 13, 2011 (version 0.9)
    • bug fixes
    • Excel now supports title and column widths parameters
  • January, 16, 2011 (version 0.8)
    • bug fixes
    • PDF support for multiple header rows and page orientation
    • DSL dependency management
  • April, 10, 2010 (version 0.7)
    • multiple bug fixes
    • enhanced formatter closure with access to the current domain object
    • CSV
      • encoding (text encoding)
    • PDF
      • font.family (global font family setting)
      • title.encoding (encoding for title font)
      • header.encoding (encoding for header font)
      • text.encoding (encoding for text font)
      • pdf.encoding (global font encoding)
      • column.widths (allows to set different column widths)
    • RTF
      • font.family (global font family setting)
      • title.encoding (encoding for title font)
      • header.encoding (encoding for header font)
      • text.encoding (encoding for text font)
      • rtf.encoding (global font encoding)
      • column.widths (allows to set different column widths)
    • XML
      • encoding (text encoding)
      • xml.root (specify root element name)
      • depth (depth for building tree affects how collections and relationships are exported)
  • November, 7, 2009 (version 0.6)
    • Better support for inherited domain class attributes
  • September 28, 2009 (version 0.5)
    • ODS export issues fixed
  • August 15, 2009 (version 0.4)
    • CSV
      • quoteChar fixed
      • lineEnd added
    • PDF
      • border.color added
      • separator.color added
  • May 31, 2009 (version 0.3)
    • Excel file extension is now xls
    • RTF export added
    • Null values are now treated gracefully
    • Specify nonexistant fields and create output for them with closures e.g. for static content like today's date
  • Apr. 16, 2009 (version 0.2)
    • Issue with missing xercesImpl.jar fixed
    • Additional output parameters to PDF export added e.g. encoding, font size
  • Feb. 15, 2009 (version 0.1)
    • Initial version released
    • Supported formats
      • CSV
      • Excel
      • ODS
      • PDF
      • XML