오픈소스 직접뷰어 기능 추가

This commit is contained in:
koj729
2026-06-15 16:10:05 +09:00
parent d13c414d7f
commit cb0c42fbeb
21 changed files with 1202 additions and 33 deletions

View File

@@ -36,6 +36,18 @@ if(data && Object.keys(data).length>0 && (data.$type == 'text'|| data.type == 't
case 'pdf':
_openPdf(fullPath,data);
break;
case 'xls':
case 'xlsx':
case 'xlsm':
_openExcel(fullPath, data);
break;
case 'docx':
_openDocx(fullPath, data);
break;
case 'hwp':
case 'hwpx':
_openHwp(fullPath, data);
break;
case 'mp4':
case 'mov':
case 'webm':
@@ -571,4 +583,265 @@ function _drawMeta(data){
container.innerHTML += line;
}
})
}
// -----------------------------------------------------------------
// 오픈소스 문서 직접 뷰잉 및 PDF 폴백 함수 정의
// -----------------------------------------------------------------
function initFallbackPdfButton(dataId, path_name, resourcePath) {
const btn = document.getElementById('fallback-pdf-btn');
if (!btn) return;
// 이전 등록된 리스너 제거를 위해 복사 대체
const newBtn = btn.cloneNode(true);
btn.parentNode.replaceChild(newBtn, btn);
newBtn.style.display = 'block';
newBtn.textContent = 'PDF로 보기';
newBtn.style.pointerEvents = 'auto';
newBtn.addEventListener('click', async () => {
newBtn.textContent = '로딩 중...';
newBtn.style.pointerEvents = 'none';
try {
// 1. 파일 메타데이터 (popup_key) 조회
let dataInfoRes = await fetch(`${path_name}/getDataInfo`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ params: { dataIdArr: [dataId], isRemoved: false, debug: "popup fallback" } })
});
let dataInfo = await dataInfoRes.json();
let result = dataInfo.result;
if (Array.isArray(result)) result = result[0];
let popupKey = result ? result.popup_key : null;
// 2. 만약 PDF 변환본이 아직 없다면 백엔드 변환 요청
if (!popupKey) {
newBtn.textContent = 'PDF 변환 요청 중...';
await fetch(`${path_name}/convertPdf`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
params: {
dataId: dataId,
resourcePath: resourcePath,
userInfoString: JSON.stringify({ user_id: 'SYSTEM', user_nm: 'Viewer User' }),
objectKey: result.object_key,
storageType: result.storage_type
}
})
});
alert('서버 측 PDF 변환이 시작되었습니다. 잠시 후 다시 클릭해 주세요.');
newBtn.textContent = 'PDF로 보기';
newBtn.style.pointerEvents = 'auto';
return;
}
// 3. PDF용 Presigned URL 생성
let downloadUrlRes = await fetch(`${path_name}/generateDownloadUrl`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ objectKey: popupKey, resourcePath: resourcePath })
});
let downloadUrlData = await downloadUrlRes.json();
if (downloadUrlData.message === 'generateDownloadUrl_success') {
let pdfUrl = downloadUrlData.url;
// 화면 초기화 및 PDF 뷰어 로드
document.getElementById('popup_viewer').innerHTML = '';
newBtn.style.display = 'none';
_openPdf(pdfUrl, {});
} else {
alert('PDF 미리보기 주소 획득에 실패했습니다.');
newBtn.textContent = 'PDF로 보기';
newBtn.style.pointerEvents = 'auto';
}
} catch (e) {
console.error(e);
alert('PDF 변환 로드 과정 중 오류가 발생했습니다.');
newBtn.textContent = 'PDF로 보기';
newBtn.style.pointerEvents = 'auto';
}
});
}
function _openExcel(path, data) {
const viewer = document.getElementById('popup_viewer');
viewer.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;font-size:1.2rem;color:#666;background:#fff;">엑셀 데이터를 불러오는 중...</div>';
fetch(path)
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
return res.arrayBuffer();
})
.then(arrayBuffer => {
viewer.innerHTML = '';
LuckyExcel.transformExcelToLucky(arrayBuffer, function(exportJson, luckysheetfile) {
if(exportJson.sheets == null || exportJson.sheets.length == 0) {
viewer.innerHTML = '<div style="display:flex;flex-direction:column;justify-content:center;align-items:center;height:100%;color:#d9534f;font-size:1.1rem;background:#fff;">엑셀 데이터를 파싱하지 못했습니다. (xls 확장자는 지원하지 않습니다.)</div>';
if (dataId && path_name) {
initFallbackPdfButton(dataId, path_name, resourcePath);
}
return;
}
if (window.luckysheet) {
window.luckysheet.destroy();
}
viewer.style.position = 'relative';
const container = document.createElement('div');
container.id = 'luckysheet_inner';
container.style.margin = '0px';
container.style.padding = '0px';
container.style.position = 'absolute';
container.style.width = '100%';
container.style.height = '100%';
container.style.left = '0px';
container.style.top = '0px';
viewer.appendChild(container);
try {
window.luckysheet.create({
container: 'luckysheet_inner',
data: exportJson.sheets,
title: exportJson.info.name || document.title,
lang: 'en',
showinfobar: false,
myFolderUrl: 'javascript:void(0)'
});
} catch (createErr) {
console.error("Luckysheet create error: ", createErr);
viewer.innerHTML = `<div style="display:flex;flex-direction:column;justify-content:center;align-items:center;height:100%;color:#d9534f;background:#fff;">
<div>엑셀 시트 생성 중 오류가 발생했습니다.</div>
<div style="font-size:0.9rem;color:#999;margin-top:8px;">에러: ${createErr.message}</div>
</div>`;
if (dataId && path_name) {
initFallbackPdfButton(dataId, path_name, resourcePath);
}
}
}, function(err) {
console.error("Luckysheet transform error: ", err);
viewer.innerHTML = `<div style="display:flex;flex-direction:column;justify-content:center;align-items:center;height:100%;color:#d9534f;background:#fff;">
<div>엑셀 파일을 읽는 중 오류가 발생했습니다.</div>
<div style="font-size:0.9rem;color:#999;margin-top:8px;">상세: ${err.message || err}</div>
</div>`;
if (dataId && path_name) {
initFallbackPdfButton(dataId, path_name, resourcePath);
}
});
})
.catch(err => {
console.error(err);
viewer.innerHTML = `<div style="display:flex;flex-direction:column;justify-content:center;align-items:center;height:100%;color:#d9534f;background:#fff;">
<div>엑셀 파일을 불러오는데 실패했습니다.</div>
<div style="font-size:0.9rem;color:#999;margin-top:8px;">에러: ${err.message}</div>
</div>`;
if (dataId && path_name) {
initFallbackPdfButton(dataId, path_name, resourcePath);
}
});
}
function _openDocx(path, data) {
const viewer = document.getElementById('popup_viewer');
viewer.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;font-size:1.2rem;color:#666;background:#fff;">워드 문서를 불러오는 중...</div>';
if (dataId && path_name) {
initFallbackPdfButton(dataId, path_name, resourcePath);
}
fetch(path)
.then(res => {
if (!res.ok) throw new Error('Word fetch failed');
return res.arrayBuffer();
})
.then(arrayBuffer => {
viewer.innerHTML = '';
const container = document.createElement('div');
container.style.width = '100%';
container.style.height = '100%';
container.style.overflow = 'auto';
container.style.padding = '20px';
container.style.boxSizing = 'border-box';
container.style.background = '#f5f5f5';
const docxInner = document.createElement('div');
docxInner.style.background = '#ffffff';
docxInner.style.margin = '0 auto';
docxInner.style.maxWidth = '800px';
docxInner.style.boxShadow = '0 4px 10px rgba(0,0,0,0.1)';
docxInner.style.padding = '40px';
container.appendChild(docxInner);
viewer.appendChild(container);
docx.renderAsync(arrayBuffer, docxInner)
.then(() => console.log("docx rendered"))
.catch(err => {
console.error(err);
docxInner.innerHTML = '<div style="color:#d9534f;text-align:center;">워드 문서 파싱 중 오류가 발생했습니다. 상단의 "PDF로 보기" 버튼을 이용해 주세요.</div>';
});
})
.catch(err => {
console.error(err);
viewer.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;color:#d9534f;background:#fff;">워드 문서를 불러오는데 실패했습니다.</div>';
});
}
function _openHwp(path, data) {
const viewer = document.getElementById('popup_viewer');
viewer.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;font-size:1.2rem;color:#666;background:#fff;">한글 문서를 불러오는 중...</div>';
if (dataId && path_name) {
initFallbackPdfButton(dataId, path_name, resourcePath);
}
fetch(path)
.then(res => {
if (!res.ok) throw new Error('HWP fetch failed');
return res.blob();
})
.then(blob => {
viewer.innerHTML = '';
const container = document.createElement('div');
container.style.width = '100%';
container.style.height = '100%';
container.style.overflow = 'auto';
container.style.padding = '20px';
container.style.boxSizing = 'border-box';
container.style.background = '#f5f5f5';
const hwpInner = document.createElement('div');
hwpInner.style.background = '#ffffff';
hwpInner.style.margin = '0 auto';
hwpInner.style.maxWidth = '800px';
hwpInner.style.boxShadow = '0 4px 10px rgba(0,0,0,0.1)';
hwpInner.style.padding = '40px';
hwpInner.style.minHeight = '100%';
container.appendChild(hwpInner);
viewer.appendChild(container);
const reader = new FileReader();
reader.onload = (e) => {
const bstr = e.target.result;
try {
new hwp.Viewer(hwpInner, bstr);
} catch (err) {
console.error("hwp.js error: ", err);
hwpInner.innerHTML = '<div style="color:#d9534f;text-align:center;">한글 문서 파싱 중 오류가 발생했습니다. 상단의 "PDF로 보기" 버튼을 이용해 주세요.</div>';
}
};
reader.readAsBinaryString(blob);
})
.catch(err => {
console.error(err);
viewer.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;color:#d9534f;background:#fff;">한글 문서를 불러오는데 실패했습니다.</div>';
});
}