Thursday, August 12, 2010

Printing HTML Documents Using Customised CSS and JavaScript

Recently, I was working on some Ruby on Rails project where users wanted to be able to print nice reports. I should admit that the gem solutions I found that time disappointed me because:
  • Most required a lot of time to understand than I had to make them work.
  • Some solutions required extra gems (and plugins) that I could not get because of usual gem error: ERROR: could not find gem XXX locally or in a repository!
One interesting fact was that the users had a defined report format which they wanted both screen layouts and printouts to be modelled from! An additional challenge was that the application was developed for use on a mouseless touchscreen computer that always open the browser in fullscreen mode. So, it would be difficult to manually select the Print command on the File menu of the browser. So after making a some Internet research, I got several solutions that I integrated to come up with mine that addresses the users' need. I present the solution here in a tutorial format so that it is easy to follow.
  1. Document Layout
Let us create a simple-and-easy-to-follow report layout using HTML tags as follows:

<html>
    <head>
    <title>The Application Name</title>
    <script src="/javascripts/report_printer.js" type="text/javascript"> </script>
    <link href="/stylesheets/report.css" media="screen" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <div id="report">
        <div id="metaData" onclick="javascript:printContent('document');" style="float: right;">
            <a> Print Report</a>
        </div>
        <div id="document">
            <div id="reportHeader"> Organization Name </div>
            <div id="reportSubHeader"> Report Name and/or Description </div>
            <div id="dataTable">
                <!-- the data table is placed here -->
            </div>
        </div>
    </div>
</body>
</html>
Linked to this file is a standalone CSS file, report.css, that contains CSS definitions for each of the div ids and classes. In this example, the CSS file is placed in stylesheets sub-directory. The metaData div contains a hyper-linked button for printing the report. The metaData div customizes the hyper-link to a button. This div is significant to the whole printing process as we will see in a moment.
  1. Adding Printing Functionality using JavaScript
With the CSS, everything looks nice on the screen. However, there are two problems:
  1. The Print command on the File menu produces clumsy output.
  2. It would be difficult to manually select the Print command on the File menu of the browser since the application is developed for use on a mouseless touchscreen computer that always open the browser in fullscreen mode.
In order to print, we create a transitional pop-up window that opens upon clicking print button and closes after the printing action completes, whether successfully or not. All this pop-up window does is initiate an onload action via print_win() function. This is a simple Javascript function that uses the default DOM print()and close() functions to print and close respectively. Here is the print_win() function:
   function print_win(){
      window.print();
      window.close();
   }
Now we let Javascript create and destroy the pop-up window. This Javascript is invoked upon clicking the print button defined in metaData div. The pop-up window will get its data from the innerHTML of the element whose id is passed as argument to printContent()function. This implies we have to make sure that all data that we would like to be printed is placed in the right div, otherwise any data outside it will not be printed. In our example, the data is placed in the document div.
We should also remember that since print_win() function belongs to the pop-up window, it will be embedded within the outer Javascript that creates the pop-up window. We place our code in report_printer.js in the javascripts sub-directory. Here is the code that does it all:
     function printContent(id){
     var data = document.getElementById(id).innerHTML;
     var popupWindow = window.open('','printwin',
          'left=100,top=100,width=400,height=400');
     popupWindow.document.write('<HTML>\n<HEAD>\n');
     popupWindow.document.write('<TITLE></TITLE>\n');
     popupWindow.document.write('<URL></URL>\n');
     popupWindow.document.write('<script>\n');
     popupWindow.document.write('function print_win(){\n');
     popupWindow.document.write('\nwindow.print();\n');
     popupWindow.document.write('\nwindow.close();\n');
     popupWindow.document.write('}\n');
     popupWindow.document.write('<\/script>\n');
     popupWindow.document.write('</HEAD>\n');
     popupWindow.document.write('<BODY onload="print_win()">\n');
     popupWindow.document.write(data);
     popupWindow.document.write('</BODY>\n');
     popupWindow.document.write('</HTML>\n');
     popupWindow.document.close();
  }
Our application is ready for printing. Try printing your document using the print button.
  1. Improving the Output
