python word/excel转换pdf无法保持原页面布局

查看 12|回复 0
作者:wzs0777   
下面的python代码在文件转换pdf是无法保持原word、excel文件的页面布局;比如我调试一个word文件,页面布局均是纵向(第一页是文本,第二页是标题+表格+备注),转换后发现第二页变为横向了
[Asm] 纯文本查看 复制代码    def convert_with_com(self, file_path, output_path):
        try:
            abs_file_path = str(file_path.absolute())
            abs_output_path = str(output_path.absolute())
            if file_path.suffix.lower() in ['.doc', '.docx']:
                word = win32com.client.Dispatch("Word.Application")
                word.Visible = False
                word.DisplayAlerts = False  # 禁用警告
                try:
                    doc = word.Documents.Open(abs_file_path)
                    # 修复参数配置
                    doc.ExportAsFixedFormat(
                        OutputFileName=abs_output_path,
                        ExportFormat=17,  # wdExportFormatPDF
                        OpenAfterExport=False,
                        OptimizeFor=0,  # wdExportOptimizeForPrint
                        BitmapMissingFonts=True,
                        CreateBookmarks=1  # wdExportCreateHeadingBookmarks
                    )
                    doc.Close(SaveChanges=False)
                finally:
                    word.Quit()
            elif file_path.suffix.lower() in ['.xls', '.xlsx']:
                excel = win32com.client.Dispatch("Excel.Application")
                excel.Visible = False
                excel.DisplayAlerts = False
                try:
                    wb = excel.Workbooks.Open(abs_file_path)
                    wb.ExportAsFixedFormat(
                        Type=0,  # xlTypePDF
                        Filename=abs_output_path,
                        Quality=0,  # xlQualityStandard
                        IncludeDocProperties=True,
                        IgnorePrintAreas=False
                    )
                    wb.Close(SaveChanges=False)
                finally:
                    excel.Quit()
            # 验证文件是否成功创建
            if output_path.exists() and output_path.stat().st_size > 0:
                return abs_output_path
            return None
        except Exception as e:
            print(f"COM转换失败: {e}")
            return None

布局, 页面

您需要登录后才可以回帖 登录 | 立即注册

返回顶部