Skip to content

Selecting a rectangle in a Pdf Document - Vuejs

If you set a PdfPages component's usermode to UserMode.DrawSelectionRectangle you can draw selection rectangles. After you've drawn the rectangle the rectangleSelect event fires and you can extract the coordinates of your rectangle.

ts
await _pages.setUserMode(UserMode.DrawSelectionRectangle);
_pages.addEventListener('rectangleselect', async (ev: Event) => {
  selected.value = { ...(ev as CustomEvent).detail }
});

See below for a full example.

Screenshot

Screenshot op draw-selection-rectangle

Code

vue
<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { PdfApplication, PdfDocument, PdfUploader, PdfPages } from "@tallcomponents/unopdf-vue";
import { UserMode } from "@tallcomponents/unopdf-vue";

// Note: this example uses Vite and retrieves the keys from the environment. 
// This should not be used in production.
// See the authentication section in the usage guide for more information.

const publickey = import.meta.env.VITE_PUBLIC_KEY;
const privatekey = import.meta.env.VITE_PRIVATE_KEY;

const app = ref<{ $el: HTMLPdfApplicationElement }>();
const document = ref<{ $el: HTMLPdfDocumentElement }>();
const pages = ref<{ $el: HTMLPdfPagesElement }>();

let selected: any = ref(undefined);

onMounted(async () => {
  await nextTick();

  const _app = app.value?.$el;
  if (_app) {
    const _pages = pages.value?.$el;
    if (_pages) {
      //#region set_mode_and_event_listener
      await _pages.setUserMode(UserMode.DrawSelectionRectangle);
      _pages.addEventListener('rectangleselect', async (ev: Event) => {
        selected.value = { ...(ev as CustomEvent).detail }
      });
      //#endregion set_mode_and_event_listener
    }
  }
});
</script>

<template>
  <h1>UnoPdf Example: Draw rectangle in Vue</h1>

  <PdfApplication
    ref="app"
    :publickey="publickey"
    :privatekey="privatekey"
  />


  <PdfDocument ref="document" />
  <PdfUploader />

  <div style="display:flex">
    <div>
      <PdfPages ref="pages" />
    </div>
    <div>
      <div style="padding: 10px">
        You can draw a selection rectangle on the page using your mouse.
      </div>
      <div
        v-if="selected"
        style="padding: 10px"
      >
        You selected: {{ selected }}
      </div>
    </div>
  </div>
</template>

Running the example

  • Download the vue - Selecting a rectangle in a Pdf Document project
  • Unzip the file to a directory vue-draw-selection-rectangle.
    shell
    unzip vue-draw-selection-rectangle.zip -d vue-draw-selection-rectangle
  • Open a terminal and go to that directory
    shell
    cd vue-draw-selection-rectangle
  • Install dependencies
    shell
    npm install
    shell
    yarn
  • Start the project
    shell
    npm run start
    shell
    yarn start