Let’s have a look at how we can send a PDF file directly to the printer for printing in Vue 3 Composition API.
Example code
<script setup>
const printFiles = (event) => {
if (event.target.files?.length) {
const receivedFile = event.target.files[0]
const fileDataUrl = window.URL.createObjectURL(receivedFile)
const pdfFileWindow = window.open(fileDataUrl)
pdfFileWindow.print()
} else {
alert('No files selected!')
}
}
</script>
<template>
<div>
<div id="np-container">
<input type="file" @change="printFiles" accept="application/pdf" />
</div>
</div>
</template>
<style scoped>
#np-container {
padding: 10px;
}
</style>
Code language: HTML, XML (xml)
Explanation
First, you will create a function named printFiles. This function will handle the change event of a file input element and will check if any files have been selected.
If files are selected, It will store the first selected file in the receivedFile variable, create a URL for the file using window.URL.createObjectURL(receivedFile), open the file in a new window using window.open(fileDataUrl), and finally, print the file using the print() method.
const receivedFile = event.target.files[0]
const fileDataUrl = window.URL.createObjectURL(receivedFile)
const pdfFileWindow = window.open(fileDataUrl)
pdfFileWindow.print()
Code language: JavaScript (javascript)
If no files are selected, it will show an alert message.
In the template, you will add an input element of type file and bind the previewFiles function to the change event. You have to specify the accept attribute to accept pdf files only.
<template>
<div>
<div id="np-container">
<input type="file" @change="previewFiles" accept="application/pdf" />
</div>
</div>
</template>
Code language: HTML, XML (xml)
And.. that’s it! Now, you know how to use the Vue 3 Composition API to send a PDF file to a printer by using the file input element and the window API.