Trying to print the document shows that the data is rightly captured but not well structured as required. Let us add report.css to the pop-up window in print mode using some Javascript code. We modify and add a simple statement in our Javascript code: popupWindow.document.write("<link href='/stylesheets/report.css' media='print' rel='stylesheet' type='text/css' />\n"); We also add a dummy line that formats the screen layout of document on the pop-up window so that it looks better. Notice that the line is similar to the previous one except that we specify the media as screen. Our function now looks like this:

     function printContent(id){
     var data = document.getElementById(id).innerHTML;
     var popupWindow = window.open('','printwin',
          'left=100,top=100,width=400,height=400');
     popupWindow.document.write('<HTML>\n<HEAD>\n');
     popupWindow.document.write('<TITLE></TITLE>\n');
     popupWindow.document.write('<URL></URL>\n');
     popupWindow.document.write("<link href='/stylesheets/report.css' media='print' rel='stylesheet' type='text/css' />\n");
    popupWindow.document.write("<link href='/stylesheets/report.css' media='screen' rel='stylesheet' type='text/css' />\n");
     popupWindow.document.write('<script>\n');
     popupWindow.document.write('function print_win(){\n');
     popupWindow.document.write('\nwindow.print();\n');
     popupWindow.document.write('\nwindow.close();\n');
     popupWindow.document.write('}\n');
     popupWindow.document.write('<\/script>\n');
     popupWindow.document.write('</HEAD>\n');
     popupWindow.document.write('<BODY onload="print_win()">\n');
     popupWindow.document.write(data);
     popupWindow.document.write('</BODY>\n');
     popupWindow.document.write('</HTML>\n');
     popupWindow.document.close();
  }

We have finished successfully. Your application should be able to produce documents that are as nice as your original screen versions. You can print directly or to files, whether PDF, PostScript, etc.

Happy coding!!

