본문으로 건너뛰기

Office 문서에 연결

Office iframe을 내장하고, @thinkfree.dev/tfo-sdk를 연결하고, 편집기를 기다린 뒤 활성 문서를 읽습니다.

결과: SDK가 iframe에 연결되어 열려 있는 문서의 데이터를 반환합니다.

시작하기 전에

  • Node.js와 npm을 준비합니다.
  • Word, Spreadsheet 또는 Presentation 문서의 Office 문서 open URL을 준비합니다.
  • 호스트 페이지가 해당 Office origin을 내장할 수 있는지 확인합니다.
  • 배포 환경에서는 HTTPS origin을 사용합니다.

npm에 공개된 @thinkfree.dev/tfo-sdk를 프로젝트 디렉터리에 설치합니다.

npm install @thinkfree.dev/tfo-sdk

일반 HTML로 실행하려면 index.html<head>에 다음 import map을 넣어 설치된 ESM 파일을 연결합니다. 이후 예제의 JavaScript는 iframe 뒤의 <script type="module"> 안에 순서대로 넣습니다. 번들러 프로젝트에서는 import map 없이 패키지 이름으로 import할 수 있습니다.

<script type="importmap">
{"imports":{"@thinkfree.dev/tfo-sdk":"./node_modules/@thinkfree.dev/tfo-sdk/dist/index.js"}}
</script>

Python 3가 설치된 경우 프로젝트 디렉터리에서 다음 명령으로 로컬 서버를 실행한 뒤 http://localhost:3000을 엽니다. file://로 HTML을 직접 열지 않습니다.

python3 -m http.server 3000 --bind 127.0.0.1

1. 편집기 내장

<iframe
id="office-frame"
title="Thinkfree Office document"
src="YOUR_OFFICE_DOCUMENT_OPEN_URL"
></iframe>

open URL은 Office/스토리지 통합이 발급합니다. SDK가 만들지 않습니다.

2. 편집기에 연결

open URL의 문서 종류에 맞는 진입점을 호출합니다 - Office.word, Office.cell(Spreadsheet), Office.show(Presentation).

import { Office } from "@thinkfree.dev/tfo-sdk";

const iframe = document.querySelector("#office-frame");
const word = Office.word(iframe); // origin is derived from iframe.src

편집기 origin은 정확해야 하며 *일 수 없습니다. SDK는 다른 origin의 메시지를 무시합니다. iframe에 아직 src가 없거나 data:/blob: URL이면 origin을 명시하십시오: Office.word(iframe, { frameworkOrigin }).

3. 편집기를 기다린 뒤 문서 읽기

whenReady()는 편집기의 SDK 브리지가 응답할 때까지 폴링하므로, iframe 로드가 시작된 직후에 바로 호출할 수 있습니다.

try {
await word.whenReady(); // default limit 60 s
const doc = word.getDocument(); // document handle; no round trip
const body = await doc.getBody();
const text = await body.getText();
console.log("Document text:", text);
} catch (error) {
console.error("Editor SDK request failed", error.code, error.message);
}

예상 결과: 콘솔에 Word 문서의 텍스트가 출력됩니다. 시간 초과는 편집기가 준비되지 않았거나, origin이 잘못되었거나, 편집기 빌드가 요청한 SDK 명령을 노출하지 않는다는 뜻입니다.

문서 메서드는 앱 핸들이 아니라 문서 핸들에 있습니다. getDocument()는 왕복 없이 그 핸들을 반환하므로, 변수에 담아 두고 getBody()를 비롯한 문서 메서드를 그 핸들에서 호출하십시오.

4. 연결 해제

window.addEventListener("pagehide", () => word.disconnect());

disconnect()는 멱등입니다. 메시지 리스너를 제거하고 대기 중인 요청을 DESTROYED 오류로 거부합니다. 편집기와 문서에는 영향이 없습니다. Office.word(iframe)을 다시 호출하면 새 핸들이 반환됩니다. iframe src를 다른 문서나 모듈로 바꾸기 전에 연결을 해제하십시오.

이 흐름이 동작하면 Word, Spreadsheet, Presentation API 레퍼런스에서 정확한 메서드, 매개변수, 반환 타입을 확인합니다.

모듈 사용해 보기

아래 코드는 위 HTML·import map·서버 설정을 사용합니다. 예제 하나를 선택해 모듈 스크립트에 넣고, iframe에 해당 문서 종류를 로드합니다. Word와 Presentation 예제는 문서를 변경하므로 샘플이나 복사본에서 실행합니다.

Word

import { Office, Word } from "@thinkfree.dev/tfo-sdk";

const iframe = document.querySelector("#office-frame");
const word = Office.word(iframe);
await word.whenReady();

const doc = word.getDocument();
const body = await doc.getBody();
const para = await body.insertParagraph("Hello from tfo-sdk");
await para.setStyle(Word.Style.HEADING_1);

Spreadsheet

// Navigation calls build a path; the terminal call makes the request.
import { Office } from "@thinkfree.dev/tfo-sdk";

const iframe = document.querySelector("#office-frame");
const cell = Office.cell(iframe);
await cell.whenReady();

const ws = await cell.getWorkbook().getWorksheet(0);
const values = await ws.getRange("A1:B2").getValues();
console.log("A1:B2 values:", values);

Presentation

import { Office, ShapePreset } from "@thinkfree.dev/tfo-sdk";

const iframe = document.querySelector("#office-frame");
const show = Office.show(iframe);
await show.whenReady();

const slides = await show.getDocument().getSlides();
if (slides.length === 0) throw new Error("Open a presentation with at least one slide.");
const shape = await slides[0].insertShape(ShapePreset.RECT);

iframe 하나는 모듈 하나에 바인딩됩니다. Spreadsheet나 Presentation을 열려면 해당 open URL을 iframe(또는 다른 iframe)에 로드하고 그 iframe에 Office.cell 또는 Office.show를 사용하십시오.

문제 해결

증상확인과 조치
INVALID_ARGUMENTiframe 요소와 문서 종류를 확인합니다. 다른 모듈에 연결한 iframe은 disconnect() 후 새로 연결합니다.
TIMEOUTiframe 안의 열기 오류부터 확인합니다. 문서가 정상 표시된 뒤 정확한 origin과 Office·SDK 버전 조합을 확인하고 재시도합니다.
FRAMEWORK_ERROR편집기 작업이 반환한 error.data.error.code
메시지가 수신되지 않음호스트와 iframe origin이 구성된 통합과 일치해야 함

모듈 가이드 - Word API, Spreadsheet API, Presentation API - 로 이어가거나, 프로덕션 애플리케이션에 SDK를 추가하기 전에 아키텍처 및 수명 주기를 읽으십시오.