简体   繁体   English

使用 xhtml2pdf 从模板创建 PDF 并上传到 S3

[英]CreatePdf with xhtml2pdf from template and upload to S3

I tried to generate Pdf file from html using xhtml2pdf, after that I want to upload to S3.我尝试使用 xhtml2pdf 从 html 生成 Pdf 文件,之后我想上传到 S3。 I had no idea how to do it, after trying a few ways but still stuck.在尝试了几种方法后,我不知道该怎么做,但仍然卡住了。 Thank you so much for your help in advance.非常感谢您提前提供帮助。

def upload_pdf_S3(pdf):
    client = boto3.client(
        's3',
        aws_access_key_id,
        aws_secret_access_key
    )
    try:
        client.upload_fileobj(pdf, 'test', 'test111.pdf')
        return True
    except ClientError as e:
        print(e)
        return False

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
    upload_pdf_S3(pdf)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

I found a way to upload the file directly to the S3 bucket without having to write it locally.我找到了一种方法,可以将文件直接上传到 S3 存储桶,而无需在本地写入。 I use a different upload function but the idea is the same:我使用不同的上传功能,但想法是一样的:

def upload_pdf_S3(pdf):
   s3 = boto3.resource('s3')
   try:
     s3.Bucket(AWS_STORAGE_BUCKET_NAME).put_object(
       Key=f"myfolder/myfile.pdf",
       Body=pdf)
     return True
   except:
     return False

The trick was that the Body parameter in put_object has to be in bytes format.诀窍是put_object中的Body参数必须采用字节格式。

pisa_status = pisa.CreatePDF(html, dest=response, link_callback=link_callback)
upload_success = upload_pdf_S3(result.getvalue())
    if not upload_success:
       return HttpResponse('File upload to S3 has failed.')

It didn't work for me using pisa.pisaDocument() , but it did with pisa.createPDF() and result.getvalue() , as the latter is the file in bytes.使用pisa.pisaDocument()对我pisa.pisaDocument() ,但它对pisa.createPDF()result.getvalue() ,因为后者是以字节为单位的文件。 In case you don't have a link_callback function, I used the same the documentation has.如果您没有 link_callback 函数,我使用文档中的相同函数。

In case someone is in the same issues, you can tried this, it will create a local file, then you can upload to S3 for example.如果有人遇到同样的问题,你可以试试这个,它会创建一个本地文件,然后你可以上传到例如 S3。

file = open('test.pdf', "w+b")
pdf = pisa.pisaDocument(BytesIO(html.encode('utf-8')), dest=file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM