웹 포털이나 보고서 도구를 구축할 때 Word 문서를 이미지 미리보기로 변환하는 경우가 자주 있습니다. Aspose.OMR Cloud SDK for PHP는 PHP 개발자가 DOCX를 JPG로 고품질로 프로그래밍 방식으로 변환할 수 있도록 지원합니다. 이 튜토리얼에서는 전체 PHP 예제와 동등한 cURL REST 워크플로우, 그리고 환경을 준비하는 데 필요한 모든 것을 확인할 수 있습니다. 끝까지 진행하면 모든 PHP 애플리케이션에 통합할 수 있는 재사용 가능한 솔루션을 얻게 됩니다.

PHP에서 Aspose.OMR Cloud SDK를 사용하여 DOCX를 JPG로 변환하는 전체 작업 예제

이 예제는 Aspose.OMR Cloud SDK for PHP를 사용하여 DOCX 파일을 JPG 이미지로 변환하는 방법을 보여줍니다.

<?php
require __DIR__ . '/vendor/autoload.php';

use Aspose\OMR\Configuration;
use Aspose\OMR\Api\ConvertApi;
use Aspose\OMR\Model\ConvertDocumentRequest;
use Aspose\OMR\ApiException;

// -----------------------------------------------------------------------------
// Configuration – replace with your actual credentials
// -----------------------------------------------------------------------------
$config = new Configuration();
$config->setAppSid('YOUR_APP_SID');
$config->setApiKey('YOUR_API_KEY');

// -----------------------------------------------------------------------------
// Initialize the Convert API
// -----------------------------------------------------------------------------
$convertApi = new ConvertApi($config);

// -----------------------------------------------------------------------------
// File paths (adjust as needed)
// -----------------------------------------------------------------------------
$inputDocxPath  = __DIR__ . '/input.docx';
$outputJpgPath  = __DIR__ . '/output.jpg';

// -----------------------------------------------------------------------------
// Prepare request – stream the input file to avoid loading whole file into memory
// -----------------------------------------------------------------------------
$inputStream = fopen($inputDocxPath, 'rb');
if ($inputStream === false) {
    throw new RuntimeException("Unable to open input file: $inputDocxPath");
}

$request = new ConvertDocumentRequest();
$request->setFile($inputStream);          // Input DOCX stream
$request->setOutputFormat('jpg');         // Desired output format
$request->setOutputFileName('output.jpg'); // Optional: name for the generated file

try {
    // -------------------------------------------------------------------------
    // Perform conversion
    // -------------------------------------------------------------------------
    $responseStream = $convertApi->convertDocument($request);

// -------------------------------------------------------------------------
    // Write the resulting JPG to disk using a buffered copy (efficient for large files)
    // -------------------------------------------------------------------------
    $outputHandle = fopen($outputJpgPath, 'wb');
    if ($outputHandle === false) {
        throw new RuntimeException("Unable to open output file: $outputJpgPath");
    }

while (!feof($responseStream)) {
        $buffer = fread($responseStream, 8192);
        if ($buffer === false) {
            throw new RuntimeException('Error reading from response stream.');
        }
        fwrite($outputHandle, $buffer);
    }

fclose($outputHandle);
    fclose($inputStream);
    fclose($responseStream);

echo "Conversion successful. JPG saved to: $outputJpgPath\n";
} catch (ApiException $e) {
    // -------------------------------------------------------------------------
    // Handle API errors (e.g., authentication, unsupported format)
    // -------------------------------------------------------------------------
    fclose($inputStream);
    echo 'API Exception: ', $e->getMessage(), PHP_EOL;
    exit(1);
} catch (Exception $e) {
    // -------------------------------------------------------------------------
    // General error handling
    // -------------------------------------------------------------------------
    if (is_resource($inputStream)) {
        fclose($inputStream);
    }
    echo 'Error: ', $e->getMessage(), PHP_EOL;
    exit(1);
}

참고: 이 코드 예제는 핵심 기능을 보여줍니다. 프로젝트에서 사용하기 전에 파일 경로와 구성 값을 실제 환경에 맞게 업데이트하고, 모든 필수 종속성이 올바르게 설치되었는지 확인하며, 개발 환경에서 충분히 테스트하십시오. 문제가 발생하면 공식 문서를 참조하거나 지원 팀에게 문의하십시오.

cURL을 사용한 REST API를 통한 DOCX에서 JPG 변환

순수 REST 접근 방식을 선호한다면, 동일한 변환을 몇 개의 cURL 명령으로 수행할 수 있습니다.

  1. 액세스 토큰 얻기 - 자리 표시자를 클라이언트 자격 증명으로 교체하십시오.
curl -X POST "https://api.aspose.cloud/connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
  1. DOCX 파일 업로드 - 이전 단계에서 받은 토큰을 사용합니다.
curl -X PUT "https://api.aspose.cloud/v4.0/omr/storage/file/input.docx" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document" \
  --data-binary "@input.docx"
  1. JPG로 변환 요청.
