目录
Getting a key
Building a demo
Customizing the experience
Working with the API and handling events
How to learn more
首页 web前端 css教程 用Adobe PDF嵌入API对PDF的控制控制

用Adobe PDF嵌入API对PDF的控制控制

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>
登录后复制

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>
登录后复制

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!');
}
登录后复制

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"}
});
登录后复制

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;
}
登录后复制

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"
  });	
}
登录后复制

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>
登录后复制

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"
  });	
}
登录后复制

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
});	
登录后复制

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));
  });
});
登录后复制

This returns:

{
  'numPages':6,
  'pdfTitle':'Microsoft Word - Document1',
  'fileName':''
}
登录后复制

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
);

}
登录后复制

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
  );

}
登录后复制

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!

以上是用Adobe PDF嵌入API对PDF的控制控制的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

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

它的出局!恭喜Vue团队完成了完成,我知道这是一项巨大的努力,而且很长时间。所有新文档也是如此。

在CI/CD上有点 在CI/CD上有点 Apr 02, 2025 pm 06:21 PM

我说的“网站”比“移动应用程序”更合适,但我喜欢Max Lynch的框架:

您可以从浏览器获得有效的CSS属性值吗? 您可以从浏览器获得有效的CSS属性值吗? Apr 02, 2025 pm 06:17 PM

我有人写了这个非常合法的问题。 Lea只是在博客上介绍了如何从浏览器中获得有效的CSS属性。那样的是这样。

在WordPress块编辑器中使用Markdown和本地化 在WordPress块编辑器中使用Markdown和本地化 Apr 02, 2025 am 04:27 AM

如果我们需要直接在WordPress编辑器中向用户显示文档,那么最佳方法是什么?

带有粘性定位的堆叠卡和一点点的杂物 带有粘性定位的堆叠卡和一点点的杂物 Apr 03, 2025 am 10:30 AM

前几天,我发现了科里·金尼文(Corey Ginnivan)网站上的这一点,当您滚动时,彼此之间的卡片堆放集。

比较浏览器的响应式设计 比较浏览器的响应式设计 Apr 02, 2025 pm 06:25 PM

这些桌面应用程序中有许多目标是同时在不同的维度上显示您的网站。因此,例如,您可以写作

如何将CSS网格用于粘头和页脚 如何将CSS网格用于粘头和页脚 Apr 02, 2025 pm 06:29 PM

CSS网格是一系列属性的集合,旨在使布局比以往任何时候都容易。像任何东西一样,那里有一点学习曲线,但是网格是

Google字体可变字体 Google字体可变字体 Apr 09, 2025 am 10:42 AM

我看到Google字体推出了新设计(Tweet)。与上一次大型重新设计相比,这感觉更加迭代。我几乎无法分辨出区别

See all articles