( ′∀`)σ≡σ☆))Д′)レ(゚∀゚;)ヘ=З=З=Зε≡(ノ´_ゝ`)ノ
<?php
// Allowed output formats
$allowedFormats = ['png', 'jpeg', 'pdf'];
// Get POST parameters
$htmlContent = $_POST['html'] ?? '';
$htmlContent = urldecode($htmlContent);
$format = $_POST['format'] ?? 'png';
$format = strtolower($format);
// Validate inputs
if (empty($htmlContent)) {
http_response_code(400);
echo "Error: Missing HTML content.";
exit;
}
if (!in_array($format, $allowedFormats)) {
http_response_code(400);
echo "Error: Invalid output format. Allowed formats: " . implode(', ', $allowedFormats);
exit;
}
// Ensure tmp directory exists
$tmpDir = __DIR__ . '/tmp/';
if (!is_dir($tmpDir)) {
mkdir($tmpDir, 0777, true);
}
// Save base64-encoded HTML to temp file
$tmpHtmlFile = $tmpDir . 'html_' . uniqid() . '.txt';
file_put_contents($tmpHtmlFile, base64_encode($htmlContent));
// Define output file path with correct extension
$tmpOutputFile = $tmpDir . 'output_' . uniqid() . '.' . $format;
// Node.js script path
$nodeScript = __DIR__ . '/savePNG3.js';
// Build and run the command
$cmd = escapeshellcmd("node '$nodeScript' '$tmpHtmlFile' '$tmpOutputFile' '$format'") . ' 2>&1';
exec($cmd, $output, $returnVar);
// Handle errors
if ($returnVar !== 0 || !file_exists($tmpOutputFile)) {
http_response_code(500);
echo "Error: Conversion failed.<br>";
echo "Details:<br>" . implode("<br>", $output);
@unlink($tmpHtmlFile);
exit;
}
// MIME types for output formats
$mimeTypes = [
'png' => 'image/png',
'jpeg' => 'image/jpeg',
'pdf' => 'application/pdf',
];
// Output file to browser
$mime = $mimeTypes[$format] ?? 'application/octet-stream';
header('Content-Description: File Transfer');
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="converted.' . $format . '"');
header('Content-Length: ' . filesize($tmpOutputFile));
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
readfile($tmpOutputFile);
// Cleanup
@unlink($tmpHtmlFile);
@unlink($tmpOutputFile);
exit;