1. 程式人生 > >python 網頁轉pdf

python 網頁轉pdf

nco css 字符串 encoding 由於 article 轉載 分開 指定

主要使用的是wkhtmltopdf的Python封裝——pdfkit

centos環境

安裝:Install python-pdfkit

pip install pdfkit

安裝:Install wkhtmltopdf

yum intsall wkhtmltopdf

windows環境下安裝wkhtmltopdf參考這篇文章:

http://blog.csdn.net/qq_14873105/article/details/51394026


Linux環境下安裝wkhtmltopdf參考這篇文章:
http://blog.csdn.net/mr_zing/article/details/52833461


使用:
import
pdfkit pdfkit.from_string(hello,python,out.pdf) #通過文本直接進行轉換 pdfkit.from_url(http://baidu.com,out.pdf) #通過網址進行轉換 pdfkit.from_file(test.html, out.pdf) #通過html文件進行轉換

我們也可以傳遞一個url或者文件名列表:

pdfkit.from_url([google.com, yandex.ru, engadget.com], out.pdf) pdfkit.from_file([file1.html
, file2.html], out.pdf)

也可以傳遞一個打開的文件:

with open(file.html) as f:
    pdfkit.from_file(f,out.pdf) 

如果想對生成的PDF作進一步處理,我們可以將其讀取到一個變量中:

#設置輸出文件為False,將結果賦給一個變量
pdf = pdfkit.form_url(http://google.com, False)

我們可以制定所有的 wkhtmltopdf 選項 http://wkhtmltopdf.org/usage/wkhtmltopdf.txt. 我們可以移除選項名字前面的 ‘--‘ .如果選項沒有值, 使用None, Falseor * 作為字典值:

options = {
 page-size: Letter,
 margin-top: 0.75in,
 margin-right: 0.75in,
 margin-bottom: 0.75in,
 margin-left: 0.75in,
 encoding: "UTF-8",
 no-outline: None
 } 
pdfkit.from_url(http://google.com, out.pdf, options=options)

默認情況下, PDFKit 將會顯示所有的 wkhtmltopdf 輸出. 如果不想看到這些信息,你需要傳遞一個 quiet 選項:

options = {
 quiet: ‘‘
 } 
 pdfkit.from_url(google.com, out.pdf, options=options)

由於wkhtmltopdf的命令語法 , TOC 和 Cover 選項必須分開指定:

toc = {
 xsl-style-sheet: toc.xsl
 } 
cover = cover.html 
pdfkit.from_file(file.html, options=options, toc=toc, cover=cover)

當我們轉換文件、或字符串的時候,可以通過css選項指定擴展的 CSS 文件。

# 單個 CSS 文件 
css = example.css 
pdfkit.from_file(file.html, options=options, css=css) 
# Multiple CSS files 
css = [example.css, example2.css] 
pdfkit.from_file(file.html, options=options, css=css)

也可以通過HTML中的meta tags傳遞任意選項:

body = """
        <html>
          <head>
            <meta name="pdfkit-page-size" content="Legal"/>
            <meta name="pdfkit-orientation" content="Landscape"/>
          </head>
          Hello World!
          </html>
        """ 
pdfkit.from_string(body, out.pdf) #with --page-size=Legal and --orientation=Landscape


轉載地址:https://www.jianshu.com/p/44ec7a83adcb


python 網頁轉pdf