flask คือ เป็นตัวที่ใช้สำหรับการสร้างเว็บไซต์ ซึ่งสามารถใช้จัดการหน้าเว็บไซต์ wkhtmltopdf คือ เป็นโปรแกรมที่ใช้สำหรับการนำ HTML มาแปลงเป็น PDF นะครับ สำหรับคนที่กำลังหา วิธีการนำไฟล์ html มาแปลงเป็น pdf นะครับ ผมมีวิธีมาแชร์ แต่ที่จริงแล้ว ตัว wkhtmltopdf สามารถนำ linkurl ของหน้าเว็บไซต์มาแปลงได้เลยก็ได้ แต่วันนี้ผมจะมาแชร์ในการ upload file เข้ามาแปลงนะครับวิธีมีดังนี้นะครับ และมีในรูปแบบของ cURL อีกด้วยครับ
รูปแบบ curl มีคำสั่งดังนี้
Code: Select all
curl -i -X POST -F fileupload=@[ชื่อไฟล์ html ] http://localhost:5000/upload
ตัวอย่าง
Code: Select all
curl -i -X POST -F fileupload=@google.html http://localhost:5000/upload
Code: Select all
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>TEST</h3>
<h3>HTML</h3>
<h3>convert</h3>
<h3>PDF</h3>
</body>
</html>
Code: Select all
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="fileupload" placeholder="password" class="form-control" id="password" required><br>
<input type="submit" value="upload" class="btn btn-success">
</form>
</body>
</html>
Code: Select all
from flask import Flask, request,url_for, render_template, send_file
import os ,subprocess
UPLOAD_FOLDER = '/home/com001/PycharmProjects/test1/uploads'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/')
def index():
return render_template('home.html')
@app.route("/upload", methods=['POST'])
def uploaded():
if request.method == 'POST':
f = request.files['fileupload']
f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
path_bin = 'wkhtmltopdf'
str ='test.pdf'
fileupload =os.path.join('uploads/', f.filename)
path = os.path.join('pdf/', str)
subprocess.call([path_bin,fileupload,path])
path_sh = 'pdf/' + str
response = send_file(path_sh)
response.headers['Content-Type'] = 'application/pdf'
response.headers['Content-Disposition'] = 'inline; filename=download.pdf'
return response
if __name__ == '__main__':
app.run(debug=True)
Code: Select all
UPLOAD_FOLDER = '/home/com001/PycharmProjects/test1/uploads'
http://www.gastonsanchez.com/visually-enforced/how-to/2017/11/10/Converting-HTML-files-to-PDF/
https://www.wkhtmltopdf.org/