Custom printing functionality is essential when dealing with dynamic content layouts that extend beyond simple tabular data. This approach anables precise control over printable regions.
Required Dependencies
Install the necessary libraries:
npm install html2canvas print-js
Import the dependencies in you're component:
import html2canvas from 'html2canvas';
import printJs from 'print-js';
Implementation Setup
Assign a ref attribute to the container element that encompasses the printable content. Ensure the parent container has explicit width and height dimensions defined.
Print Function Implementation
handlePrint() {
const printContainer = this.$refs.printArea;
const containerWidth = printContainer.offsetWidth;
const containerHeight = printContainer.offsetHeight;
const canvasElement = document.createElement('canvas');
const resolutionMultiplier = 4; // Higher values improve image quality but increase processing time
canvasElement.width = containerWidth * resolutionMultiplier;
canvasElement.height = containerHeight * resolutionMultiplier;
canvasElement.style.width = `${containerWidth * resolutionMultiplier}px`;
canvasElement.style.height = `${containerHeight * resolutionMultiplier}px`;
const context = canvasElement.getContext('2d');
context.scale(resolutionMultiplier, resolutionMultiplier);
const verticalScroll = document.documentElement.scrollTop || document.body.scrollTop;
const horizontalScroll = document.documentElement.scrollLeft || document.body.scrollLeft;
html2canvas(printContainer, {
canvas: canvasElement,
backgroundColor: null,
useCORS: true,
windowHeight: document.body.scrollHeight,
scrollX: -horizontalScroll,
scrollY: -verticalScroll
}).then((renderedCanvas) => {
const imageData = renderedCanvas.toDataURL('image/png');
printJs({
printable: imageData,
type: 'image',
documentTitle: 'Custom Print',
style: '@page{size:auto;margin: 0cm 1cm 0cm 1cm;}'
});
}).catch(error => {
console.error('Print generation failed:', error);
});
}