2
votes

I am using an ag-grid in an Angular app that is 11 columns wide. On resize of the browser, I am calling gridOptions.api.sizeColumnsToFit to allow the column widths to scale, making the grid dynamically fill the width of the browser.

In Chrome, when I press 'Ctrl + P' to see the print preview, it appears that the grid is rendered in the preview with the same width it had in the browser, which is sometimes less than the width of a printed page (would produces columns that are squished together unnecessarily), or greater than the width of a printed page (where columns are lost and data is missing).

I have tried using window.matchMedia("print") to try and call the gridOptions api before the print preview is rendered, but this is not working. The grid width is still the same it was in the browser before print was called.

this.printMediaQuery = window.matchMedia("print");
this.printMediaQuery.addListener(() => {
  if (!this.gridOptions.api) { return; }
  if (this.printMediaQuery.matches) {
      //I want to hide one column of data
      this.gridOptions.columnApi.setColumnVisible("Reopen", false);
      this.gridOptions.api.sizeColumnsToFit();
  } else {
      //I want to reshow the same column of data
      this.gridOptions.columnApi.setColumnVisible("Reopen", true);
      this.gridOptions.api.sizeColumnsToFit();
  }
});

I do not understand why this is not working. In Angular 2, what's the recommended way to go about resizing an ag-grid so that it dynamically fits the width of a printed page?

1
Did you ever find a good solution to this? I'm also having the problem of too many columns and it expands off the page for printing. I'm trying to find a way to shrink it to fit. - Kyle
@Kyle Not really. I cannot remember why exactly ag-grid's setDomLayout didn't work for us. It looks like we might have tried to use Lodash's delay method when calling sizeColumnsToFit() to wait ~300ms so that the print view would have time to be fully loaded. Then the api might resize the columns to the new view. But I'm not sure that was successful (and clearly not a reliable solution). - Aundra Miller

1 Answers

2
votes

I'd suggest making use of the Printing Layout that the grid offers itself - specifically you need to set the domLayout property to true

See the docs for more information around this: https://www.ag-grid.com/javascript-grid-for-print/