Using ReactJS to create print page - javascript

There has got to be a less brute force way of making a print page then the way I have been doing it. (See below code). Maybe with ReactJS and DOM insertions in some manner since the rest of my website is written with ReactJS? (See second example below) I have tried using the CSS #media print, but it does not work well on very complex websites in all the browser flavors. More recently, I have been making an entirely separate ReactJS website just for the print page and then passing it query strings for some of the information required on the print page. What a mess that makes!
var html: string = '<!DOCTYPE html>';
html += '<html lang="en">';
html += '<head>';
html += '<meta charset="utf-8">';
html += '<title>Title</title>';
html += '</head>';
html += '<body style="background-color: white;">';
html += '<div">';
html += getContent();
html += '</div>';
html += '</body>';
html += '</html>';
var newWin = window.open();
newWin.document.write(html);
newWin.document.close();
Second example:
var sNew = document.createElement("script");
sNew.async = true;
sNew.src = "Bundle.js?ver=" + Date.now();
var s0 = document.getElementsByTagName('script')[0];
s0.parentNode.insertBefore(sNew, s0);

Yeah there is, checkout react-print.
var React = require('react');
var ReactDOM = require('react-dom');
var PrintTemplate = require ('react-print');
class MyTemplate extends React.Component {
render() {
return (
<PrintTemplate>
<div>
<h3>All markup for showing on print</h3>
<p>Write all of your "HTML" (really JSX) that you want to show
on print, in here</p>
<p>If you need to show different data, you could grab that data
via AJAX on componentWill/DidMount or pass it in as props</p>
<p>The CSS will hide the original content and show what is in your
Print Template.</p>
</div>
</PrintTemplate>
)
}
}
ReactDOM.render(<MyTemplate/>, document.getElementById('print-mount'));

Related

Export HTML to Word Doc with continuous line number

I am trying to export HTML content - Table + paragraphs with multiple line breaks.
I want HTML content to export in word doc with Auto line numbers in word document.
I do not want it to generate in code by using loops or any other way. I want it to auto set by word doc.
I have tried below code in PHP :
$objWriter->startElement('w:sectPr');
$objWriter->startElement('w:lnNumType');
$objWriter->writeAttribute('w:countBy', '1');
$objWriter->writeAttribute('w:restart', 'continuous');
$objWriter->endElement();
I have added above code in Document.PHP under function _writeEndSection() after $borders = $_settings->getBorderSize(); in PHPWord Library and its working fine.
Can I do it in JavaScript by using XML code or mso-element tags and attribute?
I have used below code but its not working for me.
function exportHTML(){
var header = '<html xmlns:v="urn:schemas-microsoft-com:vml"'+
'xmlns:o="urn:schemas-microsoft-com:office:office"'+
'xmlns:w="urn:schemas-microsoft-com:office:word"'+
'xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"'+
'xmlns="http://www.w3.org/TR/REC-html40">'+
'<head><meta http-equiv=Content-Type content="text/html; charset=utf-8"><title></title>'+
'<xml>'+
'<w:WordDocument>'+
'<w:View>Print</w:View>'+
'<w:Zoom>75</w:Zoom>'+
'<w:DoNotOptimizeForBrowser/>'+
'</w:WordDocument>'+
'<w:sectPr>'+
'<w:lnNumType w:countBy=1 w:restart=continuous >'+
'</w:sectPr>'+
'</xml>'+
'</head>'+
'<body style="font: Arial">';
var tblNew = 'TableData';
var footer = "</body></html>";
var sourceHTML = header+tblNew+document.getElementById("source-html").innerHTML+footer;
var source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML);
var fileDownload = document.createElement("a");
document.body.appendChild(fileDownload);
fileDownload.href = source;
fileDownload.download = 'testfile.doc';
fileDownload.click();
document.body.removeChild(fileDownload);
}
Can anyone help me on this requirement? Thank You in advance.

Problems accessing a dictionary/json in a javascript function to populate a table

