Bootstrap CSS is not applied in weasyprint

萝らか妹 提交于 2020-02-29 07:16:17

问题


I have made a flask application which generates .pdf from html with weasyprint and send it as attachment. But apparently bootstrap 4 css is not applied. I can't find a solution. It is working well with pdfkit but I need weasyprint, since pythonanywhere.com does not support pdfkit.

I have tried linking bootstrap, using bootstrap css as file in my html, but there was no difference.

This is my python part, which generates and sends pdf.

@app.route('/pdf_send', methods=('GET', 'POST'))
@login_required
def pdf_send():

    rendered = render_template(
    'pdf_send2.html', 
    name=name_g, 
    surname=surname_g,
    email=email_g,
    address=address_g,
    invoice_no=invoice_no_g,
    dict_g=dict_g,
    bendra_suma_g = ('%.2f' % round(float(bendra_suma_g[0]), 2)),
    send=send_g,
    today=today_g
    )

    css_file = ('static/bootstrap.css')
    filename = 'SF-' + invoice_no_g +'.pdf'
    html = HTML(string=rendered)
    css = CSS(filename=css_file)
    html.write_pdf(filename, stylesheets=[css])
    send_email(filename, email_g)

    return redirect(url_for('index'))

回答1:


I know this is an old thread but I stumbled over it while looking for an answer to the same question, so I'm adding my workaround in case it helps anyone else. I'm going to start by pointing out that although this does work Bootstrap really isn't intended to be used for printing, and weasyprint ignores anything inside a @media query so you're going to need to add a lot of css anyway in order to make it render correctly so it's probably not worth it.

Using the code from the original question, if you add the bootstrap cdn css to the stylesheets list it will render:

html = HTML(string=rendered)
css = CSS(filename=css_file)
html.write_pdf(filename, stylesheets=[css, "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"])

However, given the issues with Bootstrap rendering, I found this trick to be considerably more useful for applying fonts.




回答2:


weasyprint doesnt work well with bootstrap .

This is the reference Link to Github site for clarity.

Whatever bootstrap classes you write will be ignored by WeasyPrint.

You can see the "Ignored ..." messsages in WeasyPrint error log(if you ever initilised).

So its better to use CSS for the print-pages



来源:https://stackoverflow.com/questions/49496398/bootstrap-css-is-not-applied-in-weasyprint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!