HTML2PDF格式问题

2 投票
1 回答
1968 浏览
提问于 2025-04-17 01:51

我正在使用HTML2PDF来把我的HTML文件和里面的CSS代码转换成PDF格式。但是我得到的输出结果不太对。我尝试了很多方法,但还是不知道我的代码哪里出了问题。有没有人能告诉我我做错了什么。

**这是我的HTML文件 (my.html) *****

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>PDF Template</title>

<style type="text/css">

body {font-family:Arial;font-size:13px;line-height:20px;color:#444444;text-align:left;margin:0;padding:40px 0;}


#wrapper {height:auto; width:660px; overflow:hidden; margin:0 auto; background-color:#E0DAE9; 
padding:15px; border:5px solid #EFECF4;}

#content {height:auto; width:620px; overflow:hidden; margin:0 auto; background-color:#FFFFFF; padding:20px;}


.left {height:auto; width:300px; overflow:hidden; float:left; margin:0 20px 0 0;}

.right {height:auto; width:300px; overflow:hidden; float:right;}

#center {height:auto; width:620px; overflow:hidden;}


</style>
</head>
<body>  
  <div id="wrapper">
     <div id="content">

    <h1>$Lopram seu chacege amtoe smgho</h1>
    <div class="left">
       <h2>Recipient:</h2>
       <p>John Doe</p>
    </div>
    <div class="right">
            <h2>Expires On:</h2>
        <p>May 20, 2012</p>
    </div>  
    <h2>Fine Print:</h2>
    <p>Lorem poeoh ochoe. Toroam ozohm. Vsoram soeaose.</p>
    <div id="center">
        <div class="left">      
        <h2>Address:</strong></h2>
        <ul>
            <li>950 XX St.</li>

        </ul>
        </div>

    </div>

   </div>   
 </div>
</body>
</html>

这是我的Python代码:

from xhtml2pdf import pisa
import cStringIO as StringIO

def CreatePDF():

    ## Let's create a file name for pdf
    file_name = "mytest.pdf"

    # Create a file object
    pdf_file = open(file_name, "wb")

    # Open pdf file
    html_file = open("my.html", 'rb')  # I also tried with open("my.html")

    # Create pdf using pisa
    pdf = pisa.CreatePDF( html_file.read(), pdf_file)

    html_file.close()
    pdf_file.close() 

1 个回答

0

html2pdf不支持CSS中的浮动布局,如果你想进行排版,可以试试用“表格”来实现。

撰写回答