C#調用Python腳本打印pdf文件

 介紹:經過pdf地址先將文件下載到本地,而後調用打印機打印,最後將下載的文件刪除。python

  環境:windows系統。(windows64位)web

     windows系統中安裝python3.6.2環境json

   資料:windows

    O2S.Components.PDFRender4NET.dll(vs項目引用,這是在C#中調用打印機)api

    python3.6.2 for windows python-3.6.2-amd64-webinstall 異步

    在python環境中添加:pywin32-221.win-amd64-py3.6 和  GSPRINT文件(python環境中執行文件下載 打印 刪除)ide

 

windows環境下安裝python環境:學習

點擊程序進行安裝........測試

推薦安裝教程:https://baijiahao.baidu.com/s?id=1606573927720991570&wfr=spider&for=pc優化

 配置打印環境:

  首先進入cmd環境導入requests模塊

 

  下載pywin32 官網 https://sourceforge.net/projects/pywin32/ 

   

找準對應版本.....

 

或者是我提供的下載地址(個人是3.6.2python版本)

接下來就是安裝了.....

 

 

而後在python環境中去測試一下

解壓

將GSPRINT文件夾與上面win32的安裝模塊文件放在一塊兒,以下:

 

 後面文件中對應地址:

 

首先從C#代碼開始

   界面預覽:這個很簡單,在wpf中能夠寫個button按鈕事件便可

 

我直接貼出打印的核心代碼:

 /* 因爲質保書後臺接口給的是pdf下載地址,因此個人思路是 先下載到本地而後打印,打印完成後在刪除文件
                     * 因爲時間倉促:文件的下載及刪除功能使用python來完成(這裏也能夠改成C#來寫)
                     * 
                     */
                    try
                    {
                        // 1:文件下載 
                        var result = PythonHelper.PdfDownload(this.model.ZhiBaoShu.DownloadUrl);
                        if (!result.Successed)
                        {
                            Dispatcher.Invoke(() =>
                            {
                                MessageBox.Show("pdf質保書下載失敗,請聯繫管理員", "打印消息", MessageBoxButton.OK, MessageBoxImage.Stop);
                                LogHelper.LogInfo($"文件:【{this.model.ZhiBaoShu.DownloadUrl}】下載失敗\r\n 錯誤:\r\n{result.Message}");
                                // 發生錯誤返回主頁
                                UtilHelper.BackToMain(this, mainPage.stpBG, () => { BackToMain(); }, null);
                            });
                        }
                        Thread.Sleep(1000);
                        _savePath = result.Result.ToString();
                        // 2:打印下載pdf文件(python打印只能打印一份,還有打印樣式未完善,因此仍是用C#來調用打印)
                        result = PythonHelper.PdfPrint(_savePath, model.ZhiBaoShu.PrinterName);
                       // result = ph.PdfPrint(_savePath, model.ZhiBaoShu.PrinterName, (short)model.ZhiBaoShu.PrintNum);
                        if (!result.Successed)
                        {
                            Dispatcher.Invoke(() =>
                            {
                                MessageBox.Show("pdf質保書打印失敗,請聯繫管理員", "打印消息", MessageBoxButton.OK, MessageBoxImage.Stop);
                                LogHelper.LogInfo($"文件:【{result.Result.ToString()}】打印失敗\r\n 錯誤:\r\n{result.Message}");
                                // 發生錯誤返回主頁
                                UtilHelper.BackToMain(this, mainPage.stpBG, () => { BackToMain(); }, null);
                            });
                        }
                        Thread.Sleep(1000);
                        //// 3:刪除pdf文件 
                        //result = PythonHelper.PdfDelete(_savePath);
                        //if (!result.Successed)
                        //{
                        //    //MessageBox.Show("pdf質保書刪除失敗", "打印消息", MessageBoxButton.OK, MessageBoxImage.Stop);
                        //    LogHelper.LogInfo($"文件:【{this.model.ZhiBaoShu.DownloadUrl}】刪除失敗\r\n 錯誤:\r\n{result.Message}");
                        //    // 發生錯誤返回主頁
                        //    //UtilHelper.BackToMain(this, mainPage.stpBG, () => { BackToMain(); }, null);
                        //    // 文件刪除失敗不表明打印失敗,因此這裏結果重置一下
                        //    result.Successed = true;
                        //}

                    }
                    catch (Exception e)
                    {

 
                    }

 

pythonhelper.cs 文件 (代碼未優化)

    /// <summary>
    /// 執行python文件
    /// </summary>
    public static class PythonHelper
    {
        /// <summary>
        /// 程序debug目錄文件路徑 
        /// </summary>
        private static string _binPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

        /// <summary>
        /// 保存本地pdf文件名 
        /// </summary>
        private static string _pdfName = DateTime.Now.ToString("HHmmss") + ".pdf";

        /// <summary>
        /// 文件下載保存本地地址+文件名 
        /// </summary>
        private static string _savePath = _binPath + "file\\" + _pdfName;

        /// <summary>
        /// pdf下載
        /// </summary>
        /// <param name="downloadurl">pdf下載地址</param>
        /// <returns>返回保存文件地址</returns>
        public static HandlingResult PdfDownload(string downloadurl)
        {
            // python文件地址 ,待處理python文件的路徑,本例中放在debug文件夾下
            string _pdfDownloadPy = _binPath + "python\\pdfdownload.py";
            var result = new HandlingResult() { Successed = false };
            try
            {
                // 拼接執行命令(方法傳參)
                ArrayList arrayList = new ArrayList();
                arrayList.Add(downloadurl);
                arrayList.Add(_savePath);
                foreach (var param in arrayList)//添加參數 
                    _pdfDownloadPy += " " + param;

                // 執行設置
                ProcessStartInfo start = new ProcessStartInfo();
                start.FileName = "python";//執行python.exe
                                          //執行python腳本的命令
                start.Arguments = _pdfDownloadPy;
                //設置運行python腳本的初始目錄 這裏注意:若是你的python腳本有文件操做,必須設置初始目錄,python腳本所在的目錄
                start.WorkingDirectory = _binPath + "python\\";
                start.UseShellExecute = false;
                start.CreateNoWindow = true;
                start.RedirectStandardOutput = true;
                start.RedirectStandardError = true;
                using (Process process = Process.Start(start))
                {
                    // 異步獲取命令行內容
                    process.BeginOutputReadLine();
                    // 爲異步獲取訂閱事件
                    process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                    {
                        // 打印python腳本中的信息
                        LogHelper.LogInfo(e.Data);
                        //MessageBox.Show(e.Data);//e.Data 就是命令行打印的最後一行信息
                    });
                }
                result.Successed = true;
                result.Result = _savePath;
            }
            catch (Exception e)
            {
                result.Successed = false;
                result.Message = e.Message;
                LogHelper.LogError(e);

            }

            return result;
        }

        /// <summary>
        /// 刪除pdf文件
        /// </summary>
        /// <param name="path">本地pdf文件全路徑</param>
        public static HandlingResult PdfDelete(string path)
        {
            string _pdfDeletePy = _binPath + "python\\pdfdelete.py";
            var result = new HandlingResult() { Successed = true };
            try
            {
                // 拼接執行命令(方法傳參)
                ArrayList arrayList = new ArrayList();
                arrayList.Add(path);
                foreach (var param in arrayList)//添加參數 
                    _pdfDeletePy += " " + param;

                // 執行設置
                ProcessStartInfo start = new ProcessStartInfo();
                start.FileName = "python";//執行python.exe
                                          //執行python腳本的命令
                start.Arguments = _pdfDeletePy;
                //設置運行python腳本的初始目錄 這裏注意:若是你的python腳本有文件操做,必須設置初始目錄,python腳本所在的目錄
                start.WorkingDirectory = _binPath + "python\\";
                start.UseShellExecute = false;
                start.CreateNoWindow = true;
                start.RedirectStandardOutput = true;
                start.RedirectStandardError = true;
                using (Process process = Process.Start(start))
                {

                    // 異步獲取命令行內容
                    process.BeginOutputReadLine();
                    // 爲異步獲取訂閱事件
                    process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                    {
                        // 打印python腳本中的信息
                        LogHelper.LogInfo(e.Data);
                        //MessageBox.Show(e.Data);//e.Data 就是命令行打印的最後一行信息
                    });
                }

            }
            catch (Exception e)
            {
                result.Successed = false;
                result.Message = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 打印pdf
        /// </summary>
        /// <param name="printPath">文件全路徑</param>
        /// <param name="printName">打印機名稱</param>
        public static HandlingResult PdfPrint(string printPath, string printName)
        {
            string _pdfPrint = _binPath + "python\\pdfprint.py";
            var result = new HandlingResult() { Successed = true };
            try
            {
                // 拼接執行命令(方法傳參)
                ArrayList arrayList = new ArrayList();
                arrayList.Add(printPath);
                arrayList.Add(printName);
                foreach (var param in arrayList)//添加參數 
                    _pdfPrint += " " + param;

                // 執行設置
                ProcessStartInfo start = new ProcessStartInfo();
                start.FileName = "python";//執行python.exe 
                start.Arguments = _pdfPrint;//執行python腳本的命令
                //設置運行python腳本的初始目錄 這裏注意:若是你的python腳本有文件操做,必須設置初始目錄,python腳本所在的目錄
                start.WorkingDirectory = _binPath + "python\\";
                start.UseShellExecute = false;
                start.CreateNoWindow = true;
                start.RedirectStandardOutput = true;
                start.RedirectStandardError = true;
                using (Process process = Process.Start(start))
                {
                    // 異步獲取命令行內容
                    process.BeginOutputReadLine();
                    // 爲異步獲取訂閱事件
                    process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                    {
                        // 打印python腳本中的信息
                        LogHelper.LogInfo(e.Data);
                        //MessageBox.Show(e.Data);//e.Data 就是命令行打印的最後一行信息
                    });
                }
            }
            catch (Exception e)
            {
                LogHelper.LogError(e);
                result.Successed = false;
                result.Message = e.Message;
            }
            return result;
        }

    }

 

