63 lines
2.7 KiB
Python
63 lines
2.7 KiB
Python
from Lib.lcfc_lib import *
|
|
from Lib.action_base import ActionBase
|
|
import docx
|
|
|
|
|
|
class ActionDocx(ActionBase):
|
|
docx_create = 1
|
|
docx_modify = 2
|
|
docx_insert = 3
|
|
|
|
def __init__(self, **kwargs):
|
|
super().__init__()
|
|
self.sub_function = kwargs['sub_function']
|
|
if self.sub_function == ActionDocx.docx_create:
|
|
self.file = kwargs['file']
|
|
self.content = kwargs['content']
|
|
elif self.sub_function == ActionDocx.docx_modify:
|
|
self.file = kwargs['file']
|
|
self.string_map = kwargs['string_map']
|
|
elif self.sub_function == ActionDocx.docx_insert:
|
|
self.input_data = kwargs.get('input_data')
|
|
self.input_file = kwargs.get('input_file')
|
|
self.dst_file = kwargs['dst_file']
|
|
self.start_str = kwargs.get('start_str')
|
|
self.end_str = kwargs.get('end_str')
|
|
self.insert_count = kwargs['insert_count']
|
|
|
|
def action(self, count, action_str):
|
|
super().action(count, action_str)
|
|
|
|
if self.sub_function == ActionDocx.docx_create:
|
|
pass # TODO
|
|
elif self.sub_function == ActionDocx.docx_modify:
|
|
doc = docx.Document(self.file)
|
|
for para in doc.paragraphs:
|
|
for key, value in self.string_map.items():
|
|
para.text = para.text.replace(key, value)
|
|
doc.save(self.file)
|
|
elif self.sub_function == ActionDocx.docx_insert:
|
|
if self.input_data is not None:
|
|
input_data = self.input_data
|
|
elif self.input_file is not None:
|
|
with open(self.input_file) as f:
|
|
input_data = f.read()
|
|
doc = docx.Document(self.dst_file)
|
|
for _i, _data in enumerate(doc.paragraphs):
|
|
if self.start_str is not None and self.end_str is not None:
|
|
if doc.paragraphs[_i].text == self.start_str and doc.paragraphs[_i + 1].text == self.end_str\
|
|
and self.insert_count:
|
|
doc.paragraphs[_i + 1].insert_paragraph_before(input_data)
|
|
self.insert_count -= 1
|
|
elif self.start_str is not None:
|
|
if doc.paragraphs[_i].text == self.start_str and self.insert_count:
|
|
doc.paragraphs[_i + 1].insert_paragraph_before(input_data)
|
|
self.insert_count -= 1
|
|
elif self.end_str is not None:
|
|
if doc.paragraphs[_i].text == self.end_str and self.insert_count:
|
|
doc.paragraphs[_i].insert_paragraph_before(input_data)
|
|
self.insert_count -= 1
|
|
doc.save(self.dst_file)
|
|
|
|
return
|