PDF. * Requires onlyoffice_convert_url (e.g. https://office.clientright.ru:9443/ConvertService.ashx or /converter). */ class OnlyOfficeTemplates_ConvertService { protected $convertUrl; protected $documentServerBase; public function __construct(array $config) { $this->convertUrl = rtrim($config['onlyoffice_convert_url'] ?? '', '/'); if (strpos($this->convertUrl, '/converter') !== false) { $this->documentServerBase = preg_replace('#/converter.*$#', '', $this->convertUrl); } else { $this->documentServerBase = preg_replace('#/ConvertService\.ashx.*$#', '', $this->convertUrl); } } /** * Convert DOCX at given URL to PDF. * * @param string $docxUrl Absolute URL to DOCX (must be accessible by Document Server) * @param string $title File name for display * @return array [ 'success' => bool, 'pdfPath' => temp file path, 'error' => message ] */ public function convertToPdf($docxUrl, $title = 'document.docx') { if (empty($this->convertUrl)) { return ['success' => false, 'error' => 'OnlyOffice conversion URL not configured (OOT_ONLYOFFICE_CONVERT_URL).']; } $key = md5($docxUrl . time()); $body = [ 'async' => false, 'filetype' => 'docx', 'key' => $key, 'outputtype' => 'pdf', 'title' => $title, 'url' => $docxUrl, ]; $ctx = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => "Content-Type: application/json\r\nAccept: application/json\r\n", 'content' => json_encode($body), 'timeout' => 120, ], 'ssl' => ['verify_peer' => false, 'verify_peer_name' => false], ]); $response = @file_get_contents($this->convertUrl, false, $ctx); if ($response === false) { return ['success' => false, 'error' => 'Conversion request failed (connection or timeout).']; } $data = json_decode($response, true); if (!$data) { $data = ['error' => -1, 'endConvert' => false]; } if (!empty($data['error'])) { return ['success' => false, 'error' => 'Conversion error code: ' . $data['error']]; } if (empty($data['endConvert']) || empty($data['fileUrl'])) { return ['success' => false, 'error' => 'Conversion did not return file URL.']; } $fileUrl = $data['fileUrl']; if (strpos($fileUrl, 'http') !== 0) { $fileUrl = rtrim($this->documentServerBase, '/') . '/' . ltrim($fileUrl, '/'); } $tempPdf = sys_get_temp_dir() . '/oot_pdf_' . uniqid() . '.pdf'; $pdfContent = @file_get_contents($fileUrl, false, stream_context_create(['http' => ['timeout' => 60], 'ssl' => ['verify_peer' => false]])); if ($pdfContent === false || strlen($pdfContent) === 0) { return ['success' => false, 'error' => 'Failed to download converted PDF from Document Server.']; } file_put_contents($tempPdf, $pdfContent); return ['success' => true, 'pdfPath' => $tempPdf]; } }