python實現word批量轉pdf

1.python實現word批量轉pdf

2.c# 實現word批量轉pdf

1.python實現word批量轉pdf

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
import glob as gb
import sys
import imp
imp.reload(sys)
import sys, os
from win32com.client import Dispatch, constants, gencache
import tkinter as tk
from tkinter.filedialog import askdirectory

#REPORT_DOC_PATH = 'C:/Users/dell/Desktop/新建文件夾'
#REPORT_PDF_PATH = 'C:/Users/dell/Desktop/新建文件夾'
root = tk.Tk()
root.withdraw()
REPORT_DOC_PATH = askdirectory()
REPORT_PDF_PATH = REPORT_DOC_PATH

def word2pdf(filename, doc):
    if doc == "Y":
        input = filename + '.doc'
    elif doc == "N":
        input = filename + '.docx'
    output = filename + '.pdf'
    pdf_name = output

    os.chdir(REPORT_DOC_PATH)

    if not os.path.isfile(input):
        print (u'%s not exist' % input)
        return False

    if (not os.path.isabs(input)):
        input = os.path.abspath(input)
    else:
        print (u'%s not absolute path' % input)
        return False

    if (not os.path.isabs(output)):
        os.chdir(REPORT_PDF_PATH)
        output = os.path.abspath(output)
    else:
        print (u'%s not absolute path' % output)
        return False

    try:
        print (input, output)
        gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
        w = Dispatch("Word.Application")
        try:
            doc = w.Documents.Open(input, ReadOnly=1)
            doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF, \
                                    Item=constants.wdExportDocumentWithMarkup,
                                    CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
        except:
            print (' exception')
        finally:
            w.Quit(constants.wdDoNotSaveChanges)

        if os.path.isfile(pdf_name):
            print ('translate success')
            return True
        else:
            print ('translate fail')
            return False
    except:
        print (' exception')
        return -1

if __name__ == '__main__':
    import os
    for dirpath, dirnames, filenames in os.walk(REPORT_DOC_PATH):
        for file in filenames:
            fullpath = os.path.join(dirpath, file)
            print (fullpath, file)
            if 'docx' in file:
                rc = word2pdf(filename = file.rstrip('.docx'), doc = "N")
            else:
                rc = word2pdf(filename = file.rstrip('.doc'), doc = "Y")

 2.c# 實現word批量轉pdf

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using Microsoft.Office.Interop.Word;

namespace Word2Pdf
{
    class Program
    {
        public static Microsoft.Office.Interop.Word.Document wordDocument { get; set; }

        static void Main(string[] args)
        {
            string strFolder_f = null;
            string strFolder_t = null;
            string strFlag = null;
            System.Console.WriteLine("請輸入Word文檔所在目錄");
            strFolder_f = System.Console.ReadLine();
            if (strFolder_f.Substring(strFolder_f.Length - 1, 1) != "\\")
            {
                strFolder_f += "\\";
            }
            strFolder_t = strFolder_f + @"pdf\";
            System.Console.WriteLine("\n創建PDF文檔,請確認!");
            System.Console.Write("y(yes) or n(no) ?  ");
            strFlag = System.Console.ReadLine();
            if (strFlag == "y")
            {
                System.Console.WriteLine("\n開始創建PDF文檔...");
                CheckFolder(strFolder_t);
                string strPdfFile = null;
                DirectoryInfo TheFolder = new DirectoryInfo(strFolder_f);

                Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
                object paramMissing = Type.Missing;

                foreach (FileInfo NextFile in TheFolder.GetFiles())
                {
                    strPdfFile = Path.ChangeExtension(strFolder_t + NextFile.Name, ".pdf");
                    wordDocument = appWord.Documents.Open(NextFile.FullName);
                    if (wordDocument != null)
                    {
                        wordDocument.ExportAsFixedFormat(strPdfFile, WdExportFormat.wdExportFormatPDF);
                        wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                        wordDocument = null;
                    }
                    System.Console.Write(".. ");
                }

                if (appWord != null)
                {
                    appWord.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    appWord = null;
                }
            }

            //KillProcessByName("WINWORD");
            GC.Collect();
            GC.WaitForPendingFinalizers();

            System.Console.Write("\n處理完畢,輸入任意鍵退出");
            System.Console.ReadKey();
        }

        static void CheckFolder(string strFolderPath)
        {
            if (Directory.Exists(strFolderPath))
            {
                Directory.Delete(strFolderPath, true);
                Directory.CreateDirectory(strFolderPath);
            }
            else
            {
                Directory.CreateDirectory(strFolderPath);
            }
        }

        static void KillProcessByName(string name)
        {
            Process[] ps = Process.GetProcessesByName(name);
            foreach (Process p in ps)
            {
                if (p.ProcessName == name)
                    p.Kill();
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章