ভূমিকা
ডেটা ইঞ্জিনিয়ারিং-स্পেশালিস্ট হয়ে টেস্টারদের থেকে টেস্ট রেজাল্ট ওয়ার্ডে পাই। একদিন টেস্টিং টিম আমাকে টুল-জেনারেটেড টেক্সট ও অটোমেটিক স্ক্রিনশট (এখানে কভার করা নয়) ওয়ার্ডে ইনসার্ট করার প্রোগ্রাম লিখতে বলল।
MS Word ডকুমেন্টে পেজ কনসেপ্ট নেই, এটি প্যারাগ্রাফ-ভিত্তিক কাজ করে। তাই ব্রেক এবং সেকশন ব্যবহার করে ডকুমেন্ট ভাগ করতে হয়।
কীভাবে করবেন
python-docxইনস্টল করুন:pip install python-docx- নতুন ডকুমেন্ট তৈরি করে প্যারাগ্রাফ ও লাইন ব্রেক যোগ করুন:
import docx WordDocx = docx.Document() Paragraph = WordDocx.add_paragraph('1. Hello World, Some Sample Text Here...') run = Paragraph.add_run() run.add_break(docx.text.run.WD_BREAK.LINE) Paragraph.add_run('2. I have just written my 2nd line and I can write more..') WordDocx.save('My_Amazing_WordDoc.docx') - প্রোগ্রামেটিক্যালি ভেরিফাই করুন:
আউটপুট:doc = docx.Document('My_Amazing_WordDoc.docx') print(f"output \n *** Document has {len(doc.paragraphs)} - paragraphs") for paragraph_number, paragraph in enumerate(doc.paragraphs): if paragraph.text: print(f"\n {paragraph.text}")*** Document has 1 - paragraphs 1. Hello World, Some Sample Text Here... 2. I have just written my 2nd line and I can write more..
- ইমেজ ডাউনলোড করে ডকুমেন্টে যোগ করুন:
import requests from docx.shared import Cm response = requests.get("https://raw.githubusercontent.com/sasankac/TestDataSet/master/Tree.jpg") image = open("Tree.jpg", "wb") image.write(response.content) image.close() image_to_add = doc.add_picture("Tree.jpg") print(f"output \n *** MY Image has width = {image_to_add.width} and Height as - {image_to_add.height}") image_to_add.width = Cm(10) image_to_add.height = Cm(10) print(f" *** My New dimensions Image has width = {image_to_add.width} and Height as - {image_to_add.height}") doc.save('report.docx')
সম্পূর্ণ কোড
import requests
from docx.shared import Cm
response = requests.get("https://raw.githubusercontent.com/sasankac/TestDataSet/master/Tree.jpg")
image = open("Tree.jpg", "wb")
image.write(response.content)
image.close()
doc = docx.Document()
image_to_add = doc.add_picture("Tree.jpg")
image_to_add.width = Cm(10)
image_to_add.height = Cm(10)
doc.save('report.docx')