第二種調用打印機方法:使用第三方O2S.Components.PDFRender4NET.dll文件調用打印機打印pdf

        /// <summary>
        /// 打印pdf文件
        /// </summary>
        /// <param name="pdfPath">文件全路徑</param>
        /// <param name="printName">打印機名稱</param>
        /// <param name="copies">打印份數</param>
        /// <returns></returns>
        public HandlingResult PdfPrint(string pdfPath, string printName, short copies = 1)
        {
            PDFFile file =null;
            var result = new HandlingResult()
            {
                Successed = true,
            };
            try
            {
                file = PDFFile.Open(pdfPath);
                PrinterSettings settings = new PrinterSettings();
                System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
                settings.PrinterName = printName; // "NPI84FFAF (HP LaserJet MFP M436)"; // 打印機名稱
                settings.PrintToFile = false;

                //設置紙張大小(能夠不設置,取默認設置)3.90 in,  8.65 in
                PaperSize ps = new PaperSize("test", 4, 9);
                ps.RawKind = 9; //若是是自定義紙張,就要大於118,(A4值爲9,詳細紙張類型與值的對照請看http://msdn.microsoft.com/zh-tw/library/system.drawing.printing.papersize.rawkind(v=vs.85).aspx)
                O2S.Components.PDFRender4NET.Printing.PDFPrintSettings pdfPrintSettings =
                    new O2S.Components.PDFRender4NET.Printing.PDFPrintSettings(settings);
                pdfPrintSettings.PaperSize = ps;
                pdfPrintSettings.PageScaling =
                    O2S.Components.PDFRender4NET.Printing.PageScaling.FitToPrinterMarginsProportional;
                pdfPrintSettings.PrinterSettings.Copies = copies;

                file.Print(pdfPrintSettings);
            }
            catch (Exception e)
            {
                LogHelper.LogError(e);
                result.Successed = false;
                result.Message = e.Message;
            }
            finally
            {
                file.Dispose();
                LogHelper.LogInfo($"{pdfPath}---打印成功");
            }

            return result;
        }

  

