I wanted to use components directly (randomcodetips.com/vue-html-to… However, Vue3 was used in the project, and the component seemed not to support it, so I used the source code of the component to try to customize the printing method to achieve clearer printing effect. Html2canvas and JSPDF were used in the first version of the project, but I don’t know why the printing effect was not clear enough. Window. Print ()
Requirement: Print everything on one A4 sheet of paper.
Implementation: Open a new window through window.open(), insert the DOM to be printed into the new page, call window.print() to realize the printing function, and set horizontal printing and other styles through media query.
Problems encountered:
- How to introduce styles?
styles.forEach((style) => {
const 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);
});
Copy the code
Create a CSS file in the public folder
- How do I set landscape printing?
Add styles to the CSS file
@media print {
@page{ size: A4 landscape; }}Copy the code
- Print without showing header footer, set margin: 0;
@media print {
@page {
size: A4 landscape;
margin: 0; }}Copy the code
- – Firefox print preview doesn’t show borders around tables (but it’s still not a great experience, you might want to try div layouts later)
table {
border-spacing: 0;
border-collapse: collapse;
}
table td {
box-shadow: 0 1px # 000 inset;
}
Copy the code
- Present the content one page at a time on A4 paper
Set the page DOM height and width to a ratio of 595 to 842
.test-view {
box-sizing: border-box;
width: 1675px;
height: 1184px;
padding: 20px;
}
Copy the code