django - pyPDF通过django合并并显示为httpresponse

原文 标签 django pdf django-admin pypdf

pyPDF merging and displaying as httpresponse through django

I'm having trouble incorporating pyPDF logic to merge two pdf files into my django site. I have written code that works to merge files when run in a python file on the local server(but I need to explicitly identify which files to merge:

from pyPdf import PdfFileReader, PdfFileWriter

output = PdfFileWriter()
input1 = PdfFileReader(file("abc_form0.pdf", "rb"))
input2 = PdfFileReader(file("abc_form1.pdf", "rb"))
total_pages = input1.getNumPages()
total_pages1 = input2.getNumPages()

for page in xrange(total_pages):
    output.addPage(input1.getPage(page))

for page in xrange(total_pages1):
    output.addPage(input2.getPage(page))


outputStream = file("output.pdf", "wb")
output.write(outputStream)
outputStream.close()

This code (from my django site) works to display a single PDF. However, when more than one PDF is selected, only the final PDF selected displays, hence the need to integrate pyPDF to create one file containing all requested files.

class ABCAdmin(admin.ModelAdmin):

    actions = ['print_selected_pdf']

    def create_pdf(self, request, queryset):
        response = HttpResponse(mimetype="application/pdf")
        response['Content-Disposition'] = 'attachment; filename=form.pdf'
        for obj in queryset:
            response.write(obj.form)
            ABC.objects.filter(pk=obj.pk).update(user=request.user,pdf_printed="1",request_time=time.strftime("%H:%M:%S"),request_date=datetime.datetime.today())
            return response

    def print_selected_pdf(self, request, queryset):
        # prints the pdfs for those that are selected,
        # regardless if the pdf_printed field is true or false
        qs = queryset.filter(pdf_printed__exact=0)
        return self.create_pdf(request, qs)

I'm struggling with finding a way to combine these two methods. What I have tried is the following, but get an IO error [Errno 2] No such file or directory: 'obj.form'. So it is not reading in obj.form - I need to find a way for it to read in these objects correctly. Anyway, this is what I've tried.

def create_pdf(self, request, queryset):
    response = HttpResponse(mimetype="application/pdf")
    response['Content-Disposition'] = 'attachment; filename=form.pdf'
    for obj in queryset:
        output = PdfFileWriter()
        input = PdfFileReader(file("obj.form","rb"))
        total_pages = input.getNumPages()
        for page in xrange(total_pages):
            output.addPage(input.GetPage(page))
        outputStream = file("output.pdf", "wb")
        response.write(outputStream)
        outputStream.close()
        ABC.objects.filter(pk=obj.pk).update(user=request.user,pdf_printed="1",request_time=time.strftime("%H:%M:%S"),request_date=datetime.datetime.today())
        return response

def print_selected_pdf(self, request, queryset):
    # prints the pdfs for those that are selected,
    # regardless if the pdf_printed field is true or false
    qs = queryset.filter(pdf_printed__exact=0)
    return self.create_pdf(request, qs)

As always, thanks for any help or tips you may be able to provide!

Answer

I used stringIO in the output stream to get around this. I also had to define each page of the PDF form to be added to the output. This works to iterate for any number of forms that I need to be requested.

def create_form(self, request, queryset):
    response = HttpResponse(mimetype="application/pdf")
    response['Content-Disposition'] = 'attachment; filename=form.pdf'
    output = PdfFileWriter()
    for obj in queryset:
        input = PdfFileReader(cStringIO.StringIO(obj.form))
        output.addPage(input.getPage(0))
        output.addPage(input.getPage(1))
        output.addPage(input.getPage(2))
        output.addPage(input.getPage(3))
        ABC_Self.objects.filter(pk=obj.pk).update(user=request.user,pdf_printed="1",request_time=time.strftime("%H:%M:%S"),request_date=datetime.datetime.today())
    outputStream = cStringIO.StringIO()
    output.write(outputStream)
    response.write(outputStream.getvalue())
    return response

翻译

