Recently, I received an inquiry about exporting selected data from a FlexGrid to a PDF document. I found this interesting. While we often brag about the amount of data the FlexGrid can hold, in this case,the user needed only a portion of the data. Wijmo supports exporting data to a PDF Document, but the wijmo.grid.pdf module does not support the ability to omit rows of the FlexGrid when saved to the PDF file. The saving process simply copies the data from the control in the browser to the PDF document. Only minimal changes can happen here—like changing the font or background color. Currently, the wijmo.grid.pdf module is based on PDFKit API, so to get the desired functionality, we would need to create our own API for a PDF generator specifically tailored to the FlexGrid. Since our specialty resides with UI controls, creating a new PDF API was out of the question. However, it is still possible to get the desired outcome. The solution is simple: use two FlexGrids. One FlexGrid contains all the data, and the other contains the selected data to export. Having the second FlexGrid appear in the application defeats the purpose, so we can hide the FlexGrid by setting the ‘display’ property to ‘none’ in markup. In pure JS, the HTML should appear something like this:
<div id="theGrid" style="width:100%;height:350px;"></div>
<div id="hiddenGrid" style="display:none;"></div>
To handle selection, I used a ‘boolean’ field to in my data objects named “exportRow”. There are other ways to do this, but this approach is the simplest. Rows with ‘checked’ checkboxes in the “Export Row” column are copied to the hidden FlexGrid just before the data is exported. Here is the Javascript code:
function exportSelectedRowsToPDF() {
// copy selected rows of #theGrid to #hiddenGrid
if (hidden == null) {
hidden = new wijmo.grid.FlexGrid('#hiddenGrid');
}
var grid_cv = grid.itemsSource;
var new\_cv = new wijmo.collections.CollectionView(grid\_cv);
for (var i = 0; i < new_cv.items.length; i++) {
if (!new_cv.items[i].exportRow) {
new_cv.removeAt(i);
i--;
}
}
hidden.itemsSource = new_cv;
//export
wijmo.grid.pdf.FlexGridPdfConverter.export(hidden, 'FlexGrid.pdf', {
scaleMode: wijmo.grid.pdf.ScaleMode.PageWidth,
exportMode: wijmo.grid.pdf.ExportMode.All,
maxPages: 10,
styles: {
cellStyle: {
backgroundColor: '#ffffff',
borderColor: '#c6c6c6'
},
headerCellStyle: {
backgroundColor: '#eaeaea'
}
},
documentOptions: {
info: {
title: 'Sample'
}
}
});
}
- Link to fiddle: http://jsfiddle.net/troy_taylor/tugz7v38/
- Read more about FlexGrid
- Documentation: FlexGrid PDF (wijmo.grid.pdf)