HOW TO:
Print, view and save a portion of the web page through javascript. (no plugins)
Example:
Using jQuery select the portion you desire.
"This is the section I would like to select!"
Now the variable myText has the text of the selected
class.
After selecting the correct content, use a button (or any other trigger option) to initiate a javascript function called window.open(URL, name, specs, replace);
To use this function correctly you need to follow it up with document.write(); & document.close(); so that you can write on the new window and then be able to close.
Example:
Click to View
In this example above, I set a variable called WinPrint to window.open(); and set some parameters -> all I did was add some style and left URL & name blank or empty string.
Once the button #myTriggerButton is clicked, the code will run through each line. After the set variable (WinPrint), document.write(); writes on the new window WinPrint. Inside the parameters, I set my first variable myText. Then document.close(); will help finish the writing. Finally the WinPrint.focus(); is there to have the popup window (WinPrint) be the focus (or be first/in front) of any other windows open at the moment.
Tip: You are not limited to just text as the parameter in document.write();
WinPrint.document.write(`
`)
You can add tags like
or
and add bootstrap classes and styling.
Summary
This is a very basic example of this use case. Now that you know how to select any part of a webpage through jQuery and open it in a new window with any custom style, you can print or save the new page as a .pdf file or whichever you desire super clean and simple. This is better than taking screenshots that could contain unnecessary content or messy styling and also helps you avoid the need to convert a file or figuring out a plugin. Save time and code!
by Sally Kang
View Play
Back