几位客户联系了我们,询问如何使用我们的 API 创建类似 Google Docs 的网络应用。 Google Docs 是一款文字处理器,允许用户在线创建和编辑文件,并实时与其他用户协作。
这篇博客文章解释了创建一个具有以下功能的 Google Docs 轻量版是多么容易:
- 富文本编辑(更改文本字体、大小、颜色、样式(粗体、斜体)、对齐方式等)。
- 实时协作编辑同一文档。多个用户可以同时访问文档并进行修改。
- 将现有 Word 文档的内容上传到编辑器。
- 将编辑器中的文本保存为 MS Word、PDF、TXT 或 HTML 文档。
我们的最终产品将如下所示:

工具和技术 – 创建类似 Google Docs 的应用
我们将在 ASP.NET Core 中开发类似 Google Docs 的 Web 应用,并使用以下两个库:
- Firepad 是一个开源的协作文本编辑器。它使用 Firebase 实时数据库作为后端,因此无需服务器端代码,只需包含 JavaScript 文件即可将其添加到任何 Web 应用程序中。
- GroupDocs.Editor for .NET 使我们能够使用任何 WYSIWYG 编辑器编辑最流行的文档格式,而无需任何额外的应用程序。我们将通过 GroupDocs.Editor 将文档加载到 Firepad 中,按需编辑文档,并将其保存回原始文档格式。
我使用过 Visual Studio for Mac 作为一款 IDE。然而,您可以根据所使用的平台,从 此处 下载 Visual Studio 的免费社区版。让我们开始吧。
创建一个新的 ASP.NET Core Web 应用程序项目,并将项目命名为 “GoogleDocsLite”。

运行应用程序以确保一切已正确设置。
集成 Firepad
我们可以通过在 <head> 部分的 _Layout.cshtml 中包含以下 JavaScript 文件,将 Firepad 添加到我们的 Web 应用中。
<!-- 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>
<!-- 用户列表 -->
<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>
请将 config 的内容替换为您自己的 Firebase 项目配置。
我们希望脚本在页面完全加载后运行。请在 _Layout.cshtml 中的 <body> 元素的 onload 属性中调用 init()。
<body onload="init()">
您的 <body> 元素应如下所示。删除任何不必要的标签,例如 <header> 或 <footer>。

如果运行项目,您会注意到 firepad 和 userlist 未正确对齐。添加以下 CSS 以调整它们的大小和位置。将其放置在 <head> 的 _Layout.cshtml 中。
<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() 方法显示它。
在 Index.cshtml 中的 <div id="userlist"> 标记之前添加以下 <form> 元素。
<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; }
运行项目并点击 选择文件。选择一个 Word 文档并点击 上传文档。目前什么也不会发生,因为我们仍然需要一个处理程序和 GroupDocs.Editor 库。
集成 GroupDocs.Editor
GroupDocs.Editor 可作为 NuGet 包获取。右键单击项目,选择 Manage NuGet Packages,搜索 GroupDocs.Editor,然后点击 Add Package。

安装后,包会出现在 Dependencies 中的 NuGet 子文件夹下。
表单数据处理
创建一个处理程序(OnPostUploadDocument()),当用户点击 Upload Document 时运行。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;
}
运行项目后,您现在应该能够将 Word 文档的内容上传到编辑器中。
在第II部分中,我已经解释了如何扩展我们的应用程序以包含以下功能:
- 将编辑器的内容下载为 MS Word、PDF、TXT 或 HTML 文档。
- 将 URL 与朋友分享,以便他们能够同时编辑文档。
请 查看。
项目的完整源代码可在 GitHub 上获取。