การใส่รูปภาพใน word ด้วย python

แชร์ความรู้ภาษา Python ไพทอน การเขียนโปรแกรมภาษาไพทอน

Moderator: mindphp, ผู้ดูแลกระดาน

kritsadak
PHP Full Member
PHP Full Member
โพสต์: 30
ลงทะเบียนเมื่อ: 24/12/2018 10:18 am

การใส่รูปภาพใน word ด้วย python

โพสต์ที่ยังไม่ได้อ่าน โดย kritsadak »

ในบทความนี้เมื่อเราสามารถสร้าง word เองได้แล้ว และต้องการจะใส่ส่วนประกอบของเนื้อหา เช่น รูปภาพก็สามารถทำได้เช่นกันด้วยภาษา python

โค้ด: เลือกทั้งหมด

from docx import Document				# Library ของ docx ที่ใช้
from docx.shared import Inches, Cm			# Library ของ docx เป็นหน่วยนิ้ว และเซนติเมตร
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH	# Library ของ docx รูปแบบของ paragraph
from docx.enum.section import WD_ORIENT		# Library ของ docx รูปแบบของหน้ากระดาษ
document = Document()
name = "Yourname Lastname"				# สร้างชื่อตัวแปรในรูปแบบ String
scale = "picture Y910"					# สร้างชื่อตัวแปรในรูปแบบ String
sections = document.sections
sections.orientation = WD_ORIENT.LANDSCAPE		# ตั้งค่าหน้ากระดาษให้เป็นแนวนอน
for section in sections:					# ตั้งค่าให้เป็นรูปแบบ 5ซม x10 ซม
  section.page_height = Cm(5)				# ความสูง
  section.page_width = Cm(10)				# ความกว้าง
  section.top_margin = Cm(0.2)				# ระยะห่างขอบบน
  section.bottom_margin = Cm(0)			# ระยะห่างขอบล่าง
  section.left_margin = Cm(0.5) 				# ระยะห่างขอบซ้าย
  section.right_margin = Cm(0.5) 			# ระยะห่างขอบขวา
print ("create WORD.....")
FIRSTLINE = document.add_paragraph(name)		# โค้ดส่วนที่ 1 ของการเพิ่มข้อมูลลงใน word
paragraph_format = FIRSTLINE.paragraph_format
FIRSTLINE.style = 'Heading 2'
SECONDLINE = document.add_paragraph(scale)		# โค้ดส่วนที่ 2 ของการเพิ่มข้อมูลลงใน word
picture = "Y910.png"					# ไฟล์รูปภาพ
THIRDLINE = document.add_picture(picture, width =Cm(2.4), height = Cm(2.0))	# ใส่รูปภาพลงไป พร้อมกับตั้งขนาดรูปภาพ
THIRDLINE = document.paragraphs[-1]
THIRDLINE.alignment = WD_ALIGN_PARAGRAPH.CENTER	# ตั้งค่ารูปภาพให้อยู่กึ่งกลาง
print ("Add picture.....")
filename = ('word.docx') 				# ชื่อไฟล์ที่ต้องการจะบันทึก
filepath = r'C:/Users/ksdkd/Desktop/'+filename		# ที่อยู่ของไฟล์ที่ต้องการจะบันทึก
document.save(filepath)
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 39