Python 如何将上传的html文件转换为pdf?(django rest框架)

Python 如何将上传的html文件转换为pdf?(django rest框架),python,django,django-rest-framework,html-to-pdf,Python,Django,Django Rest Framework,Html To Pdf,我已经在前端制作了html文件模板(ReactNative Expo,我会使用一个库将html转换为pdf,但Expo没有提供),通过将其发送到后端,我希望将其转换并保存为pdf 我是django的新手,但我确实尝试过一些搜索,我发现如下:,如果我采用这种方法,就不需要从用户那里获取多个数据,因为表单非常详细,前端足够填充。我也采用了这种方法,但我不知道我缺少了什么(),以下是我迄今为止的代码: 我希望html文件自动转换为pdf,但它仍然将其保存为html 更新: (models.py) (u

我已经在前端制作了html文件模板(ReactNative Expo,我会使用一个库将html转换为pdf,但Expo没有提供),通过将其发送到后端,我希望将其转换并保存为pdf

我是django的新手,但我确实尝试过一些搜索,我发现如下:,如果我采用这种方法,就不需要从用户那里获取多个数据,因为表单非常详细,前端足够填充。我也采用了这种方法,但我不知道我缺少了什么(),以下是我迄今为止的代码:

我希望html文件自动转换为pdf,但它仍然将其保存为html

更新:

(models.py)

(utils.py)

(views.py)

(serializer.py)


我在将动态django模板转换为pdf时使用pdfkit,它非常易于使用。您需要使用它,例如:

导入pdfkit
从django.template.loader导入get_模板
def render_to_pdf():
#准备html模板的上下文,就像准备django模板一样
template=get_template('your_template.html'))
html=template.render(context=context)
返回pdfkit.from_字符串(html)

我应该在哪里使用此代码?比如在创建它的序列化程序下,或者在模型本身下?我还发现这行代码非常有用,它来自于_文件('file.html','out.pdf')。我不需要制作另一个模板,因为我已经有一个html文件(来自用户),我只想将其转换为pdf,有可能吗?将其放在
utils.py
helper.py下。py
更方便,是的,您可以在输入中直接使用html文件。我仍然没有转换的运气,输出仍在html文件中:
“文件”:http://localhost:8000/media/Documents/2019/Questions_L93qhKk.html“
将最后一行更改为
response=HttpResponse(pdfkit.from_string(html),content_type='application/pdf')
class Questionary(models.Model):
    date = models.DateField(auto_now_add=True)
    title = models.CharField(max_length = 100)
    file = models.FileField(upload_to='Documents/%Y/%m/%d/', blank = 
           False, 
            null = False)
    def generate_obj_pdf(self):
        this = Questionary.objects.get(id=self.id)
        render_to_pdf(this.file)
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
import pdfkit
from xhtml2pdf import pisa
  def render_to_pdf(your_template):
    template = get_template(your_template.html)
    response = HttpResponse(pdfkit.from_string(html), 
               content_type='application/pdf')
    return response
    class CreateQuestionaryAPIView(CreateAPIView):
        serializer_class = CreateQuestionarySerializer
class CreateQuestionarySerializer(serializers.ModelSerializer):
    class Meta:
        model = Questionary
        fields = '__all__'