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 responseAquí 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
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);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())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 certificateLa solución fue deshabilitar la verificación SSL:
import ssl ssl._create_default_https_context = ssl._create_unverified_context