Using PDFObject to Preview PDF Files in Vue3

Publish: 2023-01-12 | Modify: 2023-01-12

Recently, I've been developing the PDF preview feature for Zdir 3. After searching online, most solutions involve using pdf.js, which is not very compatible with Vue3. It requires writing a lot of code, which is not friendly for someone like me who is new to frontend development. Is there a solution that can easily preview PDF in Vue3 with just a few lines of code? The answer is yes, and that solution is to use the PDFObject library.

Installing PDFObject

Official description: PDFObject is an open-source, standards-friendly JavaScript utility for embedding PDF files into HTML documents.

To install PDFObject:

# Install PDFObject
npm i pdfobject

Using PDFObject in Vue3

Without further ado, let's dive into the code. With just a few lines of code, we can achieve the desired result, which is much simpler compared to the messy solutions found online.

<template>
    <div id="mypdf"></div>
</template>

<script setup>
// Import PDFObject
import PDFObject from 'pdfobject'
import { ref, onMounted } from 'vue'

onMounted(() => {
    let url = "https://soft.xiaoz.org/office/hee%20hee.pdf";
    PDFObject.embed(url, "#mypdf");
})
</script>

<style scoped>
/* Set PDFObject styles according to your needs, e.g., height */
.pdfobject-container { height: 680px; border: 1rem solid rgba(0,0,0,.1); }
</style>

Result

After testing in Chrome, Edge, and Firefox browsers, the PDF preview works fine. The result is quite satisfactory.

PDFObject official website: https://pdfobject.com/


Comments