103 comments:

  1. Thanks for your good solution, you save my whole day

    ReplyDelete
  2. Thank you for the best solution!

    ReplyDelete
  3. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.

    Data Science Training in Chennai
    Data science training in bangalore
    Data science online training
    Data science training in pune
    Data science training in kalyan nagar
    Data Science with Python training in chenni

    ReplyDelete
  4. It is better to engaged ourselves in activities we like. I liked the post. Thanks for sharing.
    python training in pune
    python training institute in chennai
    python training in Bangalore

    ReplyDelete
  5. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Devops training in marathahalli
    Devops training in rajajinagar

    ReplyDelete
  6. A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.

    rpa training in electronic-city | rpa training in btm | rpa training in marathahalli | rpa training in pune

    ReplyDelete
  7. Really very happy to say,your post is very interesting to read.I never stop myself to say something about it.You’re doing a great job.Keep it up.php training in navi mumbai

    ReplyDelete
  8. I really like your blog. You make it interesting to read and entertaining at the same time. I cant wait to read more from you.
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  9. I have visited this blog first time and i got a lot of informative data from here which is quiet helpful for me indeed. 
    python Training in Pune
    python Training in Chennai
    python Training in Bangalore

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Ruby on rails project is a very nice project.
    you can learn manythings like this. Just visit us to learn more on Amazon web server course

    ReplyDelete
  12. We really feel very happy about the blog you have shared. the explanation is very clear and valuable information. it improves my development skill in SCN and checkpoints. please share the blog like this...

    eTechno Soft Solutions is a leading training institute for all kind of the Oracle Training in Bangalore with real-time experienced trainers with 100% Placement Assistance.

    ReplyDelete
  13. Hey.. I checked your blog its really useful.. Provides lot of information.. Do check my blogs also https://exploring2gether.com/fascinating-places-near-dehradun/

    ReplyDelete
  14. hey...It is highly comprehensive and elaborated. Thanks for sharing!

    Localebazar- Your single guide for exploring delicious foods, travel diaries and fitness stories.

    Visit us for more- localebazar.com

    ReplyDelete
  15. Hey.. Well explained... provides a lot of knowledge... Thanks for sharing !!
    Check this out https://exploring2gether.com/red-sauce-pasta-recipe/

    ReplyDelete

  16. Nice! its really very helpful. thanks for sharing here.
    we provide short term Course training in Delhi

    ReplyDelete
  17. Thanks for sharing such helpful information with us I appreciate your effort of writing a valuable piece. if you want to learn spanish language course. you can contact us.

    ReplyDelete
  18. nice! thanks for great information.to learn german you can contact
    best german languge institute .
    they have certified trainer.

    ReplyDelete
  19. Wonderful information ! It was very informative. keep sharing it will help others too.
    if you want to learn French Lanaguage you can vist us at https://www.classesofprofessionals.com/french-language-institute-delhi

    ReplyDelete
  20. This is a very interesting web page and I have enjoyed reading many of the articles and posts contained on the website, keep up the good work and hope to read some more interesting content in the future. Absolutely this article is incredible. i would also invite to read my content on Digital Markteing Course and share your feedback.

    ReplyDelete
  21. hey...It is highly comprehensive and elaborated. Thanks for sharing!

    Localebazar Your single guide for exploring delicious foods, travel diaries and fitness stories.

    Visit us for more-
    localebazar.com

    ReplyDelete



  22. Thanks for sharing such helpful information with us I appreciate your effort of writing a value able piece.
    i also write on Spanish Language Course in Delhi.
    Please share your review on that.

    ReplyDelete
  23. Thanks for your good solution, you save my whole day

    Download CCC Certificate

    ReplyDelete
  24. This is most informative and also this post most user friendly and super navigation to all posts.

    Devops Certification Pune
    Devops Training in Pune
    Selenium Classes in Pune Hadapsar

    ReplyDelete
  25. Very well explained and easy to understand. Thanks for sharing !!!!
    i also would like to share my content topic on French language course and German language course . please review and share your feedback.

    ReplyDelete
  26. Attend The Data Science Course Bangalore From ExcelR. Practical Data Science Course Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Science Course Bangalore.
    Data Science Course Bangalore
    Data Science Interview Questions

    ReplyDelete
  27. Thanks for sharing such valuable information with us I appreciate your effort of writing a value able piece.
    immigration consultants in Delhi

    ReplyDelete
  28. Thanks for sharing the pretty post, if you focus the certification training to enhance your skill for attaining good job in IT industry, for that you Can take the valuable certification training of Language course ( German Language Course, French language Course, Spanish Language Course) for your career growth.

    ReplyDelete
  29. Pretty article! I found some useful information in your blog....

    so here we provide,

    We provide you with flexible services and complete hybrid network solutions. It can provide your organisation with exceptional data speeds, advanced external security protection, and high-resilience by leveraging the latest SD-WAN and networking technologies to monitor, manage and strengthening your organisation’s existing network devices.

    https://www.quadsel.in/networking/>
    https://twitter.com/quadsel/
    https://www.linkedin.com/company/quadsel-systems-private-limited/
    https://www.facebook.com/quadselsystems/

    #quadsel #network #security #technologies #managedservices #Infrastructure #Networking #OnsiteResources #ServiceDeskSupport #StorageServices #WarrantyAMCServices #datacentersolutions #DataCenterBuild #EWaste #InfraConsolidation #DisasterRecovery #NetworkingServices #ImagingServices #MPS #Consulting #WANOptimisation #enduserservices

    ReplyDelete
  30. The one who does business and takes the responsibility of all the profits and losses is known as entrepreneurs. Here are tips on how to be an entrepreneur.

    For More Info Visit:-https://younity.in/2020/06/05/how-to-be-an-entrepreneur/

    ReplyDelete
  31. thanks for sharing such a informative content with us .i also want to share some info. about Online Spanish language Course, online German Language course and Online French language Course. Please share your review towards this

    ReplyDelete
  32. i really liked your blog. keep shaing these ind for valuable content with us. i also would like to tell you about some course which is very demanding now a days. courses are - Online Spanish language, Online german Language, Online French Language.





    ReplyDelete
  33. Thanks for sharing information awesome blog post Online Education Quiz website


    https://www.kaashivinfotech.com/best-final-year-project-in-information-technology/

    ReplyDelete
  34. i really liked your blog. keep shaing these ind for valuable content with us. i also would like to tell you about some course which is very demanding now a days. courses are - Online IELTS Course, Online Short Term Course .

    ReplyDelete
  35. Really useful information. Thank you so much for sharing.It will help everyone.Keep Post.

    AWS Training in Hyderabad

    ReplyDelete
  36. https://iraitechinnovation.blogspot.com/2020/09/relevance-of-cyber-security-during.html

    ReplyDelete
  37. thanks for sharing such a informative content with us .i also want to share some info. about Spanish language for kids, online German Language for kids and Online French language for Kids. Please share your review towards this

    ReplyDelete
  38. Thanks for sharing such a beautiful content with us. i would also like to introduce Japanese Classes for kids. They aim to provide high-quality education and cater to every child’s needs.

    ReplyDelete
  39. Thanks for sharing such a beautiful content with us. i also find very good content for personality development for international jobs or opportunity you must read this.

    ReplyDelete
  40. Learning English for Being a beginner learner is not easy at all. It can be easy to feel inadequate and frustrated.We encourage children to talk about events that happened in school and during the week. That's where our teacher's speciality lies. They are trained to gain faith in younger kids and help them find their identity and create trust. English classes for kids is the secret to swift language learning. The conversational approach that we use instils trust in the kids that they can speak English even if they make a minor mistake or two.

    for more information you can call us at +91-8744978672

    ReplyDelete
  41. Thanks for sharing such a beautifull content with us. Our French classes for kids are open to all children aged 8 to 20. Whether you want your children to learn a new language or allow them to do better in school if they are already learning French there, we have the right course for them.

    for more details you can contact us - +91-8744978672

    visit us - https://www.classesofprofessionals.com/french-classes-for-kids

    ReplyDelete
  42. I simply could not leave your site before sharing my reviews that i actually loved the information you shared here.i also would like to invite you to share your review on my content- IELTS coaching in Delhi, English for kids

    ReplyDelete
  43. awesome content you have shared on your blog
    you can check our GYC silicon straps high quality printing premium looking bands straps compatible for Mi Xiomi BAND 3 BAND 4. Click on the link given below

    CLICK HERE
    CLICK HERE
    CLICK HERE
    CLICK HERE

    ReplyDelete
  44. Thanks for sharing great content with us. I like reading your site's content more. I appreciate your writing skills and the way you are written. I am also a content writer and writing about a Malta work permit, please check and review that.

    ReplyDelete
  45. I just like the helpful information you provide in your articles. I will bookmark your blog and take a look at it once more here regularly.
    I am somewhat certain I’ll be informed of plenty of new stuff right here! Good luck with the following! please check and review the best visa Consultants in Delhi

    ReplyDelete
  46. Hey ,

    Great Job . You Know what ?

    I read a lot of blog posts and I never heard of such a topic. I love the subject you have done about bloggers. Very simple. I am also writing a blog related to the ielts online coaching. You can also see this.

    ReplyDelete
  47. What a fantastic post! This is so chock full of useful information I can't wait to dig deep and start utilizing the resources you have given me. your exuberance is refreshing

    you've outdone yourself this time

    This is probably the best, most concise step-by-step guide I've ever seen on how to build a successful blog. i am also writing blog about the  kindly review it french language institute in delhi .

    Classes of professional studies
    https://www.classesofprofessionals.com/

    ReplyDelete
  48. Want to set your career towards the software field? Then join hands with Infycle Technologies to make this into reality. Infycle Technologies, the best software training center in Chennai, gives the combined and best software training in Chennai, with various stages of multiple courses such as Big Data, Python, Data Science, Oracle, etc., which professional tutors will guide in the field. The Hands-on practical training and the mock interview sessions will be given to the candidates to face the interviews with full confidence. Apart from all, the candidates will be placed in the top MNC's with the highest salary package in the market. To get it all, call 7502633633 and make this happen for your happy life.Best Software Training Center in Chennai | Infycle Technologies

    ReplyDelete
  49. Reach to the best Python Training institute in Chennai for skyrocketing your career, Infycle Technologies. It is the best Software Training & Placement institute in and around Chennai, that also gives the best placement training for personality tests, interview preparation, and mock interviews for leveling up the candidate's grades to a professional level.

    ReplyDelete
  50. Amazing opportunities came with amazing time and here is our institution offering you CS executive classes and a free of cost CSEET classes. So what are you waiting for contact us or visit our website
    cs executive
    freecseetvideolectures/

    ReplyDelete
  51. hi thanku so much this information thanku so much
    home1
    visit here

    ReplyDelete
  52. GQFX Review Offers A Safe And Secure Platform To Do Forex Trading And CFDs And Our Customer Support Is Ready To Help You 24/7. You Can Easily Sign Up Your GQFX Login Account Here.

    ReplyDelete
  53. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
    data science training

    ReplyDelete
  54. This post is so interactive and informative.keep update more information...
    Java Training in Tambaram
    java course in tambaram

    ReplyDelete
  55. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet
    effective. A lot of times it’s very hard to get that “perfect balance”
    between superb usability and visual appeal. I must say you’ve done a
    very good job with this.
    manual testing training in chennai
    dba course in chennai
    java training institute in chennai

    ReplyDelete
  56. Excellent effort to make this blog more wonderful and attractive.
    data science classes in hyderabad

    ReplyDelete
  57. You completed certain reliable points there. I did a search on the subject and found nearly all people will agree with your blog.
    data science training in hyderabad

    ReplyDelete
  58. Well stated, you have furnished the right information that will be useful to everybody. Thank you for sharing your thoughts. Security measures protect your company not only from data breaches, but also from excessive financial losses, a loss of people's trust, and potential risks to brand reputation and future benefits.
    SD Wan Service Providers
    Cybersecurity Service Provider

    ReplyDelete
  59. Thanks for sharing the information
    Girvi Software
    Girvi Software

    ReplyDelete