简体   繁体   中英

Python- How to add text on desired coordinates on new word file

If the size of the document (.doc) say 1000x3000 (WidthxHeight), I need to place a text "Hello" at 400X300 coordinate points.

How to do it using python + any libraries? (Ubuntu platform)

Similar kind of problem has been addressed using Java How to add text on desired coordinates on new word file using openxml

You can't place regular text at an arbitrary position. But you can use a textbox instead. Make sure to set top and left margins to 0. The top left corner of the text will then be at the specified coordinates.

Unfortunately, Python-docx doesn't support floating shapes . But you can do it using COM Automation on a Windows computer where Word is installed. You need PyWin32 which can also be downloaded from here .

import win32com.client as win32

word = win32.gencache.EnsureDispatch('Word.Application')
doc = word.Documents.Add()

tb = doc.Shapes.AddTextbox(1, 400, 300, 100, 100)
tb.TextFrame.TextRange.Text = "Hello"
tb.TextFrame.MarginTop = 0
tb.TextFrame.MarginLeft = 0
tb.Fill.Visible = 0
tb.Line.Visible = 0

doc.SaveAs2("Hello.docx")
doc.Close()
word.Application.Quit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM