Reputation: 1195
I'm using Python3 and I have a long text file and I would like to create a new pdf and write the text inside.
I tried using reportlab but it writes only one line.
from reportlab.pdfgen pdfgen import canvas
c = canvas.Canvas("hello.pdf")
c.drawString(100,750, text)
c.save()
I know that I can tell it in which line to write what. But is there a library where I can just give the text and the margins and it will write it in the pdf file ?
Thanks
EDIT:
Or instead of that I could also use a library that easily converts txt file to pdf file ?
Upvotes: 3
Views: 4703
Reputation: 6234
Simply drawing your string on the canvas won't do your job.
If its just raw text and you don't need to do any modifications like heading and other kinds of stuff to your text, then you can simply put your text in Flowables
i.e Paragraph
, and your Flowables
can be appended to your story[]
.
You can adjust the margins according to your use.
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter
styles = getSampleStyleSheet()
styleN = styles['Normal']
styleH = styles['Heading1']
story = []
pdf_name = 'your_pdf_file.pdf'
doc = SimpleDocTemplate(
pdf_name,
pagesize=letter,
bottomMargin=.4 * inch,
topMargin=.6 * inch,
rightMargin=.8 * inch,
leftMargin=.8 * inch)
with open("your_text_file.txt", "r") as txt_file:
text_content = txt_file.read()
P = Paragraph(text_content, styleN)
story.append(P)
doc.build(
story,
)
For more information on Flowables read reportlab-userguide
Upvotes: 6