使用下面的代码,我可以轻松生成PDF:

import weasyprint

def admin_order_pdf(request, sell_id):  # working fine 
   try:
      sell = Sell.objects.get(id=sell_id)
   except Sell.DoesNotExist:
      return HttpResponse('Sell object does not exist')

   html = render_to_string('sell_invoice.html', {'sell': sell})
   response = HttpResponse(content_type='application/pdf')

   app_static_dir = os.path.join(settings.BASE_DIR, 'pdf', 'static')

   css_path = os.path.join(app_static_dir, 'css', 'css.css')

   response['Content-Disposition'] = f'filename=sell_{sell.id}.pdf'

   weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(css_path)])

   return response

然而,尽管我可以设计带有内联CSS和CSS文件的PDF,但我不知道如何将任何照片或图片插入其中.是否可以将图片/徽标添加到PDF中?如果是这样,我该如何处理呢?

推荐答案

You can easily pass encoded data using Python get logo.

def get_logo_base64_encoded_data():
    logo_path = os.path.join(settings.BASE_DIR, 'pdf', 'static', 'logo', 'logo.png')
    with open(logo_path, 'rb') as f:
        logo_data = f.read()
    return base64.b64encode(logo_data).decode()

def admin_order_pdf(request, sell_id):
    try:
        sell = Sell.objects.get(id=sell_id)
    except Sell.DoesNotExist:
        return HttpResponse('Sell object does not exist')

    html = render_to_string('sell_invoice.html', {'sell': sell, 'logo_base64_encoded_data': get_logo_base64_encoded_data()})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = f'filename=sell_{sell.id}.pdf'

   
    weasyprint.HTML(string=html).write_pdf(response)

    return response

Python相关问答推荐

已安装' owiener ' Python模块,但在导入过程中始终没有名为owiener的模块

在Docker中运行HAProxy时无法获得503服务

NumPy中的右矩阵划分,还有比NP.linalg.inv()更好的方法吗?

指示组内的rejected_time是否在creation_timestamp后5分钟内

根据网格和相机参数渲染深度

将HTML输出转换为表格中的问题

当密钥是复合且唯一时,Pandas合并抱怨标签不唯一

如何使用Jinja语法在HTML中重定向期间传递变量?

Django管理面板显示字段最大长度而不是字段名称

如何访问所有文件,例如环境变量

计算组中唯一值的数量

Python中绕y轴曲线的旋转

在Python中动态计算范围

我如何根据前一个连续数字改变一串数字?

ThreadPoolExecutor和单个线程的超时

如何根据一列的值有条件地 Select 前N组?

使用groupby方法移除公共子字符串

如何从列表框中 Select 而不出错?

Tkinter菜单自发添加额外项目

dask无groupby(ddf. agg([min,max])?''''