Search code examples
restructuredtextrst2pdf

How to style a specific container in rst2pdf


I have the following restructuredText for a page header, for which I want a logo image on the left and a document title aligned right:

.. header::

  .. container:: twocol

     .. container:: leftside

        .. image:: Logo.png
           :height: 152
           :width: 474

     .. container:: rightside

        Document Title

Currently the Document Title is left aligned in the middle of the page at the bottom of the image; and I want it right aligned at the top or middle of the page header.

Currently my style document looks like this:

styles:
    image:
        alignment: TA_LEFT

I am using rst2pdf via a python script like this:

rst2pdf.createpdf.main(["-v", "--stylesheets=simple.style", f"{out_file}2.rst", f"{out_file}2.pdf"])

UPDATE: I figured out that rightside is a class that you can use in your style and I could use alignment: TA_RIGHT, but I am not sure what attribute will make it be at the top of the header. Tried align, valign with MIDDLE and TA_MIDDLE but nothing moved.

How can I specifically style the rightside container in my style document to be at the top of the header?


Solution

  • In rst2pdf, each logical element is stacked underneath the other, regardless of width. That is, elements do not "flow" like they do in HTML.

    To put two elements side by side, the way I would do it is to use a table.

    test.rst:

    .. header::
    
        .. class:: headertable
    
            +-----------------------+----------------------+
            | .. image:: Logo.png   | .. class:: doctitle  |
            |      :height: 152     |                      |
            |      :width: 474      |    Document Title    |
            +-----------------------+----------------------+
    
    

    with style.yaml:

    styles:
      image:
        alignment: TA_LEFT
    
      doctitle: # Style text in table
        textColor: red
        alignment : TA_RIGHT
    
      headertable:
        parent: table
        commands:
          - [VALIGN, [0, 0], [-1, -1], MIDDLE]       # [0,0],[-1,-1] => entire table
          - [BACKGROUND, [0, 0], [0, 0], "#AACCCC"]  # [0,0],[0,0] => 1st cell in 1st row
          - [BACKGROUND, [1, 0], [1, 0], "#CCCCAA"]  # [1,0],[1,0] => 2nd cell in 1st row
          - [TOPPADDING, [0, 0], [-1, -1], 0]
          - [BOTTOMPADDING, [0, 0], [-1, -1], 0]
          - [LEFTPADDING, [0, 0], [-1, -1], 0]
          - [RIGHTPADDING, [0, 0], [-1, -1], 0]
    

    I've included the background colours so you can see the space each cell takes up.

    You also need to set a class onto the text in the cell so that you can override the default text styles in order to right align or change colour.

    Further details in the rst2pdf manual's table styles section and the ReportLab manual's chapter on tables.