> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/web/get-started/samples/showcase-demo-flatten-form.md).

# Flatten Form Showcase Demo Code Sample

Annotate and form flatten PDFs to permanently merge annotations and fields with page content.   Use form flattening by adding annotations and fields, then merging them into a PDF.

{% hint style="info" %}
**Requirements**

*These packages are required to use these features in production. Trial keys have unlimited access to all features*

<a href="/web/get-started/readme.md" class="button primary">Web SDK</a><a href="https://showcase.apryse.com/flatten-form" class="button primary">Live demo</a>
{% endhint %}

Easily enable annotation and form flattening capabilities to permanently merge annotations with page content.

This demo allows you to:

* Annotate a PDF
* Edit fields
* Merge fields and annotations into the page content
* Download the updated PDF

### **Implementation steps**

To add annotation and form flattening capabilities to WebViewer: Step 1: Get stared in your [preferred web stack for WebViewer](/web/get-started/readme.md) Step 2: Add the ES6 JavaScript sample code provided in this guide

Once you generate your license key, it will automatically be included in your sample code below.

{% @apryse-license-key/apryse-license-key platform="WEB\_VIEWER" variant="compact" %}

<pre class="language-js" data-line-numbers><code class="lang-js">// ES6 Compliant Syntax
// GitHub Copilot v1.0 - GPT-4 Model - July 15, 2025
// File: index.js

import WebViewer from '@pdftron/webviewer';

const licenseKey = '<code class="expression">visitor.claims.wvKey || "YOUR_WEBVIEWER_LICENSE_KEY"</code>';

// Customize the WebViewer UI
// Add custom buttons for flattening forms and downloading PDFs
const customizeUI = (instance) => {
  const { UI } = instance;

  // Flattening button
  const flattenButton = new UI.Components.CustomButton({
    dataElement: 'flattenButton',
    className: 'custom-button-class',
    label: 'Flattening',
    onClick: () => flatten(instance), // Flatten the document
    style: {
      padding: '10px 20px',
      backgroundColor: 'white',
      color: 'blue',
      border: '1px solid blue',
    }
  });

  // Download button
  const downloadButton = new UI.Components.CustomButton({
    dataElement: 'downloadPdfButton',
    className: 'custom-button-class',
    label: 'Download',
    onClick: () => download(instance), // Download with annotations
    style: {
      padding: '10px 20px',
      backgroundColor: 'blue',
      color: 'white',
    }
  });

  const defaultHeader = UI.getModularHeader('default-top-header');
  defaultHeader.setItems([...defaultHeader.items, flattenButton, downloadButton]);
};

// Flatten the form fields in the PDF document
const flatten = async (instance) => {
  const { documentViewer, PDFNet, annotationManager } = instance.Core;

  await PDFNet.initialize();
  const doc = await documentViewer.getDocument().getPDFDoc();
  const annotations = await annotationManager.exportAnnotations();

  // Run PDFNet methods with memory management
  await PDFNet.runWithCleanup(async () => {

    // lock the document before a write operation
    // runWithCleanup will auto unlock when complete
    doc.lock();

    // import annotations to PDFNet
    const fdf_doc = await PDFNet.FDFDoc.createFromXFDF(annotations);
    await doc.fdfUpdate(fdf_doc);

    // Generate appearances in a way that supports non-standard rotation
    const options = await PDFNet.PDFDoc.createRefreshOptions();
    options.setUseNonStandardRotation(true);
    await doc.refreshAnnotAppearances(options);

    // flatten all annotations in the document
    await doc.flattenAnnotations();

    // clear the original annotations
    annotationManager.deleteAnnotations(annotationManager.getAnnotationsList());
  });

  // clear the cache (rendered) data with the newly updated document
  documentViewer.refreshAll();

  // Update viewer to render with the new document
  documentViewer.updateView();

  // Refresh searchable and selectable text data with the new document
  documentViewer.getDocument().refreshTextData();
};

// Download the PDF
const download = async (instance) => {

  // Set the options for downloading the PDF
  const options = {
    flags: instance.Core.SaveOptions.LINEARIZED,
    downloadType: 'pdf'
  };

  instance.UI.downloadPdf(options);
};

WebViewer(
  {
    path: '/lib',
    initialDoc: 'https://apryse.s3.us-west-1.amazonaws.com/public/files/samples/form.pdf',
    fullAPI: true,
    enableFilePicker: true, // Enable file picker to open files. In WebViewer -> menu icon -> Open File
    licenseKey: licenseKey, 
  },
  document.getElementById('viewer')
).then((instance) => {

  // customize WebViewer UI
  customizeUI(instance);

  console.log('✅ WebViewer loaded successfully.');
}).catch((error) => {
  console.error('❌ Failed to initialize WebViewer:', error);
});
</code></pre>

[View the full sample on GitHub](https://github.com/ApryseSDK/webviewer-samples/tree/main/showcase-demos-playground)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/web/get-started/samples/showcase-demo-flatten-form.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
