Skip to content

index.html

html
<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>My PDF Viewer</title>
  <style>
    #canvas_container {
      width: 800px;
      height: 450px;
      overflow: auto;
      background: #333;
      text-align: center;
      border: solid 3px
    }
  </style>
</head>
<body>
<div id="my_pdf_viewer">
  <div id="canvas_container">
    <canvas id="pdf_renderer"></canvas>
  </div>
  <div id="navigation_controls">
    <button id="go_previous">Previous</button>
    <input id="current_page" value="1" type="number"/>
    <button id="go_next">Next</button>
  </div>
  <div id="zoom_controls">
    <button id="zoom_in">+</button>
    <button id="zoom_out">-</button>
  </div>
</div>
<script
  src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.min.js">
</script>
<script>
  const PDF_PATH = '/static/sample.pdf'
  const state = {
    pdf: null,
    currentPage: 1,
    zoom: 1
  }

  const fetchPDF = path => pdfjsLib.getDocument(path)
  const renderPDF = () => {
    state.pdf.getPage(state.currentPage).then((page) => {
      const canvas = getElem("pdf_renderer")
      const canvasContext = canvas.getContext('2d')
      const viewport = page.getViewport(state.zoom)
      const {width, height} = viewport

      Object.assign(canvas, {width, height})
      page.render({canvasContext, viewport})
    })
  }
  const isUndefinedPDF = () => state.pdf === null

  // helper
  const getElem = id => document.getElementById(id)
  const addEvent = (id, eventName, listener) => {
    getElem(id).addEventListener(eventName, listener)
  }
  const changeValue = (id, value) => {
    getElem(id).value = value
  }

  window.onload = () => {
    fetchPDF(PDF_PATH).then((pdf) => {
      state.pdf = pdf
      renderPDF()
    })

    addEvent('go_previous', 'click', () => {
      if (isUndefinedPDF() || state.currentPage == 1) return
      state.currentPage -= 1
      changeValue("current_page", state.currentPage)
      renderPDF()
    })
    addEvent('go_next', 'click', () => {
      if (isUndefinedPDF() || state.currentPage >= state.pdf._pdfInfo.numPages) {
        return
      }
      state.currentPage += 1
      changeValue("current_page", state.currentPage)
      renderPDF()
    })

    addEvent('zoom_in', 'click', () => {
      if (isUndefinedPDF()) return
      state.zoom += 0.5
      renderPDF()
    })

    addEvent('zoom_out', 'click', () => {
      if (isUndefinedPDF()) return
      state.zoom -= 0.5
      renderPDF()
    })
  }

</script>
</body>
</html>