2

I'm making a form to fill in and create a pdf through, but I'm facing a problem with text area, I want the user to input text and while writting and pressing space to go back to line like this: enter image description here

i want it to automatically show in the pdf but instead i get this: enter image description here

how can i fix it? the code for this is:

<div class="mb-2"><textarea name="element" placeholder="Elements à fournir" class="form-control"></textarea></div>

1 Answers1

1

You need to convert the line breaks from the textarea (\r or \n) into line breaks your PDF can understand (<br /> <div> <li> etc).

a simple PHP way is

$string = nl2br($string);
// converts \n to <br />

If you need to transform those line breaks on the fly (like you're capturing the input and displaying it formatted as the user types), then do it in javascript. Here is a handy function taken from: https://stackoverflow.com/a/7467863/1772933

function nl2br (str, is_xhtml) {
    if (typeof str === 'undefined' || str === null) {
        return '';
    }
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

Here is an example of how to use that function as the user is typing

$('#TextArea').keypress(function(evt){
        $('#TextArea').html(nl2br($('#TextArea').val())); // replace linebreaks first
        $('#pdfPreviewArea').html($('#TextArea').val()); // copy to #pdfPreviewArea
    });
Kinglish
  • 23,358
  • 3
  • 22
  • 43
  • sorry i dont quite understand yet, do i need to put the input inside what you commented now? – Hanaa Alaoui Belghiti May 06 '21 at 18:14
  • Explain the process - the user types in the textarea ... then what? Do they submit the form and a PDF is generated? If so, the PHP method I put above is a way to transform the input text into a formatted text. I will also amend my answer in case this is all happening via javascript – Kinglish May 06 '21 at 18:18
  • yes after typing in the textarea the user clicks submit and then what he typed needs to be shown in the generated pdf, but instead of showing it in one line i want it to go back to line whenever he presses enter just like i showed in the first pic, i defined the variable `$just=$_POST['just']; ` for that text area and put it inside pdf with `

    '.$just.'

    ';` and want it to show up same way as i've input it afetr pdf is generated
    – Hanaa Alaoui Belghiti May 06 '21 at 18:32
  • just change that one line to: `$just=nl2br($_POST['just']);` – Kinglish May 06 '21 at 18:47
  • @HanaaAlaouiBelghiti Great! Please accept this as the answer, and give an upvote if you can. Cheers – Kinglish May 06 '21 at 19:04