웹 페이지를 이미지 스냅샷으로 변환하는 것은 보고서 대시보드, 이메일 뉴스레터 또는 문서 아카이브를 구축할 때 자주 필요한 작업입니다. Aspose.OCR Cloud SDK for Java는 프로그래밍 방식으로 HTML 콘텐츠를 고품질 JPG 이미지로 렌더링할 수 있는 강력한 클라우드 기반 라이브러리를 제공합니다. 이 가이드에서는 Java에서 HTML을 JPG로 변환하는 방법을 배우게 되며, 단일 파일 변환, 배치 처리 및 성능 모범 사례를 다룹니다.

Java에서 HTML을 JPG로 변환 - 전제 조건 및 설정

시작하기 전에 다음 항목이 있는지 확인하십시오:

  • Java 8 이상이 설치되어 있어야 합니다.
  • Maven 또는 Gradle을 사용한 종속성 관리.
  • OCR 서비스용 APP SIDAPP KEY가 포함된 Aspose Cloud 계정.
  • Aspose OCR Cloud 엔드포인트에 대한 네트워크 액세스.

아래 Maven 종속성을 사용하여 프로젝트에 SDK를 추가하십시오. 동일한 좌표는 다운로드 페이지에서 확인할 수 있습니다.

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-ocr-cloud</artifactId>
    <version>25.9.0</version>
</dependency>

샘플 코드의 첫 번째 부분에 표시된 대로 필요한 클래스를 가져오고 자격 증명을 구성해야 합니다.

Java에서 HTML을 JPG로 변환 - 단계별 안내

1단계: 소스 문서를 로드하고 자격 증명을 구성합니다

Configuration 객체를 생성하고 APP SIDAPP KEY를 설정합니다. 이렇게 하면 라이브러리가 인증을 위해 준비됩니다.

Configuration config = new Configuration();
config.setAppSid(APP_SID);
config.setAppKey(APP_KEY);

2단계: OCR API 초기화

구성을 사용하여 OcrApi를 인스턴스화합니다. API 참조는 공식 API 참조에서 확인할 수 있습니다.

OcrApi ocrApi = new OcrApi(config);

3단계: 변환 요청 만들기

ConvertDocumentRequest를 생성하고, HTML 파일을 첨부한 뒤, 출력 형식으로 jpg를 지정합니다.

ConvertDocumentRequest request = new ConvertDocumentRequest();
request.setFile(new File(inputHtmlPath));
request.setOutputFormat("jpg");

4단계: 변환 실행

convertDocument를 호출하여 변환을 수행합니다. 응답에는 JPG 바이트가 포함됩니다.

ConvertDocumentResponse response = ocrApi.convertDocument(request);

단계 5: JPG 바이트를 디스크에 쓰기

반환된 바이트 배열을 FileOutputStream을 사용하여 파일에 저장합니다.

try (FileOutputStream fos = new FileOutputStream(outputJpgPath)) {
    fos.write(response.getFileData());
}

6단계 (선택 사항): 배치 변환 루프

배치 처리를 위해 폴더 내 모든 .HTML 파일을 반복하고, 각 파일에 대해 단계 3‑5를 반복하며 변환 결과를 기록합니다.

for (Path htmlPath : htmlFiles) {
    // Build request, execute conversion, write output (same as above)
    System.out.println("Converted: " + htmlPath + " -> " + outputJpgPath);
}

Java에서 HTML을 JPG로 변환 - 전체 코드 예제

다음 프로그램은 Aspose.OCR Cloud SDK for Java를 사용한 단일 파일 및 배치 변환을 모두 보여줍니다.

import com.aspose.ocr.cloud.ApiException;
import com.aspose.ocr.cloud.Configuration;
import com.aspose.ocr.cloud.api.OcrApi;
import com.aspose.ocr.cloud.model.ConvertDocumentRequest;
import com.aspose.ocr.cloud.model.ConvertDocumentResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class HtmlToJpgConverter {

// Replace with your actual Aspose OCR Cloud credentials
    private static final String APP_SID = "YOUR_APP_SID";
    private static final String APP_KEY = "YOUR_APP_KEY";

// Single conversion example
    private static void convertSingleHtml(String inputHtmlPath, String outputJpgPath) throws IOException, ApiException {
        // Prepare SDK configuration
        Configuration config = new Configuration();
        config.setAppSid(APP_SID);
        config.setAppKey(APP_KEY);

// Initialize API instance
        OcrApi ocrApi = new OcrApi(config);

// Build request
        ConvertDocumentRequest request = new ConvertDocumentRequest();
        request.setFile(new File(inputHtmlPath));
        request.setOutputFormat("jpg");

// Execute conversion
        ConvertDocumentResponse response = ocrApi.convertDocument(request);

// Write the resulting JPG bytes to file
        try (FileOutputStream fos = new FileOutputStream(outputJpgPath)) {
            fos.write(response.getFileData());
        }
    }

// Batch conversion example
    private static void convertBatchHtml(String inputFolder, String outputFolder) throws IOException, ApiException {
        // Prepare SDK configuration
        Configuration config = new Configuration();
        config.setAppSid(APP_SID);
        config.setAppKey(APP_KEY);

// Initialize API instance
        OcrApi ocrApi = new OcrApi(config);

// Ensure output directory exists
        Files.createDirectories(Paths.get(outputFolder));

// Collect all .html files from the input folder
        List<Path> htmlFiles;
        try (Stream<Path> walk = Files.walk(Paths.get(inputFolder))) {
            htmlFiles = walk.filter(Files::isRegularFile)
                    .filter(p -> p.toString().toLowerCase().endsWith(".html"))
                    .collect(Collectors.toList());
        }

// Process each file
        for (Path htmlPath : htmlFiles) {
            String fileNameWithoutExt = com.google.common.io.Files.getNameWithoutExtension(htmlPath.getFileName().toString());
            String outputJpgPath = Paths.get(outputFolder, fileNameWithoutExt + ".jpg").toString();

// Build request
            ConvertDocumentRequest request = new ConvertDocumentRequest();
            request.setFile(htmlPath.toFile());
            request.setOutputFormat("jpg");

// Execute conversion
            ConvertDocumentResponse response = ocrApi.convertDocument(request);

// Write JPG output
            try (FileOutputStream fos = new FileOutputStream(outputJpgPath)) {
                fos.write(response.getFileData());
            }

System.out.println("Converted: " + htmlPath + " -> " + outputJpgPath);
        }
    }

public static void main(String[] args) {
        try {
            // Example of single file conversion
            convertSingleHtml("sample.html", "sample.jpg");

// Example of batch conversion
            convertBatchHtml("input_html", "output_jpg");
        } catch (IOException | ApiException e) {
            e.printStackTrace();
        }
    }
}

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

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