curl -X POST "https://api.aspose.cloud/v4.0/omr/convert" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
        "FileName": "input.docx",
        "OutputFormat": "jpg",
        "OutputFileName": "output.jpg"
      }' -o response.json
  1. 생성된 JPG 다운로드.
curl -X GET "https://api.aspose.cloud/v4.0/omr/storage/file/output.jpg" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -o output.jpg

전체 참조는 공식 API 문서를 참조하십시오.

PHP와 Aspose.OMR Cloud SDK를 사용한 DOCX를 JPG로 변환하기 분석

다음 번호 매긴 설명은 PHP 워크플로에서 DOCX를 JPG로 변환하는 PHP 코드의 각 부분을 설명합니다.

  1. 구성 설정 - Configuration 클래스는 AppSid와 ApiKey를 보유합니다.
$config = new Configuration();
$config->setAppSid('YOUR_APP_SID');
$config->setApiKey('YOUR_API_KEY');
  1. API 초기화 - ConvertApi 인스턴스가 구성과 함께 생성됩니다.
$convertApi = new ConvertApi($config);
  1. 입력 스트림 준비 - DOCX 파일은 전체 파일을 메모리로 로드하는 것을 방지하기 위해 바이너리 스트림으로 열립니다.
$inputStream = fopen($inputDocxPath, 'rb');
  1. 요청 빌드 - ConvertDocumentRequest는 입력 스트림, 원하는 출력 형식(jpg), 및 선택적 출력 파일 이름을 지정합니다.
$request = new ConvertDocumentRequest();
$request->setFile($inputStream);
$request->setOutputFormat('jpg');
$request->setOutputFileName('output.jpg');
  1. 변환 실행 및 결과 저장 - convertDocument는 응답 스트림을 반환하며, 이는 버퍼링된 복사를 사용하여 output.jpg에 기록됩니다.
$responseStream = $convertApi->convertDocument($request);
$outputHandle = fopen($outputJpgPath, 'wb');
while (!feof($responseStream)) {
    $buffer = fread($responseStream, 8192);
    fwrite($outputHandle, $buffer);
}

ConvertApi 클래스에 대한 자세한 내용은 API 참조를 참조하십시오.

PHP에서 Aspose.OMR Cloud SDK를 위한 환경 준비

  1. Composer를 통해 SDK 설치
composer require aspose/aspose-omr-cloud

패키지는 release page에서도 다운로드할 수 있습니다.

  1. PHP 버전 확인 - SDK는 PHP 7.2 이상이 필요합니다.

  2. 자격 증명 설정 - 코드에서 YOUR_APP_SID와 YOUR_API_KEY를 Aspose Cloud 계정의 값으로 교체하십시오.

  3. 자동 로드 종속성 - vendor/autoload.php 파일은 Composer에 의해 생성되며 필요한 모든 클래스를 로드합니다.

이러한 단계가 완료되면, PHP에서 Aspose.OMR Cloud SDK를 사용하여 DOCX를 JPG로 변환할 준비가 되었습니다.

결론

이제 Aspose.OMR Cloud SDK를 사용하여 PHP에서 DOCX를 JPG로 효율적으로 변환하는 방법을 알게 되었습니다. 제공된 코드 샘플, REST cURL 워크플로우 및 설정 안내는 Laravel 애플리케이션을 포함한 모든 PHP 프로젝트에 통합할 수 있는 완전한 프로덕션‑준비 솔루션을 제공합니다. 상업적 사용을 위해서는 Aspose.OMR Cloud SDK for PHP 제품 페이지에서 라이선스를 구매하십시오; 임시 라이선스는 임시 라이선스 페이지에서도 이용할 수 있습니다. 오늘 바로 Word 문서를 고품질 JPG 이미지로 변환해 보세요.

자주 묻는 질문

DOCX를 PHP에서 JPG로 변환하려면 어떻게 해야 하나요?
Aspose.OMR Cloud SDK for PHP를 사용하십시오. SDK를 설치하고 자격 증명을 구성한 후 위의 PHP 코드 예제는 DOCX 파일을 JPG 이미지로 변환하는 정확한 단계를 보여줍니다.

Laravel에서 PHP로 DOCX를 JPG로 변환할 수 있나요?
예. SDK는 Laravel을 포함한 모든 PHP 프레임워크와 함께 작동합니다. 변환 로직을 컨트롤러나 서비스 클래스에 넣고 라우트에서 호출하십시오.

DOCX를 고해상도 JPG로 변환하는 가장 좋은 방법은 무엇인가요?
변환 요청에서 출력 해상도 매개변수(지원되는 경우)를 조정하십시오. SDK는 요청 본문에 DPI 설정을 지정하여 고품질 JPG 출력을 가능하게 합니다.

PHP에서 단일 스크립트로 여러 DOCX를 JPG로 변환할 수 있나요?
물론입니다. DOCX 파일 경로 배열을 순회하고 동일한 ConvertApi 인스턴스를 재사용하며 각 파일에 대해 convertDocument를 호출합니다. 이 접근 방식은 배치 처리에 잘 확장됩니다.

더 읽기