const printGrid = () => {
console.log('Print button clicked');
if (gridApi.current && gridColumnApi.current) {
console.log('Grid APIs are available');
const gridElement = document.querySelector('#myGrid') as HTMLElement;
if (gridElement) {
console.log('Grid element found');
const originalStyle = {
width: gridElement.style.width,
height: gridElement.style.height,
};
// 그리드 너비를 80%로 설정
gridElement.style.width = '80%';
gridElement.style.margin = '0 auto';
// 프린트 모드로 전환
gridApi.current.setDomLayout('print');
// 열 너비 수동 설정
const columnStates = gridColumnApi.current.getColumnState();
console.log('columnStates',columnStates);
columnStates.forEach((colState:any) => {
const newWidth = Math.max(19, colState.width * 0.9); // 최소 50px, 또는 현재 너비의 80%
console.log('newWidth',newWidth)
gridColumnApi.current.setColumnWidth(colState.colId, newWidth);
});
// 모든 그룹 확장 (만약 그룹이 있다면)
gridApi.current.expandAll();
// 렌더링이 완료된 후 인쇄
setTimeout(() => {
console.log('Printing...');
window.print();
// 원래 상태로 되돌리기
gridElement.style.width = originalStyle.width;
gridElement.style.height = originalStyle.height;
gridElement.style.margin = '';
gridApi.current.setDomLayout('normal');
// 원래 열 너비로 복원
columnStates.forEach((colState:any) => {
gridColumnApi.current.setColumnWidth(colState.colId, colState.width);
});
// 그룹 상태 복원 (필요한 경우)
gridApi.current.collapseAll();
}, 1000);
} else {
console.error('Grid element not found');
}
} else {
console.error('Grid API or Column API not initialized');
}
};
위가 전체 함수이다.
중요한 부분은 바로 이부분
columnStates.forEach((colState:any) => {
const newWidth = Math.max(19, colState.width * 0.9); // 최소 50px, 또는 현재 너비의 80%
console.log('newWidth',newWidth)
gridColumnApi.current.setColumnWidth(colState.colId, newWidth);
});
19 부분이 최소값이다. colState.width * 0.9는 전체 컬럼들의 너비값을 줄여주는 부분이다.
아래는 전체 css적용되는 부분에 넣어준다. setDomLayout('print') 할 때 적용되는 부분.
@media print {
* {
visibility: hidden; /* 기본적으로 모든 요소 숨기기 */
}
#myGrid, #myGrid *, #myGridBar, #myGridBar * {
visibility: visible; /* 그리드와 그 자식 요소들만 표시 */
}
#myGrid {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: auto !important; /* 그리드 높이를 자동으로 */
}
#myGridBar {
position: absolute;
top: 0; /* myGridBar를 페이지 상단에 고정 */
left: 0;
width: 100%;
height: auto !important; /* 높이를 자동으로 설정 */
color: black; /* 글자 색상을 검정으로 설정 */
background-color: white; /* 필요시 배경색을 흰색으로 설정 */
z-index: 100; /* 다른 요소 위에 표시되도록 설정 */
}
}
여기서 myGrid는 어디냐?면 aggrid적용된 부분에 id가 myGrid
<div id="myGrid" className="w-full flex-1 ag-theme-alpine">
<AgGridReact ref={gridRef} rowData={data} columnDefs={def} defaultColDef={defaultColDef} />
</div>
뭐 이런 식이다!
print에 대한 aggrid 의 공식 문서도 참조하도록 하자~
'■ Web개발 > Ag-grid' 카테고리의 다른 글
Ag-grid 사용하는 법. (0) | 2021.10.05 |
---|---|
ag-grid 가로 세로 색칠 column, row 색깔 변경 (0) | 2021.05.27 |
ag-grid 에서 AgGridColumn에 반올림 값 적용시키기 (0) | 2021.05.27 |