I can't find a way how to write output data (lists or function return) into pdf in python. This is my simple code. I want to write the i
of data list line by line in pdf. But the output shows only [1,2,3,4,5,6]
.
Which pdf module is would be better for me to use?
import fpdf
data=[1,2,3,4,5,6]
pdf = fpdf.FPDF(format='letter')
pdf.add_page()
pdf.set_font("Arial", size=12)
for i in str(data):
pdf.write(5,i)
pdf.output("testings.pdf")
You are doing everything correct to write output into a PDF. But you are not getting the result you "want" because your Python code is not correct!
for i in str(data):
.. do stuff with i here ..
does not do what you think it does. As soon as you convert data
to a string, per str(data)
, it magically becomes the string
[1, 2, 3, 4, 5, 6]
Then the for
loop iterates over the contents of that string – its characters – and writes them one by one to the PDF.
That is your first error. Yes, you must supply a string to pdf.write
– but only of each separate item you want to write, not the entire input object.
The second is assuming pdf.write
outputs a line including a return at the end. It does not:
This method prints text from the current position. When the right margin is reached (or the \n character is met), a line break occurs and text continues from the left margin. Upon method exit, the current position is left just at the end of the text.
(https://pyfpdf.readthedocs.io/en/latest/reference/write/index.html)
You can use ln
to insert line breaks, or append \n
at the end of each string just before writing it.
Working code:
import fpdf
data=[1,2,3,4,5,6]
pdf = fpdf.FPDF(format='letter')
pdf.add_page()
pdf.set_font("Arial", size=12)
for i in data:
pdf.write(5,str(i))
pdf.ln()
pdf.output("testings.pdf")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With