여러 고객이 우리에게 접근하여 API를 사용해 Google Docs와 같은 웹 앱을 만드는 방법을 물어보았습니다. Google Docs은 사용자가 온라인으로 파일을 만들고 편집하며 다른 사용자와 실시간으로 협업할 수 있는 워드 프로세서입니다.
이 블로그 게시물에서는 다음 기능을 갖춘 Google Docs의 라이트 버전을 만드는 것이 얼마나 쉬운지 설명합니다:
- 풍부한 텍스트 편집(텍스트 글꼴, 크기, 색상, 스타일(굵게, 기울임), 정렬 등 변경).
- 동일한 문서에 대한 실시간 협업 편집. 여러 사용자가 동시에 문서에 접근하여 수정할 수 있습니다.
- 기존 Word 문서의 내용을 편집기로 업로드합니다.
- 편집기의 텍스트를 MS Word, PDF, TXT 또는 HTML 문서로 저장합니다.
우리 최종 제품은 다음과 같이 보일 것입니다:

도구 및 기술 – Google Docs와 같은 앱 만들기
우리는 ASP.NET Core에서 Google Docs와 같은 웹 앱을 개발하고 다음 두 라이브러리를 사용할 것입니다:
- Firepad 은(는) 오픈 소스 협업 텍스트 편집기입니다. 백엔드로 Firebase 실시간 데이터베이스를 사용하므로 서버 측 코드를 필요로 하지 않으며 JavaScript 파일을 포함하기만 하면 모든 웹 앱에 추가할 수 있습니다.
- GroupDocs.Editor for .NET 은(는) 가장 많이 사용되는 문서 형식을 WYSIWYG 편집기를 사용하여 추가 애플리케이션 없이 편집할 수 있는 기능을 제공합니다. 우리는 GroupDocs.Editor를 통해 문서를 Firepad에 로드하고, 원하는 방식으로 문서를 편집한 뒤 원본 문서 형식으로 다시 저장합니다.
Visual Studio for Mac을(를) IDE로 사용했습니다. 그러나 플랫폼에 따라 무료 커뮤니티 에디션 Visual Studio를 여기에서 다운로드할 수 있습니다. 시작해 보겠습니다.
새 ASP.NET Core 웹 애플리케이션 프로젝트를 만들고 프로젝트 이름을 “GoogleDocsLite”로 지정합니다.

애플리케이션을 실행하여 모든 설정이 올바르게 구성되었는지 확인하십시오.
Firepad 통합
다음 JavaScript 파일들을 <head> 섹션에 포함시켜 _Layout.cshtml에 Firepad를 웹 앱에 추가할 수 있습니다.
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/7.13.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.13.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.13.2/firebase-database.js"></script>
<!-- CodeMirror -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.17.0/codemirror.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.17.0/codemirror.css" />
<!-- Firepad -->
<link rel="stylesheet" href="https://firepad.io/releases/v1.5.9/firepad.css" />
<script src="https://firepad.io/releases/v1.5.9/firepad.min.js"></script>
<!-- userlist -->
<script src="~/js/firepad-userlist.js"></script>
<link rel="stylesheet" href="~/css/firepad-userlist.css" />
Firepad를 만들기 위해 Firebase, CodeMirror를 초기화한 다음 Firepad를 초기화합니다. 다음 스크립트와 HTML 코드를 Index.cshtml에 추가합니다.
<script>
function init() {
// Initialize Firebase.
// TODO: replace with your Firebase project configuration.
var config = {
apiKey: '',
authDomain: "",
databaseURL: ""
};
firebase.initializeApp(config);
// Get Firebase Database reference.
var firepadRef = getExampleRef();
// Create CodeMirror (with lineWrapping on).
var codeMirror = CodeMirror(document.getElementById('firepad'), { lineWrapping: true });
// Create a random ID to use as our user ID (we must give this to firepad and FirepadUserList).
var userId = Math.floor(Math.random() * 9999999999).toString();
// Create Firepad (with rich text features and our desired userId).
var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror,
{ richTextToolbar: true, richTextShortcuts: true, userId: userId });
// Create FirepadUserList (with our desired userId).
var firepadUserList = FirepadUserList.fromDiv(firepadRef.child('users'),
document.getElementById('userlist'), userId);
}
// Helper to get hash from end of URL or generate a random one.
function getExampleRef() {
var ref = firebase.database().ref();
var hash = window.location.hash.replace(/#/g, '');
if (hash) {
ref = ref.child(hash);
} else {
ref = ref.push(); // generate unique location.
window.location = window.location + '#' + ref.key; // add it as a hash to the URL.
}
if (typeof console !== 'undefined') {
console.log('Firebase data: ', ref.toString());
}
return ref;
}
</script>
<div id="userlist"></div>
<div id="firepad"></div>
자신의 Firebase 프로젝트 구성으로 config의 내용을 교체하십시오.
페이지가 완전히 로드된 후에 스크립트가 실행되기를 원합니다. _Layout.cshtml의 <body> 요소의 onload 속성에서 init() 를 호출하십시오.
<body onload="init()">
귀하의 <body> 요소는 다음과 같이 보여야 합니다. <header> 또는 <footer>와 같은 불필요한 태그는 제거하십시오.

프로젝트를 실행하면 firepad와 userlist가 제대로 정렬되지 않은 것을 확인할 수 있습니다. 크기와 위치를 조정하려면 다음 CSS를 추가하세요. _Layout.cshtml의 <head> 안에 배치합니다.
<style>
html {
height: 100%;
}
body {
margin: 0;
height: 100%;
}
/* We make the user list 175px and firepad fill the rest of the page. */
#userlist {
position: absolute;
left: 0;
top: 50px;
bottom: 0;
height: auto;
width: 175px;
}
#firepad {
position: absolute;
left: 175px;
top: 50px;
bottom: 0;
right: 0;
height: auto;
}
</style>
Firepad가 성공적으로 설정되었습니다.
기존 Word 문서의 내용을 편집기에 업로드
이제 사용자가 Word 문서를 업로드하고 편집기에서 해당 내용을 볼 수 있도록 하겠습니다. 프런트 엔드에서는 타입이 file인 <input> 요소를 추가합니다. 백 엔드에서는 GroupDocs.Editor 라이브러리를 사용하여 Word 문서를 HTML 문자열로 변환한 다음 Firepad의 setHtml() 메서드로 표시합니다.
다음 <form> 요소를 Index.cshtml의 <div id="userlist"> 태그 앞에 추가하십시오.
<form method="post" enctype="multipart/form-data" id="uploadForm">
<input asp-for="UploadedDocument" />
<input type="submit" value="Upload Document" class="btn btn-primary" asp-page-handler="UploadDocument" />
</form>
Index.cshtml.cs에서 일치하는 속성을 정의합니다.
[BindProperty]
public IFormFile UploadedDocument { get; set; }
프로젝트를 실행하고 Choose file을 클릭합니다. Word 문서를 선택하고 Upload Document를 클릭합니다. 아직 핸들러와 GroupDocs.Editor 라이브러리가 필요하기 때문에 아무 일도 일어나지 않습니다.
GroupDocs.Editor 통합
GroupDocs.Editor 은 NuGet 패키지로 제공됩니다. 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 Manage NuGet Packages 를 선택한 다음 GroupDocs.Editor 를 검색하고 Add Package 를 클릭합니다.

