Search code examples
pdflib

PDFlib - place wrapping text using "textflow" in top-left corner instead of bottom-left


Given: a) a long paragraph of text that can only be 10cm wide. Height is unlimited, paragraph text should wrap when it hits the right margin; b) a page with topdown=true.

I'm trying to use combination of add_textflow() and fit_textflow() to do it. but PDFlib places paragraph in the lower-left corner, while known coordinates for that paragraph are for the top-left corner.

My code:

$p->begin_page_ext($width, $height);
$p->set_option("usercoordinates=true");
$p->set_option("topdown=true");

...

$tf = 0;
$tf = $p->add_textflow($tf, 'My loooong wrapping paragraph, 'fontname=Helvetica fontsize=10 encoding=unicode charref');
$result = $p->fit_textflow($tf, $lowerLeftX, $lowerLeftY, $upperRightX, $upperRightY, 'fitmethod=nofit');
$p->delete_textflow($tf);

Question: What can I do to supply coordinates as: $p->fit_textflow($tf, $topLeftX, $topLeftY, $lowerRightX, $lowerRightY)?

I tried adding position={left top} to fit_textflow() options, but PDFlib is throwing error.


Solution

  • first of all, your code missed the non optional parameter $option in the begin_page_ext() call. In your case you might use

    $p->begin_page_ext($width, $height, "topdown=true");
    

    so you get rid of the additional set_option() call.

    Textflow output starts always at the top of the fitbox (the area where the text will be placed) no line will be written behind the right border. So your requirement is the default.

    You might start using with starter_textflow.php sample to get a first impression how you can use it (especially for long text, which do not fit to the given fitbox). As well many further samples within the PDFlib cookbook show further (more complex) aspects: https://www.pdflib.com/pdflib-cookbook/textflow/

    In your case, you might simple work with:

    $lowerLeftX = 0;
    $lowerLeftY = $height;          // this is the page height
    $upperRightX = 10 * 72 / 2.54;  // this is 10 cm in the default coordinate system
    $upperRightY = 0;               // this is the top border of the page
    
    $result = $p->fit_textflow($tf, $lowerLeftX, $lowerLeftY, $upperRightX, $upperRightY, 'fitmethod=nofit');
    

    Please see PDFlib 9.2 Tutorial, chapter 3.2.1 "Coordinate Systems" for details on the coordinate system.