9

I am trying to render a PDF document within my Flask application. For this, I am using the following HTML template:

<!DOCTYPE html>

<html>
<head>
<style>
    @page {
        margin:0
    }
    h1 {
        color:white;
    }
    .header{
        background: #0a0045;
        height: 250px;
    }
    .center {
        position: relative;
        top: 50%;
        left: 50%;
        -ms-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
        text-align:center;
    }

</style>
</head>
<body>
<div class="header">
    <div class="center">
        <h1>Name</h1>
    </div>
</div>
</body>
</html>

I keep getting white margins at the top and right/left of my header section:

How to remove margins from this PDF ?

Is there a way to remove them?

Edit:

Below is the code used to generate the PDF file using WeasyPrint in my Flask app:

def generate_pdf(id):
    element = Element.query.filter_by(id=id).first()
    attri_dict = get_element_attri_dict_for_tpl(element)
    html = render_template('element.html', attri_dict=attri_dict)
    pdf = HTML(string=html).write_pdf()
    destin_loc = app.config['ELEMENTS_FOLDER']
    timestamp = dt.datetime.now().strftime('%Y%m%d%H%M%S')
    file_name = '_'.join(['new_element', timestamp])
    path_to_new_file = destin_loc + '/%s.pdf' % file_name
    f = open(path_to_new_file, 'wb')
    f.write(pdf)
    filename = return_latest_element_path()
    return send_from_directory(directory=app.config['ELEMENTS_FOLDER'],
                           filename=filename,
                           as_attachment=True)
Cheers
  • 123
  • 2
  • 7
  • How are you using Weasyprint? – ChrisGPT was on strike Sep 30 '19 at 21:29
  • Thanks for the reply Chris, I added the code used to render the pdf document using Flask-WeasyPrint to the original question. – Cheers Oct 01 '19 at 19:50
  • That's not what I'm asking for. I'm asking for the _code_ that generates your PDF. Also, that screenshot appears to show a browser rendering HTML. Shouldn't you be showing a PDF? – ChrisGPT was on strike Oct 02 '19 at 03:29
  • The post was edited again, I think this is the code you were asking for. The generated pdf document (element.pdf) looks exactly as displayed in the browser, with the top and side margins. – Cheers Oct 02 '19 at 19:42

2 Answers2

18

Maybe you forgot " ; " or/and " mm ", it works:

@page {
        size: A4; /* Change from the default size of A4 */
        margin: 0mm; /* Set margin on each page */
      }
Rodrigo Pereira
  • 393
  • 2
  • 11
3

The weasyprint uses 3 sources of css, one of them is default user agent stylesheet (https://doc.courtbouillon.org/weasyprint/stable/api_reference.html#supported-features)

That defines:

body {
    display: block;
    margin: 8px;
}

make sure to override that margin on tag and you will loose the margin.

bnkd
  • 31
  • 2