[python-win32] Use of streams than path in `wc.Dispatch("Word.Application").Documents.Open(docx_path)

Vishesh Mangla manglavishesh64 at gmail.com
Sun Mar 14 00:44:02 EST 2021


class PrepMessage:
    def __init__(self):
        self.msg = EmailMessage()
        self.templates = {}

    def _get_template(self, template_path):

        try:
            return copy.deepcopy(self.templates[template_path])
        except KeyError:
            with open(template_path, "rb") as f:
                source_stream = StringIO(f.read())
            self.templates[template_path] = DocxTemplate(source_stream)
            source_stream.close()

            return self.templates[template_path]

    def _get_html_string(self, html_path):
        """ Read message html file"""
        if html_path[-1] == "l":
            html_path = html_path[-1]
        with codecs.open(html_path, "r") as fp:
            stream = fp.read()
        os.remove(html_path)
        return stream

    def _get_mime(self, path):
        mime = mimetypes.guess_type(path)[0]
        if mime:
            return mime
        elif path.endswith(".rar"):
            return "application/x-rar-compressed"
        else:
            raise TypeError("Filetype not supported invalid")

    def __setitem__(self, name, val, *args, **kwargs):
        if name == "To":
            self.msg.__setitem__("To", self._get_formatted_to(val))
        elif name == "Subject":
            self.msg.__setitem__("Subject", self
._get_formatted_subject(val))

        elif name == "From":
            self.msg.__setitem__("From", self._get_formatted_from(val))

    def _get_formatted_to(self, to):
        return ", ".join([i.strip() for i in to.split(",")])

    def _get_formatted_subject(self, subject):
        return subject

    def _get_formatted_from(self, from_):
        return from_

    def add_attachments(self, attachments):
        for file_ in map(lambda x: x.strip(), attachments.split(",")):

            if os.path.exists(file_):
                with open(file_, "rb") as fp:

                    file_name = pathlib.Path(file_).name
                    maintype, subtype = self._get_mime(file_name).split("/")
                    self.msg.add_attachment(
                        fp.read(),
                        maintype=maintype,
                        subtype=subtype,
                        filename=file_name,
                    )

    def _get_path_of_converted_word_to_html(self, docx_string_io):
        TODO:
        word = wc.Dispatch("Word.Application")
        doc = word.Documents.Open(docx_path)
        html_path = "a.html"
        doc.SaveAs(html_path, 8)

        doc.Close()
        word.Quit()
        os.remove(docx_path)
        return html_path

    def add_alternative(self, docx_template_path, context):
        template = self._get_template(docx_template_path)
        template.render(context)

        target_stream = StringIO()
        template.save(target_stream)



        self.msg.add_alternative(
             self._get_html_string(
            self._get_path_of_converted_word_to_html(Path(word_doc))
        ),
            subtype="html",
        )


On Sun, Mar 14, 2021 at 11:10 AM <manglavishesh64 at gmail.com> wrote:

>
>
> To convert docx to html , one would do
>
> word = wc.Dispatch("Word.Application")
>
> doc = word.Documents.Open(docx_path)
>
> doc.SaveAs(html_path, 8)
>
> But here we require paths. I am using python-docx-template . I read a
> docx file, template it, then save to a StringIO(). But now I have to first
> save the doc as .docx, then open it and then create .html files, then deal
> with PermissionErrors. How can I use the StringIO() in place of paths.
> Something like this:
>
>
>
> word = wc.Dispatch("Word.Application")
>
> doc = word.Documents.Open(docx_string_io)
>
> doc.SaveAs(html_stream, 8)
>
>
>
>
>
> Sent from Mail <https://go.microsoft.com/fwlink/?LinkId=550986> for
> Windows 10
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/python-win32/attachments/20210314/5a017689/attachment-0001.html>


More information about the python-win32 mailing list