def makeRealWordDoc(infile, outfile): word = gencache.EnsureDispatch("Word.Application") try: worddoc = word.Documents.Open(FileName=infile) try: worddoc.TablesOfContents.Add(Range=word.ActiveWindow.Selection.Range, \ RightAlignPageNumbers=1, \ UseHeadingStyles=1, \ UpperHeadingLevel=1, \ LowerHeadingLevel=2, \ IncludePageNumbers=1, \ AddedStyles='', \ UseHyperlinks=1, \ HidePageNumbersInWeb=1) worddoc.TablesOfContents(1).TabLeader = constants.wdTabLeaderDots worddoc.TablesOfContents.Format = constants.wdIndexIndent word.ActiveWindow.ActivePane.View.SeekView = constants.wdSeekCurrentPageHeader word.Selection.TypeText( Text="Dive Into Python\t\thttp://diveintopython.org/") word.ActiveWindow.ActivePane.View.SeekView = constants.wdSeekCurrentPageFooter word.NormalTemplate.AutoTextEntries("- PAGE -").Insert( Where=word.ActiveWindow.Selection.Range) word.ActiveWindow.View.Type = constants.wdPrintView worddoc.TablesOfContents(1).Update() worddoc.SaveAs(FileName=outfile, \ FileFormat=constants.wdFormatDocument) finally: worddoc.Close(0) del worddoc finally: word.Quit() del word
def __init__(self): self.folders = DictList("folders") gencache.EnsureDispatch("Outlook.Application") ConnectionGrammar.__init__(self, name="outlook control", context=AppContext(executable="outlook"), app_name="Outlook.Application")
def onDrag(self, event): data = wx.FileDataObject() obj = event.GetEventObject() dropSource = wx.DropSource(obj) dropSource.SetData(data) #next line will make the drop target window come to top, allowing us #to get the info we need to do the work, if it's Explorer result = dropSource.DoDragDrop(0) #get foreground window hwnd h = win32gui.GetForegroundWindow() #get explorer location s = gencache.EnsureDispatch('Shell.Application') #s = win32com.client.Dispatch("Shell.Application") loc, outdir = None, None for w in s.Windows(): if int(w.Hwnd) == h: loc = w.LocationURL if loc: outdir = loc.split('///')[1] #print (outdir) outdir = unquote(outdir) print(outdir) #got what we need, now download to outfol #if outdir and os.path.isdir(outdir): # self.dloadItems(event, outdir) return
def word2pdf(): ''' (1) 转换当前目录下的 word 为 pdf ''' if not os.path.isdir(g_output_path): os.mkdir(g_output_path) # 创建目录 names = os.listdir(g_path) word_list = [name for name in names if name.endswith(('.doc', '.docx'))] pdf_list = [name for name in names if name.endswith('.pdf')] word = gencache.EnsureDispatch('Word.Application') # 调用 word 的 API for word_name in word_list: print('---开始转换:', word_name) pdf_name = os.path.splitext(word_name)[0]+'.pdf' if pdf_name in pdf_list: continue word_path = g_path+'/' + word_name pdf_path = g_output_path+'/'+pdf_name try: doc = word.Documents.Open(word_path, ReadOnly=1) doc.ExportAsFixedFormat(pdf_path, constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) except Exception as e: print('---转换失败,异常是:{}'.format(e)) finally: print('---转换成功:', pdf_name) word.Quit(constants.wdDoNotSaveChanges) # 退出 print('---全部转换完毕')
def TestWord(): # Try and load the object exposed by Word 8 # Office 97 - _totally_ different object model! try: # NOTE - using "client.Dispatch" would return an msword8.py instance! print "Starting Word 8 for dynamic test" word = win32com.client.dynamic.Dispatch("Word.Application") TestWord8(word) word = None # Now we will test Dispatch without the new "lazy" capabilities print "Starting Word 8 for non-lazy dynamic test" dispatch = win32com.client.dynamic._GetGoodDispatch("Word.Application") typeinfo = dispatch.GetTypeInfo() attr = typeinfo.GetTypeAttr() olerepr = win32com.client.build.DispatchItem(typeinfo, attr, None, 0) word = win32com.client.dynamic.CDispatch(dispatch, olerepr) dispatch = typeinfo = attr = olerepr = None TestWord8(word) except pythoncom.com_error: print "Starting Word 7 for dynamic test" word = win32com.client.Dispatch("Word.Basic") TestWord7(word) print "Starting MSWord for generated test" from win32com.client import gencache word = gencache.EnsureDispatch("Word.Application.8") TestWord8(word)
def word2pdf(wordfile, pdffile): word = gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(wordfile, ReadOnly = 1) doc.ExportAsFixedFormat(pdffile, constants.wdExportFormatPDF, Item = constants.wdExportDocumentWithMarkup, CreateBookmarks = constants.wdExportCreateHeadingBookmarks) word.Quit(constants.wdDoNotSaveChanges)
def excel2pdf(self, excelPath, pdfPath): xlApp = gencache.EnsureDispatch('Excel.Application') xls = xlApp.Workbooks.Open(excelPath, ReadOnly=1) xls.ExportAsFixedFormat(0, pdfPath, Quality=constants.xlQualityStandard, IgnorePrintAreas=False) xlApp.Quit()
def word2PDF(wordFile, pdfFile): print(f'转换PDF: -->{pdfFile}') w = gencache.EnsureDispatch('Word.Application') doc = w.Documents.Open(wordFile, ReadOnly=1) doc.ExportAsFixedFormat(pdfFile, constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) w.Quit(constants.wdDoNotSaveChanges)
def Connect(): global NOTIFY, GATE #the below is required in order to establish the com-object links #that way you don't need to run makepy first gencache.EnsureModule('{A9595CA1-4980-11D5-ADF6-00508BAFB07F}', 0, 1, 0) GATE = gencache.EnsureDispatch('TradingTechnologies.TTAPI.TTAPI') NOTIFY = client.DispatchWithEvents('TTAPI.TTInstrNotify', InstrNotify) print('connected... ')
def word2pdf(self, wordPath, pdfPath): word = gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(wordPath, ReadOnly=1) doc.ExportAsFixedFormat( pdfPath, constants.wdExportFormatPDF, # OptimizeFor=constants.wdExportOptimizeForPrint, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) word.Quit(constants.wdDoNotSaveChanges)
def get_doc_props(sub, filer): _, ext = os.path.splitext(filer) if ext == ".xls" or ext == ".xlsx": xl = gencache.EnsureDispatch('Excel.Application') xl.visible = True ss = xl.Workbooks.Open(sub + "\\" + filer) props = ss.BuiltInDocumentProperties() print(props) info = os.stat(sub + "\\" + filer) print(info) ss.Close()
def load_com(*names): result = None for name in names: try: result = gencache.EnsureDispatch(name) break except com_error: continue if result is None: raise com_error("Unable to load any of the provided com objects.") return result
def docx_pdf(docx_path, pdf_path): #word_app = Dispatch("Word.Application") word_app = gencache.EnsureDispatch("Word.Application") try: doc = word_app.Documents.Open(docx_path, ReadOnly=1) doc.ExportAsFixedFormat(pdf_path, constants.wdExportFormatPDF,\ Item=constants.wdExportDocumentWithMarkup,\ CreateBookmarks=constants.wdExportCreateHeadingBookmarks) except Exception, err: #print err print str(err).decode("string_escape")
def merge_docx(src1_docx_path, src2_docx_path, dst_docx_path): #word_app = Dispatch("Word.Application") word_app = gencache.EnsureDispatch("Word.Application") try: output = word_app.Documents.Add() output.Application.Selection.Range.InsertFile(src2_docx_path) output.Application.Selection.Range.InsertFile(src1_docx_path) doc = output.Range(output.Content.Start, output.Content.End) output.SaveAs(dst_docx_path) output.Close() except Exception, err: #print err print str(err).decode("string_escape")
def test(): oldcwd = os.getcwd() try: session = gencache.EnsureDispatch("MAPI.Session") try: session.Logon(GetDefaultProfileName()) except pythoncom.com_error as details: print("Could not log on to MAPI:", details) return except pythoncom.error: # no mapi.session - let's try outlook app = gencache.EnsureDispatch("Outlook.Application") session = app.Session try: TestUser(session) TestAddress(session) DumpFolders(session) finally: session.Logoff() # It appears Exchange will change the cwd on us :( os.chdir(oldcwd)
def createPdf(wordPath, pdfPath): """ word转pdf :param wordPath: word文件路径 :param pdfPath: 生成pdf文件路径 """ word = gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(wordPath, ReadOnly=1) doc.ExportAsFixedFormat(pdfPath, constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) word.Quit(constants.wdDoNotSaveChanges)
def active_pres(): """ @visible: Set PowerPoint application window to visible Grabs the active PowerPoint application and creates a COM object representing the active presentation. """ try: p = win32Client.GetActiveObject("PowerPoint.Application") except com_error: p = win32ClientGen.EnsureDispatch("PowerPoint.Application") return p.ActivePresentation
def headfoot_docx(src_docx_path, template_docx_path, dst_docx_path): #word_app = Dispatch("Word.Application") word_app = gencache.EnsureDispatch("Word.Application") try: section0_header0 = None section0_footer0 = None output = word_app.Documents.Add() output.Application.Selection.Range.InsertFile(src_docx_path) outdoc = output.Range(output.Content.Start, output.Content.End) for section_index, section in enumerate(outdoc.Sections): for header_index, header in enumerate(section.Headers): #print 'section [%d], header [%d]'%(section_index, header_index) #print header.Range.Text section0_header0 = header break for footer_index, footer in enumerate(section.Footers): #print 'section [%d], footer [%d]'%(section_index, footer_index) #print footer.Range.Text section0_footer0 = footer break ############################################################### template_doc = word_app.Documents.Open(template_docx_path) for section_index, section in enumerate(template_doc.Sections): for header_index, header in enumerate(section.Headers): #print 'section [%d], header [%d]'%(section_index, header_index) #print header.Range.Text template_section0_header0 = header break for footer_index, footer in enumerate(section.Footers): #print 'section [%d], footer [%d]'%(section_index, footer_index) #print footer.Range.Text template_section0_footer0 = footer break #print template_section0_header0.Range.Text #print template_section0_footer0.Range.Text template_section0_header0.Range.Copy() section0_header0.Range.Paste() template_section0_footer0.Range.Copy() section0_footer0.Range.Paste() template_doc.Close() ################################################################ output.SaveAs(dst_docx_path) output.Close() except Exception, err: #print err print str(err).decode("string_escape")
def ppt_to_jpg(input_path, output_path): powerpoint = gencache.EnsureDispatch('Powerpoint.application') try: powerpoint.DisplayAlerts = 0 ppt = powerpoint.Presentations.Open(input_path) for i, slide in enumerate(ppt.Slides): slide.Select full_path = os.path.join(output_path, "%d.jpg" % i) slide.Export(full_path, "JPG") return 0 except Exception as e: traceback.format_exc() return 1 finally: powerpoint.Quit()
def word2Pdf(wordFile, pdfFile): try: print('Word Excel Export ...') word = gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(wordFile, ReadOnly=1) # input('Open ...') doc.ExportAsFixedFormat( pdfFile, constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) print("pdfFile:", pdfFile) word.Quit(constants.wdDoNotSaveChanges) except Exception as e: print(str(e))
def getOpenedFileObject(name): if name in comobj_cache: try: #http://stackoverflow.com/questions/3500503/check-com-interface-still-alive o = comobj_cache[name] o._oleobj_.GetTypeInfoCount() return o except: del comobj_cache[name] ctx, rot = pythoncom.CreateBindCtx(0), pythoncom.GetRunningObjectTable() for i in rot: if i.GetDisplayName(ctx, None) == name: comobj_cache[name] = gencache.EnsureDispatch( rot.GetObject(i).QueryInterface(pythoncom.IID_IDispatch)) return comobj_cache[name]
def convert_word_to_pdf(docx_path, pdf_path): """ 将word文档转换成pdf文件 """ CoInitialize() word = gencache.EnsureDispatch('Word.Application') word.Visible = 0 word.DisplayAlerts = 0 try: doc = word.Documents.Open(docx_path, ReadOnly=1) doc.ExportAsFixedFormat( pdf_path, constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) except Exception, e: print(e)
def ppt_to_pdf(filename, results): ''' ppt 和 pptx 文件转换 ''' name = os.path.basename(filename).split('.')[0] + '.pdf' exportfile = os.path.join(results, name) if os.path.isfile(exportfile): print(name, "已经转化了") return p = gencache.EnsureDispatch("PowerPoint.Application") try: ppt = p.Presentations.Open(filename, False, False, False) except Exception as e: print(os.path.split(filename)[1], "转化失败,失败原因%s" % e) ppt.ExportAsFixedFormat(exportfile, 2, PrintRange=None) print('保存 PDF 文件:', exportfile) p.Quit()
def processFile(filename, path, getter=None, always=False): if type(filename) == list: for f, g in zip(filename, getter): processFile(f, path, g, always) return working += 1 name, end = parseFileName(filename) if always == True or (end in [ 'doc', 'docx', 'pdf', 'zip', 'ppt', 'pptx', 'xls', 'xlsx', 'mp3' ]): if getter != None: tryTimes = 10 done = False for i in range(tryTimes): try: file = getter() done = True except BaseException as e: if tryTimes - i > 1: toaster.show_toast('%s下载失败' % filename[:8], '正在重试……') else: toaster.show_toast('%s下载失败' % filename[:8], '失败次数过多,请重新发送。') if done == True: break with open(os.path.join(path, filename), 'wb') as f: f.write(file) if end == 'doc' or end == 'docx': wps = gencache.EnsureDispatch('kwps.Application') doc = wps.Documents.Open(os.path.join(path, filename)) pdf = os.path.join(path, parseFileName(filename)[0] + '.pdf') doc.SaveAs(pdf, FileFormat=17) doc.Close() elif end == 'zip': manager = zipfile.ZipFile(os.path.join(path, filename)) fullnames = manager.namelist() filenames = [i.split('/')[-1] for i in fullnames] for index, i in enumerate(filenames): if i == '': del filenames[i] del fullnames[i] getters = [lambda f=i: manager.read(f) for i in fullnames] processFile(filenames, path, getters, always) elif end == 'pdf' or end == 'ppt' or end == 'pptx' or end == 'xls' or end == 'xlsx' or end == 'mp3': pass working -= 1
def word_2_pdf(wordPath: Path, pdfPath: Path): """ word转pdf :param wordPath: word文件路径 :param pdfPath: 生成pdf文件路径 """ try: pythoncom.CoInitialize() word = gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(str(wordPath), ReadOnly=1) doc.ExportAsFixedFormat(str(pdfPath), constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) word.Quit(constants.wdDoNotSaveChanges) return True except Exception as e: logger.info(e) return False
def to_excel(self, xl_app=None, resize_columns=True): from win32com.client import Dispatch, gencache if xl_app is None: xl_app = Dispatch("Excel.Application") xl_app = gencache.EnsureDispatch(xl_app) # Add a new workbook with the correct number of sheets. # We aren't allowed to create an empty one. assert self.worksheets, "Can't export workbook with no worksheets" sheets_in_new_workbook = xl_app.SheetsInNewWorkbook try: xl_app.SheetsInNewWorkbook = float(len(self.worksheets)) self.workbook_obj = xl_app.Workbooks.Add() finally: xl_app.SheetsInNewWorkbook = sheets_in_new_workbook # Rename the worksheets, ensuring that there can never be two sheets with the same # name due to the sheets default names conflicting with the new names. sheet_names = {s.name for s in self.worksheets} assert len(sheet_names) == len(self.worksheets), "Worksheets must have unique names" for worksheet in self.workbook_obj.Sheets: i = 1 original_name = worksheet.Name while worksheet.Name in sheet_names: worksheet.Name = "%s_%d" % (original_name, i) i += 1 for worksheet, sheet in zip(self.workbook_obj.Sheets, self.worksheets): worksheet.Name = sheet.name # Export each sheet (have to use itersheets for this as it sets the # current active sheet before yielding each one). for worksheet, sheet in zip(self.workbook_obj.Sheets, self.itersheets()): worksheet.Select() sheet.to_excel(workbook=self, worksheet=worksheet, xl_app=xl_app, rename=False, resize_columns=resize_columns) return self.workbook_obj
def doc2pdf(docPath, pdfPath): """ convert a doc/docx document to pdf format :param doc: path to document """ docPathTrue = os.path.abspath( docPath) # bugfix - searching files in windows/system32 pdfPath = os.path.abspath(pdfPath) if client is None: # 判断环境,linux环境这里肯定为None return doc2pdf_linux(docPathTrue, pdfPath) word = gencache.EnsureDispatch('kwps.Application') doc = word.Documents.Open(docPathTrue, ReadOnly=1) doc.ExportAsFixedFormat( pdfPath, constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) word.Quit(constants.wdDoNotSaveChanges)
def word_to_pdf(word_path, encrypts): pythoncom.CoInitialize() word_path = os.path.abspath(word_path) word = gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(word_path, ReadOnly=1) word_name = os.path.basename(word_path) file_name, ext = os.path.splitext(word_name) pdfPath = os.path.join(UPLOAD_BASE_PATH, ATTACHMENT, 'src', 'pdf') os.makedirs(pdfPath, exist_ok=True) pdf_path = os.path.join(pdfPath, file_name + '.pdf') doc.ExportAsFixedFormat( pdf_path, constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) pdf_path, thumb_path, page_num = img_insert_pdf(pdf_path, qrcode_Bytes(encrypts)) # word.Quit(constants.wdDoNotSaveChanges) # 保存错误 return pdf_path, thumb_path, page_num
def __init__(self, signature, title, icon="", configTool="", hint="", isDaemon=False, eventHandler=None, classes=[]): self.app = gencache.EnsureDispatch("libsnarl25.SnarlApp") for d in constants.__dicts__: # we must find the right dictionary ... if 'ERROR_NOTIFICATION_NOT_FOUND' in d: # this is it ! break codes = d.items() codes.sort(reverse=True) self.statCodes = dict([[v, k] for k, v in codes[6:]]) self.statCodes[codes[2][1]] = codes[2][0] # added SUCCESS self.classes = NotifClasses(classes) if eventHandler: self.SetEventHandler(eventHandler) self.SetTo(configTool, hint, icon, isDaemon, signature, title)
def Start_Word_PDF(self): if self.filename[-4:] == "docx" or self.filename[-3:] == "dox": reply = QMessageBox.question( win, '温馨提示!', '程序开始执行时,因为计算量大可能会导致卡顿,这是正常现象,请不要乱点,请耐心稍等一会儿!!!', QMessageBox.Yes | QMessageBox.No, (QMessageBox.Yes)) if reply == QMessageBox.Yes: pass else: self.Start_Word_PDF() Word_pdf_path = self.filename.replace(self.filename[-4:], "pdf") word = gencache.EnsureDispatch('Word.Application') doc = word.Documents.Open(self.filename, ReadOnly=1) doc.ExportAsFixedFormat(Word_pdf_path, constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) word.Quit(constants.wdDoNotSaveChanges) self.textedit_one.moveCursor(QTextCursor.End) self.textedit_one.insertPlainText( f"\nWord文件已成功转换PDF文件,请前往Word同目录下查看!!!\n\n生成路径为:{Word_pdf_path}\n") else: QMessageBox.question(win, '温馨提示!', '请检查是否为Word文件!!', QMessageBox.Yes | QMessageBox.No, (QMessageBox.Yes))