PdfExport

Generates PDF/PNG files from the Grid component.

A server-side service is required to perform the export operation. Check out PDF Export Server documentation and installation steps here

When your server is up and running, it listens to requests. The Export feature sends a request to the specified URL with the HTML fragments. The server generates a PDF (or PNG) file and returns a download link (or binary, depending on sendAsBinary config). Then the Export feature opens the link in a new tab and the file is automatically downloaded by your browser. This is configurable, see openAfterExport config.

The exportServer URL must be configured. The URL can be localhost if you start the server locally, or your remote server address.

This feature will not work properly when Store uses lazyLoad

Usage

const grid = new Grid({
    features : {
        pdfExport : {
            exportServer : 'http://localhost:8080' // Required
        }
    }
})

// Opens popup allowing to customize export settings
grid.features.pdfExport.showExportDialog();

// Simple export
grid.features.pdfExport.export({
    columns : grid.columns.map(c => c.id)
}).then(result => {
    // Response instance and response content in JSON
    let { response } = result;
});

Exporting large datasets

PDF Export feature supports streaming generated pages using WebSocket connection. If server does not support it, then feature will use single HTTP request with all the data. For big datasets that can lead to page crashing when running out of memory. WebSocket support allows feature to send pages to the server one by one and then wait for the server to respond with a link to the file or the file itself.

Feature will check API status of the export server and starting from version 2.0.1, the server response will allow WebSocket connections.

Exporters

There are three exporters available by default: singlepage, multipage and multipagevertical:

  • singlepage - generates single page with content scaled to fit the provided paperFormat
  • multipage - generates as many pages as required to fit all requested content, unscaled
  • multipagevertical - a combination of two above: it scales content horizontally to fit into page width and then puts overflowing content on vertical pages. Like a scroll.

Loading resources

If you face a problem with loading resources when exporting, the cause might be that the application and the export server are hosted on different servers. This is due to Cross-Origin Resource Sharing (CORS). There are 2 options how to handle this:

  • Allow cross-origin requests from the server where your export is hosted to the server where your application is hosted;
  • Copy all resources keeping the folder hierarchy from the server where your application is hosted to the server where your export is hosted and setup paths using translateURLsToAbsolute config and configure the export server to give access to the path:
const grid = new Grid({
    features : {
        pdfExport : {
            exportServer : 'http://localhost:8080',
            // '/resources' is hardcoded in WebServer implementation
            translateURLsToAbsolute : 'http://localhost:8080/resources'
        }
    }
})
// Following path would be served by this address: http://localhost:8080/resources/
node ./src/server.js -h 8080 -r web/application/styles

where web/application/styles is a physical root location of the copied resources, for example:

Export server structure with copied
resources

This feature is disabled by default. For info on enabling it, see GridFeatures.

Configs

37

Common

disabledInstancePlugin
listenersEvents

Export file config

fileFormat: pdf | png= pdf

Format of the exported file, either pdf or png.

fileName: String

Name of the exported file.

orientation: portrait | landscape= portrait

Orientation. Options are portrait and landscape.

paperFormat: A0 | A1 | A2 | A3 | A4 | A5 | Legal | Letter= A4

Export paper format. Available options are A1...A5, Legal, Letter.

rowsRange: all | visible= all

Specifies which rows to export. all for complete set of rows, visible for only rows currently visible.

Other

alignRows: Boolean= false

Set to true to align row top to the page top on every exported page. Only applied to multipage export.

clientURL: String

Export server will navigate to this url first and then will change page content to whatever client sent. This option is useful with react dev server, which uses a strict CORS policy.

A config object to apply to the ExportDialog widget.

exporters: Exporter[]= ["SinglePageExporter","SinglePageUnscaledExporter","MultiPageExporter","MultiPageVerticalExporter"]

List of exporter classes to use in export feature

exporterType: singlepage | singlepageunscaled | multipage | multipagevertical | String= singlepage

Type of the exporter to use. Should be one of the configured exporters

exportMask: String= "Generating pages..."

A message to be shown when Export feature is performing export.

exportProgressMask: String= "Waiting for response from server..."

A message to be shown when export is almost done.

exportServer: String

URL of the print server.

An object containing the Fetch options to pass to the export server request. Use this to control if credentials are sent and other options, read more at MDN.

footerTpl: function

A template function used to generate a page footer. It is passed an object with ´currentPage´ and `totalPages´ properties.

let grid = new Grid({
     appendTo   : 'container',
     features : {
         pdfExport : {
             exportServer : 'http://localhost:8080/',
             footerTpl    : () => '<div class="demo-export-footer"><h3>© 2020 CoolCorp Inc</h3></div>'
         }
     }
});
ParameterTypeDescription
dataObject

Data object

data.currentPageNumber

Current page number

data.totalPagesNumber

Tolal pages count

Returns: String
headerTpl: function

A template function used to generate a page header. It is passed an object with ´currentPage´ and `totalPages´ properties.

