朋友公司有需求,类似对报表先进行加密然后下载,密码是员工的出生年月。
#xml文件
<act_window
name="打印工资"
id="print_hr_payslip"
multi="True"
key2="client_action_multi"
res_model="hr.payslip.export"
src_model="hr.payslip"
view_mode="form"
target="new"
view_type="form"/>
<record model="ir.ui.view" id="hr_payslip_export_form">
<field name="name">hr.payslip.export.form</field>
<field name="model">hr.payslip.export</field>
<field name="arch" type="xml">
<form string="打印工资">
<group>
<p>批量打印下载的工资单。工资单解压密码是员工生日。(如:员工生日2020年6月8号 则密码: 2020-06-08)</p>
</group>
<footer>
<button string="下载" name="export" type="object"/>
</footer>
</form>
</field>
</record>
#model.py
@api.multi
def export(self):
active_ids = self.env.context.get('active_ids',[])
ids_str = ','.join([str(id) for id in active_ids])
return {
'type': 'ir.actions.act_url',
'url':'/export_password_pdf?ids=%s'%ids_str,
'target':'new'
}
#model.py
class ExportPasswordPdf(http.Controller):
'''
下载带密码的pdf zip文件
'''
@http.route('/export_password_pdf', auth='user', type='http')
def export_password_pdf(self,**data):
'''
'''
ids_str = data.get('ids')
ids = ids_str.split(',')
ids = [int(id) for id in ids]
payslips = request.env['hr.payslip'].sudo().search([('id','in',ids)])
# 取报表,生成pdf,加密
pdf_temps = []
for pl in payslips:
pdf = request.env.ref('hr_payroll.action_report_payslip').render_qweb_pdf([pl.id])[0] #取得报表
pdf_reader = PyPDF2.PdfFileReader(io.BytesIO(pdf)) #进行加密操作
pdf_writer = PyPDF2.PdfFileWriter()
for page_num in range(pdf_reader.numPages):
page_obj = pdf_reader.getPage(page_num)
pdf_writer.addPage(page_obj)
#设置密码
if not pl.employee_id.birthday:
password = '123456'
else:
year = pl.employee_id.birthday.year
month = pl.employee_id.birthday.month
day = pl.employee_id.birthday.day
password = ('%s%s%s'%(year, (month if month > 10 else '0%s'%month), (day if day > 10 else '0%s'%day)))
pdf_writer.encrypt(str(password))
#创建临时文件夹存放文件,
pdf_fd, pdf_path = tempfile.mkstemp(suffix='.pdf', prefix='export_password_pdf_%s.'%pl.id)
with open(pdf_path,'wb') as pdf_file:
pdf_writer.write(pdf_file)
month = pl.date_from.month
pdf_temps.append({
# 这里文件的名字
'arcname':'%s_%s_%s%s01_工资表.pdf' % (pl.id,pl.employee_id.work_email,pl.date_from.year,(month if month > 10 else '0%s'%month)),
'pdf_file':pdf_path
})
#将多个文件打包成zip文件
temp_file_fd, temp_file_path = tempfile.mkstemp(suffix='.zip', prefix='export_password_pdf.')
with zipfile.ZipFile(temp_file_path,'w',zipfile.ZIP_DEFLATED) as myzip:
for pdf in pdf_temps:
myzip.write(pdf.get('pdf_file'),arcname=pdf.get('arcname'))
with open(temp_file_path, 'rb') as myzipfile:
myzipcontent = myzipfile.read()
for temporary_file in pdf_temps:
try:
os.unlink(temporary_file.get('pdf_file'))
except (OSError, IOError):
_logger.error('Error when trying to remove file %s' % temporary_file)
filename = '工资单.zip'
ziphttpheaders = [('Content-Type', 'application/zip'), ('Content-Length', len(myzipcontent)),('Content-Disposition', content_disposition(filename))]
return request.make_response(myzipcontent, headers=ziphttpheaders)
制作不易,点赞鼓励哈
网友评论