我将以Python中的字符串形式读取130多个excel文件。我想将每一行写成pdf。 整个Excel文件只有1张A5景观图。我可以轻松地在bash外壳中批量打印pdf。
我导入PyPDF2
我可以使用以下方法创建pdf或一系列pdf文件:
with open(path + fileName, 'wb') as out:
pdf_writer.write(out)
但是我太笨了,看不到如何在这个pdf文件中写一个字符串。如果我尝试写一个字符串变量,我只会得到错误。如果我将字符串转换为字节,就会出错。
如何将字符串输入pdf?
string ='任何旧字符串'
答案 0 :(得分:1)
我知道您要求使用PyPDF2
,但使用FPDF
的方法更简单:
# https://pyfpdf.readthedocs.io/en/latest/
import fpdf #pip3 intall fpdf
pdf = fpdf.FPDF(format='letter') #pdf format
pdf.add_page() #create new page
pdf.set_font("Arial", size=12) # font and textsize
pdf.cell(200, 10, txt="your text", ln=1, align="L")
pdf.cell(200, 10, txt="your text", ln=2, align="L")
pdf.cell(200, 10, txt="your text", ln=3, align="L")
pdf.output("test.pdf")
正如您提到的那样,您不了解PyPDF文档,所以我认为FPDF
是一个不错的开始。
PyPDF2更适合读取和合并pdf文件。
如果您确实想使用PyPDF2,则可以使用canvas
来实现文本。
答案 1 :(得分:1)
PyPDF2
是一个很好的选择,当您需要更改现有的PDF时,但是当您需要从头创建PDF时,它需要pdf格式的知识。
您可能会考虑使用其他库来完成此任务,即pdfkit
(https://github.com/JazzCore/python-pdfkit),示例程序:
import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')