Inserting line breaks into PDF

前端 未结 13 1510
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 12:34

I\'m generating some PDF file on the fly using PHP. My problem is I need to insert line breaks in some part of the text that will be inserted in the PDF file. Something like

相关标签:
13条回答
  • 2020-11-30 12:44

    I have simply replaced the "\n" with "<br>" tag. Worked fine. It seems TCPDF render the text as HTML

    $strText = str_replace("\n","<br>",$strText);
    $pdf->MultiCell($width, $height,$strText, 0, 'J', 0, 1, '', '', true, null, true);
    
    0 讨论(0)
  • 2020-11-30 12:44

    The solution I've found was:

    $text = 'Line one\n\nLine two');
    $text = explode('\n', $text);
    
    foreach ($text as $txt){
        $pdf->Write($txt);
        $pdf->Ln();
    }
    

    So this way, you may have any number of \n in any position, if you're getting this text dinamically from the database, it will break lines correctrly.

    0 讨论(0)
  • 2020-11-30 12:45

    If you are using fpdf, in order to be able to use line breaks you will need to use a multi-line text cell as described here.

    If you use this, then line breaks in your text should be interpreted and converted correctly.

    Just a quick example:

    $pdf->Multicell(0,2,"This is a multi-line text string\nNew line\nNew line"); 
    

    Here, 2 is the height of the multi-line text box. I don't know what units that's measured in or if you can just set it to 0 and ignore it. Perhaps try it with a large number if at first it doesn't work.

    0 讨论(0)
  • 2020-11-30 12:46

    Or just try this after each text passage for a new line.

    $pdf->Write(0, ' ', '*', 0, 'C', TRUE, 0, false, false, 0) ;

    0 讨论(0)
  • 2020-11-30 12:49

    I changed '\n' for chr(10) and it worked:

    $pdf->MultiCell(0,5,utf8_decode($variable1 . chr(10) . $variable2),1);
    
    0 讨论(0)
  • 2020-11-30 12:51

    Another option is to use TCPDF::Ln(). It adds a line to the PDF with the option to set the height.

    If the newlines are within your content already then MultiCell() is probably the way to go, as others have mentioned, but I find I like using:

    $pdf->Cell(0, 0, 'Line 1', 0, 0, 'C');
    $pdf->Ln();
    $pdf->Cell(0, 0, 'Line 2', 0, 0, 'C');
    

    It confuses me that Cell() and MultiCell() take in different arguments so I tend to stick to using Cell() only. Also it reads like a newline character for the PDF the same as \n reads like a newline character in text or <br> in HTML.

    0 讨论(0)
提交回复
热议问题