Search code examples
phphtmlcsshtml2pdf

How to center absolutely positioned elements in css for a pdf


I'm trying to center the names(#box2) and the topic(#box1) on top of an image.

<?php require_once('seminar_config.php'); ?>

<a href="print.certificate.php">Print</a>

<body>
<?php
$participants = $db->get_results("SELECT participant FROM tbl_participants WHERE state=1");
$topics = $db->get_results("SELECT topic FROM tbl_topics");
if(!empty($participants)){
?>
<?php ob_start(); ?>
<div id="container">
<img src="certificate.jpg"/>
<?php foreach($topics as $a=>$b){ ?>
<?php foreach($participants as $k=>$v){ ?>
    <img src="certificate.jpg"/>
    <div id="box1" class="common"><?php echo $b->topic; ?></div>
    <div id="box2" class="common"><?php echo $v->participant; ?></div>
<?php } ?>
<?php } ?>  
</div>
<?php $_SESSION['certificates'] = ob_get_contents(); ?>
<?php ob_flush(); ?>    
<?php } ?>
</body>

And here's the script that creates the pdf:

<?php require_once('html2pdf/html2pdf.class.php'); ?>
<?php
$html2pdf = new HTML2PDF('L', 'A4', 'en');
$html2pdf->writeHTML('<style>

    #box1{  
        margin-top: 350px;
    }

    #box2{  
        margin-top: 200px;
    }

    .common{
        height: 20px;
        left: 630px;
        right: 630px;
        text-align: center;
        position: absolute;
        left: 0;
        top: 0;
        font-size:20px;
    }
</style>'.

$_SESSION['certificates']);
$html2pdf->Output('random.pdf');
?>

I have no problem with the center positioning of the names and topic if I'm not using html2pdf to generate pdf files. But if I use html2pdf everything is ruined. Please help me center things in css when using html2pdf.


Solution

  • Here is what I use to position divs in center.

    Say you want to position div with id=test

    CSS

    #test {
       width: 500px;
       margin: 0 auto; //auto margin to left and right
    }