Getting browsers to print HTML pages that are meant for on-screen display is a good way to go mad. They differ in what they consider printable - in my experience, Chrome is very happy printing long blocks of text, but Firefox and Safari don’t print stuff with certain CSS rules.
Your best bet is to construct a new page with a printable version of your text, and run the JS window.print()
command.
<script>
function printPage(text){
var printWindow = window.open('_blank');
printWindow.document.open('text/plain');
printWindow.document.write(text);
printWindow.print();
printWindow.close();
}
</script>
Here’s an example of an app with lots of text. It’s got a print button that opens a new tab containing just the text, and takes you back to the main app when you’ve printed.
https://anvil.works/build#clone:NPHXVEIHY3HWQFOJ=KYHQSBP7SLOTXREUFHQVNZXS
https://print-robinson-crusoe.anvil.app
The Printer
Form is a CustomHTML Form that has the JS printing function in it. The ‘print’ button runs self.call_js('printPage', text
) when it is clicked.
You can tinker with the text
variable in the Button’s event handler in order to set the text out how you want. That’s in Python, so no need to write any JavaScript. As a simple example, I’ve replaced newlines with HTML <br>
so the paragraphs are still there:
text = text.replace('\n', '<br>')
Here’s a GIF: