หลายลูกค้าได้ติดต่อเราและสอบถามว่าพวกเขาจะสร้างเว็บแอปคล้าย Google Docs ด้วย API ของเราได้อย่างไร Google Docs เป็นโปรแกรมประมวลผลคำที่ช่วยให้ผู้ใช้สร้างและแก้ไขไฟล์ออนไลน์พร้อมกับทำงานร่วมกับผู้ใช้คนอื่นแบบเรียลไทม์

โพสต์บล็อกนี้อธิบายว่าการสร้างเวอร์ชัน Lite ของ Google Docs ที่มีคุณสมบัติดังต่อไปนี้นั้นง่ายแค่ไหน:

  • การแก้ไขข้อความแบบ Rich Text (เปลี่ยนแบบอักษร, ขนาด, สี, สไตล์ (หนา, เอียง), การจัดแนว ฯลฯ)
  • การแก้ไขร่วมแบบเรียลไทม์ของเอกสารเดียวกัน ผู้ใช้หลายคนสามารถเข้าถึงเอกสารพร้อมกันและแก้ไขได้
  • อัปโหลดเนื้อหาของเอกสาร Word ที่มีอยู่เข้าสู่ตัวแก้ไข
  • บันทึกข้อความในตัวแก้ไขเป็นเอกสาร MS Word, PDF, TXT หรือ HTML

ผลิตภัณฑ์สุดท้ายของเราจะมีลักษณะดังนี้:

อินเทอร์เฟซแอปคล้าย Google Docs

เครื่องมือและเทคโนโลยี – สร้างแอปคล้าย Google Docs

เราจะพัฒนาเว็บแอปแบบ Google Docs ใน ASP.NET Core และใช้ไลบรารีสองตัวต่อไปนี้:

  • Firepad เป็นเครื่องมือแก้ไขข้อความแบบเปิดต้นฉบับและทำงานร่วมกัน มันใช้ Firebase Realtime Database เป็นแบ็กเอนด์จึงไม่ต้องมีโค้ดฝั่งเซิร์ฟเวอร์และสามารถเพิ่มลงในเว็บแอปใดก็ได้โดยเพียงแค่รวมไฟล์ JavaScript
    • GroupDocs.Editor for .NET ให้ความสามารถในการแก้ไขรูปแบบเอกสารที่นิยมที่สุดโดยใช้ WYSIWYG editor ใดก็ได้โดยไม่ต้องใช้แอปพลิเคชันเพิ่มเติม เราจะโหลดเอกสารผ่าน GroupDocs.Editor ไปยัง Firepad, แก้ไขเอกสารตามที่ต้องการและบันทึกกลับไปยังรูปแบบเอกสารต้นฉบับ

ฉันได้ใช้ Visual Studio for Mac เป็น IDE อย่างไรก็ตาม คุณสามารถดาวน์โหลดเวอร์ชัน Community ฟรีของ Visual Studio ตามแพลตฟอร์มของคุณได้จาก ที่นี่ เริ่มกันเถอะ.

สร้างโครงการ ASP.NET Core Web Application ใหม่และตั้งชื่อโครงการเป็น “GoogleDocsLite”.

สร้างเว็บแอป ASP.NET Core ใหม่

เรียกใช้แอปพลิเคชันเพื่อให้แน่ใจว่าทุกอย่างถูกตั้งค่าอย่างถูกต้อง

รวม Firepad

เราสามารถเพิ่ม Firepad ไปยังเว็บแอปของเราได้โดยการรวมไฟล์ JavaScript ต่อไปนี้ในส่วน <head> ของ _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. เพิ่มสคริปต์และโค้ด 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 ด้วย config ของโครงการ Firebase ของคุณเอง.

เราต้องการให้สคริปต์ทำงานหลังจากหน้าโหลดเสร็จสมบูรณ์ เรียก init() จากแอตทริบิวต์ onload ขององค์ประกอบ <body> ใน _Layout.cshtml.

<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 และดูเนื้อหาของมันในตัวแก้ไข. ในส่วนหน้า ให้เพิ่มองค์ประกอบ <input> ที่มีประเภทเป็น file. ในส่วนหลัง ให้ใช้ไลบรารี GroupDocs.Editor เพื่อแปลงเอกสาร Word เป็นสตริง HTML แล้วแสดงผลด้วยเมธอด setHtml() ของ Firepad.

เพิ่มองค์ประกอบ <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; }

Run the project and click Choose file. Select a Word document and click Upload Document. Nothing happens yet because we still need a handler and the GroupDocs.Editor library.

รวม GroupDocs.Editor

GroupDocs.Editor มีให้ใช้เป็นแพ็คเกจ NuGet. คลิกขวาที่โครงการ, เลือก Manage NuGet Packages, ค้นหา GroupDocs.Editor, แล้วคลิก Add Package.

เพิ่ม GroupDocs.Editor ผ่าน NuGet Package Manager

หลังจากการติดตั้ง แพ็กเกจจะปรากฏภายใต้โฟลเดอร์ย่อย NuGet ใน Dependencies.

การจัดการข้อมูลฟอร์ม

สร้างตัวจัดการ (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 ดึงเนื้อหาเริ่มต้นของตัวแก้ไขแล้ว เราแนบ callback ไปยังประเภทเหตุการณ์นี้และใน callback เราจะส่งสตริง DocumentContent เป็นอาร์กิวเมนต์ให้เมธอด setHtml() ของอ็อบเจกต์ firepad โปรดเพิ่มโค้ดต่อไปนี้ในฟังก์ชัน init() ในไฟล์ Index.cshtml.

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.

ดูเพิ่มเติม