Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Hướng dẫn tạo paragraph và chèn hình ảnh vào Word với python-docx

Giới thiệu

File Word hoạt động dựa trên paragraph (đoạn văn), không có khái niệm "trang". Để chia trang, dùng page break hoặc section break. Bài viết hướng dẫn tạo document, thêm paragraph, xuống dòng, chèn hình ảnh và resize.

Cài đặt

pip install python-docx requests

Tạo document và thêm paragraph

import docx

doc = docx.Document()

# Thêm paragraph đầu tiên
para = doc.add_paragraph('1. Hello World, Some Sample Text Here...')

# Thêm run (đoạn văn bản cùng style) và xuống dòng
run = para.add_run()
run.add_break(docx.text.run.WD_BREAK.LINE)

# Tiếp tục thêm text vào cùng paragraph
para.add_run('2. I have just written my 2nd line and I can write more...')

# Lưu file
doc.save('My_Amazing_WordDoc.docx')

Kiểm tra file vừa tạo

doc = docx.Document('My_Amazing_WordDoc.docx')
print(f'Document has {len(doc.paragraphs)} paragraphs')
for i, para in enumerate(doc.paragraphs):
    if para.text.strip():
        print(f'{i}: {para.text}')

Chèn hình ảnh từ URL

import requests
from docx.shared import Cm

# Tải ảnh từ GitHub (copyright free từ unsplash)
url = 'https://raw.githubusercontent.com/sasankac/TestDataSet/master/Tree.jpg'
response = requests.get(url)
with open('Tree.jpg', 'wb') as f:
    f.write(response.content)

# Thêm ảnh vào document
doc = docx.Document('My_Amazing_WordDoc.docx')
img = doc.add_picture('Tree.jpg')
print(f'Original size: {img.width}, {img.height}')  # EMU units

# Resize ảnh (10cm x 10cm)
img.width = Cm(10)
img.height = Cm(10)
print(f'New size: {img.width}, {img.height}')

doc.save('report.docx')

Lưu ý quan trọng

  • Đơn vị mặc định của python-docx là EMU (English Metric Unit): 1 cm = 360,000 EMU.
  • Dùng docx.shared.Cm, Inches, Pt, Em để đổi đơn vị dễ dàng.
  • add_picture() tạo paragraph mới chứa ảnh.
  • Để ảnh và text cùng dòng: thêm ảnh vào run của paragraph: run.add_picture().

Code hoàn chỉnh

import requests
import docx
from docx.shared import Cm

# 1. Tải ảnh
url = 'https://raw.githubusercontent.com/sasankac/TestDataSet/master/Tree.jpg'
img_data = requests.get(url).content
with open('Tree.jpg', 'wb') as f:
    f.write(img_data)

# 2. Tạo document mới
doc = docx.Document()

# 3. Thêm text
para = doc.add_paragraph('Báo cáo kết quả test')
run = para.add_run('\nNgày test: 2024-01-15')
run.bold = True

# 4. Thêm ảnh và resize
img = doc.add_picture('Tree.jpg', width=Cm(12))  # Chỉ set width, height tự scale

# 5. Thêm page break và nội dung mới
doc.add_page_break()
doc.add_paragraph('Trang 2: Chi tiết lỗi...')

# 6. Lưu
doc.save('report.docx')
print('Đã tạo report.docx')

Kết quả

File report.docx chứa: text có format, ảnh 12cm rộng, ngắt trang, nội dung trang 2.