头图

Abstract: Simple 5 steps to integrate the powerful PDF annotation development kit, including cloud server. This article introduces how to integrate it into jQuery and HTML projects. The sample code is complete and simple. You can complete the project integration by copying and pasting. Other annotation tools based on pdf.js can also be integrated by referring this post.
Demo Snapshot

1. Code package and Demo

1.1 Package Introduction

ElasticPDF is based on the open source pdf.js and adds a variety of out-of-the-box PDF annotation features. The code package continues the independent and completely offline structure style of pdf.js-dist, and only adds offline Javascript code to support annotations. It can be quickly and perfectly integrated into any project environment that can run Javascript, HTML, and CSS, and run perfectly in both public and intranet environments.
Project Structure

1.2 Online Demo

For the different features and budget requirements, there are two versions of the products, they are only differ in the final annotation saving stage, demos are as follows:

① Annotation synthesis version: https://demos.libertynlp.com/#/pdfjs-annotation\
② Professional annotation version: https://www.elasticpdf.com/demo

2. Move to the target project

Move the Elasticpdf code package to any location in the jQuery or HTML project. Here I put it in the top-level folder.
Code Position

3. Import the pdf-viewer file

Use <iframe> to import the viewer.html file in the elasticpdf code package. Be careful not to write the wrong path.

<iframe id='pdfjs-iframe' src="elasticpdf/web/viewer.html" frameborder="0" width="100%"
    height="770px"></iframe>

Call the initialization function after assigning the parameters. The server storing the PDF file needs to return a request header that supports cross-domain, otherwise a CORS error will be reported. For specific methods, see the article Server site setting cross-domain request header.

    //Get elasticpdf_viewer
    var elasticpdf_viewer = document.getElementById('elasticpdf-iframe').contentWindow;
    window.onload = function() {
        elasticpdf_viewer.initialApp({
            'language': 'en', // interactive language, supports Chinese and English
            'view_model': { // browsing mode
                'read_only': false, // whether to edit annotations
                'show_annotation': true, // whether to display annotations
                'show_annotation_list': true, // whether to display the annotation list on the right by default
            },
            'watermark': {
                'activate': false, // whether to enable watermark
                'watermark_text': 'elasticpdf', // watermark text
            },
            'theme': 'light', // color theme, there are three theme colors: light (bright), soft (eye protection) and dark (dark)
            'pdf_url': 'https://app.elasticpdf.com/web/tutorial.pdf',
            'edit_others_annotation': true, // Whether to allow the current user to edit other people's annotations
            'member_info': { // User information
                'member_id': '20250202',
                'member_name': 'elasticpdf',
            },
        });
    }

4. Export PDF and annotation data

There are two ways to save annotation data, and we recommend method 2.

Method 1: Merge file and annotations

Write annotations to PDF and then download the entire document. Generally, users can use the Ctrl+S shortcut key and UI button to complete this. This method does not require the support of backend services at all.

You can use the following code if you need to save the PDF file with writing annotations to the server.

// Bind this function to DOM to trigger PDF saving
    function getPDFData() {
        elasticpdf_viewer.getPDFData();
    }

    // Receive PDF data and upload to the server
    window.addEventListener('message', (e) => {
        if (e.data.source != 'elasticpdf') {
            return;
        }

        // Receive PDF data
        if (e.data.function_name == 'downloadPDF') {
            let file_name = e.data.content['file_name'];
            let pdf_blob = e.data.content['pdf_blob'];
            let pdf_base64 = e.data.content['pdf_base64'];

            // Receive PDF data, pdf_base64 string data can be quickly uploaded to the server
            postService('upload-pdf-data', {
                'file_name': file_name,
                'file_id': '123ddasfsdffads',
                'file_data': pdf_base64,
            });
        }
    });

Method 2: Save annotations separately

Save the annotation file separately. For cloud synchronization scenarios, you can export the annotation file as a JSON file, transfer and save it on the server, and then reload and display it to continue editing the annotation.

This method only requires an online PDF original file and only transfers a small volume of annotations (usually less than 1M in size), which can save a lot of storage and broadband costs.

// In the callback function after PDF annotation editing, all annotation files can be read and uploaded to the server
    window.addEventListener('message', (e) => {
        if (e.data.source != 'elasticpdf') {
            return;
        }

        // PDF annotation editing callback, annotations can be exported here and transmitted to the server
        if (e.data.function_name == 'annotationsModified') {
            // Only get PDF annotation files, do not write to PDF
            let this_data = elasticpdf_viewer.pdfAnnotation.outputAnnotations();
            let annotation_content = JSON.stringify(this_data['file_annotation']);
            let file_name = this_data['file_name'];
            postService('upload-annotation-data', {
                'file_name': file_name,
                'file_id': '123ddasfsdffads',
                'file_annotation': annotation_content,
            });
        }
    });

5. Reload PDF and annotation data

When you save PDF annotations at the server separately, you can download it from the server again after loading the PDF file and reload them to continue editing.

 // In the callback function after PDF loading is completed
    // you can request the corresponding annotation from the server and reload it on PDF.
    window.addEventListener('message', (e) => {
        if (e.data.source != 'elasticpdf') {
            return;
        }

        // PDF loading is completed, you can reload the annotation file stored on the server
        if (e.data.function_name == 'pdfLoaded') {
            let file_name = 'tutorial.pdf'
            let annotation_content = await postService('get-annotation-data', {
                'file_name': 'tutorial.pdf',
                'file_id': '123ddasfsdffads',
            });
            // Annotation reloads and displays on current file
            elasticpdf_viewer.setPureFileAnnotation({
                'file_annotation': annotation_content
            });
        }
    });

