File size: 22,419 Bytes
8e2959f 21da54e aaa3dc1 21da54e aaa3dc1 21da54e aaa3dc1 8e2959f aaa3dc1 21da54e 8e2959f 21da54e aaa3dc1 1d4c41b 21da54e aaa3dc1 d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e 1d4c41b 21da54e 1d4c41b 21da54e 1d4c41b 21da54e 1d4c41b 21da54e 1d4c41b 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e 1d4c41b 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e aaa3dc1 21da54e aaa3dc1 d1278b8 21da54e d1278b8 21da54e aaa3dc1 21da54e aaa3dc1 21da54e d1278b8 21da54e 1d4c41b 21da54e aaa3dc1 21da54e 1d4c41b 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e d1278b8 21da54e aaa3dc1 21da54e aaa3dc1 21da54e b4297f5 d1278b8 aaa3dc1 d1278b8 aaa3dc1 8e2959f aaa3dc1 |
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 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 |
import puppeteer from 'puppeteer';
class ScreenshotService {
constructor() {
this.browser = null;
this.isInitialized = false;
this.maxRetries = 3;
this.browserLaunchRetries = 0;
this.maxBrowserLaunchRetries = 3;
this.isClosing = false;
}
async initBrowser() {
if (this.isClosing) {
console.log('浏览器正在关闭中,等待重新初始化...');
this.browser = null;
this.isClosing = false;
}
if (!this.browser) {
try {
console.log('初始化Puppeteer浏览器...');
this.browser = await puppeteer.launch({
headless: 'new',
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--single-process',
'--disable-gpu',
'--disable-background-timer-throttling',
'--disable-backgrounding-occluded-windows',
'--disable-renderer-backgrounding',
'--disable-features=TranslateUI',
'--disable-extensions',
'--hide-scrollbars',
'--mute-audio',
'--no-default-browser-check',
'--disable-default-apps',
'--disable-background-networking',
'--disable-sync',
'--metrics-recording-only',
'--disable-domain-reliability',
'--disable-component-extensions-with-background-pages',
'--force-device-scale-factor=1',
'--enable-precise-memory-info',
'--disable-features=VizDisplayCompositor',
'--run-all-compositor-stages-before-draw',
'--disable-new-content-rendering-timeout',
'--disable-ipc-flooding-protection',
'--disable-hang-monitor',
'--disable-prompt-on-repost',
'--max_old_space_size=512'
],
timeout: 30000,
protocolTimeout: 30000
});
// 监听浏览器断开连接事件
this.browser.on('disconnected', () => {
console.log('Puppeteer浏览器连接断开');
this.browser = null;
this.isClosing = false;
});
// 监听目标创建事件
this.browser.on('targetcreated', (target) => {
console.log('新目标创建:', target.type());
});
// 监听目标销毁事件
this.browser.on('targetdestroyed', (target) => {
console.log('目标销毁:', target.type());
});
console.log('Puppeteer浏览器初始化完成');
this.browserLaunchRetries = 0;
} catch (error) {
console.error('Puppeteer浏览器初始化失败:', error);
this.browserLaunchRetries++;
if (this.browserLaunchRetries <= this.maxBrowserLaunchRetries) {
console.log(`尝试重新初始化浏览器 (${this.browserLaunchRetries}/${this.maxBrowserLaunchRetries})`);
await this.delay(2000); // 等待2秒后重试
return this.initBrowser();
} else {
throw new Error(`浏览器初始化失败,已重试${this.maxBrowserLaunchRetries}次: ${error.message}`);
}
}
}
// 验证浏览器是否仍然连接
try {
await this.browser.version();
} catch (error) {
console.warn('浏览器连接已断开,重新初始化:', error.message);
this.browser = null;
return this.initBrowser();
}
return this.browser;
}
async closeBrowser() {
if (this.browser && !this.isClosing) {
try {
this.isClosing = true;
console.log('正在关闭Puppeteer浏览器...');
await this.browser.close();
console.log('Puppeteer浏览器已关闭');
} catch (error) {
console.warn('关闭浏览器时出错:', error.message);
} finally {
this.browser = null;
this.isClosing = false;
}
}
}
// 延迟函数
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// 从HTML中提取PPT尺寸信息
extractPPTDimensions(htmlContent) {
try {
// 从JavaScript中提取PPT_DIMENSIONS
const dimensionMatch = htmlContent.match(/window\.PPT_DIMENSIONS\s*=\s*{\s*width:\s*(\d+),\s*height:\s*(\d+)\s*}/);
if (dimensionMatch) {
return {
width: parseInt(dimensionMatch[1]),
height: parseInt(dimensionMatch[2])
};
}
// 从viewport meta标签中提取
const viewportMatch = htmlContent.match(/width=(\d+),\s*height=(\d+)/);
if (viewportMatch) {
return {
width: parseInt(viewportMatch[1]),
height: parseInt(viewportMatch[2])
};
}
// 从CSS中提取
const cssMatch = htmlContent.match(/width:\s*(\d+)px.*height:\s*(\d+)px/);
if (cssMatch) {
return {
width: parseInt(cssMatch[1]),
height: parseInt(cssMatch[2])
};
}
// 默认尺寸
return { width: 960, height: 720 };
} catch (error) {
console.warn('提取PPT尺寸失败,使用默认尺寸:', error.message);
return { width: 960, height: 720 };
}
}
// 优化HTML内容以确保精确截图
optimizeHtmlForScreenshot(htmlContent, targetWidth, targetHeight) {
console.log(`优化HTML for精确截图, 目标尺寸: ${targetWidth}x${targetHeight}`);
// 在<head>标签后立即插入截图优化代码
const optimizedHtml = htmlContent.replace(
/(<head[^>]*>)/i,
`$1
<meta name="screenshot-mode" content="true">
<style id="screenshot-precise-control">
/* 截图模式:绝对精确的尺寸控制 */
*, *::before, *::after {
margin: 0 !important;
padding: 0 !important;
box-sizing: border-box !important;
border: none !important;
outline: none !important;
}
html {
width: ${targetWidth}px !important;
height: ${targetHeight}px !important;
min-width: ${targetWidth}px !important;
min-height: ${targetHeight}px !important;
max-width: ${targetWidth}px !important;
max-height: ${targetHeight}px !important;
overflow: hidden !important;
position: fixed !important;
top: 0 !important;
left: 0 !important;
margin: 0 !important;
padding: 0 !important;
transform: none !important;
transform-origin: top left !important;
}
body {
width: ${targetWidth}px !important;
height: ${targetHeight}px !important;
min-width: ${targetWidth}px !important;
min-height: ${targetHeight}px !important;
max-width: ${targetWidth}px !important;
max-height: ${targetHeight}px !important;
overflow: hidden !important;
position: fixed !important;
top: 0 !important;
left: 0 !important;
margin: 0 !important;
padding: 0 !important;
transform: none !important;
transform-origin: top left !important;
}
.slide-container {
width: ${targetWidth}px !important;
height: ${targetHeight}px !important;
min-width: ${targetWidth}px !important;
min-height: ${targetHeight}px !important;
max-width: ${targetWidth}px !important;
max-height: ${targetHeight}px !important;
position: fixed !important;
top: 0 !important;
left: 0 !important;
overflow: hidden !important;
transform: none !important;
transform-origin: top left !important;
margin: 0 !important;
padding: 0 !important;
box-shadow: none !important;
z-index: 1 !important;
}
/* 隐藏所有滚动条 */
html::-webkit-scrollbar,
body::-webkit-scrollbar,
*::-webkit-scrollbar {
display: none !important;
width: 0 !important;
height: 0 !important;
}
html {
scrollbar-width: none !important;
}
/* 禁用用户交互 */
* {
-webkit-user-select: none !important;
-moz-user-select: none !important;
-ms-user-select: none !important;
user-select: none !important;
-webkit-user-drag: none !important;
-khtml-user-drag: none !important;
-moz-user-drag: none !important;
-o-user-drag: none !important;
user-drag: none !important;
pointer-events: none !important;
}
/* 强制移除响应式样式 */
.browse-mode,
.browse-mode html,
.browse-mode body,
.browse-mode .slide-container {
display: block !important;
position: fixed !important;
width: ${targetWidth}px !important;
height: ${targetHeight}px !important;
min-width: ${targetWidth}px !important;
min-height: ${targetHeight}px !important;
max-width: ${targetWidth}px !important;
max-height: ${targetHeight}px !important;
transform: none !important;
background-color: transparent !important;
top: 0 !important;
left: 0 !important;
margin: 0 !important;
padding: 0 !important;
box-shadow: none !important;
}
</style>`
);
// 在</body>前插入截图专用JavaScript
const finalHtml = optimizedHtml.replace(
/(<\/body>)/i,
`
<script id="screenshot-precision-script">
// 截图模式强制设置
window.SCREENSHOT_EXACT_MODE = true;
window.PPT_TARGET_WIDTH = ${targetWidth};
window.PPT_TARGET_HEIGHT = ${targetHeight};
// 立即执行强制设置,确保尺寸精确
(function() {
const targetW = ${targetWidth};
const targetH = ${targetHeight};
console.log('截图模式精确设置开始:', targetW + 'x' + targetH);
const html = document.documentElement;
const body = document.body;
// 强制设置根元素
const setElementSize = (element, width, height) => {
if (!element) return;
element.style.cssText = \`
width: \${width}px !important;
height: \${height}px !important;
min-width: \${width}px !important;
min-height: \${height}px !important;
max-width: \${width}px !important;
max-height: \${height}px !important;
overflow: hidden !important;
margin: 0 !important;
padding: 0 !important;
position: fixed !important;
top: 0 !important;
left: 0 !important;
border: none !important;
outline: none !important;
transform: none !important;
transform-origin: top left !important;
box-sizing: border-box !important;
\`;
};
// 设置HTML和Body
setElementSize(html, targetW, targetH);
setElementSize(body, targetW, targetH);
// 移除可能的响应式类
html.classList.remove('browse-mode');
body.classList.remove('browse-mode');
// 设置容器
const container = document.querySelector('.slide-container');
if (container) {
container.style.cssText = \`
width: \${targetW}px !important;
height: \${targetH}px !important;
min-width: \${targetW}px !important;
min-height: \${targetH}px !important;
max-width: \${targetW}px !important;
max-height: \${targetH}px !important;
position: fixed !important;
top: 0 !important;
left: 0 !important;
overflow: hidden !important;
margin: 0 !important;
padding: 0 !important;
border: none !important;
outline: none !important;
transform: none !important;
box-shadow: none !important;
z-index: 1 !important;
\`;
}
console.log('截图模式精确设置完成');
})();
// DOM加载完成后再次确认
document.addEventListener('DOMContentLoaded', function() {
const html = document.documentElement;
const body = document.body;
const container = document.querySelector('.slide-container');
// 最终强制设置,确保完全生效
[html, body].forEach(element => {
if (element) {
element.style.width = '${targetWidth}px';
element.style.height = '${targetHeight}px';
element.style.minWidth = '${targetWidth}px';
element.style.minHeight = '${targetHeight}px';
element.style.maxWidth = '${targetWidth}px';
element.style.maxHeight = '${targetHeight}px';
element.style.margin = '0';
element.style.padding = '0';
element.style.border = 'none';
element.style.outline = 'none';
element.style.overflow = 'hidden';
element.style.position = 'fixed';
element.style.top = '0';
element.style.left = '0';
element.style.transform = 'none';
}
});
if (container) {
container.style.width = '${targetWidth}px';
container.style.height = '${targetHeight}px';
container.style.minWidth = '${targetWidth}px';
container.style.minHeight = '${targetHeight}px';
container.style.maxWidth = '${targetWidth}px';
container.style.maxHeight = '${targetHeight}px';
container.style.position = 'fixed';
container.style.top = '0';
container.style.left = '0';
container.style.margin = '0';
container.style.padding = '0';
container.style.border = 'none';
container.style.outline = 'none';
container.style.overflow = 'hidden';
container.style.transform = 'none';
container.style.boxShadow = 'none';
}
console.log('DOM加载后的最终尺寸确认完成');
});
</script>
$1`
);
console.log('HTML优化完成,已注入精确尺寸控制代码');
return finalHtml;
}
async generateScreenshotWithRetry(htmlContent, options = {}, retryCount = 0) {
try {
await this.initBrowser();
console.log(`开始生成截图... (尝试 ${retryCount + 1}/${this.maxRetries + 1})`);
// 从HTML中提取PPT的精确尺寸
const dimensions = this.extractPPTDimensions(htmlContent);
console.log(`检测到PPT尺寸: ${dimensions.width}x${dimensions.height}`);
// 优化HTML内容以确保精确截图
const optimizedHtml = this.optimizeHtmlForScreenshot(htmlContent, dimensions.width, dimensions.height);
// 创建新页面
let page = null;
try {
page = await this.browser.newPage();
// 设置页面超时
page.setDefaultTimeout(30000);
page.setDefaultNavigationTimeout(30000);
// 设置精确的viewport尺寸
await page.setViewport({
width: dimensions.width,
height: dimensions.height,
deviceScaleFactor: options.deviceScaleFactor || 2, // 高清截图
});
// 设置页面内容
await page.setContent(optimizedHtml, {
waitUntil: ['load', 'domcontentloaded'],
timeout: 30000
});
// 等待页面完全渲染
await page.waitForTimeout(2000);
// 执行最终的尺寸验证和强制设置
await page.evaluate((targetWidth, targetHeight) => {
const html = document.documentElement;
const body = document.body;
const container = document.querySelector('.slide-container');
// 最终强制设置,确保精确尺寸
const forceSize = (element, width, height) => {
if (!element) return;
element.style.width = width + 'px';
element.style.height = height + 'px';
element.style.minWidth = width + 'px';
element.style.minHeight = height + 'px';
element.style.maxWidth = width + 'px';
element.style.maxHeight = height + 'px';
element.style.margin = '0';
element.style.padding = '0';
element.style.border = 'none';
element.style.outline = 'none';
element.style.overflow = 'hidden';
element.style.transform = 'none';
if (element !== container) {
element.style.position = 'fixed';
element.style.top = '0';
element.style.left = '0';
}
};
forceSize(html, targetWidth, targetHeight);
forceSize(body, targetWidth, targetHeight);
if (container) {
forceSize(container, targetWidth, targetHeight);
container.style.position = 'fixed';
container.style.top = '0';
container.style.left = '0';
container.style.boxShadow = 'none';
container.style.zIndex = '1';
}
// 验证尺寸设置结果
const verification = {
html: html.offsetWidth + 'x' + html.offsetHeight,
body: body.offsetWidth + 'x' + body.offsetHeight,
container: container ? container.offsetWidth + 'x' + container.offsetHeight : 'none',
target: targetWidth + 'x' + targetHeight
};
console.log('最终尺寸验证:', verification);
// 如果尺寸不匹配,记录警告
if (html.offsetWidth !== targetWidth || html.offsetHeight !== targetHeight) {
console.warn('HTML尺寸不匹配目标尺寸!');
}
return verification;
}, dimensions.width, dimensions.height);
// 再次等待以确保所有更改生效
await page.waitForTimeout(1000);
// 执行截图,使用精确的剪裁区域
const screenshot = await page.screenshot({
type: options.format || 'jpeg',
quality: options.quality || 95,
clip: {
x: 0,
y: 0,
width: dimensions.width,
height: dimensions.height
},
omitBackground: false, // 包含背景
captureBeyondViewport: false, // 不截取视口外内容
});
console.log(`截图成功生成,尺寸: ${dimensions.width}x${dimensions.height}, 数据大小: ${screenshot.length} 字节`);
return screenshot;
} finally {
if (page) {
try {
await page.close();
} catch (error) {
console.warn('关闭页面时出错:', error.message);
}
}
}
} catch (error) {
console.error(`截图生成失败 (尝试 ${retryCount + 1}):`, error.message);
// 如果是目标关闭错误或连接断开,重置浏览器
if (error.message.includes('Target closed') ||
error.message.includes('Connection closed') ||
error.message.includes('Protocol error')) {
console.log('检测到浏览器连接问题,重置浏览器实例');
this.browser = null;
this.isClosing = false;
}
// 如果还有重试机会,进行重试
if (retryCount < this.maxRetries) {
console.log(`等待 ${(retryCount + 1) * 2} 秒后重试...`);
await this.delay((retryCount + 1) * 2000);
return this.generateScreenshotWithRetry(htmlContent, options, retryCount + 1);
}
throw new Error(`截图生成失败,已重试${this.maxRetries}次: ${error.message}`);
}
}
async generateScreenshot(htmlContent, options = {}) {
return this.generateScreenshotWithRetry(htmlContent, options, 0);
}
// 兼容旧方法名
async captureScreenshot(htmlContent, width, height, options = {}) {
console.log('使用兼容方法captureScreenshot,建议使用generateScreenshot');
return this.generateScreenshot(htmlContent, options);
}
// 清理资源
async cleanup() {
await this.closeBrowser();
}
}
// 创建单例实例
const screenshotService = new ScreenshotService();
// 进程退出时清理资源
process.on('exit', async () => {
await screenshotService.cleanup();
});
process.on('SIGINT', async () => {
await screenshotService.cleanup();
process.exit(0);
});
process.on('SIGTERM', async () => {
await screenshotService.cleanup();
process.exit(0);
});
export default screenshotService; |