Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

แปลง HTML เป็น PDF ด้วย Python (pdfkit, wkhtmltopdf)


ใช้ pdfkit` (wrapper ของ `wkhtmltopdf`) แปลง HTML เป็น PDF

การติดตั้ง

pip install pdfkit
# Ubuntu/Debian:
sudo apt-get install wkhtmltopdf
# Windows: ดาวน์โหลด wkhtmltopdf และเพิ่ม PATH

3 วิธีการแปลง

  1. จากไฟล์ HTML: pdfkit.from_file('input.html', 'output.pdf')
  2. จาก URL: pdfkit.from_url('https://example.com', 'output.pdf')
  3. จากสตริง: pdfkit.from_string('HTML content', 'output.pdf')

ตัวอย่างโค้ด

import pdfkit

# 1. ไฟล์ HTML
pdfkit.from_file('my_test.html', 'my_output.pdf')

# 2. URL
pdfkit.from_url('https://www.google.co.in/', 'my_testpdf.pdf')

# 3. String
pdfkit.from_string('

Hello PDF

', 'testpdf.pdf')