複数の顧客から、当社の API を使用して Google Docs のようなウェブアプリを作成する方法について問い合わせがありました。 Google Docs は、ユーザーがオンラインでファイルを作成・編集し、リアルタイムで他のユーザーと共同作業できるワードプロセッサです。

このブログ記事では、以下の機能を備えたGoogle Docsのライトバージョンを簡単に作成できる方法を説明します:

  • リッチテキスト編集(テキストのフォント、サイズ、色、スタイル(太字、斜体)、配置などの変更)。
  • 同じドキュメントのリアルタイム共同編集。複数のユーザーが同時にドキュメントにアクセスし、編集できます。
  • 既存の Word ドキュメントの内容をエディタにアップロード。
  • エディタ内のテキストを MS Word、PDF、TXT、または HTML ドキュメントとして保存。

最終的な製品は次のようになります:

Google Docs のようなアプリインターフェイス

ツールとテクノロジー – Google Docs のようなアプリを作成

ASP.NET CoreでGoogle DocsのようなWebアプリを開発し、次の2つのライブラリを使用します:

  • Firepad はオープンソースの共同テキストエディタです。バックエンドに Firebase Realtime Database を使用するため、サーバー側のコードは不要で、JavaScript ファイルを組み込むだけで任意の Web アプリに追加できます。
    • GroupDocs.Editor for .NET は、追加のアプリケーションなしで任意の WYSIWYG エディタを使用して、最も一般的なドキュメント形式を編集できる機能を提供します。GroupDocs.Editor を介してドキュメントを Firepad にロードし、必要な方法でドキュメントを編集し、元のドキュメント形式に戻して保存します。

私は Visual Studio for Mac を IDE として使用しています。ただし、プラットフォームに応じて、Visual Studio の無料コミュニティエディションを こちら からダウンロードできます。さあ、始めましょう。

新しい ASP.NET Core Web Application プロジェクトを作成し、プロジェクト名を “GoogleDocsLite” にします。

新しい ASP.NET Core Web アプリを作成

アプリケーションを実行して、すべてが正しく設定されていることを確認してください。

Firepad の統合

次の JavaScript ファイルを <head> セクションの _Layout.cshtml に含めることで、Web アプリに 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 を初期化します。Index.cshtml に以下のスクリプトと HTML コードを追加します。

<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 を追加してください。<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() メソッドで表示します。

次の <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; }

プロジェクトを実行し、ファイルを選択 をクリックします。Word ドキュメントを選択し、ドキュメントをアップロード をクリックします。まだハンドラと GroupDocs.Editor ライブラリが必要なため、何も起こりません。

GroupDocs.Editor の統合

GroupDocs.Editor は NuGet パッケージとして利用できます。プロジェクトを右クリックし、Manage NuGet Packages を選択し、GroupDocs.Editor を検索して、Add Package をクリックします。

NuGet パッケージ マネージャーで GroupDocs.Editor を追加

インストール後、パッケージは 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 はリスニング用に 2 つのイベントを提供します。そのうちの 1 つは ‘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 文字列を htmlDecode() メソッドに最初に渡し、setHtml() メソッドに渡す前に行ったことに気付いたかもしれません。それは <、> などの文字エンティティを記号(< と >)に置き換えるためです。htmlDecode() メソッドは以下のようになります。

function htmlDecode(input) {
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes[0].nodeValue;
}

プロジェクトを実行すると、Word ドキュメントの内容をエディタにアップロードできるようになります。

この投稿のpart IIでは、アプリケーションを拡張して以下の機能を含める方法を説明しました:

  • エディタのコンテンツを MS Word、PDF、TXT、または HTML ドキュメントとしてダウンロードします。
  • URL を友達と共有し、同時にドキュメントを編集できるようにします。

ぜひご確認ください。

プロジェクトの完全なソースコードはGitHubで入手できます。

関連項目