Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove margins from PDF? (Generated using WeasyPrint)

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)
like image 838
Cheers Avatar asked Sep 30 '19 21:09

Cheers


1 Answers

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 */
      }
like image 125
Rodrigo Pereira Avatar answered Sep 19 '22 04:09

Rodrigo Pereira