-
Notifications
You must be signed in to change notification settings - Fork 0
/
saveAsPdfWithCookies.js
179 lines (150 loc) · 5.02 KB
/
saveAsPdfWithCookies.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
const puppeteer = require('puppeteer');
const readline = require('readline');
let browser;
async function launchBrowser() {
if (!browser) {
console.log('Launching browser...');
browser = await puppeteer.launch({
headless: false,
executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
args: ['--no-sandbox', '--disable-setuid-sandbox',"--hide-scrollbars"], // Add additional args if needed
});
console.log('Browser launched.');
}
return browser;
}
async function openPage(url) {
console.log(`Opening page: ${url}`);
const page = await browser.newPage();
const width = 1010;
const height = 1080;
await page.setViewport({ width, height });
await page.goto(url, { waitUntil: 'networkidle2', timeout: 60000 });
await page.waitForSelector('.grafana-app', { timeout: 60000 });
await new Promise(resolve => setTimeout(resolve, 2000));
console.log('Page opened and loaded.');
return page;
}
async function scrollPage(page) {
console.log('Scrolling the page...');
await page.evaluate(async () => {
$(".grafana-app").attr({style: 'height: 50000px'});
let lastPanel = $(".grafana-app").find('[data-panelid]').last();
$(".grafana-app").attr({style: 'height: '+(lastPanel.offset().top + lastPanel.height()+50)+'px'});
var totalHeight = 0;
var distance = 200;
var timer = setInterval(() => {
var scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
if(totalHeight >= scrollHeight){
clearInterval(timer);
}
}, 50);
});
await new Promise(resolve => setTimeout(resolve, 2000));
await page.evaluate(() => window.scrollTo({ top: 0, behavior: 'smooth' }));
await new Promise(resolve => setTimeout(resolve, 2000));
console.log('Scrolling completed.');
}
async function checkPanels(page) {
console.log('Checking panels status...');
return await page.evaluate(() => {
const panelData = grafanaRuntime.getPanelData();
let panelsDone = 0;
let panelsErrored = 0;
for (const key in panelData) {
if (panelData[key] === undefined) {
} else if (panelData[key].state === "Done") {
panelsDone++;
}else if (panelData[key].state === "Error") {
panelsErrored++;
}
}
return { panelsDone, panelsErrored };
});
}
async function waitForPanels(page, panelsCount, timeout) {
const startTime = new Date().getTime();
while (true) {
const { panelsDone, panelsErrored } = await checkPanels(page);
console.log(`Panels done: ${panelsDone}, Panels errored: ${panelsErrored}`);
if (panelsDone >= panelsCount) {
if (panelsErrored > 0) {
console.log('Panels done but with errors.');
}
return true;
}
if (new Date().getTime() - startTime > timeout) {
return false;
}
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
async function saveAsPDF(page, path) {
console.log(`Saving page as PDF: ${path}`);
await page.pdf({
path: path,
format: 'A4',
printBackground: true,
margin: { top: '0.0in', right: '0.0in', bottom: '0.0in', left: '0.0in' },
scale: 0.79,
preferCSSPageSize: false,
});
console.log(`PDF "${path}" generated successfully.`);
}
async function loadAndSave(url, filename) {
await launchBrowser();
const page = await openPage(url);
try {
await scrollPage(page);
const panelsCount = 1;
const panelsLoaded = await waitForPanels(page, panelsCount, 60000);
if (!panelsLoaded) {
console.error('Timeout: Not all panels loaded successfully.');
throw new Error('Timeout: Not all panels loaded successfully.');
} else {
console.log(`${panelsCount} panels loaded successfully.`);
}
await saveAsPDF(page, filename);
await page.close();
} catch (error) {
console.error('Error:', error);
await page.close();
}
}
async function waitForUserInput() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
return new Promise((resolve) => {
rl.question('Please log in and then press "y" to continue: ', (answer) => {
rl.close();
if (answer.toLowerCase() === 'y') {
resolve();
} else {
console.log('User did not confirm. Exiting...');
process.exit(1);
}
});
});
}
async function saveReport(userId){
return await loadAndSave('https://grafana.andrewa.co.uk/d/ddqd1prkhe1hcc/user-report?orgId=2&var-userId='+userId+'&from=now-90d&to=now&kiosk', `report-${userId}.pdf`);
}
(async () => {
await launchBrowser();
const initialPage = await openPage('https://grafana.andrewa.co.uk/login');
console.log('Please log in using the opened browser window.');
await waitForUserInput();
console.log('Continuing with the rest of the script...');
await initialPage.close();
await saveReport(3483);
await saveReport(970);
await saveReport(7158);
await saveReport(2031);
if (browser) {
await browser.close();
}
})();