以上是C#部分代碼,如下python腳本就比較簡單了。

注:其實能夠只寫一個打印方法便可,爲了流程看到清楚,因此一個操做一個方法文件。

 

1:根據地址下載pdf文件 pdfdownload.py

# -*- coding: utf-8 -*-

# 聲明字符編碼
# coding:utf-8
import os, sys
from requests import get
def dwnloadpfd(file_path, save_path):
    '''
    根據file_path地址下載文件保存到save_path路徑中
    :param file_path:下載地址
    :param save_path: 保存地址
    :return:True或False
    '''
    try:
        head = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.89 Safari/537.36"
        }
        response =get(file_path, headers=head).content
        with open(save_path, 'wb') as f:
            f.write(response)
        print('%s--下載成功'%(save_path))
        return save_path
    except Exception as e:
        print(e)
        return None

if __name__ == "__main__":
    #url = ""
    #dwnloadpfd(url, "musics/1.pdf")
    # 接收參數
    dwnloadpfd(sys.argv[1], sys.argv[2])

  

 2:打印pdf文件:pdfprint.py

# -*- coding: utf-8 -*-

# 聲明字符編碼
# coding:utf-8
import os, sys
import win32api
import win32print
import json
from handlingresult import handlingresult

GHOSTSCRIPT_PATH = "C:\\Program Files\\gs\\gs9.27\\bin\\gswin64.exe"
GSPRINT_PATH = "C:\\Program Files\\GSPRINT\\gsprint.exe"


