主要使用的是wkhtmltopdf的Python封裝——pdfkitcss
centos環境html
安裝:Install python-pdfkitpython
pip install pdfkit
安裝:Install wkhtmltopdfwindows
yum intsall wkhtmltopdf
windows環境下安裝wkhtmltopdf參考這篇文章:centos
Linux環境下安裝wkhtmltopdf參考這篇文章:http://blog.csdn.net/qq_14873105/article/details/51394026
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或者文件名列表:ui
pdfkit.from_url(['google.com', 'yandex.ru', 'engadget.com'], 'out.pdf') pdfkit.from_file(['file1.html', 'file2.html'], 'out.pdf')
也能夠傳遞一個打開的文件:google
with open('file.html') as f: pdfkit.from_file(f,'out.pdf')
若是想對生成的PDF做進一步處理,咱們能夠將其讀取到一個變量中:url
#設置輸出文件爲False,將結果賦給一個變量 pdf = pdfkit.form_url('http://google.com', False)
咱們能夠制定全部的 wkhtmltopdf 選項 http://wkhtmltopdf.org/usage/wkhtmltopdf.txt. 咱們能夠移除選項名字前面的 '--' .若是選項沒有值, 使用None, Falseor * 做爲字典值:spa
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 選項:.net
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