Utilizing Laravel 8 and InertiaJS (Vue js)
In order to generate PDF, I am using the html2pdf.js library and have created a component specifically for this purpose: ExportPdf.vue
Below is the code for the ExportPdf.vue component :
<template>
<div>
<button class="px-6 py-3 rounded bg-gray-600 hover:bg-gray-900 text-white text-sm font-bold whitespace-no-wrap"
@click="exportToPDF">Export to PDF
</button>
</div>
</template>
<script>
import html2pdf from 'html2pdf.js'
export default {
props:{
area: HTMLDivElement,
name : String,
orientation : {
type: String,
default(){
return 'landscape'
}
}
},
methods:{
exportToPDF () {
html2pdf(this.area, {
margin: [1.5, 1],
filename: this.name + '.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: {scale: 2},
jsPDF: { unit: 'cm', format: 'a4', orientation: this.orientation , floatPrecision: 16 }
})
}
}
}
</script>
To utilize this component, simply include it within any other component where you want to extract content into a PDF file like so:
<export-pdf name="file name" :area="$refs.content" />
Make sure to reference the specific Div you wish to extract using ref, as shown below:
<div ref="content">
<!-- Content to Extract into PDF -->
</div>
The issue arises when switching between components, causing the component to no longer function properly unless the page is refreshed.
After further investigation, I discovered that the prop (this.area which receives the $refs.content from the parent) inside the ExportPdf component was undefined. This could be due to the component being mounted before the $refs.content is initialized in the parent component.
A temporary solution I found was to add a conditional check (v-if) to the ExportPdf component in each parent component, setting a boolean value to true in the parent component's mounted method. This resolves the issue of the prop being undefined without requiring a page refresh. However, this approach can be cumbersome to implement in every parent component.
For example: Parent template :
<export-pdf v-if="isMounted" name="Liste des consommables des équipements" :area="$refs.content" />
data(){
return {
isMounted : false,
}
},
mounted(){
this.isMounted = true
}
Are there any suggestions on how to improve this process?
Thank you.