File size: 12,739 Bytes
8e2959f b4297f5 1d4c41b 8e2959f b4297f5 1d4c41b b4297f5 900310e b4297f5 900310e b4297f5 8e2959f b4297f5 8e2959f 1d4c41b 8e2959f 1d4c41b 900310e 8e2959f 1d4c41b 900310e 8e2959f 900310e b4297f5 8e2959f b4297f5 900310e 1d4c41b b4297f5 1d4c41b 8e2959f 1d4c41b 8e2959f 1d4c41b 900310e 1d4c41b 900310e b4297f5 8e2959f b4297f5 8e2959f b4297f5 1d4c41b 8e2959f b4297f5 8e2959f b4297f5 1d4c41b 900310e b4297f5 1d4c41b b4297f5 1d4c41b b4297f5 8e2959f |
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 |
import puppeteer from 'puppeteer';
class ScreenshotService {
async generateScreenshot(htmlContent, options = {}) {
let browser = null;
let pptDimensions = { width: 1000, height: 750 }; // 默认值
try {
console.log('Starting Puppeteer browser...');
// 提取PPT的实际尺寸和长宽比
pptDimensions = this.extractPptDimensions(htmlContent);
console.log('Extracted PPT dimensions:', pptDimensions);
// 更适合容器环境的Puppeteer配置
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',
'--disable-gpu',
'--disable-background-timer-throttling',
'--disable-backgrounding-occluded-windows',
'--disable-renderer-backgrounding',
'--disable-web-security',
'--disable-features=TranslateUI',
'--disable-extensions',
'--disable-component-extensions-with-background-pages',
'--disable-default-apps',
'--mute-audio',
'--no-default-browser-check',
'--autoplay-policy=user-gesture-required',
'--disable-background-mode',
'--disable-plugins',
'--disable-translate',
'--disable-ipc-flooding-protection',
'--memory-pressure-off',
'--max_old_space_size=4096'
],
timeout: 30000,
protocolTimeout: 30000
});
console.log('Browser launched successfully');
const page = await browser.newPage();
console.log('New page created');
// 设置页面视窗大小为PPT的精确尺寸
await page.setViewport({
width: pptDimensions.width,
height: pptDimensions.height,
deviceScaleFactor: 2 // 高分辨率
});
console.log(`Viewport set to exact PPT size: ${pptDimensions.width}x${pptDimensions.height}`);
// 修改HTML内容,确保PPT容器精确匹配视窗尺寸,消除白边
const modifiedHtmlContent = this.modifyHtmlForScreenshot(htmlContent, pptDimensions);
// 设置HTML内容
await page.setContent(modifiedHtmlContent, {
waitUntil: 'domcontentloaded',
timeout: 10000
});
console.log('HTML content set');
// 等待渲染完成
await page.waitForTimeout(1500);
// 验证页面中的PPT容器尺寸是否精确匹配
const actualDimensions = await page.evaluate(() => {
const container = document.getElementById('slideContainer');
const body = document.body;
const html = document.documentElement;
if (container) {
const rect = container.getBoundingClientRect();
return {
container: {
width: rect.width,
height: rect.height,
left: rect.left,
top: rect.top
},
body: {
width: body.offsetWidth,
height: body.offsetHeight
},
html: {
width: html.offsetWidth,
height: html.offsetHeight
},
viewport: {
width: window.innerWidth,
height: window.innerHeight
}
};
}
return null;
});
console.log('Page dimensions verification:', actualDimensions);
// 确保页面尺寸完全匹配PPT尺寸
if (actualDimensions && (
Math.abs(actualDimensions.viewport.width - pptDimensions.width) > 1 ||
Math.abs(actualDimensions.viewport.height - pptDimensions.height) > 1
)) {
console.warn('Page dimensions do not match PPT dimensions exactly, adjusting...');
await page.setViewport({
width: pptDimensions.width,
height: pptDimensions.height,
deviceScaleFactor: 2
});
await page.waitForTimeout(500);
}
console.log('Taking precise screenshot...');
// 截取精确的PPT内容区域,不包含任何白边
const screenshot = await page.screenshot({
type: 'jpeg',
quality: 95,
// 使用clip精确截取PPT内容区域
clip: {
x: 0,
y: 0,
width: pptDimensions.width,
height: pptDimensions.height
},
timeout: 10000
});
console.log('Screenshot taken successfully, size:', screenshot.length);
return screenshot;
} catch (error) {
console.error('Screenshot generation error:', error);
// 返回一个错误图片而不是抛出异常
return this.generateErrorImage(error.message, pptDimensions);
} finally {
if (browser) {
try {
await browser.close();
console.log('Browser closed');
} catch (closeError) {
console.error('Error closing browser:', closeError);
}
}
}
}
// 从HTML内容中提取PPT尺寸信息和长宽比
extractPptDimensions(htmlContent) {
// 方法1:从JavaScript变量中提取尺寸 - 这是最准确的方法
const dimensionsMatch = htmlContent.match(/window\.PPT_DIMENSIONS\s*=\s*{\s*width:\s*(\d+),\s*height:\s*(\d+)\s*}/);
if (dimensionsMatch) {
const width = parseInt(dimensionsMatch[1]);
const height = parseInt(dimensionsMatch[2]);
console.log('Extracted dimensions from JavaScript:', { width, height });
return { width, height };
}
// 方法2:从CSS样式中提取尺寸
const cssMatch = htmlContent.match(/\.slide-container\s*{\s*[^}]*width:\s*(\d+)px;[^}]*height:\s*(\d+)px;/s);
if (cssMatch) {
const width = parseInt(cssMatch[1]);
const height = parseInt(cssMatch[2]);
console.log('Extracted dimensions from CSS:', { width, height });
return { width, height };
}
// 方法3:从内联样式中提取尺寸
const inlineMatch = htmlContent.match(/width:\s*(\d+)px[^;]*;\s*height:\s*(\d+)px/);
if (inlineMatch) {
const width = parseInt(inlineMatch[1]);
const height = parseInt(inlineMatch[2]);
console.log('Extracted dimensions from inline styles:', { width, height });
return { width, height };
}
// 默认尺寸 - 使用标准PPT 16:9 比例
console.warn('Could not extract PPT dimensions from HTML, using default 16:9 ratio');
return { width: 1280, height: 720 }; // 16:9 标准比例
}
// 修改HTML内容以适应截图需求,确保零白边
modifyHtmlForScreenshot(htmlContent, pptDimensions) {
const { width, height } = pptDimensions;
// 创建完全匹配PPT尺寸的HTML,消除所有可能的白边
let modifiedHtml = htmlContent;
// 设置严格的CSS样式,确保页面尺寸完全匹配PPT尺寸
modifiedHtml = modifiedHtml.replace(
/<style>[\s\S]*?<\/style>/,
`<style>
* {
margin: 0 !important;
padding: 0 !important;
box-sizing: border-box !important;
border: none !important;
}
html {
width: ${width}px !important;
height: ${height}px !important;
overflow: hidden !important;
background: transparent !important;
min-width: ${width}px !important;
min-height: ${height}px !important;
max-width: ${width}px !important;
max-height: ${height}px !important;
}
body {
width: ${width}px !important;
height: ${height}px !important;
overflow: hidden !important;
font-family: 'Microsoft YaHei', Arial, sans-serif !important;
background: transparent !important;
position: absolute !important;
top: 0 !important;
left: 0 !important;
margin: 0 !important;
padding: 0 !important;
min-width: ${width}px !important;
min-height: ${height}px !important;
max-width: ${width}px !important;
max-height: ${height}px !important;
}
.slide-container {
width: ${width}px !important;
height: ${height}px !important;
position: absolute !important;
top: 0 !important;
left: 0 !important;
margin: 0 !important;
padding: 0 !important;
overflow: hidden !important;
background-color: var(--slide-bg-color, #ffffff) !important;
transform: none !important;
transform-origin: top left !important;
min-width: ${width}px !important;
min-height: ${height}px !important;
max-width: ${width}px !important;
max-height: ${height}px !important;
}
/* 确保所有元素都相对于slide-container定位 */
.slide-container > * {
position: absolute !important;
}
/* 确保背景图片也严格匹配尺寸 */
.slide-container::before {
width: ${width}px !important;
height: ${height}px !important;
top: 0 !important;
left: 0 !important;
margin: 0 !important;
padding: 0 !important;
}
</style>`
);
// 移除所有可能影响尺寸的JavaScript,确保固定尺寸
modifiedHtml = modifiedHtml.replace(
/<script>[\s\S]*?<\/script>/g,
`<script>
// 截图模式 - 固定尺寸,消除白边
console.log('Screenshot mode - exact dimensions: ${width}x${height}');
// 确保页面加载完成后设置精确的尺寸
window.addEventListener('load', function() {
// 设置容器精确尺寸
const container = document.getElementById('slideContainer');
if (container) {
container.style.cssText = \`
width: ${width}px !important;
height: ${height}px !important;
position: absolute !important;
top: 0 !important;
left: 0 !important;
margin: 0 !important;
padding: 0 !important;
transform: none !important;
overflow: hidden !important;
\`;
}
// 设置body和html精确尺寸
document.body.style.cssText = \`
width: ${width}px !important;
height: ${height}px !important;
margin: 0 !important;
padding: 0 !important;
overflow: hidden !important;
position: absolute !important;
top: 0 !important;
left: 0 !important;
\`;
document.documentElement.style.cssText = \`
width: ${width}px !important;
height: ${height}px !important;
margin: 0 !important;
padding: 0 !important;
overflow: hidden !important;
\`;
console.log('Exact dimensions applied for screenshot');
});
// 禁用所有可能的缩放和调整
window.addEventListener('resize', function(e) {
e.preventDefault();
e.stopPropagation();
});
</script>`
);
return modifiedHtml;
}
// 生成错误提示图片 - 使用动态尺寸
generateErrorImage(errorMessage = '截图生成失败', dimensions = { width: 1280, height: 720 }) {
const { width, height } = dimensions;
const canvas = `
<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
<rect width="${width}" height="${height}" fill="#f8f9fa"/>
<rect x="50" y="50" width="${width - 100}" height="${height - 100}" fill="white" stroke="#dee2e6" stroke-width="2"/>
<text x="${width / 2}" y="${height / 2 - 20}" text-anchor="middle" font-family="Arial" font-size="24" fill="#6c757d">
截图生成失败
</text>
<text x="${width / 2}" y="${height / 2 + 20}" text-anchor="middle" font-family="Arial" font-size="16" fill="#868e96">
${errorMessage}
</text>
</svg>
`;
return Buffer.from(canvas);
}
}
export default new ScreenshotService(); |