Upload screenshotService.js
Browse files
backend/src/services/screenshotService.js
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import puppeteer from 'puppeteer';
|
2 |
+
|
3 |
+
class ScreenshotService {
|
4 |
+
async generateScreenshot(htmlContent, options = {}) {
|
5 |
+
const browser = await puppeteer.launch({
|
6 |
+
headless: true,
|
7 |
+
args: [
|
8 |
+
'--no-sandbox',
|
9 |
+
'--disable-setuid-sandbox',
|
10 |
+
'--disable-dev-shm-usage',
|
11 |
+
'--disable-accelerated-2d-canvas',
|
12 |
+
'--no-first-run',
|
13 |
+
'--no-zygote',
|
14 |
+
'--single-process', // <- this one doesn't work in Windows
|
15 |
+
'--disable-gpu'
|
16 |
+
]
|
17 |
+
});
|
18 |
+
|
19 |
+
try {
|
20 |
+
const page = await browser.newPage();
|
21 |
+
|
22 |
+
// 设置页面视窗大小,匹配PPT的4:3比例
|
23 |
+
await page.setViewport({
|
24 |
+
width: 1000,
|
25 |
+
height: 750,
|
26 |
+
deviceScaleFactor: 2 // 高分辨率
|
27 |
+
});
|
28 |
+
|
29 |
+
// 设置HTML内容
|
30 |
+
await page.setContent(htmlContent, { waitUntil: 'networkidle0' });
|
31 |
+
|
32 |
+
// 等待页面完全加载
|
33 |
+
await page.waitForTimeout(1000);
|
34 |
+
|
35 |
+
// 截图
|
36 |
+
const screenshot = await page.screenshot({
|
37 |
+
type: 'jpeg',
|
38 |
+
quality: 85,
|
39 |
+
fullPage: false
|
40 |
+
});
|
41 |
+
|
42 |
+
return screenshot;
|
43 |
+
} finally {
|
44 |
+
await browser.close();
|
45 |
+
}
|
46 |
+
}
|
47 |
+
}
|
48 |
+
|
49 |
+
export default new ScreenshotService();
|