JSFiddle - React, Tailwind, and code Playground
by musicreader
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<div class="content">
<button class="print-btn" onclick="window.print()">Print this page</button>
<button class="print-layout-btn" onclick="togglePrintLayout()">Toggle Print Layout</button>
<button onclick="generateImage()">Generate Image of Page</button>
<div class="main-content">
<div class="article">
<h2>Article Title</h2>
<p>This is the main content of the article. When printing, the layout will change and the sidebar will be hidden.</p>
</div>
<div class="sidebar">
<h3>Sidebar</h3>
<p>This is a sidebar that contains additional information. It will not be shown in the print layout.</p>
</div>
</div>
</div>
<footer>
<p>© 2024 My Website</p>
</footer>
CSS
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.content {
background-color: #f4f4f4;
padding: 20px;
}
header, footer {
background-color: #333;
color: white;
text-align: center;
padding: 10px 0;
}
header {
margin-bottom: 20px;
}
.main-content {
display: flex;
justify-content: space-between;
}
.sidebar {
width: 30%;
background-color: #ddd;
padding: 10px;
}
.article {
width: 65%;
}
/* Print-specific layout */
@media print {
body {
font-size: 12pt;
margin: 10mm;
}
header, footer {
background-color: white;
color: black;
border-bottom: 1px solid #ccc;
padding: 5px 0;
}
.main-content {
display: block;
}
.sidebar {
display: none;
}
.article {
width: 100%;
}
.print-btn {
display: none;
}
}
JavaScript
let printStylesApplied = false;
let appliedPrintRules = [];
function togglePrintLayout() {
if (!printStylesApplied) {
// Apply the print styles
let stylesheets = document.styleSheets;
for (let sheet of stylesheets) {
try {
let rules = sheet.cssRules || sheet.rules;
for (let rule of rules) {
if (rule.media && rule.media.mediaText === 'print') {
for (let subRule of rule.cssRules) {
document.styleSheets[0].insertRule(subRule.cssText, document.styleSheets[0].cssRules.length);
appliedPrintRules.push(subRule.cssText); // Save the applied rules to remove them later
}
}
}
} catch (e) {
console.warn('Could not access stylesheet: ', e);
}
}
printStylesApplied = true;
} else {
// Remove the previously applied print styles
let styleSheet = document.styleSheets[0];
let currentRules = styleSheet.cssRules || styleSheet.rules;
for (let i = currentRules.length - 1; i >= 0; i--) {
if (appliedPrintRules.includes(currentRules[i].cssText)) {
styleSheet.deleteRule(i);
}
}
// Clear applied rules
appliedPrintRules = [];
printStylesApplied = false;
}
}
function generateImage() {
html2canvas(document.body).then(function(canvas) {
let link = document.createElement('a');
link.download = 'dummy_page_image.png';
link.href =...