convert html to pdf using django

412 Views Asked by At

I try to convet html with tailwind style to pdf in django and I use many library like weasyprint, pdfkit and xhtml2pdf but the style doesn't apply so there any solution for this issue

1

There are 1 best solutions below

0
sglmr On

Okay, I’m on my phone, so I apologize for the hacky copy+paste, lack of doc strings, and messy imports. I’ve had success with rendering a Django template and returning a PDF with the following code:

# services.py

from django.conf import settings
from .models import Proposal
from num2words import num2words
import requests


# PDF Generation
from django.contrib.staticfiles import finders
from django.template.loader import get_template
from xhtml2pdf import pisa
from io import BytesIO


def print_proposal(pk):
    logger.info("Generating PDF for pk: %s", pk)

    proposal = Proposal.objects.get(pk=pk)
    logger.debug("Found proposal %s", proposal)

    context = {
        "proposal": proposal,
        "price_words": num2words(proposal.final_price).title(),
    }
    template = get_template("proposals/print/base.html")
    html = template.render(context)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)

    if not pdf.err:
        return result.getvalue()
    else:
        logger.error("There was an error generating the PDF document.\n%s", pdf.err)
    return None

```python
# views.py


from django.shortcuts import redirect
from django.template.response import TemplateResponse
from .models import Proposal, Deliverable
from .forms import ProposalForm
from django.http import FileResponse, HttpResponse, HttpResponseServerError
from django.contrib.auth.mixins import LoginRequiredMixin


from django.views.generic import View

from .services import print_proposal


class ProposalPrintView(LoginRequiredMixin, View):
    def get(self, request, *args, **kwargs):
        logging.debug("View ProposalPrintView GET for pk: %s", kwargs["pk"])
        pdf = print_proposal(pk=kwargs["pk"])
        return HttpResponse(pdf, content_type="application/pdf")