Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.3K
Views
Salida de PDF usando Weasyprint que no muestra imágenes (Django)

Estoy tratando de generar PDF en Django usando la biblioteca Weasyprint, pero las imágenes no aparecen en el PDF generado. Probé URLs relativas y estáticas para las imágenes, pero incluso la URL estática no muestra la imagen. Al abrir el propio HTML en Chrome, las imágenes sí se muestran.

Aquí está mi vista de generación de pdf en el archivo views.py:

 def pdf_generation(request, some_slug) stud = Student.objects.get(some_slug=some_slug) studid = stud.some_slug context = {'studid':studid} html_string = render_to_string('templates/pdf_gen.html', context) html = HTML(string=html_string) pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/css/detail_pdf_gen.css')]); response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="mypdf.pdf"' return response

Aquí está la parte del HTML de la imagen:

 <DIV id="p1dimg1"> <IMG src="{% static 'img/image.jpg' %}" alt=""> </DIV>

Y el CSS:

 #page_1 #p1dimg1 {position:absolute;top:0px;left:0px;z- index:-1;width:792px;height:1111px;} #page_1 #p1dimg1 #p1img1 {width:792px;height:1111px;}

Muchísimas gracias

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Arreglado por:

Agregue base_url=request.build_absolute_uri() para que

 html = HTML(string=html_string)

se convierte

 html = HTML(string=html_string, base_url=request.build_absolute_uri())

Eso permitirá direcciones URL relativas en el archivo HTML.

Para las imágenes, solo las imágenes PNG parecen funcionar por alguna razón.

Para que los estilos HTML se muestren en el PDF, agregue Presentational_hints=True según los documentos de Weasyprint:

 pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/css/detail_pdf_gen.css')], presentational_hints=True);
over 4 years ago · Santiago Trujillo Report

0

Configure la estática para la ruta de su imagen como:

 {% load static %} <img src="{% static 'images/your_image.png %}" alt="" />

y luego debe pasar la base_url en la clase HTML de Weasyprint como:

 HTML(string=html_string, base_url=request.build_absolute_uri())
over 4 years ago · Santiago Trujillo Report

0

Después de agregar HTML(string=html_string, base_url=request.build_absolute_uri()) a mi configuración, las imágenes aún no se cargaban. Tuve que usar el registro a continuación para identificar el problema real.

 import logging logger = logging.getLogger('weasyprint') logger.addHandler(logging.FileHandler('/tmp/weasyprint.log'))

Luego revise el archivo de registro /tmp/weasyprint.log para ver si hay errores.

El verdadero problema para mí fue:

 urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate

La solución fue deshabilitar la verificación SSL:

 import ssl ssl._create_default_https_context = ssl._create_unverified_context
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!