问题描述
以下是生成pdf文件并返回的视图中的代码。
def pdf_file(request,id):
pti=Pti.objects.get(pk=id)
po=PurchaseOrder.objects.get(pk=id)
inv=Invoices.objects.get(pk=id)
reimbinv=Reimbursement.objects.get(pk=id)
buffer=io.BytesIO()
pdf=canvas.Canvas(buffer)
pdf.pagewidth=A4[0]
pdf.pageheight=A4[1]
pdf.setTitle(inv.title)
MARGIN_LEFT=MARGIN_RIGHT=10
MARGIN_TOP=MARGIN_BOTTOM=10
MT_WIDTH=A4[0]-(MARGIN_LEFT+MARGIN_RIGHT)
MT_HEIGHT=A4[1]-(MARGIN_BOTTOM+MARGIN_TOP)
HT_HEIGHT=MT_HEIGHT*35/100
BT_HEIGHT=MT_HEIGHT*30/100
FT_HEIGHT=MT_HEIGHT*35/100
mainTable=Table(
[
#[jazz_top_header(MT_WIDTH,HT_HEIGHT*15/100)],[genHeader(MT_WIDTH,HT_HEIGHT,po.poNumber)],],MT_WIDTH,HT_HEIGHT
)
mainTable.setStyle([
style.BOTTOM_PADDING_ALL_ZERO,style.LEFT_PADDING_ALL_ZERO,style.TOP_PADDING_ALL_ZERO,style.VALIGN_ALL,])
mainTable.wrapOn(pdf,0)
mainTable.drawOn(pdf,MARGIN_LEFT,MARGIN_BOTTOM)
pdf.showPage()
pdf.save()
#response=HttpResponse(content_type='application/pdf')
buffer.seek(0)
return FileResponse(buffer,as_attachment=True,filename='hello.pdf')
并调用以下函数
def genHeader(width,height,po_number):
heightList=[
#height*10/100,# 10% for Jazz
height*10/100,#20% for PTI heading
height*10/100,#10% for agreement etc
height*10/100,#10% for location etc
height*10/100,#10% for certificate of PTI
#height*50/100 #40% for text
]
data_row=[
[generateTable(width,heightList[0],'''<b>Permission To Invoice</b>''',style.TEXT_ALIGN_CENTER)],['Department:','''<u>Marketing</u>''','Agreement/PO No:',str(po_number)],['Location:','''<u>Islamabad</u>''','Contractor Name:','Fish Bowl Pvt. Ltd'],['Certificate Of Permission to Invoice:-','',''],]
head_section_table=Table(
data_row,#[jazz_top_header(width,heightList[0])],#[generateTable(width,'<b>Permission To Invoice</b>',#[custom_colBasedTables(width,heightList[1],arr_data_row1,style.TEXT_ALIGN_RIGHT)],heightList[2],arr_data_row2,width/4,heightList
)
return head_section_table
另一种方法
def generateTable(width,txt,txt_align_position):
res_table=Table([[txt]],width,height)
res_table.setStyle([txt_align_position,style.VALIGN_ALL])
return res_table
这里样式在styles.py中适当调整
class style:
TEXT_ALIGN_CENTER=(
'ALIGN',(0,0),(-1,-1),'CENTER'
)
TEXT_ALIGN_RIGHT=(
'ALIGN','RIGHT'
)
TEXT_ALIGN_LEFT=(
'ALIGN','LEFT'
)
BOTTOM_PADDING_ALL_ZERO=(
'BOTTOMPADDING',0
)
TOP_PADDING_ALL_ZERO=(
'BOTTOMPADDING',0
)
LEFT_PADDING_ALL_ZERO=(
'LEFTPADDING',0
)
RIGHT_PADDING_ALL_ZERO=(
'RIGHTPADDING',0
)
VALIGN_ALL=(
'VALIGN','TOP'
)
代码工作得很好,但 pdf 是在垂直中间生成的。我试图设置VALIGN也仍然不起作用。任何解决此问题的建议。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)