1

Is there a simple means of superscripting a substring (e.g. a '%' symbol) of a string in Python when writing that string to a PDF using reportlab via the drawString() method?

Let's say for example, printing a string such as '37%', where I want the '%' symbol to be a superscripted.

My current workaround I suppose is to instead use two separate calls to the drawString() method and specify separate font sizes for each, with coordinates that effectively simulate the superscript notation. Are there any other feasible workarounds that limit this to one call of the drawString() method?

rahlf23
  • 8,869
  • 4
  • 24
  • 54

2 Answers2

2

If you end up doing a lot with math and formulas you may wish to consider using LaTex which can be converted to a pdf.

I don't think what you are asking is doable with the drawString method but reportlab offers another method that allows it.

This article should be of great help to you: https://www.blog.pythonlibrary.org/2018/02/06/reportlab-101-the-textobject/

Adapting directly from the article gives us this code:

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

def apply_scripting(textobject, text, rise):
    textobject.setFont("Helvetica-Oblique", 8)
    textobject.setRise(rise)
    textobject.textOut(text)
    textobject.setFont("Helvetica-Oblique", 12)
    textobject.setRise(0)

def main():
    canvas_obj = canvas.Canvas("textobj_rising.pdf",
                               pagesize=letter)

    # Create textobject
    textobject = canvas_obj.beginText()
    textobject.setFont("Helvetica-Oblique", 12)

    # Set text location (x, y)
    textobject.setTextOrigin(10, 730)

    textobject.textOut('37')
    apply_scripting(textobject, '%', 4)

    canvas_obj.drawText(textobject)
    canvas_obj.save()


if __name__ == '__main__':
    main()

Which creates a pdf like this:

pdf with superscript

The advantage of this over drawString twice is you don't need to figure out the coordinates for where to place the % symbol.

Zev
  • 3,423
  • 1
  • 20
  • 41
  • 1
    Awesome solution, worked exactly as I needed it to! Thank you for the helpful linked article as well. – rahlf23 Jul 31 '18 at 02:31
0

You can use matplotlib.pyplot to do this :

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.set(title= r'This is an expression:  $37^{\%}$')

plt.show()
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45
  • It doesn't look like this is saved as a string however. Would I be able to pass this to the drawString() method when printing a string to a reportlab generated PDF? – rahlf23 Jul 26 '17 at 20:44