1. 程式人生 > 其它 >介面控制元件DevExtreme——輕鬆將TreeList資料匯出為PDF格式

介面控制元件DevExtreme——輕鬆將TreeList資料匯出為PDF格式

DevExtreme擁有高效能的HTML5 / JavaScript小部件集合,使您可以利用現代Web開發堆疊(包括React,Angular,ASP.NET Core,jQuery,Knockout等)構建互動式的Web應用程式,該套件附帶功能齊全的資料網格、互動式圖表小部件、資料編輯器等。

DevExtreme v22.1正式版下載

匯出為PDF

要啟用Data Grid的PDF匯出選項,請匯入jsPDF庫。在元件中,設定export.enabled屬性為true然後指定匯出格式。接下來的操作顯示DataGrid中的Export按鈕,單擊此按鈕時,將觸發dataGrid.onExporting

函式(其中開發者應該呼叫pdfExporter.exportDataGrid(options)方法)。

<dx-data-grid ...
(onExporting)="onExporting($event)"
>
<dxo-export
[enabled]="true"
[formats]="['pdf']"
></dxo-export>
</dx-data-grid>
import { Component } from '@angular/core';
import { exportDataGrid } from 'devextreme/pdf_exporter';
import { jsPDF } from 'jspdf';

// ...

export class AppComponent {
onExporting(e) {
const doc = new jsPDF();
exportDataGrid({
jsPDFDocument: doc,
component: e.component,
}).then(() => {
doc.save('DataGrid.pdf');
});
}
}

單元格自定義

開發人員可以自定義單元格內容並在PDF文件中繪製自定義單元格。

customizeCell函式允許開發者為匯出的PDF文件自定義單個DataGrid單元格的外觀(例如,可以更改單元格使用的字型樣式)。

onExporting(e) {
const doc = new jsPDF();
exportDataGrid({
jsPDFDocument: doc,
component: e.component,
customizeCell({ gridCell, pdfCell }) {
//...
}
}).then(() => {
doc.save('DataGrid.pdf');
});
}

如果希望在繪製單元格時覆蓋預設繪製邏輯並應用自己的繪製邏輯,請使用customDrawCell函式。在下面的例子中,這個函式在PDF文件中為" Website "列繪製並自定義一個單元格:

onExporting(e) {
const doc = new jsPDF();
exportDataGrid({
jsPDFDocument: doc,
component: e.component,
customDrawCell({ gridCell, pdfCell }) {
//...
}
}).then(() => {
doc.save('DataGrid.pdf');
});
}

頁首和頁尾

開發人員可以輕鬆地嚮導出的DataGrid新增頁首和頁尾。

DataGrid元件位於PdfExportDataGridProps中指定點的PdfExportDataGridProps.topLeft 屬性的頁首之前。

對於頁尾位置,使用customDrawCell函式,這個函式允許開發者計算元件最右邊單元格的座標。

匯出圖片

jsPDF庫API還允許將自定義內容匯出為PDF(如影象),對於影象匯出,可以呼叫jsPDF.addImage方法,然後處理onRowExporting事件為匯出的DataGrid定製行。

onExporting(e) {
const doc = new jsPDF();
exportDataGrid({
jsPDFDocument: doc,
component: e.component,
onRowExporting: (e) => {
// Customize rows
},
customDrawCell: (e) => {
// Detect picture cell
doc.addImage(e.gridCell.value, 'PNG', e.rect.x, e.rect.y, e.rect.w, e.rect.h);
e.cancel = true;
}
}).then(() => {
doc.save('DataGrid.pdf');
});
}

匯出多個網格

要將多個DataGrid元件匯出到一個檔案中,並在PDF文件的不同頁面上排列它們,請在Promises鏈中使用pdfExporter.exportDataGrid(options)方法。

exportGrids() {
const doc = new jsPDF();
DevExpress.pdfExporter.exportDataGrid({
jsPDFDocument: doc,
component: gridOneInstance,
}).then(() => {
doc.addPage();
DevExpress.pdfExporter.exportDataGrid({
jsPDFDocument: doc,
component: gridTwoInstance,
}).then(() => {
doc.save('MultipleGrids.pdf');
});
});
}

更多DevExpress線上公開課、中文教程資訊請上中文網獲取