如何在pdf的css中居中绝对定位元素


How to center absolutely positioned elements in css for a pdf

我正在尝试将名称(#box2)和主题(#box1)居中于图像的顶部。

<?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>

下面是创建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');
?>

如果我不使用html2pdf生成pdf文件,我对名称和主题的中心定位没有问题。但如果我使用html2pdf,一切都毁了。当使用html2pdf时,请帮助我在css中居中。

大多数常见的HTML-to-PDF程序要么不理解CSS,要么理解得很差。如果您的HTML可以正常工作,但不能很好地使用html2pdf转换为PDF,您可以给wkhtmltopdf一个机会https://github.com/antialize/wkhtmltopdf

如果您想居中。common,请尝试以下操作:

    .common{
       position: absolute;
       left: 50%;
       top: 0;
       font-size:20px;
       width:600px;
       margin-left:-300px;
    }

老问题,但我今天有类似的问题。在尝试了html和css历史上的每一种方法后,我是如何解决这个问题的。我使用了JorisW:

这样的表
<table style='width:100%' align='center'>
    <tr>
        <td>
            <img src="image.gif">
        </td>
    </tr>
</table>

这是我用来将div放置在中间的方法。

假设你想用id=test来定位div

CSS

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

尝试使用表格和内联css样式

<table align="left" width="100%" style="page-break-after:always; margin-top:25px; margin-left:25px; font-family:tahoma; font-size:20px; ">
<tr><td>Your info</td></tr>
</table>