Reputation: 4764
I am trying to use javascript to print out a text field from a dbase where the textfield is served by php to a textarea that has an id. The print javascript function takes the content from the textarea using getElementById and prints it. But here is the issue. To display properly in the textarea, the textfield has newlines in it. These are invisible in the textarea. They just show up as line breaks. (They are also invisible using PHP admin in the dbase tables. They show up there as linebreaks as well).
However, to get the linebreaks to show up when you print the text, they need to be converted into <br>
. Otherwie, you see and print a runown sentence.
I think I need to search for something in the javascript variable, perhaps \n and replace with
However, I can't seem to get linebreaks to display in printed page (wich is html based.)
Can anyone suggest right way to do this? Thanks.
Flawed code: js f
unction printit(id) {
var toprint = document.getElementById(id).innerHTML;
toprint = toprint.replace("\n","<br>");
win = window.open();
self.focus();
win.document.open();
win.document.write('<'+'html'+'><'+'head'+'><'+'style'+'>');
win.document.write('body, td { font-family: Verdana; font-size: 10pt;}');
win.document.write('<'+'/'+'style'+'><'+'/'+'head'+'><'+'body'+'>');
win.document.write(toprint);
win.document.write('<'+'/'+'body'+'><'+'/'+'html'+'>');
win.document.close();
win.print();
win.close();
}
html
<textarea id="textarea">A whole bunch
of text
with line breaks
goes here
</textarea><a href="javascript:void(0);" onclick="printit('textarea');">Print text</a>
Upvotes: 0
Views: 411
Reputation: 1708
The best solution for displaying newline characters in HTML is using the CSS white-space property.
Upvotes: 0
Reputation: 66673
I believe you need it printed out exactly the way it is appearing in the text area. The textarea applies line-wrapping to its content. These are not line-break characters and cannot be replaced as such.
Append the content to an element with the same width as the textarea before priting.
i.e.
...
win.document.write('<'+'/'+'style'+'><'+'/'+'head'+'><'+'body'+'>');
// element with same width as textarea
win.document.write('<div style="width: '+ document.getElementById(id).offsetWidth +'px">');
win.document.write(toprint);
win.document.write('</div>');
win.document.write('<'+'/'+'body'+'><'+'/'+'html'+'>');
...
Upvotes: 0
Reputation: 3345
You're probably only replacing the first line break. Try the global flag to replace them all:
toprint = toprint.replace(/\n/g, '<br />');
Upvotes: 1