何人かのお客様から、APIを使用してウェブアプリのようなGoogleドキュメントを作成する方法を尋ねられました。 Google Docsは、ユーザーが他のユーザーとリアルタイムで共同作業しながら、オンラインでファイルを作成および編集できるワードプロセッサです。

このブログ投稿では、次の機能を備えたライトバージョンのGoogleドキュメントを簡単に作成できることを説明しています。

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

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

アプリインターフェースのようなGoogleドキュメント

ツールとテクノロジー–アプリのようなGoogleドキュメントを作成する

ASP.NET CoreでWebアプリのようなGoogleドキュメントを開発し、次の2つのライブラリを使用します。

  • ファイアパッド is an open-source, collaborative text editor. It uses the Firebase Realtime Database as a backend so it requires no server-side code and can be added to any web app simply by including the JavaScript files.
  • GroupDocs.Editor for .NET gives us an ability to edit most popular document formats using any WYSIWYG editor without any additional applications. We will load document via GroupDocs.Editor into Firepad, edit document in a way we want and save it back to original document format.

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

新しいASP.NETCoreWebアプリケーションプロジェクトを作成し、プロジェクトに「GoogleDocsLite」という名前を付けます。

新しいASP.NETCoreWebアプリを作成します

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

Firepadを統合する

次のJavaScriptファイルをWebアプリに含めることで、FirepadをWebアプリに追加できます。 Layout.cshtmlのセクション。

<!-- 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プロジェクトの設定に置き換えてください。

Webページがすべてのコンテンツ(スクリプトファイル、CSSファイルなど)を完全にロードしたら、上記のスクリプトを実行する必要があります。したがって、のonLoadイベント属性からinit()関数を呼び出します。 Layout.cshtmlの要素。

<body onload="init()">

あなたの<body> 要素は次のようになります。 のような不要なタグが含まれている場合<header><footer> 、それらを削除してください。

ボディエレメント

プロジェクトを実行すると、firepadとuserlistが正しく配置されていないことに気付くでしょう。次のCSSコードを使用して、ファイアパッドとユーザーリストのサイズ/位置を調整してください。内に次のコードを追加できます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ドキュメントのコンテンツをアップロードする方法をユーザーに提供したいと思います。フロントエンドに、ユーザーがローカルマシンからWord文書を選択できるようにするファイルタイプの要素。バックエンドでは、GroupDocs.Editorライブラリを使用して、WordドキュメントのコンテンツをHTML文字列として取得します。最後に、FirepadのsetHtml()メソッドを使用して、テキストエディタにコンテンツを表示します。

以下を追加します前のIndex.cshtmlファイルの要素鬼ごっこ。

<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文書を選択し、[文書のアップロード]ボタンをクリックします。 Index.cshtml.csでハンドラーをまだ定義していないため、何も起こりません。これを行う前に、まずプロジェクトにGroupDocs.Editorライブラリを追加しましょう。

GroupDocs.Editorを統合する

GroupDocs.EditorはNuGetパッケージとして利用できるため、プロジェクトに簡単に追加できます。プロジェクトを右クリックして、[NuGetパッケージの管理]オプションを選択します。 [NuGetパッケージの管理]ウィンドウが開き、[参照]タブを選択して、検索フィールドにGroupDocs.Editorと入力します。 GroupDocs.Editorが最初の結果として表示され、それを選択して、[パッケージの追加]ボタンをクリックします。

NuGetパッケージマネージャーを介してGroupDocs.Editorを追加します

パッケージが正常に追加されると、依存関係フォルダーのNuGetサブフォルダーの下に表示されます。

フォームデータの処理

次に、ユーザーが[ドキュメントのアップロード]ボタンをクリックしたときに呼び出されるハンドラー(OnPostUploadDocument()メソッド)を記述します。 UploadedDocumentオブジェクト(タイプIFormFile)には、アップロードされたドキュメントのコンテンツが含まれています。まず、ドキュメントをサーバーに保存してから、GroupDocs.Editorライブラリを使用してコンテンツをHTML文字列として取得します。 Index.cshtml.csファイルに次のコードを追加してください。

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つは、Firepadが最初のエディターコンテンツを取得すると起動する「ready」です。このイベントタイプにコールバックをアタッチし、コールバックで、FirepadオブジェクトのsetHtml()メソッドへの引数としてDocumentContent文字列を渡します。 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.");
        }
    }
});

setHtml()メソッドに渡す前に、最初にdocumentContent文字列をhtmlDecode()メソッドに渡したことに気付いたかもしれません。 <、>などの文字エンティティを記号(<および>)に置き換えることです。 htmlDecode()メソッドは次のようになります。

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

プロジェクトを実行すると、Word文書のコンテンツをエディターにアップロードできるようになります。

この投稿のパートIIでは、アプリケーションを拡張して次の機能を含める方法について説明しました。

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

チェックしてください

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

関連項目