Workbook: Export to PDF (JavaScript)
Workbook: Export to PDF (JavaScript)
This script triggers a job to export a workbook to PDF and downloads the PDF-formatted file after it is ready.
Refer to the Sigma REST API Recipes QuickStart for step-by-step instructions.
Example script
JavaScript
1 // This script triggers an export to PDF job with date range parameters, and downloads the export once ready. 2 // The export will be the entire workbook in PDF format. 3 4 // Load environment variables from a specific .env file for configuration 5 require('dotenv').config({ path: 'sigma-api-recipes/.env' }); 6 7 // Import the function to obtain a bearer token from the authenticate-bearer module 8 const getBearerToken = require('../get-access-token'); 9 10 // Import Axios for making HTTP requests 11 const axios = require('axios'); 12 13 // Load necessary modules for file handling 14 const fs = require('fs'); 15 const path = require('path'); 16 17 // Load use-case specific variables from environment variables 18 const baseURL = process.env.baseURL; // Base URL for the Sigma API 19 const workbookId = process.env.WORKBOOK_ID; // Workbook ID from which to export data 20 21 async function initiateExport(accessToken) { 22 // Prepare the options for the export request with correct format and filters 23 const exportOptions = { 24 workbookId: workbookId, 25 format: { type: 'pdf', layout: 'portrait' }, // Export as PDF in portrait layout 26 }; 27 28 console.log('Final export options:', JSON.stringify(exportOptions, null, 2)); 29 30 try { 31 const response = await axios.post( 32 `${baseURL}/workbooks/${workbookId}/export`, 33 exportOptions, 34 { headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' } } 35 ); 36 console.log('Export initiated successfully, response:', response.data); 37 return response.data.queryId; // Extract and return the query ID from the response 38 } catch (error) { 39 console.error('Failed to initiate export:', error); 40 return null; 41 } 42 } 43 44 async function checkExportReady(queryId, accessToken) { 45 // Continuously check if the export is ready for download 46 console.log(`Checking export readiness for queryId: ${queryId}`); 47 while (true) { 48 try { 49 const response = await axios.get( 50 `${baseURL}/query/${queryId}/download`, 51 { headers: { Authorization: `Bearer ${accessToken}` }, responseType: 'stream' } 52 ); 53 54 if (response.status === 200) { // Check if the export is ready 55 console.log('Export is ready for download.'); 56 return response.data; 57 } else { 58 console.log(`Received unexpected status code: ${response.status}`); 59 } 60 } catch (error) { 61 if (error.response && error.response.status === 204) { 62 // Export not ready yet, wait before retrying 63 console.log('Export is not ready yet. Waiting to retry...'); 64 await new Promise(resolve => setTimeout(resolve, 10000)); 65 } else { 66 console.error('Failed to check export status:', error); 67 return null; 68 } 69 } 70 } 71 } 72 73 async function downloadExport(data, filename) { 74 // Handle the download of the export file 75 const filePath = path.join(__dirname, filename); 76 const writer = fs.createWriteStream(filePath); 77 78 return new Promise((resolve, reject) => { 79 data.pipe(writer); 80 let error = null; 81 82 writer.on('error', err => { 83 error = err; 84 writer.close(); 85 reject(err); 86 }); 87 88 writer.on('finish', () => { 89 if (!error) { 90 console.log(`Export downloaded successfully to: ${filePath}`); 91 resolve(true); 92 } 93 }); 94 }); 95 } 96 97 async function exportWorkflow() { 98 // Main workflow to manage the export process 99 const accessToken = await getBearerToken(); 100 if (!accessToken) { 101 console.error('Failed to obtain bearer token.'); 102 return; 103 } 104 105 const queryId = await initiateExport(accessToken); 106 if (!queryId) { 107 console.error('Failed to initiate export or obtain queryId.'); 108 return; 109 } 110 111 const data = await checkExportReady(queryId, accessToken); 112 if (data) { 113 await downloadExport(data, 'PlugsSalesPerformanceDashboard.pdf'); 114 } else { 115 console.error('Failed to prepare the export for download.'); 116 } 117 118 // Forcibly exit the process if the script is still hanging 119 process.exit(0); 120 } 121 122 exportWorkflow();
Endpoints used
- Get authentication token:
getBearerTokenfunction - Initiate an export:
${baseURL}/workbooks/${workbookId}/export - Check the export status and download the file:
${baseURL}/query/${queryId}/download

