Preview PDF Files in Vue 3 Using PDFObject

vue3 pdf previewpdfobjectembed pdf in vuepdf viewer library
Published·Modified·

Recently, while developing the PDF preview feature for Zdir 3, I searched online and found that most solutions rely on pdf.js. However, pdf.js has poor compatibility with Vue 3 and requires writing a lot of custom code, which is not very friendly for frontend beginners like me. Is there a solution that can handle Vue 3 PDF preview with just a few lines of code? The answer is yes: use the PDFObject library.

Install PDFObject

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

Install PDFObject:

# Install PDFObject
npm i pdfobject

Using PDFObject in Vue 3

Without further ado, here is the code. The core implementation is just a few lines, much cleaner than 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 as needed, such as height */
.pdfobject-container { height: 680px; border: 1rem solid rgba(0,0,0,.1); }
</style>

Result

Tested successfully in Chrome, Edge, and Firefox browsers, with good preview results.

PDFObject Official Website: https://pdfobject.com/