순수 REST 방식을 선호한다면, 동일한 변환을 cURL 명령으로 수행할 수 있습니다. 워크플로는 인증, 파일 업로드, 변환 요청 및 결과 다운로드로 구성됩니다.

1. Authenticate and Get Access Token

YOUR_CLIENT_IDYOUR_CLIENT_SECRET를 귀하의 자격 증명으로 교체하십시오.

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"

응답에는 이후 호출에서 사용할 access_token이 포함되어 있습니다.

2. 소스 HTML 파일 업로드

토큰을 변수 $TOKEN에 저장했다고 가정합니다.

curl -X POST "https://api.aspose.cloud/v4.0/ocr/upload" \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@sample.html"

업로드는 저장된 문서를 식별하는 fileId를 반환합니다.

3. 변환 실행

JPG로 변환을 요청합니다.

curl -X POST "https://api.aspose.cloud/v4.0/ocr/convert?outputFormat=jpg&fileId=$FILE_ID" \
  -H "Authorization: Bearer $TOKEN"

응답 본문에는 JPG 바이너리 데이터가 포함되어 있습니다.

4. 출력 파일 다운로드

바이너리 스트림을 로컬 파일에 저장합니다.

curl -X GET "https://api.aspose.cloud/v4.0/ocr/download?fileId=$FILE_ID&format=jpg" \
  -H "Authorization: Bearer $TOKEN" \
  -o sample.jpg

요청 매개변수 및 오류 처리에 대한 자세한 내용은 공식 API 문서를 참조하십시오.

결론

Java에서 HTML을 JPG로 변환하는 것은 Aspose.OCR Cloud SDK for Java를 사용하면 간단합니다. 설정 단계를 따라가고 제공된 코드 샘플을 사용하거나 cURL로 REST API를 호출하면 웹 콘텐츠에 대한 이미지 미리보기를 빠르고 안정적으로 생성할 수 있습니다. 프로덕션 배포를 위해 적절한 라이선스를 획득하는 것을 기억하세요; 가격 세부 정보는 제품 페이지에서 확인할 수 있으며, 임시 라이선스 페이지에서 임시 라이선스를 요청할 수 있습니다. 오늘 바로 HTML‑to‑JPG 변환을 통합하여 애플리케이션의 시각적 경험을 향상시키세요.

자주 묻는 질문

  • HTML을 Java에서 많은 코드를 작성하지 않고 JPG로 변환하려면 어떻게 해야 하나요?
    워크스루에 표시된 한 줄 코드를 사용하십시오: ConvertDocumentRequest를 생성하고 파일과 outputFormat"jpg"로 설정한 다음 ocrApi.convertDocument(request)를 호출합니다. SDK가 렌더링을 처리하고 JPG 바이트를 반환합니다.

  • Java에서 HTML 파일을 일괄적으로 JPG로 변환할 수 있나요?
    예. 예제의 convertBatchHtml 메서드는 디렉터리를 순회하며 각 .HTML 파일에 대한 요청을 생성하고 각 JPG 출력을 기록합니다. 이 접근 방식은 대용량 컬렉션에서도 잘 확장됩니다.

  • HTML을 JPG로 변환하는 Java 코드는 무엇인가요?
    위의 전체 코드 예제는 필요한 정확한 Java 코드를 보여줍니다. 여기에는 자격 증명 구성, 요청 빌드, 실행 및 파일 쓰기가 포함됩니다.

  • 구매 라이선스 구매 전에 변환을 테스트할 수 있는 방법이 있나요?
    개발 중 비용 없이 라이브러리를 평가하기 위해 임시 라이선스 페이지에서 임시 라이선스를 얻을 수 있습니다.

자세히 읽기