-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathtest.js
More file actions
86 lines (75 loc) · 2.1 KB
/
test.js
File metadata and controls
86 lines (75 loc) · 2.1 KB
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
import puppeteer from 'puppeteer';
import path from 'path';
import fs from 'fs';
import os from 'os';
import tmp from 'tmp';
async function test() {
const outputDir = os.tmpdir();
const outputPath = path.join(outputDir, 'test.pdf');
console.log('Creating temporary HTML file...');
tmp.file({ postfix: '.html' }, async (err, tmpHtmlPath, tmpHtmlFd) => {
if (err) {
console.error('Error creating temp file:', err);
return;
}
console.log('Temp HTML path:', tmpHtmlPath);
fs.closeSync(tmpHtmlFd);
const html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
@page {
margin: 20px;
size: letter portrait;
}
body { font-family: Arial; }
</style>
</head>
<body>
<h1>Test PDF Generation</h1>
<p>This is a test.</p>
</body>
</html>
`;
try {
console.log('Writing HTML content...');
await fs.promises.writeFile(tmpHtmlPath, html);
console.log('Launching browser...');
const browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
try {
console.log('Creating new page...');
const page = await browser.newPage();
console.log('Loading HTML file...');
await page.goto(`file://${tmpHtmlPath}`, {
waitUntil: 'networkidle0',
timeout: 30000
});
console.log('Generating PDF...');
await page.pdf({
path: outputPath,
format: 'letter',
margin: {
top: '20mm',
right: '20mm',
bottom: '20mm',
left: '20mm'
},
printBackground: true
});
console.log('PDF generated successfully');
console.log('Output path:', outputPath);
console.log('File exists:', fs.existsSync(outputPath));
} finally {
await browser.close();
}
} catch (error) {
console.error('Error:', error);
}
});
}
test();