4

Here is a supposed solution I have found. https://stackoverflow.com/a/2180417

I am trying to implement it but I am not able to do so.

Here is my current code:

utils.py

from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template

from xhtml2pdf import pisa

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, link_callback=fetch_resources)
     if not pdf.err:
          return HttpResponse(result.getvalue(), content_type='application/pdf')
     return None

def fetch_resources(uri, rel):
    path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))

    return path

views.py

 from django.http import HttpResponse
 from django.views.generic import View

 from yourproject.utils import render_to_pdf #created in step 4

 class GeneratePdf(View):
     def get(self, request, *args, **kwargs):
         data = {
              'today': datetime.date.today(), 
              'amount': 39.99,
             'customer_name': 'Cooper Mann',
             'order_id': 1233434,
         }
         pdf = render_to_pdf('pdf/invoice.html', data)
         return HttpResponse(pdf, content_type='application/pdf')

Everything loads correctly if I just render a normal template so I know the problem is with this part of the process. The invoice.html template includes a url such as /home/images/products/1231

<img src='{{ photo.url }}'>
questnofinterest
  • 309
  • 1
  • 3
  • 12

2 Answers2

1

no need set the fetch resources. its works for me

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)
    if not pdf.err:
     return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

also try to refer this link html-template-to-pdf-in-django

Robert
  • 3,373
  • 1
  • 18
  • 34
1

To render the image inside the pdf you need to make an image callback with the following function:

def link_callback(uri, rel):
    """
    Convert HTML URIs to absolute system paths so xhtml2pdf can access those
    resources
    """
    # use short variable names
    sUrl = settings.STATIC_URL      # Typically /static/
    sRoot = settings.STATIC_ROOT    # Typically /home/userX/project_static/
    mUrl = settings.MEDIA_URL       # Typically /static/media/
    mRoot = settings.MEDIA_ROOT     # Typically /home/userX/project_static/media/

    # convert URIs to absolute system paths
    if uri.startswith(mUrl):
        path = os.path.join(mRoot, uri.replace(mUrl, ""))
    elif uri.startswith(sUrl):
        path = os.path.join(sRoot, uri.replace(sUrl, ""))
    else:
        return uri  # handle absolute uri (ie: http://some.tld/foo.png)

    # make sure that file exists
    if not os.path.isfile(path):
            raise Exception(
                'media URI must start with %s or %s' % (sUrl, mUrl)
            )
    return path

Next you add your rendering function.

Link: Biblioteca xhtml2pdf

If this answer has helped you, mark it as an answer.

Danilo Rodrigues
  • 373
  • 3
  • 17