Import Annotation Posts

Show saved annotations from database in document using PDFTron

Here we will learn how to import annotations saved in the database using PDFTron.

In my last blog, we have learned how to save annotations in the database.

Events for import annotation

At the time of document load, we will get all annotations saved in the database using AJAX call and then we'll import that annotation. Now the question is if we import annotation then that will be drawn and again annotation changed event will fire and again annotation will be saved (as I say in my last blog), so this will become an infinite flow, but we can overcome this problem by checking if an annotation is imported or not. If an annotation is not imported then only we'll save annotation in the database process otherwise we'll ignore it.

When we draw any annotation, the "annotationChanged" event will be fired, and check if it is an imported annotation, then we can ignore it(eg, save annotation process).

Here is an example of how to import annotations from the database.

Example

WebViewer({
    path: 'path_to_the_PDFTron_'lib'_folder_on_your_server',
    css: 'webviewer_css',
    licenseKey: 'YOUR_PDF_TRON_LICENSE_KEY',
    initialDoc: 'YOUR_FILE URL' //url of a file to load
}, document.getElementById('viewer'))
    .then(function (instance) {
        let docViewer = instance.docViewer;
        let annotManager = instance.annotManager;

        annotManager.on('annotationChanged', (annots, action, e) => {
            //if annotation is imported we'll return
            if (e.imported) return;
            //when document will loaded we'll get annotations fro db
            docViewer.on('documentLoaded', function () {
                $.ajax({
                    url: `URL_TO_SAVE_ANNOTATION`,
                    type: 'GET',
                    success: function (result) {
                        if (result.success) {
                            result.data.forEach(annotationObj => {

      annotManager.importAnnotations(annotationObj.annotation);
                            });
                        }
                    },
                    error: function (result) {
                        console.log(result);
                    }
                });
            });
        });
    });
December 28, 20201 minuteMonika VaghasiyaMonika Vaghasiya