主要使用的是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