Print only selected items per page

I was asked to provide some complex printing features to a dynamically generated page. The page is designed to display each entry with a checkbox. Then one print button at the bottom of the page. The idea is to allow the user to select the check box next to each entry that they want to print, and then when they click the print button at the bottom of the page, only those entries that are selected will be printed.

I suppose some combination of CSS and Javascript is required, but I really don't know. Any ideas? Thanks in advance!

+4
source share
2 answers

Php solution

If you have something like

<form method="post" action="print.php"> <p>Select the records to be printed</p> <p> <input type="checkbox" name="records[]" value="1"><div class="record">Record 1</div><br> <input type="checkbox" name="records[]" value="2"><div class="record">Record 2</div><br> <input type="checkbox" name="records[]" value="3"><div class="record">Record 3</div> </p> </form> 

You will automatically receive the $_POST['records'] array with all the values ​​of the selected records in it in your PHP script print.php . (Note that this only works if the name of all the flags is the same and ends with [] )

Then the php script could do something like:

 <?php foreach ($record in $_POST['records']) { // fetch the record with id $record from the database (or similar) // print this record to the page } echo "<script>window.print();</script>"; // or put that into the onload attribute of the body tag ?> 

JavaScript and CSS

Another possible possibility would be to do all this through javascript. Therefore, you will need to check each checkbox if it will be checked when the print button is pressed, and then removes or hides all records that have not been checked.

A useful thing is the css media property, with which you can define additional styles that apply only to specific devices. This code can execute everything without javascript, except for the onclick="window.print()" attribute in your print button:

 @media print { input{ display: none; /* hides all input elements for the printer */ } .record { display: none; /* hide all records by default */ } input[checked] + .record, input:checked + div.record { /* display all that are immediately preceeded by a input with checked attribute */ display: block; } } 

Please note that I tested it only in Safari (where the pseudo-slot: verified leads to the desired result, not the attribute selector) and will work only for newer versions of browsers with css3 and selector .

+4
source

Create print.php to which you submit the form (with the selected checkboxes) - only the selected content will be displayed on the page exactly the way you want it to look in print, and then javascript window.print() onload is called.

+1
source

Source: https://habr.com/ru/post/1403070/


All Articles