If you're facing compatibility issues with Vue 3 for a specific plugin, one alternative is to create your own plugin based on vue-html-to-paper:
- To begin, make a new folder named 'plugins' in the project root directory. Inside this folder, add a file called
VueHtmlToPaper.js
with the code provided below:
// Custom function to add styles to the document
function addStyles(win, styles) {
styles.forEach((style) => {
let link = win.document.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", style);
win.document.getElementsByTagName("head")[0].appendChild(link);
});
}
const VueHtmlToPaper = {
install(app, options = {}) {
app.config.globalProperties.$htmlToPaper = (
el,
localOptions,
cb = () => true
) => {
// Default settings
let defaultName = "_blank",
defaultSpecs = ["fullscreen=yes", "titlebar=yes", "scrollbars=yes"],
defaultReplace = true,
defaultStyles = [];
let {
name = defaultName,
specs = defaultSpecs,
replace = defaultReplace,
styles = defaultStyles
} = options;
// Checking for local options and updating if present
if (!!localOptions) {
if (localOptions.name) name = localOptions.name;
if (localOptions.specs) specs = localOptions.specs;
if (localOptions.replace) replace = localOptions.replace;
if (localOptions.styles) styles = localOptions.styles;
}
specs = !!specs.length ? specs.join(",") : "";
const element = window.document.getElementById(el);
if (!element) {
alert(`Element to print #${el} not found!`);
return;
}
const url = "";
const win = window.open(url, name, specs, replace);
win.document.write(`
<html>
<head>
<title>${window.document.title}</title>
</head>
<body>
${element.innerHTML}
</body>
</html>
`);
addStyles(win, styles);
setTimeout(() => {
win.document.close();
win.focus();
win.print();
win.close();
cb();
}, 1000);
return true;
};
}
};
export default VueHtmlToPaper;
To integrate this custom plugin into your project, simply copy the code, replace instances of Vue
with app
, and then import it in the main.js
:
import { createApp } from 'vue'
import App from './App.vue'
import VueHtmlToPaper from './plugins/VueHtmlToPaper'
let app=createApp(App);
app.use(VueHtmlToPaper)
app.mount('#app')
You can now use this plugin in any component like so:
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png">
<!-- SOURCE -->
<div id="printMe">
<h1>Print me!</h1>
</div>
<!-- OUTPUT -->
<button @click="print">print</button>
</div>
</template>
<script lang="ts">
import {
defineComponent
} from 'vue';
import HelloWorld from '@/components/HelloWorld.vue'; /
export default defineComponent({
name: 'Home',
components: {
HelloWorld,
},
methods: {
print() {
this.$htmlToPaper('printMe')
}
},
mounted() {
}
});
</script>
Check out the LIVE DEMO for a working example.