我在合并pyPDF逻辑以将两个pdf文件合并到django站点时遇到麻烦。我已经编写了可以在本地服务器上的python文件中运行时合并文件的代码(但我需要明确标识要合并的文件:

from pyPdf import PdfFileReader, PdfFileWriter

output = PdfFileWriter()
input1 = PdfFileReader(file("abc_form0.pdf", "rb"))
input2 = PdfFileReader(file("abc_form1.pdf", "rb"))
total_pages = input1.getNumPages()
total_pages1 = input2.getNumPages()

for page in xrange(total_pages):
    output.addPage(input1.getPage(page))

for page in xrange(total_pages1):
    output.addPage(input2.getPage(page))


outputStream = file("output.pdf", "wb")
output.write(outputStream)
outputStream.close()


此代码(来自我的django网站)可显示单个PDF。但是,当选择多个PDF时,仅显示最终的PDF,因此需要集成pyPDF来创建一个包含所有请求文件的文件。

class ABCAdmin(admin.ModelAdmin):

    actions = ['print_selected_pdf']

    def create_pdf(self, request, queryset):
        response = HttpResponse(mimetype="application/pdf")
        response['Content-Disposition'] = 'attachment; filename=form.pdf'
        for obj in queryset:
            response.write(obj.form)
            ABC.objects.filter(pk=obj.pk).update(user=request.user,pdf_printed="1",request_time=time.strftime("%H:%M:%S"),request_date=datetime.datetime.today())
            return response

    def print_selected_pdf(self, request, queryset):
        # prints the pdfs for those that are selected,
        # regardless if the pdf_printed field is true or false
        qs = queryset.filter(pdf_printed__exact=0)
        return self.create_pdf(request, qs)


我正在努力寻找一种将这两种方法结合起来的方法。我尝试了以下操作,但出现IO错误[Errno 2]没有此类文件或目录:'obj.form'。所以它不是在obj.form中读取-我需要找到一种方法来使其正确读取这些对象。无论如何,这就是我尝试过的。

def create_pdf(self, request, queryset):
    response = HttpResponse(mimetype="application/pdf")
    response['Content-Disposition'] = 'attachment; filename=form.pdf'
    for obj in queryset:
        output = PdfFileWriter()
        input = PdfFileReader(file("obj.form","rb"))
        total_pages = input.getNumPages()
        for page in xrange(total_pages):
            output.addPage(input.GetPage(page))
        outputStream = file("output.pdf", "wb")
        response.write(outputStream)
        outputStream.close()
        ABC.objects.filter(pk=obj.pk).update(user=request.user,pdf_printed="1",request_time=time.strftime("%H:%M:%S"),request_date=datetime.datetime.today())
        return response

def print_selected_pdf(self, request, queryset):
    # prints the pdfs for those that are selected,
    # regardless if the pdf_printed field is true or false
    qs = queryset.filter(pdf_printed__exact=0)
    return self.create_pdf(request, qs)


与往常一样,感谢您可能提供的任何帮助或提示!
最佳答案
我在输出流中使用stringIO来解决此问题。我还必须定义要添加到输出中的PDF表单的每一页。这可以迭代我需要的任何数量的表格。

def create_form(self, request, queryset):
    response = HttpResponse(mimetype="application/pdf")
    response['Content-Disposition'] = 'attachment; filename=form.pdf'
    output = PdfFileWriter()
    for obj in queryset:
        input = PdfFileReader(cStringIO.StringIO(obj.form))
        output.addPage(input.getPage(0))
        output.addPage(input.getPage(1))
        output.addPage(input.getPage(2))
        output.addPage(input.getPage(3))
        ABC_Self.objects.filter(pk=obj.pk).update(user=request.user,pdf_printed="1",request_time=time.strftime("%H:%M:%S"),request_date=datetime.datetime.today())
    outputStream = cStringIO.StringIO()
    output.write(outputStream)
    response.write(outputStream.getvalue())
    return response
相关推荐

python - 导入与系统模块同名的模块

python - 列user_id不是唯一的,对于Django UserProfiles

python - 扩展新的用户创建表单Django

python - python + django:无法使用Popen找到模块

ajax - 使用Dajax调用Django视图

python - Django按最新评分列出所有作者

python - Django项目中的通配符子域

django - 我如何从Django查询中提取字段名称和值

python - 如何从Django网站启动Python脚本?

django - 如何从PyCharm运行South manage.py命令?