wngrtzk
Posts: 5
Joined: Sun Jan 26, 2020 9:52 pm

Dynamic height of generated PDF based on content

Sun Apr 19, 2020 3:50 pm

Hi,

I am writing a script that:
1) Pulls a random sentence from a .txt file
2) Creates a PDF with the generated sentence

Some sentences are quite long and span more than one line. For various reasons I want the page size of the PDF to be fixed width and dynamic height based on the content.

Here is a rough visual demonstration of what I mean:

Example 1:
__________________
A short sentence.
__________________

Example 2:
__________________
A longer sentence
that span over
several lines.
__________________

Is there any way to to this?

I have been using fpdf which doesn't seem to have any kind of auto-height option. Is there any other library that may be able to do this?

At the moment, my script looks like this:

Code: Select all

#!/usr/bin/env python 3

import fpdf
import random

def GetRandomLineFromFile(filename):
  with open(filename,"r") as f:
    lines = f.read().split("\n")
  return lines[random.randint(0, len(lines)-1)]

line = GetRandomLineFromFile("thousandsofsentences.txt")

pdf = fpdf.FPDF()
pdf.add_page()
pdf.set_font("Arial", size=16)
pdf.write(5,(line))
pdf.output('generatedsentence.pdf', 'F')

Return to “Python”