Some test text!

menu

Customize or modify a PDF before saving

This JavaScript sample lets you customize or modify a PDF, DOCX, XLSX or PPTX document before it is saved/downloaded (no servers or other external dependencies required). In this example annotations are flattened before saving the PDF. This functionality allows you to do a variety of modifications to the document before downloading – some common examples include adding stamps / watermarks to the PDF or injecting information into a document. In the case of MS Office files, modifications are saved into the PDF file.This sample works on all browsers (including IE10) and mobile devices without using plug-ins. Learn more about our JavaScript PDF Library.

Get StartedSamplesDownload

To run this sample, get started with a free trial of PDFTron SDK.

JavaScript

HTML

(exports => {
  const PDFNet = exports.PDFNet;
  const mergeAndSave = (doc, xfdf) => {
    const main = async () => {
      // Import XFDF into FDF, then merge data from FDF into PDF
      // Annotations
      const fdfDoc = await PDFNet.FDFDoc.createFromXFDF(xfdf);

      const pitr = await doc.getPageIterator();
      let page;
      let annotObj;
      /* eslint no-await-in-loop: 0 */
      for (; await pitr.hasNext(); pitr.next()) {
        try {
          page = await pitr.current();
          for (let i = await page.getNumAnnots(); i > 0; ) {
            annotObj = await page.getAnnot(--i);
            switch (await annotObj.getType()) {
              case PDFNet.Annot.Type.e_Widget:
              case PDFNet.Annot.Type.e_Link:
              case PDFNet.Annot.Type.e_Sound:
              case PDFNet.Annot.Type.e_Movie:
              case PDFNet.Annot.Type.e_FileAttachment:
                // these are not supported for import from webviewer
                break;
              default:
                page.annotRemoveByIndex(i);
                break;
            }
          }
        } catch (e) {
          console.log('Error Removing Annotations: ' + e);
          (await page.getSDFObj()).erase('Annots');
        }
      }

      await doc.fdfMerge(fdfDoc);

      // run any custom logic here
      await doc.flattenAnnotations();

      const docbuf = await doc.saveMemoryBuffer(PDFNet.SDFDoc.SaveOptions.e_linearized);
      return docbuf;
    };
    // add your own license key as the second parameter, e.g. PDFNet.runWithCleanup(main, 'YOUR_LICENSE_KEY')
    return PDFNet.runWithCleanup(main);
  };

  const customDownload = options => {
    const docViewer = readerControl.docViewer;
    const am = docViewer.getAnnotationManager();
    const annotationsToRemove = am.getAnnotationsList();
    const currentDocument = docViewer.getDocument();
    return PDFNet.initialize()
      .then(() => currentDocument.getPDFDoc())
      .then(pdfDoc => mergeAndSave(pdfDoc, options.xfdfString))
      .then(data => {
        // since we are flattening annotations we should remove the existing annotations in webviewer
        // and rerender so that the file displays correctly

        am.deleteAnnotations(annotationsToRemove);
        // clear the cache
        docViewer.refreshAll();
        // update viewer with new document
        docViewer.updateView();
        // Annotations may contain text so we need to regenerate
        // our text representation
        docViewer.getDocument().refreshTextData();
        return data;
      });
  };

  window.addEventListener('documentLoaded', () => {
    const doc = readerControl.docViewer.getDocument();
    doc.getFileData = customDownload;
  });
})(window);
// eslint-disable-next-line spaced-comment
//# sourceURL=config.js
close

Free Trial

Get unlimited trial usage of PDFTron SDK to bring accurate, reliable, and fast document processing capabilities to any application or workflow.

Select a platform to get started with your free trial.

Unlimited usage. No email address required.

Join our live demo to learn about use cases & capabilities for WebViewer

Learn more
close