1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
|
"use client";
import React, {
useState,
useEffect,
useRef,
SetStateAction,
Dispatch,
} from "react";
import { WebViewerInstance } from "@pdftron/webviewer";
import { Loader2 } from "lucide-react";
import { toast } from "sonner";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
interface BasicContractSignViewerProps {
contractId?: number;
filePath?: string;
isOpen?: boolean;
onClose?: () => void;
onSign?: (documentData: ArrayBuffer) => Promise<void>;
instance: WebViewerInstance | null;
setInstance: Dispatch<SetStateAction<WebViewerInstance | null>>;
}
export function BasicContractSignViewer({
contractId,
filePath,
isOpen = false,
onClose,
onSign,
instance,
setInstance,
}: BasicContractSignViewerProps) {
const [fileLoading, setFileLoading] = useState<boolean>(true);
const viewer = useRef<HTMLDivElement>(null);
const initialized = useRef(false);
const isCancelled = useRef(false);
const [showDialog, setShowDialog] = useState(isOpen);
// 다이얼로그 상태 동기화
useEffect(() => {
setShowDialog(isOpen);
}, [isOpen]);
// WebViewer 초기화
useEffect(() => {
if (!initialized.current && viewer.current) {
initialized.current = true;
isCancelled.current = false;
requestAnimationFrame(() => {
if (viewer.current) {
import("@pdftron/webviewer").then(({ default: WebViewer }) => {
if (isCancelled.current) {
console.log("📛 WebViewer 초기화 취소됨");
return;
}
// viewerElement이 확실히 존재함을 확인
const viewerElement = viewer.current;
if (!viewerElement) return;
WebViewer(
{
path: "/pdftronWeb",
licenseKey: process.env.NEXT_PUBLIC_PDFTRON_WEBVIEW_KEY,
fullAPI: true,
},
viewerElement
).then((instance: WebViewerInstance) => {
setInstance(instance);
setFileLoading(false);
const { disableElements, setToolbarGroup } = instance.UI;
disableElements([
"toolbarGroup-Annotate",
"toolbarGroup-Shapes",
"toolbarGroup-Insert",
"toolbarGroup-Edit",
// "toolbarGroup-FillAndSign",
"toolbarGroup-Forms",
]);
setToolbarGroup("toolbarGroup-View");
});
});
}
});
}
return () => {
if (instance) {
instance.UI.dispose();
}
isCancelled.current = true;
setTimeout(() => cleanupHtmlStyle(), 500);
};
}, []);
// 문서 로드
useEffect(() => {
if (!instance || !filePath) return;
console.log("📄 파일 로드 시도:", { filePath });
// filePath를 /api/files/ 엔드포인트를 통해 접근하도록 변환
// 한글 파일명의 경우 URL 인코딩 처리
const normalizedPath = filePath.startsWith('/') ? filePath.substring(1) : filePath;
const encodedPath = normalizedPath.split('/').map(part => encodeURIComponent(part)).join('/');
const apiFilePath = `/api/files/${encodedPath}`;
console.log("📄 파일 로드 시도:", { originalPath: filePath, encodedPath: apiFilePath });
loadDocument(instance, apiFilePath);
}, [instance, filePath]);
// 간소화된 문서 로드 함수
const loadDocument = async (instance: WebViewerInstance, documentPath: string) => {
setFileLoading(true);
try {
const { documentViewer } = instance.Core;
await documentViewer.loadDocument(documentPath, { extension: 'pdf' });
} catch (err) {
console.error("문서 로딩 중 오류 발생:", err);
toast.error("문서를 불러오는데 실패했습니다.");
} finally {
setFileLoading(false);
}
};
// 서명 저장 핸들러
const handleSave = async () => {
if (!instance) return;
try {
const { documentViewer } = instance.Core;
const doc = documentViewer.getDocument();
// 서명된 문서 데이터 가져오기
const documentData = await doc.getFileData({
includeAnnotations: true,
});
// 외부에서 제공된 onSign 핸들러가 있으면 호출
if (onSign) {
await onSign(documentData);
} else {
// 기본 동작 - 서명 성공 메시지 표시
toast.success("계약서가 성공적으로 서명되었습니다.");
}
handleClose();
} catch (err) {
console.error("서명 저장 중 오류 발생:", err);
toast.error("서명을 저장하는데 실패했습니다.");
}
};
// 다이얼로그 닫기 핸들러
const handleClose = () => {
if (onClose) {
onClose();
} else {
setShowDialog(false);
}
};
// 인라인 뷰어 렌더링 (다이얼로그 모드가 아닐 때)
if (!isOpen && !onClose) {
return (
<div className="border rounded-md overflow-hidden" style={{ height: '600px' }}>
<div ref={viewer} className="h-[100%]">
{fileLoading && (
<div className="flex flex-col items-center justify-center py-12">
<Loader2 className="h-8 w-8 text-blue-500 animate-spin mb-4" />
<p className="text-sm text-muted-foreground">문서 로딩 중...</p>
</div>
)}
</div>
</div>
);
}
// 다이얼로그 뷰어 렌더링
return (
<Dialog open={showDialog} onOpenChange={handleClose}>
<DialogContent className="w-[70vw]" style={{ maxWidth: "none" }}>
<DialogHeader>
<DialogTitle>기본계약서 서명</DialogTitle>
<DialogDescription>
계약서를 확인하고 서명을 진행해주세요.
</DialogDescription>
</DialogHeader>
<div className="h-[calc(70vh-60px)]">
<div ref={viewer} className="h-[100%]">
{fileLoading && (
<div className="flex flex-col items-center justify-center py-12">
<Loader2 className="h-8 w-8 text-blue-500 animate-spin mb-4" />
<p className="text-sm text-muted-foreground">문서 로딩 중...</p>
</div>
)}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleClose} disabled={fileLoading}>
취소
</Button>
<Button onClick={handleSave} disabled={fileLoading}>
서명 완료
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
// WebViewer 정리 함수
const cleanupHtmlStyle = () => {
// iframe 스타일 정리 (WebViewer가 추가한 스타일)
const elements = document.querySelectorAll('.Document_container');
elements.forEach((elem) => {
elem.remove();
});
};
|