Overview:
I am creating a web page using Python and generating both html as well as javascript in my code. Additionally, I am parsing through csv files and converting their table data to html. I want to be able to click on a line of text and the associated table data for that text would then be loaded into an iframe on the currently active web page. The problem I am having, is that my javascript function is not recognizing the key I send it to retrieve the corresponding table data. If I manually enter the key to return the table data, the correct data is returned - though the table doesn't load. However, if I generate the key programmatically, it returns as 'undefined' even though the strings appear to be identical.
Goal:
I need to figure out if there is something wrong with either the syntax, or the format of the key I am using to try and retrieve the table data. Secondly, I need to figure out why the table data is not being correctly loaded into my iframe.
Example:
import pandas
opening_html = """<!DOCTYPE html><h1> Test</h1><div style="float:left">"""
table_html = pandas.DataFrame({'Col_1':['this', 'is', 'a', 'test']}).to_html()
tables_dict = {'test-1 00': table_html}
java_variables = "%s" % json.dumps(tables_dict)
table_frame = """<iframe name="table_frame" style="position:fixed; top:100px; width:750; height:450"></iframe>"""
test_link_text = """ test-1<br>"""
java = """<script type='text/javascript'>
var table_filename = """ + java_variables + ";"
java += """function send_table_data(obj) {
var t = obj.text + ' 00';
alert(t)
//This line below will not work
var table_data = table_filename[t];
//But this line will return the correct value
var table_data = table_filename['test-1 00'];
alert(table_data);
//This line should load the data, but does nothing
document.getElementsByName('table_frame').src = table_data;
}
</script>"""
html_text = """<head>
<link rel="stylesheet" href="style.css">
</head>""" + test_link_text + table_frame + """<body>""" + "</div>" + java + '</body>'
with open('test_table_load.html', 'w') as w:
w.write(html_text)
EDIT: I did just figure out that for some reason there was a default space at the beginning of the var t - so using trim() seemed to fix that. Now, the only issue left is why the data doesn't load into the table.
It looks like you figured out your typo with the space that was messing with your key, so this is for your second question.
Your code
So to get your table to populate in the iframe you need to fix three things:
To edit the HTML contents of your iframe you should be setting the .srcdoc element, not .src
The document.getElementsByName() function will return an array of HTML elements so in order to get the element you want you should do one of the following:
(recommended) switch to using document.getElementById and use id='table_frame' in your iframe tags
select the first element of the array by using document.getElementsByName('table_frame')[0]
The anchor tag that you're using as the trigger for your function is redirecting you back to the original HTML page, stopping you from seeing any of the changes your javascript function is making. A simple solution to this is to switch to using a <button> element in place of <a>.
Here is what your code looks like with the fixes:
import pandas
import json
opening_html = """<!DOCTYPE html><h1>Test</h1><div style="float:left">"""
table_html = pandas.DataFrame({'Col_1':['this', 'is', 'a', 'test']}).to_html()
tables_dict = {'test-1 00': table_html}
java_variables = "%s" % json.dumps(tables_dict)
table_frame = """<iframe id="table_frame" style="position:fixed; top:100px; width:750; height:450"></iframe>"""
test_link_text = """<button href='' onclick="send_table_data(this);"> test-1</button><br>"""
java = """<script type='text/javascript'>
var table_filename = """ + java_variables + ";"
#for the button, innerText needs to be used to get the button text
java += """function send_table_data(obj) {
var t = obj.innerText + ' 00';
alert(t)
//This line below will not work
var table_data = table_filename[t];
//But this line will return the correct value
var table_data = table_filename['test-1 00'];
alert(table_data);
//This line should load the data, but does nothing
document.getElementById('table_frame').srcdoc = table_data;
}
</script>"""
html_text = """<head>
<link rel="stylesheet" href="style.css">
</head>""" + test_link_text + table_frame + """<body>""" + "</div>" + java + '</body>'
with open('test_table_load.html', 'w') as w:
w.write(html_text)
Other Recommendations
I strongly suggest looking into some python frameworks that can assist you in generating your website, either using HTML templates like Flask, or a library that can assist in generating HTML using Python. (I would recommend Dash for your current use case)

Dividing a string in 2 parts and placing each part in a different new string

