Cách thêm số trang vào tài liệu với python-docx trong Python
Để thêm chữ “Trang” trước số trang dạng “Trang 1/5” trong Header của tài liệu Word bằng thư viện python-docx
, bạn có thể sử dụng OxmlElement
để thêm các field code và văn bản vào tài liệu.
![](https://www.vniteach.com/wp-content/uploads/2023/11/python.jpeg.pagespeed.ce_.5dXdsrTOcm.jpg)
Dưới đây là một ví dụ cụ thể để thêm số trang vào Header của tài liệu Word bằng python-docx
:
from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
# Tạo một tài liệu mới
doc = Document()
# Thêm section cuối cùng
section = doc.sections[-1]
# Tạo Header cho section này
header = section.header
# Tạo một đối tượng Paragraph trong Header
paragraph = header.paragraphs[0] if header.paragraphs else header.add_paragraph()
# Thiết lập căn chỉnh cho đoạn văn bản trong header là bên phải
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
# Thêm text "Trang " vào Paragraph
run = paragraph.add_run('Trang ')
# Thêm text vào Paragraph, sử dụng OxmlElement để thêm PAGE field
field_code = ' PAGE '
fld_xml = OxmlElement('w:fldSimple')
fld_xml.set(qn('w:instr'), field_code)
run._r.append(fld_xml)
# Thêm dấu "/" để phân tách giữa số trang hiện tại và tổng số trang
run.add_text('/')
# Thêm field NUMPAGES để hiển thị tổng số trang
fld_xml = OxmlElement('w:fldSimple')
fld_xml.set(qn('w:instr'), ' NUMPAGES ')
run._r.append(fld_xml)
# Thiết lập cỡ chữ cho số trang là 12pt
run.font.size = Pt(12)
# Lưu tài liệu với tên file 'document_with_page_number.docx'
doc.save('document_with_page_number.docx')
Giải thích:
- Chúng ta sử dụng
paragraph.add_run('Trang ')
để thêm văn bản “Trang ” vào Paragraph. - Sau đó, sử dụng
OxmlElement
để thêm các field code{ PAGE }
và{ NUMPAGES }
vào tài liệu như đã làm trước đó. OxmlElement
được sử dụng để tạo và thiết lập các phần tử XML chứa các field code nhưfldSimple
với các mã lệnh{ PAGE }
và{ NUMPAGES }
.- Thiết lập cỡ chữ cho số trang là 12pt bằng cách sử dụng
run.font.size = Pt(12)
.
Khi bạn chạy đoạn mã này và mở tệp document_with_page_number.docx
, bạn sẽ thấy số trang dạng “Trang 1/5” ở phần Header bên phải của tài liệu Word, với chữ “Trang” đi trước số trang.