Python Generate tables in PDF

    技术2022-07-10  92

    今天,使用python生成PDF文档,然后在生成的PDF中创建自定义表格。

    Today, you generate PDF documents in Python, and then create custom tables in the generated PDF. (1)使用python生成pdf文档需要的最基本的包是pdfgen。它属于reportlab模块,而reportlab模块并没有默认集成到python的安装包中,所以需要安装该模块。 (2)pdfgen提供了一个绘画操作的对象canvas。canvas可以看作是带有笛卡尔坐标(X, Y)的一张白纸,默认坐标(0, 0)位于页面的左下角。默认X向右侧延伸,而Y向上延伸。

    (1) The most basic package required to generate PDF documents using Python is PDFGen.It belongs to the ReportLab module, which is not integrated into the Python installation package by default, so you need to install it.

    (2) PDFGen provides an object canvas for drawing operations.A canvas can be thought of as a piece of white paper with cartesian coordinates (X, Y). The default coordinates (0, 0) are located in the lower left corner of the page.By default X goes to the right and Y goes up.

    参考下面的资料信息:

    Refer to the following information: Table and Tablestyle TableStyle user Methods 1.TableStyle(commandSequence) The creation method initializes the TableStyle with the argument command sequence eg: LIST_STYLE = TableStyle( [('LINEABOVE', (0,0), (-1,0), 2, colors.green), ('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black), ('LINEBELOW', (0,-1), (-1,-1), 2, colors.green), ('ALIGN', (1,1), (-1,-1), 'RIGHT')] 2. TableStyle.add(commandSequence) This method allows you to add commands to an existing TableStyle, i.e. you can build up TableStyles in multiple statements. eg: LIST_STYLE.add('BACKGROUND', (0,0), (-1,0), colors.Color(0,0.7,0.7)) 3.TableStyle.getCommands() This method returns the sequence of commands of the instance. cmds = LIST_STYLE.getCommands() 4.TableStyle Commands TableStyle Cell Formatting Commands FONT - takes fontname, optional fontsize and optional leading. FONTNAME (or FACE) - takes fontname. FONTSIZE (or SIZE)- takes fontsize in points; leading may get out of sync. LEADING- takes leading in points. TEXTCOLOR- takes a color name or (R,G,B) tuple. ALIGNMENT (or ALIGN)- takes one of LEFT, RIGHT and CENTRE (or CENTER) or DECIMAL. LEFTPADDING- takes an integer, defaults to 6. RIGHTPADDING- takes an integer, defaults to 6. BOTTOMPADDING- takes an integer, defaults to 3. TOPPADDING- takes an integer, defaults to 3. BACKGROUND- takes a color defined by an object, string name or numeric tuple/list, or takes a list/tuple describing a desired gradient fill which should contain three elements of the form [DIRECTION, startColor, endColor] where DIRECTION is either VERTICAL or HORIZONTAL. ROWBACKGROUNDS- takes a list of colors to be used cyclically. COLBACKGROUNDS- takes a list of colors to be used cyclically. VALIGN- takes one of TOP, MIDDLE or the default BOTTOM TableStyle Line Commands Line commands begin with the identifier, the start and stop cell coordinates and always follow this with the thickness (in points) and color of the desired lines. Colors can be names, or they can be specified as a (R, G, B) tuple, where R, G and B are floats and (0, 0, 0) is black. The line command names are: GRID, BOX, OUT- LINE, INNERGRID, LINEBELOW, LINEABOVE, LINEBEFORE and LINEAFTER. BOX and OUTLINE are equivalent, and GRID is the equivalent of applying both BOX and INNERGRID. #TableStyle Span Commands Our Table classes support the concept of spanning, but it isn't specified in the same way as html. The style specification SPAN, (sc,sr), (ec,er) indicates that the cells in columns sc - ec and rows sr - er should be combined into a super cell with con- tents determined by the cell (sc, sr). The other cells should be present, but should contain empty strings or you may get unexpected results.

    先来一下测试生成PDF的代码:

    Let's first test the PDF generation code:

    #引入所需要的基本包 from reportlab.pdfgen import canvas #设置绘画开始的位置 def draw_data(c): c.drawString(1, 2, "123") #定义要生成的pdf的名称 c=canvas.Canvas("test.pdf") #调用函数进行绘画,并将canvas对象作为参数传递 draw_data(c) #showPage函数:保存当前页的canvas c.showPage() #save函数:保存文件并关闭canvas c.save()

    看看我实现的代码,仅供参考:

    Take a look at the code I implemented, for reference only:

    导入库:

    import # -*- coding: utf-8 -*- #字体库 import reportlab.lib.fonts #canvas画图的类库 from reportlab.pdfgen.canvas import Canvas #用于定位的inch库,inch将作为我们的高度宽度的单位 from reportlab.lib.units import inch

    创建PDF,写创建表格的代码,这部分代码是我自己编写的,如果有问题请及时和我联系,非常感谢您的反馈。

    Create PDF and write the code to create the table. I wrote the code myself. If you have any questions, please contact me in time.  def create_table(canvas,row,col,start_y1,start_x1): for i in range(row): canvas.line((start_x1) * inch, (start_y1-0.5*i) * inch, 7 * inch, (start_y1-0.5*i) * inch) for j in range(col): #1 2.2 3.4 4.6 5.8 7 canvas.line((start_x1+j*1.2) * inch, (start_y1-0.5*i) * inch, (start_x1+j*1.2) * inch, (start_y1-0.5*i-0.1) * inch)#5.9 canvas.line((start_x1+j*1.2) * inch, (start_y1-0.5*i-0.1-0.05) * inch, (start_x1+j*1.2) * inch, (start_y1-0.5*i-0.1-0.05-0.2)* inch)#5.65 canvas.line((start_x1+j*1.2) * inch, (start_y1-0.5*i-0.1-0.05-0.2-0.05) * inch, (start_x1+j*1.2) * inch, (start_y1-0.5*i-0.1-0.05-0.2-0.05-0.1) * inch)#5.5 #写入数据 for i in range(row): for j in range(col-1): canvas.drawString((start_x1+j*1.2+0.45) * inch, (start_y1-0.5*i-0.3) * inch, "00") def pdf_head(canvas, headtext): #setFont是字体设置的函数,第一个参数是类型,第二个是大小 canvas.setFont("Helvetica-Bold", 11.5) #--------------------------------------------------------------- # draw a line segment from (x1,y1) to (x2,y2) create_table(canvas, 16,6,11,1)#5行5列的表格 # --------------------------------------------------------------- if __name__ == "__main__": #声明Canvas类对象,传入的就是要生成的pdf文件名字 can = Canvas('re.pdf') pdf_head(can, "000") #showpage将保留之前的操作内容之后新建一张空白页 can.showPage() #将所有的页内容存到打开的pdf文件里面。 can.save()

    result:

     I hope I can help you,If you have any questions, please  comment on this blog or send me a private message. I will reply in my free time.

    Processed: 0.009, SQL: 9