Michael
Michael

Reputation: 7839

Place a vertical or rotated text in a PDF with Python

I'm currently generating a PDF with PyFPDF. I also need to add a vertical/rotated text. Unfortunately, it's not directly supported in PyPDF2 as far as I see. There are solutions for FPDF for PHP.

Is there a way to insert vertical or rotated text in a PDF from Python, either with PyFPDF or with another library?

Upvotes: 5

Views: 2832

Answers (2)

abu
abu

Reputation: 459

You can also take a look at fpdf2 (fork of a previous port of fpdf from PHP to Python).

Example of my own code posted as a fpdf2 issue here:

from fpdf import FPDF
pdf = FPDF(orientation="P", unit="mm", format="A4")
pdf.add_page()
pdf.set_font("times")
a,x,y=90,10,295 # angle + x,y text origin of a left side banner
with pdf.rotation(angle=a, x=x, y=y):
    pdf.text(x=x, y=y, text="Banner from left bottom to left top corners") 
pdf.output("fpdf-lateral-banner-text.pdf")

See also further possible improvements of this code suggested by the extremely helpful fpdf2 maintainers in their discussions forum.

Upvotes: 0

J. Owens
J. Owens

Reputation: 852

I believe you can do so with PyMuPDF. I've inserted text with the module before but not rotated text. There is a rotate parameter in the insertText method so hopefully it will work for you.

It can be done as follows:

import fitz
doc = fitz.open(filename)
page = doc[0]
point = fitz.Point(x, y) # in PDF units (1 / 72 of an inch)
page.insertText(
  point,
  text="Hello World",
  fontsize=8,
  fontname="Helvetica", # Use a PDF Base 14 Fonts, else check documentation
  color=(0, 0, 0),
  rotate=90
)
doc.save(filename, incremental=True)
doc.close()

Upvotes: 1

Related Questions