Table of Contents
Getting a key
Building a demo
Customizing the experience
Working with the API and handling events
How to learn more
Home Web Front-end CSS Tutorial Wrangling Control Over PDFs with the Adobe PDF Embed API

Wrangling Control Over PDFs with the Adobe PDF Embed API

Mar 24, 2025 am 09:21 AM

Wrangling Control Over PDFs with the Adobe PDF Embed API

By our last estimate, there are now more PDFs in the world than atoms in the universe (not verified by outside sources) so chances are, from time to time, you’re going to run into a PDF document or two. Browsers do a reasonably good job of handling PDFs. Typically, clicking a link to a PDF will open a new tab in your browser with custom UI and rendering per browser. Here’s the same PDF opened in Edge, Chrome, Firefox, and Safari, respectively:

As expected, each browser puts its own spin on things but one thing is consistent — all of them take over the entire viewport to render the PDF. While this is useful for giving the reader as much real estate to consume the PDF as possible, it would sometimes be desirable to have more control over the PDF experience. This is where the Adobe PDF Embed API comes in. The PDF Embed API is a free JavaScript library that lets you display PDFs inline with the rest of your content along with giving you control over the tools UI, supporting annotations and events, and more. Let’s walk through some examples of what it’s like to work with the library.

Getting a key

Before we begin, you’ll need to register for a key. If you head over to our Getting Started page, you’ll see a link to let you create new credentials:

If you don’t have an account with Adobe yet you’ll need to create one. You’ll be prompted to give the credentials a name and an application domain. While the name isn’t terribly important, the application domain is. The key you get will be restricted to a particular domain. You can only enter one domain here, so to start, you can use localhost or use cdpn.io as the domain if you want to try it on CodePen. If you want to use the API in both local and production environments, you can create multiple projects in the console or use HOSTS file configurations. (The ability to specify multiple domains for credentials is on the radar.)

Hit the lovely blue “Create Credentials” button and you’ll get your key:

If you’re curious and want to see what the Embed API can do right away, click on “Get Code Samples” which brings you to an interactive online demo. But since we’re hardcore coders who build our own editors before we go to work, let’s dive right into a simple example.

Building a demo

First, let’s build an HTML page that hosts our PDF. I’ve been a web developer for twenty years and am now an expert at designing beautiful HTML pages. Here’s what I came up:

<html>
  <head></head>
  <body>
    <h1>Cats are Everything</h1>
    <p>
      Cats are so incredibly awesome that I feel like
      we should talk about them more. Here's a PDF
      that talks about how awesome cats are.
    </p>
		
    <!-- PDF here! -->

    <p>
      Did you like that? Was it awesome? I think it was awesome! 
    </p>
  </body>
</html>
Copy after login

I put it up a bit of CSS, of course:

I honestly don’t know why Adobe hired me as a developer evangelist because, clearly, I should be on a design team. Anyway, how do we get our PDF in there? The first step is to add our library SDK:

<script src="https://documentcloud.adobe.com/view-sdk/main.js"></script>
Copy after login

Now we need a bit of JavaScript. When our library loads, it fires an event called adobe_dc_view_sdk.ready. Depending on how you load your scripts and your framework of choice, it’s possible the event fires before you even get a chance to check for it.

We can also check for the existence of window.AdobeDC. We can handle both by chaining to a function that will set up our PDF.

if (window.AdobeDC) displayPDF();
else {
  document.addEventListener("adobe_dc_view_sdk.ready", () => displayPDF());
}

function displayPDF() {
  console.log('Lets do some AWESOME PDF stuff!');
}
Copy after login

Alright, so how do we display the PDF? To accept all the defaults we can use the following snippet:

let adobeDCView = new AdobeDC.View({clientId: ADOBE_KEY, divId: "mypdf" });
adobeDCView.previewFile({
  content:{location: {url: "https://static.raymondcamden.com/enclosures/cat.pdf"}},
  metaData:{fileName: "cat.pdf"}
});
Copy after login

Let’s break that down. First, we create a new AdobeDC.View object. The clientId value is the key from earlier. The divId is the ID of a

in the DOM where the PDF will render. I removed the HTML comment I had earlier and dropped in an empty
with that ID. I also used some CSS to specify a width and height for it:
#mypdf {
  width: 100%;
  height: 500px;
}
Copy after login

The previewFile method takes two main arguments. The first is the PDF URL. The PDF Embed API works with either URLs or File Promises. For URLs, we want to ensure we’ve got CORS setup properly. The second value is metadata about the PDF which, in this case, is the filename. Here’s the result:

Here’s a complete CodePen of the example, and yes, you can clone this, modify it, and continue to use the key.

You’ll notice the UI contains the same tools you would expect in any PDF viewer, along with things like the ability to add notes and annotations.

Note the “Save” icon in the figure above. When downloaded, the PDF will include the comments and lovely marker drawings.

Customizing the experience