I have a string (resultString) that contains long html codes. These codes are grouped in 2 main DIVs, window and Popup.
resultString = "<div id=\"window\">window content --- long html codes</div><div id=\"PopUp\">Popup content --- long html codes</div>"
Now I want to retrieve the html content of window and popup DIVs separately and place them in 2 different strings (stringWindow and stringPopup).
stringWindow = "<div id=\"window\">window content --- long html codes</div>";
stringPopup = "<div id=\"PopUp\">Popup content --- long html codes</div>";
Is there any simple way to do so in jQuery/javascript? The stringWindow is constructed in an Ajax json webmethod function. Any help is well appreciated! Thanks in advance.
You can use filter() and outerHTML
Using filter you can filter element with certain selector
Now you can use outerHTML for getting html content
var resultString = "<div id=\"window\">window content --- long html codes</div><div id=\"PopUp\">Popup content --- long html codes</div>",
stringWindow, stringPopup;
stringWindow = $(resultString).filter('#window')[0].outerHTML;
stringPopup = $(resultString).filter('#PopUp')[0].outerHTML;
console.log(stringPopup, stringPopup);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Trivial in jQuery:
var resultString = "<div id=\"window\">window content --- long html codes</div><div id=\"PopUp\">Popup content --- long html codes</div>"
var $doc = $("<div>" + resultString + "</div>");
var stringWindow = $doc.find('#window').text();
var stringPopup = $doc.find('#PopUp').text();
console.log("window", stringWindow);
console.log("popup", stringPopup);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Not much harder in plain JS.
If by "Just the content" you don't mean "text" but markup inside the div, then replace text() with html().
EDIT: made into executable snippet.
A version that doesn't use jQuery, doesn't assume it is in the document or can be put into the document but still interprets it as HTML -
var domParser = new DOMParser(),
doc = domParser.parseFromString(resultString, "text/html"),
content = ["window", "PopUp"].map(function(id) {
return doc.querySelector("#" + id).innerHTML;
}),
stringWindow = content[0],
stringPopup = content[1];
Try this. It works for me. Demo
resultString = "<div id=\"window\">window content --- long html codes</div> <div id=\"PopUp\">Popup content --- long html codes</div>";
var res = resultString.split("</div>");
stringWindow = res[0].replace(/^<div[^>]*>|<\/div>$/g, '');
stringPopup = res[1].replace(/^<div[^>]*>|<\/div>$/g, '');
Hope It Helps.
I think this may help you :-
var resultString = "<div id=\"window\">window content --- long html codes</div><div id=\"PopUp\">Popup content --- long html codes</div>"
var splitter = document.createElement('div');
splitter.innerHTML = resultString;
var window = $(splitter).find("#window")
var poppup = $(splitter).find("#PopUp")
Mark as an answer if it helps
This is one way to do it with C#...
It may help...
Given your result string as...
resultString = "<div id=\"window\">window content --- long html codes</div><div id=\"PopUp\">Popup content --- long html codes</div>"
following should work..
string resultPopUp = resultString.Substring(resultString.IndexOf("<div id=\"PopUp"));
string resultWindow = resultString.Substring(resultString.IndexOf("<div id=\"window"), resultString.Length - resultString.IndexOf("<div id=\"PopUp\">")+2);
Maintaining the string structure as <div id=\"*****\"> this should work....
if you want just the content do somthing like this:
with jQuery:
stringWindow =$('#window').innerHTML
stringPopup =$('#PopUp').innerHTML
Only JS:
stringWindow =document.getElementById('window').innerHTML
stringPopup =document.getElementById('Popup').innerHTML

innerHTML not updating display

