Skip to content
ComPDF

如何使用 ComPDFKit for Web 创建 Vanilla JavaScript 应用

前提条件

要开始使用,您需要:

  • 最新的稳定版本的 Node.js。
  • 与 npm 兼容的包管理器。
  • 申请许可证密钥:联系 ComPDFKit 销售团队 获取免费的 30 天试用许可证。

将 ComPDFKit for Web 包从 npm 安装到您的 Vanilla JS 项目中:

shell
npm i @compdfkit_pdf_sdk/webviewer --save
  1. 将包含运行 ComPDFKit Web 演示所需的静态资源文件的 "webviewer" 文件夹添加到项目的公共资源文件夹中。您需要复制的文件夹是 node_modules/@compdfkit_pdf_sdk/webviewer/dist
shell
cp ./node_modules/@compdfkit_pdf_sdk/webviewer/webviewer.global.js ./
cp -a ./node_modules/@compdfkit_pdf_sdk/webviewer/dist/. ./webviewer
  1. 创建 index.html

您需要知道的是,当您使用 Web SDK 时,需要使用参数 "path" 来告诉它静态资源的位置。如果不执行此步骤,则它们将相对于当前路径。

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ComPDFKit Web Viewer</title>
</head>
<!-- Import WebViewer as a script tag -->
<script src='./webviewer.global.js'></script>
<body>
  <div id="app" style="width: 100%; height: 100vh;"></div>
</body>
</html>
  1. 添加一个 script 标签并使用 Vanilla JavaScript 初始化 ComPDFKitViewer for Web。
html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ComPDFKit Web Viewer</title>
</head>
<!-- Import WebViewer as a script tag -->
<script src='./webviewer.global.js'></script>
<body>
  <div id="app" style="width: 100%; height: 100vh;"></div>

  <script>
    let docViewer = null;

    ComPDFKitViewer.init({
      path: '/',
      pdfUrl: '/webviewer/example/developer_guide_web.pdf',
      license: '<Input your license here>'
    }, document.getElementById('app')).then((core) => {
      docViewer = core.docViewer;

      docViewer.addEvent('documentloaded', async () => {
        console.log('document loaded');
      })
    })
  </script>
</body>
</html>
  1. 为了在本地主机上显示,我们需要在此步骤中设置服务器环境
shell
npm install -g http-server
  1. 启动您的网站
shell
http-server -a localhost -p 8080

在浏览器中打开 http://localhost:8080。然后您可以看到要显示的 PDF 文件。