let grid = new Grid({
    appendTo   : 'container',
    features : {
        pdfExport : {
            exportServer : 'http://localhost:8080/',
            headerTpl : ({ currentPage, totalPages }) => `
                <div class="demo-export-header">
                    <img src="coolcorp-logo.png"/>
                    <dl>
                        <dt>Date: ${DateHelper.format(new Date(), 'll LT')}</dt>
                        <dd>${totalPages ? `Page: ${currentPage + 1}/${totalPages}` : ''}</dd>
                    </dl>
                </div>`
         }
    }
});
ParameterTypeDescription
dataObject

Data object

data.currentPageNumber

Current page number

data.totalPagesNumber

Tolal pages count

Returns: String
keepPathName: Boolean= true

When true links are converted to absolute by combining current window location (with replaced origin) with resource link. When false links are converted by combining new origin with resource link (for angular)

keepRegionSizes: Object<String, Boolean>

By default, subGrid width is changed to fit all exported columns. To keep certain subGrid size specify it in the following form:

keepRegionSizes : {
    locked : true
}
lockPaperSize: Boolean= false

Defines if printed/exported page should contain @page style with paper size and orientation specified.

openAfterExport: Boolean= true

When true, page will attempt to download generated file.

openInNewTab: Boolean= false

False to open in the current tab, true - in a new tab

repeatHeader: Boolean= false

Set to true to show column headers on every page. This will also set alignRows to true. Only applies to MultiPageVertical exporter.

A function that determines when to capture the HTML for exported rows. When set to null (the default), the export happens immediately without waiting. The function receives the export configuration as a parameter. The rendering process works in chunks, using the same approach as the Grid component - displaying visible rows with an additional buffer.

Examples:

// simple timeout
new Grid({
    features : {
        pdfExport : {
            rowReadyCondition : async () => await new Promise(resolve => setTimeout(resolve, 100))
        }
    }
});

// waiting for a condition
new Grid({
    features : {
        pdfExport : {
            rowReadyCondition : async () => await promiseWithCondition
        }
    }
});
Returns: void
sendAsBinary: Boolean= false

Set to true to receive binary file from the server instead of download link.

showErrorToast: Boolean= true

Set to false to not show Toast message on export error.

translateURLsToAbsolute: Boolean | String= true

True to replace all linked CSS files URLs to absolute before passing HTML to the server. When passing a string the current origin of the CSS files URLS will be replaced by the passed origin.

For example: css files pointing to /app.css will be translated from current origin to {translateURLsToAbsolute}/app.css

Determines whether to stream exported pages directly to the export server using WebSocket connection to offload client application. false - use legacy mode which first collected all pages locally and then passed them in a single request true - stream pages directly to the server null (default) - ask export server for WebSocket support and use it if possible

Maximum time in ms to wait for the response over the websocket connection

Misc

clientInstancePlugin
localeClassLocalizable
localizableLocalizable

Properties

21

Common

disabledInstancePlugin

Class hierarchy

isPdfExport: Boolean= truereadonly
Identifies an object as an instance of PdfExport class, or subclass thereof.
isPdfExport: Boolean= truereadonlystatic
Identifies an object as an instance of PdfExport class, or subclass thereof.
isEventsEvents
isInstancePluginInstancePlugin
isLocalizableLocalizable

Other

currentExportPromise: Promise | null

When export is started from GUI (ExportDialog), export promise can be accessed via this property.

Returns the instantiated export dialog widget as configured by exportDialog

isExporting: Booleanreadonly

This yields true if an export/print operation is ongoing.

A function that determines when to capture the HTML for exported rows. When set to null (the default), the export happens immediately without waiting. The function receives the export configuration as a parameter. The rendering process works in chunks, using the same approach as the Grid component - displaying visible rows with an additional buffer.

Examples:

// simple timeout
new Grid({
    features : {
        pdfExport : {
            rowReadyCondition : async () => await new Promise(resolve => setTimeout(resolve, 100))
        }
    }
});

// waiting for a condition
new Grid({
    features : {
        pdfExport : {
            rowReadyCondition : async () => await promiseWithCondition
        }
    }
});
Returns: void

Determines whether to stream exported pages directly to the export server using WebSocket connection to offload client application. false - use legacy mode which first collected all pages locally and then passed them in a single request true - stream pages directly to the server null (default) - ask export server for WebSocket support and use it if possible

Maximum time in ms to wait for the response over the websocket connection

Lifecycle

configBase

Misc

clientInstancePlugin
localeHelperLocalizable
localeManagerLocalizable

