如何在现有Excel导出基础上实现Qlik Sense对象的PDF导出?
Qlik Sense Mashup 同时支持Excel和PDF导出的实现方案
Qlik Sense中导出PDF和Excel的逻辑不同:table.exportData仅支持导出结构化数据格式(如OOXML、CSV),PDF属于可视化导出或自定义数据表格导出,不能直接沿用Excel的导出方式,以下是两种可行实现思路:
方案一:使用Qlik原生API导出对象可视化PDF
这个方法会直接导出Qlik对象(如表格)的渲染结果,和Qlik Sense界面内的PDF导出效果一致。
修改核心代码
替换原代码中table.exportData的部分,改用对象模型的exportPdf方法:
// Get table object app.getObject('QFgJHd').then(function(model) { // 等待对象渲染完成(避免未渲染完成导致导出空白) setTimeout(() => { // 导出对象为PDF model.exportPdf({ download: true, filename: 'exported_data.pdf' }).then(exportLink => { // 同时生成Excel下载链接 qlik.table(model).exportData({ download: false, format: 'OOXML' }).then(excelLink => { var downloadLinkElement = document.getElementById('downloadLink'); downloadLinkElement.innerHTML = ` <a href="${exportLink}" download="exported_data.pdf">Download PDF</a> <br> <a href="${excelLink}" download="exported_data.xlsx">Download Excel</a> `; }); }).catch(error => { console.error('Error exporting PDF:', error); alert('Error exporting PDF. See console for details.'); }); }, 1000); // 延迟1秒确保对象渲染完成,可根据实际调整 }).catch(error => { console.error('Error getting table object:', error); alert('Error getting table object. See console for details.'); });
注意事项
- 必须确保Qlik对象已经在页面上渲染完成,否则导出的PDF会是空白,也可以通过监听对象的
valid状态替代定时器 - 用户需要拥有Qlik Sense的导出权限
exportPdf方法返回直接可下载的链接,无需额外处理
方案二:导出数据后用第三方库生成自定义PDF
如果需要自定义PDF的样式(比如自定义表头、单元格格式、添加标题等),可以先导出结构化数据,再用jsPDF+autoTable库生成PDF。
步骤1:引入第三方库
在<head>中添加CDN链接:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.8.2/jspdf.plugin.autotable.min.js"></script>
步骤2:修改导出逻辑
先导出Excel数据,再用数据生成PDF:
// Get table object app.getObject('QFgJHd').then(async function(model) { var table = qlik.table(model); // 导出Excel数据(获取链接) const excelLink = await table.exportData({ download: false, format: 'OOXML' }); // 导出原始JSON数据用于生成PDF const rawData = await table.exportData({ download: false, format: 'JSON' }); const data = JSON.parse(rawData); // 初始化PDF文档 const { jsPDF } = window.jspdf; const doc = new jsPDF(); // 添加PDF标题 doc.setFontSize(16); doc.text('Exported Data Report', 14, 20); // 生成PDF表格 doc.autoTable({ head: [data.headers.map(h => h.qFallbackTitle)], body: data.rows.map(row => row.map(cell => cell.qText)), startY: 30, theme: 'striped' }); // 生成PDF下载链接 const pdfBlob = doc.output('blob'); const pdfUrl = URL.createObjectURL(pdfBlob); // 显示两个下载链接 var downloadLinkElement = document.getElementById('downloadLink'); downloadLinkElement.innerHTML = ` <a href="${pdfUrl}" download="exported_data.pdf">Download Custom PDF</a> <br> <a href="${excelLink}" download="exported_data.xlsx">Download Excel</a> `; }).catch(error => { console.error('Error:', error); alert('Error exporting data. See console for details.'); });
优势
- 完全自定义PDF的布局、样式、内容
- 不依赖Qlik对象的渲染,直接用数据生成PDF,适合不需要可视化样式的场景
内容的提问来源于stack exchange,提问作者uriel
相关产品推荐
相关产品推荐

