This article is simultaneously published on my wechat official account. You can follow it by scanning the QR code at the bottom of the article or searching for geek navigation on wechat.

General situation of

In daily work and life, sometimes the need is to convert HTML into PDF, there are many online tools, but generally online conversion or only one transfer, and even some tools need to recharge….

The preparatory work

The library we use today is: PDfKit installation: PDfKit

pip install pdfkit
Copy the code

Install on your own operating system: wkhtmlTopdf

Ubuntu

sudo apt-get install wkhtmltopdf
Copy the code

Mac

brew install Caskroom/cask/wkhtmltopdf
Copy the code

CentOS

sudo yum intsall wkhtmltopdf
Copy the code

windows

Download address: https://wkhtmltopdf.org/downloads.html and configure the system environment variablesCopy the code

### begin conversion

import pdfkit

pdfkit.from_url('https://www.jianshu.com'.'out.pdf')    
Copy the code

It seems to work pretty well, and it supports a lot

Local Html file

import pdfkit

pdfkit.from_file('jianshu.htm'.'out.pdf')   

Copy the code

string

import pdfkit
 
pdfkit.from_string('HelloWorld'.'out.pdf')
Copy the code

Open the file

import pdfkit

with open('jianshu.htm'.'r') as f:
	pdfkit.from_file(f,'out.pdf')   

Copy the code

Multiple HTML conversions simultaneously

import pdfkit

pdfkit.from_url(['https://www.jianshu.com/'.'https://www.baidu.com/'].'out.pdf')

#pdfkit.from_file(['jianshu.htm','jianshu1.htm'],'out.pdf')  
Copy the code

Custom parameters

If the above parameters do not meet your requirements, some parameters can be customized:

import pdfkit
options={
   'page-size':'A4'.#Letter
    'margin-top':'0.75 in'.'margin-right':'0.75 in'.'margin-bottom':'0.75 in'.'margin-left':'0.75 in'.'encoding':"UTF-8".'no-outline':None
}    
pdfkit.from_url('https://www.jianshu.com/'.'out1.pdf', options=options)

Copy the code

It’s a powerful tool with lots of parameters and methods, but the general requirements are pretty much covered. If you need more depth, you can refer to the following documents:

Pdfkit documentation: pypi.org/project/pdf… Wkhtmltopdf parameters: www.kongzhizhen.com/%E7%94%9F%E…

The following is the qr code picture of my official account, welcome to follow.