pdfvuer

repository·master·Indexed 21 days ago

https://github.com/arkokoley/pdfvuer

A Vue-based PDF viewer that leverages Mozilla's PDF.js to render PDF documents. It supports features such as auto-resizing, text layers, annotations, and custom scaling. Compatible with Vue 2 and Vue 3, the library provides a <pdf> component and a createLoadingTask method for manual PDF initialization.

Tokens
2.3K
Snippets
10
Records
13
Agent score
75%

What's inside pdfvuer

  1. Configure PDF scaling modes

    master

    The scale prop controls how the PDF is sized within its container. You can provide a specific numeric scale (e.g., 1.5) or use automatic modes:

    • 'page-width': Automatically calculates the scale required to make the PDF page match the width of the container.
    • 'page-height': Automatically calculates the scale required to make the PDF page match the height of the container.

    When using 'page-width' or 'page-height', the component emits an update:scale event with the calculated numeric value, allowing you to sync the state in your parent component.

  2. Install Pdfvuer as a Vue plugin

    master

    You can install pdfvuer globally in your Vue application using Vue.use(). This registers the Pdfvuer component automatically, making it available throughout your application.

    import Pdfvuer from 'pdfvuer';
    
    // In your Vue entry file (e.g., main.js)
    Vue.use(Pdfvuer);
  3. Basic usage of the pdf component

    master

    To use pdfvuer in a basic setup, import the component and provide a src prop containing the URL of the PDF file. You can also use the loading slot to display content while the PDF is loading.

    Note: import 'pdfjs-dist/build/pdf.worker.entry' is not required since version 1.9.1.

    <template>
      <pdf src="./static/relativity.pdf" :page="1">
        <template slot="loading">
          loading content here...
        </template>
      </pdf>
    </template>
    
    <script>
    import pdf from 'pdfvuer'
    
    export default {
      components: {
        pdf
      }
    }
    </script>
  4. Use createLoadingTask to load PDF data

    master

    The createLoadingTask(src) static method creates a PDFJS loading task. This task can be passed directly to the :src prop of the <pdf> component, allowing you to interact with the PDF object (e.g., to get the total number of pages) before or during rendering.

    import pdfvuer from 'pdfvuer'
    
    // Create a task that can be used as the :src prop
    const pdfdata = pdfvuer.createLoadingTask('./static/relativity.pdf');
    
    // The task returns a promise that resolves to the PDF document
    pdfdata.then(pdf => {
      console.log('Total pages:', pdf.numPages);
    });
  5. Configure transpileDependencies for pdfjs-dist

    master

    When using pdfvuer in a Vue CLI project, you may need to ensure that pdfjs-dist is transpiled correctly to avoid compatibility issues in certain environments. You can do this by adding 'pdfjs-dist' to the transpileDependencies array in your vue.config.js file.

    module.exports = {
        transpileDependencies: [
            'pdfjs-dist'
        ]
    }
  6. Handle pdfvuer component events

    master

    The <pdf> component emits the following events:

    EventPayloadDescription
    @numpagesNumberThe total number of pages in the PDF.
    @loadingBooleanIndicates the current loading state of the PDF.
    @errorFunctionHandler for errors occurring during loading or drawing.
    @link-clickedObjectHandler for clicked links within the PDF. The payload contains pageNumber and other link metadata.

    Example: Handling @link-clicked

    handle_pdf_link: function (params) {
      // params contains pageNumber
      var page = document.getElementById(String(params.pageNumber));
      page.scrollIntoView();
    }
  7. Configure pdf component props

    master

    The <pdf> component accepts the following props:

    PropTypeDefaultDescription
    :srcString / Object''The URL or data of the PDF file. Accepts string, TypedArray, DocumentInitParameters, or PDFDataRangeTransport (see PDFJS.getDocument()).
    :pageNumber1The page number to display.
    :rotateNumber0Page rotation in degrees (must be multiples of 90).
    :scaleNumber / String'page-width'Scaling factor. When using 'page-width' or the :resize prop, the component emits update:scale to sync the computed scale. Use .sync modifier in Vue 2.
    :resizeBooleanfalseEnables auto-resizing on window resize.
    :annotationBooleanfalseEnables the annotation layer.
    :textBooleantrueEnables the text layer.
  8. Use the Pdfvuer component

    master

    The Pdfvuer component is the primary entry point for rendering PDF files in a Vue application. It accepts a source (URL, object, or Promise), page number, rotation, and scaling options. It also supports enabling text layers for selection and annotation layers for hyperlinks.

    Key Props:

    • src (String | Object | Promise): The source of the PDF. Can be a URL string, a configuration object, or a loading task promise.
    • page (Number): The page number to display (defaults to 1).
    • rotate (Number): Rotation in degrees (defaults to 0).
    • scale (Number | String): The zoom level. Supports numeric values or special strings: 'page-width' and 'page-height'.
    • resize (Boolean): If true, the component will automatically re-scale to fit the container width when the container is resized.
    • annotation (Boolean): Enables the annotation layer (e.g., for hyperlinks). Defaults to false.
    • text (Boolean): Enables the text layer for text selection. Defaults to true.
    <template>
      <Pdfvuer 
        src="/path/to/document.pdf" 
        :page="1" 
        :scale="'page-width'" 
        :resize="true" 
        :annotation="true"
      />
    </template>
  9. Register the Pdfvuer component manually

    master

    If you prefer not to install the plugin globally, you can import the default export and register it as a local component in your Vue component definition.

    import Pdfvuer from 'pdfvuer';
    
    export default {
      components: {
        Pdfvuer
      }
    };
  10. Create a PDF loading task with createLoadingTask

    master

    The createLoadingTask exported function allows you to manually initialize a PDF loading task. This is useful if you want to handle password prompts or progress tracking before passing the task to the Pdfvuer component.

    Parameters:

    • src (String | Object): A URL string or a configuration object compatible with pdfjs-dist's getDocument.
    • options (Object): An optional object containing callbacks:
      • onPassword: Callback triggered when a password is required.
      • onProgress: Callback triggered during the loading process.

    Returns a promise-like object that Pdfvuer can consume via the src prop.

    import { createLoadingTask } from 'pdfvuer';
    
    const loadingTask = createLoadingTask('/my-file.pdf', {
      onPassword: (password) => {
        // handle password prompt
      },
      onProgress: (progress) => {
        console.log(`Loading: ${progress.loaded} / ${progress.total}`);
      }
    });