Functions

33

Other

Starts the export process. Accepts a config object which overrides any default configs. NOTE. Component should not be interacted with when export is in progress

ParameterTypeDescription
configPdfExportConfig
Returns: Promise -

Object of the following structure

{
    response // Response instance
}

This method accepts all stylesheets (link and style tags) which are supposed to be put on the page. Use this hook method to filter or modify them.

new Grid({
    features: {
        pdfExport: {
            // filter out inline styles and bootstrap.css
            filterStyles: styles => styles.filter(item => !/(link|bootstrap.css)/.test(item))
        }
    }
});
ParameterTypeDescription
stylesString[]
Returns: String[] -

List of stylesheets to put on the exported page

Handles output of the receiveExportContent. Server response can be of two different types depending on sendAsBinary config:

  • application/json In this case JSON response contains url of the file to download
  • application/octet-stream In this case response contains stream of file binary data

If openAfterExport is true, this method will try to download content.

ParameterTypeDescription
responseResponse
configObject

Export config

config.exportServerString

URL of the export server.

config.orientationString

Page orientation. portrait/landscape.

config.paperFormatString

Paper format as supported by puppeteer. A4/A3/...

config.fileFormatString

File format. PDF/PNG.

config.fileNameString

Name to use for the saved file.

config.clientURLString

URL to navigate before export. See clientURL.

config.sendAsBinaryString

Tells server whether to return binary file instead of download link. See sendAsBinary

Sends request to the export server and returns Response instance. This promise can be cancelled by the user by clicking on the toast message. When the user clicks on the toast, abort method is called on the promise returned by this method. If you override this method you can implement abort method like in the snippet below to cancel the request.

class MyPdfExport extends PdfExport {
    receiveExportContent(pages, config) {
        let controller;

        const promise = new Promise(resolve => {
            controller = new AbortController();
            const signal = controller.signal;

            fetch(url, { signal })
                .then(response => resolve(response));
        });

        // This method will be called when user clicks on the toast message to cancel the request
        promise.abort = () => controller.abort();

        return promise;
    }
}

const grid = new Grid({ features: { myPdfExport : {...} } });

grid.features.myPdfExport.export().catch(e => {
    // In case of aborted request do nothing
    if (e.name !== 'AbortError') {
        // handle other exceptions
    }
});
ParameterTypeDescription
pagesObject[]

Array of exported pages. Each page has html property, which includes HTML of the exported page.

configObject

Export config

config.exportServerString

URL of the export server.

config.orientationString

Page orientation. portrait/landscape.

config.paperFormatString

Paper format as supported by puppeteer. A4/A3/...

config.fileFormatString

File format. PDF/PNG.

config.fileNameString

Name to use for the saved file.

config.clientURLString

URL to navigate before export. See clientURL.

config.sendAsBinaryString

Tells server whether to return binary file instead of download link.

Returns: Promise -

Returns Response instance

LstaticLocalizable
onEvents
relayAllEvents
triggerEvents
unEvents

Configuration

applyDefaultsstaticBase

Events

Lifecycle

destroystaticBase

Misc

doDisableInstancePlugin
initClassstaticBase
isOfTypeNamestaticBase
mixinstaticBase
optionalLstaticLocalizable

Events

8

Fires on the owning Grid before export started. Return false to cancel the export.

// Adding a listener using the "on" method
pdfExport.on('beforePdfExport', ({ config }) => {

});
ParameterTypeDescription
configPdfExportConfig

Export config

Fires when export progress changes

// Adding a listener using the "on" method
pdfExport.on('exportStep', ({ progress, text }) => {

});
ParameterTypeDescription
progressNumber

Current progress, 0-100

textString

Optional text to show

Fires on the owning Grid when export has finished

// Adding a listener using the "on" method
pdfExport.on('pdfExport', ({ response, error }) => {

});
ParameterTypeDescription
responseResponse

Optional response, if received

errorError

Optional error, if exception occurred

catchAllEvents
destroyEvents
disableInstancePlugin
enableInstancePlugin

Event handlers

8

Called on the owning Grid before export started. Return false to cancel the export.

new PdfExport({
    onBeforePdfExport({ config }) {

    }
});
ParameterTypeDescription
configPdfExportConfig

Export config

Called when export progress changes

new PdfExport({
    onExportStep({ progress, text }) {

    }
});
ParameterTypeDescription
progressNumber

Current progress, 0-100

textString

Optional text to show

Called on the owning Grid when export has finished

new PdfExport({
    onPdfExport({ response, error }) {

    }
});
ParameterTypeDescription
responseResponse

Optional response, if received

errorError

Optional error, if exception occurred

onDestroyEvents
onDisableInstancePlugin
onEnableInstancePlugin

Typedefs

1