설치 후, 패키지는 Dependencies 안의 NuGet 하위 폴더에 나타납니다.
폼 데이터 처리
사용자가 Upload Document를 클릭할 때 실행되는 핸들러 (OnPostUploadDocument())를 만듭니다. UploadedDocument (형식 IFormFile)에는 파일 데이터가 포함됩니다. 파일을 저장한 후 GroupDocs.Editor를 사용하여 내용을 HTML로 읽습니다.
private readonly IWebHostEnvironment _hostingEnvironment;
public string DocumentContent { get; set; }
public IndexModel(IWebHostEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public void OnPostUploadDocument()
{
var projectRootPath = Path.Combine(_hostingEnvironment.ContentRootPath, "UploadedDocuments");
var filePath = Path.Combine(projectRootPath, UploadedDocument.FileName);
UploadedDocument.CopyTo(new FileStream(filePath, FileMode.Create));
ShowDocumentContentInTextEditor(filePath);
}
private void ShowDocumentContentInTextEditor(string filePath)
{
WordProcessingLoadOptions loadOptions = new WordProcessingLoadOptions();
Editor editor = new Editor(filePath, delegate { return loadOptions; }); //passing path and load options (via delegate) to the constructor
EditableDocument document = editor.Edit(new WordProcessingEditOptions()); //opening document for editing with format-specific edit options
DocumentContent = document.GetContent();
}
Firepad는 두 개의 이벤트를 제공한다. 그 중 하나는 ‘ready‘이며, Firepad가 초기 편집기 내용을 가져오면 한 번 발생한다. 우리는 이 이벤트 유형에 콜백을 연결하고, 콜백에서 DocumentContent 문자열을 firepad 객체의 setHtml() 메서드에 인수로 전달한다. Index.cshtml의 init() 함수에 다음 코드를 추가하십시오.
firepad.on('ready', function () {
if (firepad.isHistoryEmpty()) {
var documentContent = '@Model.DocumentContent';
if (documentContent.length != 0) {
firepad.setHtml(htmlDecode(documentContent));
} else {
firepad.setText("Welcome to your own private pad! Share the URL above and collaborate with your friends.");
}
}
});
우리는 documentContent 문자열을 setHtml() 메서드에 전달하기 전에 먼저 htmlDecode() 메서드에 전달했다는 것을 눈치채셨을 수도 있습니다. 이는 <, >와 같은 문자 엔티티를 기호(< 및 >)로 교체하기 위함입니다. htmlDecode() 메서드는 다음과 같습니다.
function htmlDecode(input) {
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes[0].nodeValue;
}
프로젝트를 실행하면 이제 워드 문서의 내용을 편집기에 업로드할 수 있습니다.
이 게시물의 part II에서, 애플리케이션을 확장하여 다음 기능들을 포함할 수 있는 방법을 설명했습니다:
- 편집기의 내용을 MS Word, PDF, TXT 또는 HTML 문서로 다운로드합니다.
- URL을 친구와 공유하여 동시에 문서를 편집할 수 있습니다.
부디 확인해 보세요.
프로젝트의 전체 소스 코드는 GitHub에서 확인할 수 있습니다.