tiến hành thực hiện lưu giống hệt word và tích hợp tính năng in luôn. có thể tải về lưu offile
Đây là cách mình khuyên nếu bạn muốn preview giống Word nhất mà vẫn dùng Python + Flask. Rất nhiều hệ thống quản lý tài liệu sử dụng mô hình này.
Kiến trúc
Người dùng nhập dữ liệu
│
▼
python-docx
│
▼
Tạo file .docx tạm
│
▼
LibreOffice Headless
│
▼
file.pdf
│
▼
pdf.js
│
▼
Preview trên Web
Bước 1. Cài LibreOffice
Download
https://www.libreoffice.org/download/download-libreoffice/
Cài bình thường.
Thông thường sẽ nằm ở
C:\Program Files\LibreOffice\program\
Trong đó có
soffice.exe
Bước 2. Test convert
Ví dụ có
D:\temp\bienban.docx
Mở CMD
"C:\Program Files\LibreOffice\program\soffice.exe" ^
--headless ^
--convert-to pdf ^
"D:\temp\bienban.docx" ^
--outdir D:\temp
Nếu thành công sẽ hiện
convert D:\temp\bienban.docx -> D:\temp\bienban.pdf
Bước 3. Python
Ví dụ
import subprocess
LIBREOFFICE = r"C:\Program Files\LibreOffice\program\soffice.exe"
def convert_to_pdf(docx_file, output_folder):
subprocess.run([
LIBREOFFICE,
"--headless",
"--convert-to",
"pdf",
docx_file,
"--outdir",
output_folder
], check=True)
Gọi
convert_to_pdf(
r"D:\temp\hoso.docx",
r"D:\temp"
)
Sẽ sinh
hoso.pdf
Bước 4. Flask
Ví dụ route
@app.route("/preview/pdf/<int:id>")
def preview_pdf(id):
pdf_path = tao_pdf(id)
return send_file(
pdf_path,
mimetype="application/pdf"
)
Bước 5. Front-end
Thay
docx-preview
bằng
pdf.js
Import
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/5.4.54/pdf.min.mjs" type="module"></script>
Hoặc đơn giản hơn
<iframe
src="/preview/pdf/15"
width="100%"
height="100%">
</iframe>
Là đã xem được.
Bước 6. Live Preview
Hiện nay bạn đang
Input
↓
POST
↓
python-docx
↓
docx-preview
Đổi thành
Input
↓
POST
↓
python-docx
↓
temp.docx
↓
LibreOffice
↓
temp.pdf
↓
Trả PDF
↓
pdf.js
Tốc độ
LibreOffice chạy khá nhanh.
Ví dụ biên bản 5~10 trang
DOCX
↓
≈ 0.3~1 giây
Nếu mỗi lần gõ một ký tự lại convert thì sẽ hơi chậm. Nên:
- Chờ người dùng ngừng gõ khoảng 500–800 ms rồi mới tạo lại PDF.
- Hoặc có nút "Làm mới xem trước" nếu tài liệu rất lớn.
Cách chuyên nghiệp hơn (nên dùng)
Thay vì mỗi lần mở đều khởi động LibreOffice, hãy chạy LibreOffice ở chế độ listener (dịch vụ nền):
"C:\Program Files\LibreOffice\program\soffice.exe" ^
--headless ^
--accept="socket,host=127.0.0.1,port=2002;urp;"
Sau đó Python kết nối tới LibreOffice đang chạy sẵn để chuyển đổi. Cách này nhanh hơn nhiều vì không phải khởi động soffice.exe mỗi lần.
Với hệ thống của bạn
Bạn đang phát triển một hệ thống quản lý biên bản thí nghiệm bằng Flask + python-docx, nên mình đề xuất kiến trúc sau:
Word Template (.docx)
│
python-docx
│
temp.docx
│
LibreOffice Headless (listener)
│
temp.pdf
│
pdf.js Viewer
│
Preview gần như giống hệt Microsoft Word
Kiến trúc này còn có lợi thế là sau này bạn có thể dễ dàng bổ sung ký số PDF, đóng dấu, in ấn hoặc lưu trữ hồ sơ điện tử mà không cần thay đổi nhiều trong hệ thống.

