logo
HWPJS
  • 가이드
  • API
  • 명세서
  • 로드맵
  • 백로그
    가이드
    빠른 시작
    설치하기
    데모
    CLI 사용 가이드
    예제
    개발 환경 설정
    Previous pageCLI 사용 가이드Next page개발 환경 설정

    #예제

    HWPJS를 사용하는 다양한 예제를 확인하세요.

    #기본 예제

    Web
    React Native
    Node.js
    // buffer-polyfill을 먼저 import한 후
    import './buffer-polyfill';
    import * as hwpjs from '@ohah/hwpjs';
    
    // 파일 입력에서 HWP 파일 읽기
    const fileInput = document.querySelector('input[type="file"]');
    fileInput.addEventListener('change', async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;
    
      try {
        const arrayBuffer = await file.arrayBuffer();
        const data = new Uint8Array(arrayBuffer);
    
        // JSON으로 변환
        const result = hwpjs.toJson(data);
        console.log('변환 성공:', result);
      } catch (error) {
        console.error('변환 실패:', error);
      }
    });
    import { Hwpjs } from '@ohah/hwpjs';
    import RNFS from 'react-native-fs';
    import { Platform } from 'react-native';
    
    try {
      // 파일 경로 설정
      const filePath = Platform.OS === 'ios' 
        ? `${RNFS.MainBundlePath}/document.hwp`
        : `${RNFS.DocumentDirectoryPath}/document.hwp`;
    
      // 파일을 base64로 읽기
      const fileData = await RNFS.readFile(filePath, 'base64');
    
      // base64를 ArrayBuffer로 변환
      const binaryString = atob(fileData);
      const length = binaryString.length;
      const bytes = new Uint8Array(length);
      for (let i = 0; i < length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }
    
      // HWP 파일 파싱 (ArrayBuffer 직접 사용)
      const result = Hwpjs.toJson(bytes.buffer);
      console.log('변환 성공:', result);
    } catch (error) {
      console.error('변환 실패:', error);
    }
    import { readFileSync } from 'fs';
    import { toJson } from '@ohah/hwpjs';
    
    try {
      const fileBuffer = readFileSync('./document.hwp');
      const data = new Uint8Array(fileBuffer);
      const result = toJson(data);
      console.log('변환 성공:', result);
    } catch (error) {
      if (error instanceof Error) {
        console.error('변환 실패:', error.message);
      } else {
        console.error('변환 실패:', error);
      }
    }

    #마크다운 변환

    Web
    React Native
    Node.js
    import './buffer-polyfill';
    import * as hwpjs from '@ohah/hwpjs';
    
    const fileInput = document.querySelector('input[type="file"]');
    fileInput.addEventListener('change', async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;
    
      try {
        const arrayBuffer = await file.arrayBuffer();
        const data = new Uint8Array(arrayBuffer);
    
        // 마크다운으로 변환
        const markdownResult = hwpjs.toMarkdown(data, {
          image: 'base64',
          useHtml: true,
          includeVersion: true,
          includePageInfo: false,
        });
        console.log('마크다운 변환 성공:', markdownResult.markdown);
      } catch (error) {
        console.error('변환 실패:', error);
      }
    });
    import { Hwpjs } from '@ohah/hwpjs';
    import RNFS from 'react-native-fs';
    import { Platform } from 'react-native';
    
    try {
      const filePath = Platform.OS === 'ios' 
        ? `${RNFS.MainBundlePath}/document.hwp`
        : `${RNFS.DocumentDirectoryPath}/document.hwp`;
      const fileData = await RNFS.readFile(filePath, 'base64');
      
      // base64를 ArrayBuffer로 변환
      const binaryString = atob(fileData);
      const length = binaryString.length;
      const bytes = new Uint8Array(length);
      for (let i = 0; i < length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }
    
      const result = Hwpjs.toMarkdown(bytes.buffer, {
        image: 'base64',
        useHtml: false,
        includeVersion: false,
        includePageInfo: false,
      });
      console.log('마크다운 변환 성공:', result.markdown);
    } catch (error) {
      console.error('변환 실패:', error);
    }
    import { readFileSync } from 'fs';
    import { toMarkdown } from '@ohah/hwpjs';
    
    try {
      const fileBuffer = readFileSync('./document.hwp');
      const result = toMarkdown(fileBuffer, {
        image: 'base64',
        useHtml: false,
        includeVersion: false,
        includePageInfo: false,
      });
      console.log('마크다운 변환 성공:', result.markdown);
    } catch (error) {
      console.error('변환 실패:', error);
    }

    #HTML 변환

    Web
    React Native
    Node.js
    import './buffer-polyfill';
    import * as hwpjs from '@ohah/hwpjs';
    
    const fileInput = document.querySelector('input[type="file"]');
    fileInput.addEventListener('change', async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;
    
      try {
        const arrayBuffer = await file.arrayBuffer();
        const data = new Uint8Array(arrayBuffer);
    
        // HTML로 변환 (이미지는 base64로 임베드)
        const html = hwpjs.toHtml(data, {
          includeVersion: true,
          includePageInfo: false,
        });
        
        // HTML을 화면에 표시
        const outputDiv = document.getElementById('output');
        if (outputDiv) {
          outputDiv.innerHTML = html;
        }
      } catch (error) {
        console.error('변환 실패:', error);
      }
    });
    import { Hwpjs } from '@ohah/hwpjs';
    import RNFS from 'react-native-fs';
    import { Platform } from 'react-native';
    import { WebView } from 'react-native-webview';
    
    try {
      const filePath = Platform.OS === 'ios' 
        ? `${RNFS.MainBundlePath}/document.hwp`
        : `${RNFS.DocumentDirectoryPath}/document.hwp`;
      const fileData = await RNFS.readFile(filePath, 'base64');
      
      // base64를 ArrayBuffer로 변환
      const binaryString = atob(fileData);
      const length = binaryString.length;
      const bytes = new Uint8Array(length);
      for (let i = 0; i < length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }
    
      const html = Hwpjs.toHtml(bytes.buffer, {
        includeVersion: false,
        includePageInfo: false,
      });
      
      // WebView로 HTML 표시
      <WebView source={{ html }} />
    } catch (error) {
      console.error('변환 실패:', error);
    }
    import { readFileSync, writeFileSync } from 'fs';
    import { toHtml } from '@ohah/hwpjs';
    
    try {
      const fileBuffer = readFileSync('./document.hwp');
      
      // HTML로 변환 (이미지는 base64로 임베드)
      const html = toHtml(fileBuffer, {
        includeVersion: true,
        includePageInfo: false,
      });
      
      // HTML 파일로 저장
      writeFileSync('./output.html', html, 'utf-8');
      console.log('HTML 변환 성공: output.html');
      
      // 또는 이미지를 별도 파일로 저장하려면
      // const htmlWithImages = toHtml(fileBuffer, {
      //   imageOutputDir: './images',
      //   htmlOutputDir: './',
      //   includeVersion: true,
      //   includePageInfo: false,
      // });
      // writeFileSync('./output.html', htmlWithImages, 'utf-8');
    } catch (error) {
      console.error('변환 실패:', error);
    }

    HTML 변환 특징:

    • 기본적으로 이미지는 base64 데이터 URI로 HTML에 임베드됩니다
    • imageOutputDir 옵션을 지정하면 이미지를 별도 파일로 저장하고 상대 경로로 참조합니다
    • 완전한 HTML 문서 (<html>, <head>, <body> 포함)를 생성합니다
    • CSS 클래스 기반 스타일링을 사용합니다

    #buffer-polyfill.ts 파일 생성

    Web 환경에서는 WASM을 사용하기 위해 buffer-polyfill.ts를 먼저 import해야 합니다.

    프로젝트에 buffer-polyfill.ts 파일을 생성하고 다음 내용을 추가하세요:

    // Buffer polyfill for napi-rs WASM compatibility
    // This must be imported before any WASM modules
    if (typeof globalThis.Buffer === 'undefined') {
      globalThis.Buffer = class Buffer extends Uint8Array {
        static from(data: any) {
          if (data instanceof Uint8Array) return data;
          if (data instanceof ArrayBuffer) return new Uint8Array(data);
          if (Array.isArray(data)) return new Uint8Array(data);
          return new Uint8Array(data);
        }
        static isBuffer(obj: any) {
          return obj instanceof Uint8Array;
        }
      } as any;
    }
    
    // Ensure Buffer is set on window as well for compatibility
    if (typeof window !== 'undefined' && typeof window.Buffer === 'undefined') {
      (window as any).Buffer = globalThis.Buffer;
    }