Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pywin32 save .docx as pdf

I'm using Word 2013 to automatically create a report as a docx and then save it as a pdf format.

But when I call the function SaveAs2(), the script pop out the "save as" windows and throws this exception :

(-2147352567, 'Exception occurred.', (0, u'Microsoft Word', u'Command failed', u'wdmain11.chm', 36966, -2146824090), None)

Here is my code to open and to save as a new file:

self.path = os.path.abspath(path)

self.wordApp = win32.Dispatch('Word.Application')  #create a word application object
self.wordApp.Visible = False  # if false hide the word application (app does't open but still usable)

self.document = self.wordApp.Documents.Open(self.path + "/" + documentRef)  # opening the template file



absFileName = "D:\\test.pdf"
        self.document.SaveAs2(FileName=absFileName,FileFormat=17)

And I'm using : python2.7 with pywin32 (build 219)

Does someone had an idea why it doesn't work?

like image 337
RenShan Avatar asked May 27 '15 11:05

RenShan


People also ask

How do I convert a DOCX to PDF in Python?

You can use the docx2pdf python package to bulk convert docx to pdf. It can be used as both a CLI and a python library. It requires Microsoft Office to be installed and uses COM on Windows and AppleScript (JXA) on macOS. Just used your package to print my .

How do I convert a DOCX file to PDF in Linux?

If you have either of the above mentioned software installed on your system, open terminal and run the following command to install cups-pdf utility. Then navigate to System > Administration > Printing in Linux system. Create a new printer, set it as a PDF file printer, and name it as “pdf”.


1 Answers

There are a couple of nice libraries to handle this task:

  • python-docx
  • xtopdf

There is also an example of doing exactly this in this ActiveState Recipe Convert Microsoft Word files to PDF with DOCXtoPDF


If you insist on using Windows API(s) there is also an example of doing this via win32com in this recipe Convert doc and docx files to pdf


You could also do this using comtypes (Thanks to .doc to pdf using python)

Example:

import os
import sys


import comtypes.client


wdFormatPDF = 17


def covx_to_pdf(infile, outfile):
    """Convert a Word .docx to PDF"""

    word = comtypes.client.CreateObject('Word.Application')
    doc = word.Documents.Open(infile)
    doc.SaveAs(outfile, FileFormat=wdFormatPDF)
    doc.Close()
    word.Quit()
like image 67
James Mills Avatar answered Oct 18 '22 04:10

James Mills