All the above communications with the server require network functions. The backend server needs a program to receive and save data. We have simple PHP, Python and Java code examples for reference.

The code of the sample function postService() that initiates the request on the front end is as follows.

// function connecting backend program
    async function postService(url, data) {
        var new_data = new URLSearchParams();
        var encrpte_data = data;
        new_data.append('data', encrpte_data);
        
        var base_url = "your-server-url";
        var posturl = base_url + url;
        const response = await fetch(posturl, {
            method: 'POST',
            headers: {},
            body: new_data, 
        });

        
        const resp = await response.json();
        resp['data'] = JSON.parse(resp['data']);
        
        return resp;
    }

Summary

So far, the code of integrating the elasticpdf project into the jQuery and HTML projects has been introduced. The complete sample file code is as follows. If you have other application requirements, welcome to contact us and we will provide you with sample code.

This project can also be easily integrated into Vue, React, jQuery, Angular, Nuxt.js, WordPress, Svelte, Vite, Android, Electron, ASP.NET, Blazor, PHP, Laravel, PWA, Flutter and other projects. Welcome to check out the relevant blogs on our site.

<!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>
                jQuery and HTML project sample code
                The elasticpdf code package is placed in the top-level folder
            </title>
        </head>
        <body>
            <button onclick="getPDFData()">Get data</button>
            <iframe id='elasticpdf-iframe' src="elasticpdf/web/viewer.html" frameborder="0" width="100%"
                height="770px"></iframe>
        </body>
        <script type="text/javascript">
            //Get elasticpdf_viewer
            var elasticpdf_viewer = document.getElementById('elasticpdf-iframe').contentWindow;
            window.onload = function() {
                elasticpdf_viewer.initialApp({
                    'language': 'en', //Interactive language, supports Chinese and English
                    'view_model': { // Browsing mode
                        'read_only': false, // Can you edit annotations?
                        'show_annotation': true, // Whether to display annotations
                        'show_annotation_list': true, // Whether to display the annotation list on the right by default
                    },
                    'watermark': {
                        'activate': false, // Whether to enable watermark
                        'watermark_text': 'elasticpdf', // Watermark text
                    },
                    'theme': 'light', // Color theme, there are three theme colors: light (bright), soft (eye protection) and dark (dark)
                    'pdf_url':'https://app.elasticpdf.com/web/tutorial.pdf',
                    'edit_others_annotation': true, // Whether to allow the current user to edit other people's annotations
                    'member_info': { // User information
                        'member_id': 'elasticpdf_id',
                        'member_name': 'elasticpdf_name',
                    },
                });
            }

            // Get PDF data
            function getPDFData() {
                elasticpdf_viewer.getPDFData();
            }

            window.addEventListener('message', (e) => {
                if (e.data.source != 'elasticpdf') {
                    return;
                }

                // Receive PDF data
                if (e.data.function_name == 'downloadPDF') {
                    let file_name = e.data.content['file_name'];
                    let pdf_blob = e.data.content['pdf_blob'];
                    let pdf_base64 = e.data.content['pdf_base64'];
                    // Receive PDF data, where pdf_base64 can be quickly uploaded to the server
                    postService('upload-pdf-data', {
                        'file_name': file_name,
                        'file_id': '123ddasfsdffads',
                        'file_data': pdf_base64,
                    });
                }

                // PDF annotation editing callback, annotations can be exported here and transferred to the server
                if (e.data.function_name == 'annotationsModified') {
                    // Only get the PDF annotation file, do not write to the PDF
                    let this_data = elasticpdf_viewer.pdfAnnotation.outputAnnotations();
                    let annotation_content = JSON.stringify(this_data['file_annotation']);
                    let file_name = this_data['file_name'];
                    postService('upload-annotation-data', {
                        'file_name': file_name,
                        'file_id': '123ddasfsdffads',
                        'file_annotation': annotation_content,
                    });
                }

                // PDF loading is completed. You can import the annotation file stored on the server here
                if (e.data.function_name == 'pdfLoaded') {
                    let file_name = 'tutorial.pdf'
                    let annotation_content = await postService('get-annotation-data', {
                        'file_name': 'tutorial.pdf',
                        'file_id': '123ddasfsdffads',
                    });
                    // Annotation reloads and displays in the current file
                    elasticpdf_viewer.setPureFileAnnotation({
                        'file_annotation': annotation_content
                    });
                }
            });

            // Function for network communication with the backend server
            async function postService(url, data) {
                var new_data = new URLSearchParams();
                var encrpte_data = data;
                new_data.append('data', encrpte_data);
                var base_url = "your-server-url";
                var posturl = base_url + url;
                const response = await fetch(posturl, {
                    method: 'POST',
                    headers: {},
                    body: new_data,
                });

                const resp = await response.json();
                resp['data'] = JSON.parse(resp['data']);
                return resp;
            }
        </script>
    </html>

Tips: This article was first published on https://www.elasticpdf.com ,Please indicate the source when republishing: https://www.elasticpdf.com/blog/integrate-pdfjs-annotation-li...


ElasticPDF
2 声望1 粉丝

选择 IT 是因为热爱编程!ElasticPDF 是一款新国产 PDF 编辑器开发框架,基于开源 pdf.js 的渲染框架,增加了批注功能,批注产品力接近Adobe Acrobat,支持全离线运行,适用于公网及内网系统。