From time to time, I have tried to print Anvil pages, as displayed in the browser.
I can scroll down as many “pages” as I want. However, when I try to print, I get only what currently fits on 1 page, not the full height of the report.
My goal is to print a dead-simple, pre-paginated, 132-column by 66-line report, in its entirety, from the user’s browser, using a properly-sized monospaced font. The user should not have to jump through browser- or word-processor-specific hoops (including downloads). A big, dumb “Print Me” button would be ideal.
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.
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:
To configure your layout, you might consider using the PyPDF2 library that’s installed in Server Modules - pass the text to a server function, convert it to a PDF, return it and print it.
Think I’ve finally got something working, and it didn’t need any PDF complications.
Changed the type to “text/html”, so that I could use standard page breaks every 66 lines, as stated in my initial post. To insert those page breaks, and not leave trailing blank pages (Edge does not optimize them away), I used the following code:
lines = get_open_form().label_report_contents.text.split('\r\n')
while (lines and lines[-1] == ''): # remove trailing blank lines
lines.pop()
num_lines = len(lines)
pages = []
for group in xrange(0, num_lines, LINES_PER_PAGE):
page = '\r\n'.join(lines[group:group+LINES_PER_PAGE])
pages.append('<pre style="font-size:9px">' + page + '</pre>')
self.call_js('printPage',
'<p style="page-break-before: always">'.join(pages)
)
My lines end in \r\n (instead of \n) to accommodate downloading by Windows users.
EDIT: added font size setting, in case the user’s browser is set to print at 100% scale, instead of “Shrink to fit”.