def pdfprint(full_file_name, print_name=win32print.GetDefaultPrinter()):
    '''
    根據指定的打印機打印pdf文件
    :param full_file_name:文件全路徑
    :param print_name:打印機名稱(默認打印機)
    :return:
    '''
    result = handlingresult()
    try:
        # portraint:縱向 landscape:橫向
        win32api.ShellExecute(
            0,
            'open',
            GSPRINT_PATH,
            '-ghostscript "' + GHOSTSCRIPT_PATH + '" -landscape -printer "' + print_name + '" "' + full_file_name + '"',
            '.',
            0
        )
        result.Message = '%s---打印成功' % (full_file_name)
        result.Result = None
        result.Successed = True
    except Exception as e:
        result.Message = '%s---打印異常:\n %s' % (full_file_name, str(e))
        result.Result = None
        result.Successed = False
    js = json.dumps(result, default=lambda obj: obj.__dict__, sort_keys=True, indent=4)
    return js


if __name__ == "__main__":
    path ="D:\\1.pdf" #"E:\\開發項目\\學習項目\\Python\\MusicDownLoad\\musics\\1.pdf"
    name = "NPIE091D5 (HP LaserJet MFP M227fdw)"  # win32print.GetDefaultPrinter()  # "NPI84FFAF (HP LaserJet MFP M436)" #
    print(pdfprint(path, name))

    # len(sys.argv)
    # print(sys.argv[1])  # 文件路徑
    # print(sys.argv[2:])  # 打印機名稱
    # name = ' '.join(sys.argv[2:])
    # print(name)
    # # 打印機名稱中有可能有空格
    # print(pdfprint(sys.argv[1], name))

  

  

 3:打印完成後便可刪除文件 pdfdelete.py

# -*- coding: utf-8 -*-

# 聲明字符編碼
# coding:utf-8
import os, sys
def pdfdelete(full_path):
    '''
    根據文件全路徑地址刪除
    :param full_path:文件路徑
    :return:True或False
    '''
    try:
        if (os.path.exists(full_path)):
            os.remove(full_path)
            print(full_path + '---刪除成功')
            return True
        else:
            print(full_path + '---刪除文件不存在')
            return False
    except Exception as e:
        print(str(e))
        return False

if __name__ == "__main__":
    pdfdelete(sys.argv[1])

  

補充:獲取打印機狀態

# -*- coding: utf-8 -*-

# 聲明字符編碼
# coding:utf-8
import os, sys
import win32api
import win32print
import json
from handlingresult import handlingresult

GHOSTSCRIPT_PATH = "C:\\Program Files\\gs\\gs9.27\\bin\\gswin64.exe"
GSPRINT_PATH = "C:\\Program Files\\GSPRINT\\gsprint.exe"

# 詳細參考:https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/1625e9d9-29e4-48f4-b83d-3bd0fdaea787
# 對應:win32api 最上面有
PRINTER_STATUE_STR = {
    "2": "打印機處於錯誤狀態",
    "4096": "打印機沒法打印",
    "262144": "打印機沒有碳粉",
    "128": "打印機處於脫機狀態",
    "2097152": "打印機內存不足",
    "524288": "打印機沒法打印當前頁面",
    "8": "紙張卡在打印機中",
    "16": "打印機缺紙",
    "64": "打印機有一個未指定的紙張問題",
    "1": "打印機暫停",
    "131072": "打印機墨粉不足",
    "1048576": "打印機出現錯誤"
}



def printer_status_code(printer_name):
    '''
    根據打印機名稱獲取狀態
    :param printer_name:
    :return:
    '''
    result = handlingresult()
    try:
        hPrinter = win32print.OpenPrinter(printer_name)
        dic = win32print.GetPrinter(hPrinter, 2)
        stuta_int = dic.get('Status', 0)# 獲取狀態值
        result.Result = stuta_int
        stuta = PRINTER_STATUE_STR.get(str(stuta_int), None)
        if stuta == None:
            result.Message = '打印機狀態:%s:\n %s' % (printer_name, result.Result)
            result.Successed = True
        else:
            result.Message = '打印機狀態:%s:\n %s' % (printer_name, stuta)
            result.Successed = False

    except Exception as e:
        result.Message = '打印機獲取狀態異常:%s:\n %s' % (printer_name, str(e))
        result.Result = None
        result.Successed = False
    js = json.dumps(result, default=lambda obj: obj.__dict__, sort_keys=True, indent=4)
    return js


if __name__ == "__main__":
    name = ' '.join(sys.argv[1:])
    print(printer_status_code(printer_name=name))
    # code = printer_status_code(
    #     "Brother Color Leg Type1 Class Driver")  # Brother Color Leg Type1 Class Driver  HP LaserJet MFP M436 PCL-6  NPI84FFAF (HP LaserJet MFP M436)
    # print(code)

  

 注:上面python調用打印機進行打印的份數這些設置後續有待完善。(打印份數能夠循環調用打印便可)

相關文章
相關標籤/搜索