Alright, you’ve seen the basic example, so let’s kick it up a bit and customize the experience. One of the first ways we may do that is by changing the embed mode which controls how the PDF is displayed. The library has four different ones supported:

  • Sized Container — The default mode used to render a PDF inside a
    container. It renders one page at a time.
  • Full Window — Like Sized Container in that it will “fill” its parent
    , but displays the entire PDF in one “stream” you can scroll through.
  • In-Line — Displays it in a web page, like Sized Container, but renders every page in a vertical stack. Obviously, don’t use this with some large 99-page PDF unless you hate your users. (But if you already display one of those “Sign up for our newsletter” modal windows when a person visits your site, or your site autoplays videos, then by all means, go ahead and do this.)
  • Lightbox — Displays the PDF in a centered window while greying out the rest of the content. The UI to close the display is automatically included.

To specify a different view, a second argument of options can be passed. For example:

function displayPDF() {
  console.log('Lets do some AWESOME PDF stuff!');
  let adobeDCView = new AdobeDC.View({clientId: ADOBE_KEY, divId: "mypdf" });
  adobeDCView.previewFile({
    content:{location: {url: "https://static.raymondcamden.com/enclosures/cat.pdf"}},
    metaData:{fileName: "cat.pdf"}
  }, 
  {
    embedMode: "IN_LINE"
  });	
}
Copy after login

Note that in in-line mode, the height specified for your div will be ignored so that the PDF can stretch it’s legs a bit. You can view this version of the demo here: https://codepen.io/cfjedimaster/pen/OJpJRKr

Let’s consider another example – using lightbox along with a button lets us give the user the chance to load the PDF when they want. We can modify our HTML like so:

<html>
  <head></head>
  <body>
    <h1>Cats are Everything</h1>
    <p>
      Cats are so incredibly awesome that I feel like
      we should talk about them more. Here's a PDF
      that talks about how awesome cats are.
    </p>
		
    <!-- PDF here! -->
    <button  disabled>Show PDF</button>

    <p>
      Did you like that? Was it awesome? I think it was awesome! 
    </p>
  </body>
</html>
Copy after login

I’ve added a disabled button to the HTML and removed the empty

. We won’t need it as the lightbox mode will use a modal view. Now we modify the JavaScript:

const ADOBE_KEY = 'b9151e8d6a0b4d798e0f8d7950efea91';

if(window.AdobeDC) enablePDF();
else {
  document.addEventListener("adobe_dc_view_sdk.ready", () => enablePDF());
}

function enablePDF() {
  let btn = document.querySelector('#showPDF');
  btn.addEventListener('click', () => displayPDF());
  btn.disabled = false;
}

function displayPDF() {
  console.log('Lets do some AWESOME PDF stuff!');
  let adobeDCView = new AdobeDC.View({clientId: ADOBE_KEY });
  adobeDCView.previewFile({
    content:{location: {url: "https://static.raymondcamden.com/enclosures/cat.pdf"}},
    metaData:{fileName: "cat.pdf"}
  }, 
  {
    embedMode: "LIGHT_BOX"
  });	
}
Copy after login

There are two main changes here. First, checking that the library is loading (or has loaded) runs enablePDF, which removes the disabled property from the button and adds a click event. This runs displayPDF. Notice how the initializer does not use the divId anymore. Second, note the embedMode mode change. You can try this yourself via the Pen below.

You have more customization options as well, including tweaking the UI menus and icons to enable and disable various features:

adobeDCView.previewFile({
	content:{location: {url: "https://static.raymondcamden.com/enclosures/cat.pdf"}},
	metaData:{fileName: "cat.pdf"}
}, 
{
	showDownloadPDF: false,
	showPrintPDF: false,
	showAnnotationTools: false,
	showLeftHandPanel: false
});	
Copy after login

You can most likely guess what this does, but here’s a shot with the default options:

And here’s how it looks with those options disabled:

By the way, just so we’re clear, we definitely know that disabling the download button doesn’t “protect” the PDF seen here, the URL is still visible in via View Source.

Again, this is only a small example, so be sure to check the customization docs for more examples.

Working with the API and handling events

Along with customizing the UI, we also get fine grained control over the experience after it’s loaded. This is supported with an API that can return information about the PDF as well as the ability to listen for events.

Working with the API uses the result of the previewFile method. We haven’t used that yet, but it returns a Promise. One use of the API is to get metadata. Here’s an example:

let resultPromise = adobeDCView.previewFile({
  content:{location: {url: "https://static.raymondcamden.com/enclosures/cat.pdf"}},
  metaData:{fileName: "cat.pdf"}
}, { embedMode:"SIZED_CONTAINER" });	

resultPromise.then(adobeViewer => {
  adobeViewer.getAPIs().then(apis => {
    apis.getPDFMetadata()
    .then(result => console.log(result))
    .catch(error => console.log(error));
  });
});
Copy after login

This returns:

{
  'numPages':6,
  'pdfTitle':'Microsoft Word - Document1',
  'fileName':''
}
Copy after login

