【问题标题】:Generated pdf report in reportlab is not similar to original text data在reportlab中生成的pdf报告与原始文本数据不相似
【发布时间】:2017-10-29 14:08:39
【问题描述】:

我正在尝试从文本文件生成 pdf 文档,但输出与文本文件中的记录不匹配。

pdf 输出数据是从页面底部而不是顶部开始的。

请大家给点意见

下面是代码:

提前致谢。

from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.lib.colors import magenta, red

file = open("Computingdata.txt", "r")  # text file I need to convert
    lines = file.read()
file.close()

report = canvas.Canvas('mypdf4.pdf')#new pdf report i am creating
report.setFont("Times-Roman", 20)
report.setFillColor(red)
report.drawCentredString(150, 2.5*inch, "Student details")

report.setFillColor(magenta)
size = 12
y = 2.0*inch
#x = 1.3*inch
for line in lines.split(';'):
    report.setFont("Helvetica", size)
    report.drawString(30,y, line)
    y = y-size*1.2
    #size = size+0.5
report.save() 

只是补充一下,输出以这种形式出现 身份证
用户名
登录名
密码

姓名
年龄:

而不是 ID USERID LOGIN-NAME PASSWORD SURNAME NAME AGE。

【问题讨论】:

    标签: python pdf reportlab


    【解决方案1】:

    谢谢大家,我已经能够通过以下调整的代码解决我遇到的所有问题:

    from reportlab.pdfgen import canvas
    #from reportlab.lib.units import inch
    from reportlab.lib.colors import magenta, red
    
    file = open(""yourdata"", "r")  # text file I need to convert
    lines = file.read()
    file.close()
    report = canvas.Canvas('mypdf5.pdf')#new pdf report i am creating
    report.setFont("Times-Roman", 20)
    report.setFillColor(red)
    report.drawCentredString(100, 800, "Student details")
    
    report.setFillColor(magenta)
    size = 12
    y = 790
    #y = 2.0*inch
    #x = 1.3*inch
    for line in lines.split('\n'):
    report.setFont("Helvetica", size)
        report.drawString(10, y, line)
        #y = y-size*1.2
        #size = size+0.5
        y = y - 10
    report.save() 
    

    编辑: 如果您的输入文本文件有这么多分隔符,那么您应该这样做

    import re
    
    file = open("yourdata", "r")  # text file I need to convert
    lines = file.read()
    lines2 = re.split('; |\n', lines)
    file.close()
    

    使用 re 包,您可以在文本文件中包含所有分隔符,以便在 reportlab 生成的 pdf 文件上轻松显示确切内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2018-05-07
      • 1970-01-01
      相关资源
      最近更新 更多