First, hello everyone as I'm new here.
To summarize my problem, I read the content of an XML file to display in a table.
The basic function to do this works well, I created a derivated function to include a search filter related to an input field.
The search algorithm works well and I'm able to preview the HTML code of the search result using the alert() function and this code seems proper and can be displayed in a browser properly as it would be supposed to. However the innerHTML code of the concerned div is not updated...
I would appreciate any kind of input or solution anyone could provide as I've been stuck on this ! Thanks !
Here is the code :
function printListMod2(){
//Search parameters ?
var searchContent = document.getElementById("searchField").value;
var i=0;
newHTML = "<table id=\"tableInstrus\">";
for (i=0;i<listInstrus.length;i++){
filename = returnFilename(i);
title = returnTitle(i);
tempo = returnTempo(i);
sample = returnSample(i);
multi = returnMulti(i);
style1 = returnStyle1(i);
style2 = returnStyle2(i);
var regEx = new RegExp(searchContent, 'gi');
var resultSearch = title.match(regEx);
if(resultSearch!=null){
if(i%2==0){
newHTML += "<tr class=\"tr0\"><td class=\"idColumn\">"+(i+1)+"</td><td class=\"emptyColumn\"></td><td class=\"nameColumn\">"+title+"</td><td class=\"tempoColumn\">"+tempo+"</td><td class=\"sampleColumn\">"+sample+"</td><td class=\"multiColumn\">"+multi+"</td><td class=\"styleColumn\">"+style1+"</td><td class=\"styleColumn\">"+style2+"</td><td class=\"addLink\"><a id="+filename+" onclick=\"addLinkToPlaylist("+i+")\"><img title=\"Add to playlist\" class=\"addButton\" src=\"images/buttonAdd.png\"/></a></td><td class=\"playLink\"><a onclick=\"playTrack("+i+","+true+")\"><img title=\"Play this track\" class=\"playButton\" src=\"images/buttonPlaySmall.png\"/></a></td></tr>";
}
else{
newHTML += "<tr class=\"tr1\"><td class=\"idColumn\">"+(i+1)+"</td><td class=\"emptyColumn\"></td><td class=\"nameColumn\">"+title+"</td><td class=\"tempoColumn\">"+tempo+"</td><td class=\"sampleColumn\">"+sample+"</td><td class=\"multiColumn\">"+multi+"</td><td class=\"styleColumn\">"+style1+"</td><td class=\"styleColumn\">"+style2+"</td><td class=\"addLink\"><a id="+filename+" onclick=\"addLinkToPlaylist("+i+")\"><img title=\"Add to playlist\" class=\"addButton\" src=\"images/buttonAdd.png\"/></a></td><td class=\"playLink\"><a onclick=\"playTrack("+i+","+true+")\"><img title=\"Play this track\" class=\"playButton\" src=\"images/buttonPlaySmall.png\"/></a></td></tr>";
}
}
}
newHTML += "<tr><td class=\"idColumn\"></td><td id=\"emptyColumn\"></td><td class=\"nameColumn\"></td><td class=\"tempoColumn\"></td><td class=\"sampleColumn\"></td><td class=\"multiColumn\"></td><td></td><td></td></tr>";
newHTML += "</table>";
alert(newHTML); //this displays the HTML code properly
document.getElementById("listDiv").innerHTML = newHTML; //this doesn't seem to do anything...
}
Is your script being executed before the document has finished loading?
Then it won't find #listDiv because the div doesn't exist yet.
I would check the javascript console output for errors and check if the following code doesn't return undefined:
{
...
console.log( document.getElementById('listDiv') );
}

How to take a print out of a html table using PHP

I have a table in a PHP page. It is a invoice.
So I want to print it after adding items to it,
and I had already done the coding part and all the things are working properly.
Now I just want to print that invoice table to a paper
by pressing a button. I searched on Google but no clue is found to do that.
Can any one help me?
This is my table on right hand side. It is populated by the form in left hand side
so I just want to print that right hand side table:
Try this one:
Add an attribute id to your table your_content
Place an anchor tag :
Print
And add script:
This script will initially show print preview of the content that is inside your table.
<script lang='javascript'>
$(document).ready(function(){
$('#printPage').click(function(){
var data = '<input type="button" value="Print this page" onClick="window.print()">';
data += '<div id="div_print">';
data += $('#your_content').html();
data += '</div>';
myWindow=window.open('','','width=200,height=100');
myWindow.innerWidth = screen.width;
myWindow.innerHeight = screen.height;
myWindow.screenX = 0;
myWindow.screenY = 0;
myWindow.document.write(data);
myWindow.focus();
});
});
Copy the script part and put it on the top of your page. And put the print link, [above anchor tag] wherever you want. And make sure you have included the jquery script file.
This would be too trivial of a situation for something like jQuery so you should use plain Javascript to do it. Place this somewhere on your page and see if it works:
Print
<script type="text/javascript">
function printPage(){
var tableData = '<table border="1">'+document.getElementsByTagName('table')[0].innerHTML+'</table>';
var data = '<button onclick="window.print()">Print this page</button>'+tableData;
myWindow=window.open('','','width=800,height=600');
myWindow.innerWidth = screen.width;
myWindow.innerHeight = screen.height;
myWindow.screenX = 0;
myWindow.screenY = 0;
myWindow.document.write(data);
myWindow.focus();
};
</script>​​​​​​
You can see the demo here: http://jsfiddle.net/Pxqtb/
i used this code and it solved my problem. thank you all for helping me.....
function printlayout() {
var data = '<input type="button" value="Print this page" onClick="window.print()">';
var DocumentContainer = document.getElementById('printlayout');
//data += $('printlayoutable').html();
//data += '</div>';
var WindowObject = window.open('', "TrackHistoryData",
"width=740,height=325,top=200,left=250,toolbars=no,scrollbars=yes,status=no,resizable=no");
WindowObject.document.writeln(DocumentContainer.innerHTML);
//WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
You have a few options. (1) If you create a new HTML page with just the invoice, the user can print that page using the browser's print capacity. (2) Alternatively, you can allow the user to download an invoice document which you create and print that. (3) You can use the JavaScript command window.print(); in conjunction with #1. Have a look at this.

Categories