Along with API calls, we also have deep analytics integration. While the docs go into great detail (and talk about integration with Adobe Analytics), you can handle PDF viewing and interacting events in any way that makes sense to you.

For example, since we know how many pages are in a PDF, and we can listen for events like viewing a page, we can notice when a person has viewed every page. To build this, I modified the JavaScript, like so:

const ADOBE_KEY = 'b9151e8d6a0b4d798e0f8d7950efea91';

//used to track what we've read
const pagesRead = new Set([1]);
let totalPages, adobeDCView, shownAlert=false;

if(window.AdobeDC) displayPDF();
else {
  document.addEventListener("adobe_dc_view_sdk.ready", () => displayPDF());
}

function displayPDF() {
  console.log('Lets do some AWESOME PDF stuff!');
  adobeDCView = new AdobeDC.View({clientId: ADOBE_KEY, divId: "mypdf" });
	
  let resultPromise = adobeDCView.previewFile({
    content:{location: {url: "https://static.raymondcamden.com/enclosures/cat.pdf"}},
    metaData:{fileName: "cat.pdf"}
  }, { embedMode:"SIZED_CONTAINER" });	

  resultPromise.then(adobeViewer => {
    adobeViewer.getAPIs().then(apis => {
      apis.getPDFMetadata()
      .then(result => {
        totalPages = result.numPages;
        console.log('totalPages', totalPages);
        listenForReads();
      })
      .catch(error => console.log(error));
    });
  });
	
}

function listenForReads() {
	
  const eventOptions = {
    enablePDFAnalytics: true
  }

  adobeDCView.registerCallback(
  AdobeDC.View.Enum.CallbackType.EVENT_LISTENER,
  function(event) {
    let page = event.data.pageNumber;
    pagesRead.add(page);
    console.log(`view page ${page}`);
    if(pagesRead.size === totalPages && !shownAlert) {
      alert('You read it all!');
      shownAlert = true;
    }
  }, eventOptions
);

}
Copy after login

Notice that after I get information about the page count, I run a function that starts listening for page viewing events. I use a Set to record each unique page, and when the total equals the number of pages in the PDF, I alert a message. (Of course, we don’t know if the reader actually read the text.) While admiditely a bit lame, you can play with this yourself here:

const ADOBE_KEY = 'b9151e8d6a0b4d798e0f8d7950efea91';

//used to track what we've read
const pagesRead = new Set([1]);
let totalPages, adobeDCView, shownAlert=false;

if(window.AdobeDC) displayPDF();
else {
  document.addEventListener("adobe_dc_view_sdk.ready", () => displayPDF());
}

function displayPDF() {
  console.log('Lets do some AWESOME PDF stuff!');
  adobeDCView = new AdobeDC.View({clientId: ADOBE_KEY, divId: "mypdf" });
	
  let resultPromise = adobeDCView.previewFile({
    content:{location: {url: "https://static.raymondcamden.com/enclosures/cat.pdf"}},
    metaData:{fileName: "cat.pdf"}
  }, { embedMode:"SIZED_CONTAINER" });	

  resultPromise.then(adobeViewer => {
    adobeViewer.getAPIs().then(apis => {
      apis.getPDFMetadata()
      .then(result => {
        totalPages = result.numPages;
        console.log('totalPages', totalPages);
        listenForReads();
      })
      .catch(error => console.log(error));
    });
  });
	
}

function listenForReads() {
	
  const eventOptions = {
    listenOn: [ AdobeDC.View.Enum.PDFAnalyticsEvents.PAGE_VIEW ],
    enablePDFAnalytics: true
  }

  adobeDCView.registerCallback(
    AdobeDC.View.Enum.CallbackType.EVENT_LISTENER,
    function(event) {
      /*
       console.log("Type " + event.type);
       console.log("Data " + JSON.stringify(event.data));
      */
      let page = event.data.pageNumber;
      pagesRead.add(page);
      console.log(`view page ${page}`);
      if(pagesRead.size === totalPages && !shownAlert) {
        alert('You read it all!');
        shownAlert = true;
      }
    }, eventOptions
  );

}
Copy after login

How to learn more

I hope this introduction to the Embed API has been useful. Here are some resources to help you get deeper into it:

  • Start off by perusing the docs as it does a great job going over all the details.
  • We’ve got a live demo that lets you see everything in action and will even generate code for you.
  • If you have questions or need support, we’ve got a forum for questions and you can use the adobe-embed-api on StackOverflow as well.
  • If you need to work with PDFs at the server level, we’ve got the Adobe PDF Tools API as well as a crazy cool Adobe Document Generation tool you may like. These aren’t free like the PDF Embed API, but you can trial them for six months and test them out by signing up.

Lastly, we are absolutely open to feedback on this. If you’ve got suggestions, ideas, questions, or anything else, feel free to reach out!

The above is the detailed content of Wrangling Control Over PDFs with the Adobe PDF Embed API. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

See all articles