"Error 0x80070057: The parameter is incorrect" when unzipping files

1

I created a function to create multiple PDFs with Weasyprint, zip them together and download the zip file. When trying to extract the folder on Windows 10 with the in-house zip program i get this error:

"An unexpected error is keeping you from copying the file. [...] Error 0x80070057" <

I can skip the error and the files get extracted. However in the best case scenario I'd like to prevent this error.

def get_all_shareholder_reports(request):
   current_shareholders = list(models.objects.all())

    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, "a") as zip_file:

        for shareholder in current_shareholders:
            pdf_file_handle = io.BytesIO()
            context_dict = get_report_details(pk=shareholder.shareholder_id)

            html_string = render_to_string('template.html',
                                           context_dict)

            html_handler = HTML(string=html_string, base_url=request.build_absolute_uri())
            html_handler.write_pdf(target=pdf_file_handle)
            pdf_file_handle.seek(0)
            pdf_string = pdf_file_handle.getvalue()
            pdf_file_name ='Shareholder_Report_{}_{}_{}.pdf'.format(context_dict['shareholder'].forename,
                                                                     context_dict['shareholder'].surname,
                                                                     datetime.datetime.now().strftime(
                                                                         "%d_%m_%Y_%H:%M:%S"))
            zip_file.writestr(zinfo_or_arcname=pdf_file_name, data=pdf_string)

    zip_buffer.seek(0)
    response = HttpResponse(zip_buffer.getvalue(), content_type="application/x-zip-compressed")

    response['Content-Disposition'] = 'attachment; filename=%s' % 'myzip.zip'

    return response
python
django
zipfile
weasyprint
asked on Stack Overflow Jul 23, 2019 by P. Maino • edited Jul 23, 2019 by P. Maino

2 Answers

2

I figured it out: The zip file didn't like the ":" in the filename. Removing them fixed the issue.

pdf_file_name ='Shareholder_Report_{}_{}_{}.pdf'.format(context_dict['shareholder'].forename,
                                                                     context_dict['shareholder'].surname,
                                                                     datetime.datetime.now().strftime(
                                                                         "%d_%m_%Y_%H_%M_%S"))
answered on Stack Overflow Jul 30, 2019 by P. Maino
1

You basically need to clean the filename for all reserved characters in Windows: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions

So the following should do it "filename".replaceAll("[<>:\"/\\\\|?*]", "")

answered on Stack Overflow Jul 25, 2020 by olio

User contributions licensed under CC BY-SA 3.0