Adobe PDF Embed API를 사용하여 PDF에 대한 랭글 링 제어
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
#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 Embed API를 사용하여 PDF에 대한 랭글 링 제어의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!
본 웹사이트의 성명본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.핫 AI 도구
Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱
AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.
Undress AI Tool
무료로 이미지를 벗다
Clothoff.io
AI 옷 제거제
Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!
인기 기사
KB5055612 수정 방법 Windows 10에 설치되지 않습니까?4 몇 주 전 By DDD<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌<garden> : 정원 재배 - 완전한 돌연변이 가이드3 몇 주 전 By DDDNordhold : Fusion System, 설명4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌뜨거운 도구
메모장++7.3.1
사용하기 쉬운 무료 코드 편집기
SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.
스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경
드림위버 CS6
시각적 웹 개발 도구
SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)
- Full Window — Like Sized Container in that it will “fill” its parent

새로운 프로젝트가 시작될 때, Sass 컴파일은 눈을 깜박이게합니다. 특히 BrowserSync와 짝을 이루는 경우 기분이 좋습니다.

이번 주에 플랫폼 뉴스 라운드 업 RONDUP, Chrome은로드에 대한 새로운 속성, 웹 개발자를위한 접근성 사양 및 BBC Move를 소개합니다.

이것은 처음으로 HTML 요소를보고 있습니다. 나는 그것을 잠시 동안 알고 있었지만 아직 스핀을 위해 그것을 가져 갔다. 그것은 꽤 시원하고 있습니다

구매 또는 빌드는 기술 분야의 고전적인 논쟁입니다. 신용 카드 청구서에 라인 항목이 없기 때문에 물건을 구축하는 것이 저렴할 수 있지만

한동안 iTunes는 팟 캐스팅에서 큰 개 였으므로 "Podcast 구독"을 링크 한 경우 다음과 같습니다.

이번 주에 타이포그래피를 검사하기위한 편리한 북마크 인 Roundup, JavaScript 모듈과 Facebook의 Facebook 등을 어떻게 가져 오는지 땜질하기 위해 대기하는 편리한 북마크 인 Roundup과 Facebook의

사이트에서 방문자 및 사용 데이터를 추적하는 데 도움이되는 분석 플랫폼이 많이 있습니다. 아마도 널리 사용되는 Google 웹 로그 분석
