說起pdf就想到了一款很適用的工具,那就是pdfkit,在前幾天的項目中,有一個功能要實現,為了實現這一個功能,於是我大海茫茫中查詢各種百科,不負眾望的讓我找到了我心怡的工具,想必也就是它了。好了廢話也不多說了,開始進入高潮部分吧~~~
1、說明
pdfkit,把HTML·+ CSS格式的文件轉換成PDF格式文檔的一種工具。
其實,它就是html轉換成PDF工具包wkhtmltopdf的Python封裝,所以,必須安裝wkhtmktopdf。一般情況下,wkhtmkltopdf需要手動安裝,尤其要注意的是Windows下,需要把wkhtmltopdf的bin執行文件路徑添加到PATH變量中。
2、安裝
請參考《Python抓取網頁並保存為PDF》里面各個安裝包的安裝
3、API說明
def from_url(url, output_path, options=None, toc=None, cover=None, configuration=None, cover_first=False): """ 把從URL獲取文件轉換為PDF文件 :param url: URL 或 URL列表 :參數,output_path: 輸出PDF文件的路徑。如果是參數等於False,意味着文件將會以字符串的形式返回,得到文本文件。 :param options: (可選) dict with wkhtmltopdf global and page options, with or w/o '--' :param toc: (可選) dict with toc-specific wkhtmltopdf options, with or w/o '--' :param cover: (可選) string with url/filename with a cover html page :param configuration: (可選)實例化 pdfkit.configuration.Configuration() :param configuration_first: (optional) if True, cover always precedes TOC 返回值:成功返回True """ r = PDFKit(url, 'url', options=options, toc=toc, cover=cover,configuration=configuration, cover_first=cover_first) return r.to_pdf(output_path)
def from_file(input, output_path, options=None, toc=None, cover=None, css=None, configuration=None, cover_first=False): """ Convert HTML file or files to PDF document :param input: path to HTML file or list with paths or file-like object :param output_path: path to output PDF file. False means file will be returned as string. :param options: (optional) dict with wkhtmltopdf options, with or w/o '--' :param toc: (optional) dict with toc-specific wkhtmltopdf options, with or w/o '--' :param cover: (optional) string with url/filename with a cover html page :param css: (optional) string with path to css file which will be added to a single input file :param configuration: (optional) instance of pdfkit.configuration.Configuration() :param configuration_first: (optional) if True, cover always precedes TOC Returns: True on success """ r = PDFKit(input, 'file', options=options, toc=toc, cover=cover, css=css, configuration=configuration, cover_first=cover_first) return r.to_pdf(output_path)
def from_string(input, output_path, options=None, toc=None, cover=None, css=None, configuration=None, cover_first=False): """ Convert given string or strings to PDF document :param input: string with a desired text. Could be a raw text or a html file :param output_path: path to output PDF file. False means file will be returned as string. :param options: (optional) dict with wkhtmltopdf options, with or w/o '--' :param toc: (optional) dict with toc-specific wkhtmltopdf options, with or w/o '--' :param cover: (optional) string with url/filename with a cover html page :param css: (optional) string with path to css file which will be added to a input string :param configuration: (optional) instance of pdfkit.configuration.Configuration() :param configuration_first: (optional) if True, cover always precedes TOC Returns: True on success """ r = PDFKit(input, 'string', options=options, toc=toc, cover=cover, css=css, configuration=configuration, cover_first=cover_first) return r.to_pdf(output_path)
4、舉例說明
4.1 簡單的例子
import pdfkit pdfkit.from_url('https://www.google.com.hk','out1.pdf') pdfkit.from_file('123.html','out2.pdf') pdfkit.from_string('Hello!','out3.pdf')
也可以傳遞一個url或者文件名列表:
pdfkit.from_url(['https://www.google.com.hk','https://baidu.com','http://cn.bing.com/'],'out_0.pdf') pdfkit.from_file(['122.html','123.html'],'out_1.pdf')
如何你想對生成的PDF作進一步處理,你可以將其讀取到一個變量中:
pdf=pdfkit.from_url('https://www.google.com.hk',False)
你可以指定所有的 wkhtmltopdf選項 。你可以移除選項名字前面的 ‘–’ .如果選項沒有值, 使用None, False或者“*”作為字典值:
在views視圖中可以加上options進行頁面布局調試
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('https://www.google.com.hk','out1.pdf',options=options)
默認情況下, PDFKit 將會顯示所有的wkhtmltopdf輸出. 如果你不想看到這些信息,你需要傳遞一個quiet選項:
options = {'quiet':''} pdfkit.from_url('https://www.google.com.hk','out1.pdf',options=options)
由於wkhtmltopdf的命令語法 ,TOC和Cover選項必須分開指定:
toc={'xsl-style-sheet':'toc.xsl'} cover='124.html' pdfkit.from_file('122.html', options=options, toc=toc, cover=cover)
當你轉換文件、或字符串的時候,你可以通過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)
配置
每個API調用都有一個可選的參數。這應該是pdfkit.configuration() API 調用的一個實例。采用configuration 選項作為初始化參數。可用的選項有:
wkhtmltopdf——wkhtmltopdf二進制文件所在的位置。默認情況下pdfkit會嘗試使用which(在類UNIX系統中) 或where(在Windows系統中)來判斷。
meta_tag_prefix–pdfkit的前綴指定 meta tags(元標簽) - 默認情況是pdfkit-
示例 :針對wkhtmltopdf不在系統路徑中(不在$PATH里面)
config=pdfkit.configuration(wkhtmltopdf='/opt/bin/wkhtmltopdf')) pdfkit.from_string(html_string, output_file, configuration=config)
配置文件路勁是你當時下載wkhtmltopdf安裝的路徑,然后把它加入在里面,''out.pdf''可以更改名字,屬於pdf文件名。
config = pdfkit.configuration(wkhtmltopdf='C:\\Python27\\wkhtmltopdf\bin\\wkhtmltopdf.exe') pdfkit.from_url('http://google.com', 'out.pdf')
為了在前端一點擊生成pdf下面就是顯示pdf文件直接點擊查看
#pdf版本導入 def html_str(html_str): import pdfkit print "in export pdf" options = { 'page-size': 'A3', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8", 'no-outline': None } # css = {} config = pdfkit.configuration(wkhtmltopdf='D:\\pdf\\wkhtmltopdf\\bin\\wkhtmltopdf.exe') file = pdfkit.from_string(html_str, False, options=options, configuration=config)#字符串方式 return file
里面還運用到了django 模板渲染功能,如果是使用字符串方式的話,可以使用這個方法,簡單方便。。。。
#pdf調用方式 def export_pdf(request, pk): quotation_id = pk t = TemplateResponse(request, 'quotation.html', locals()) t.render() # print t.content file = html_str(t.content) response = StreamingHttpResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="product.pdf"' return response
ps:
win7 64位系統下,
第一步:
下載下面鏈接中
https://wkhtmltopdf.org/downloads.html
Windows (MinGW) 0.12.4 32-bit / 64-bit for Windows XP/2003 or later; standalone
pip install pdfkit
安裝到路徑:
D:\software\wkhtmltopdf
打開控制面板
系統變量Path中加入
D:\software\wkhtmltopdf\bin
與其他路徑用";"隔開