C#Call Python script to print pdf file

Keywords: C# Python Windows encoding

Introduction: Download the file locally through the pdf address, then call the printer to print, and delete the downloaded file.

Environment: Windows system.(windows64 bit)

Install Python 3.6.2 environment on windows system

Data:

    O2S.Components.PDFRender4NET.dll (vs project reference, this is calling the printer in C#)

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

    Add in python environment: pywin32-221.win-amd64-py3.6 and GSPRINT files (execute file download, print delete in python environment)

 

Install python environment in windows environment:

Click on the program to install...

Recommended installation tutorials: https://baijiahao.baidu.com/s?id=1606573927720991570&wfr=spider&for=pc

Configure the printing environment:

First import the requests module into the cmd environment

 

Download pywin32 website  https://sourceforge.net/projects/pywin32/ 

   

Find the corresponding version...

 

Or the download address I provided (my version is 3.6.2 python)

Next up is the installation...

 

 

Then test it in a python environment

decompression

Put the GSPRINT folder with the installation module file of win32 above, as follows:

 

The corresponding address in the following file:

 

Start with C#code first

Interface Preview: This is simple, you can write a button button event in wpf

 

I paste out the printed core code directly:

 /* Since the warranty backend interface gives the pdf download address, my idea is to download the file locally and print it, then delete the file when printing is complete
                     * Due to a rush of time: download and delete files using python (you can also change to C#here)
                     * 
                     */
                    try
                    {
                        // 1: File Download 
                        var result = PythonHelper.PdfDownload(this.model.ZhiBaoShu.DownloadUrl);
                        if (!result.Successed)
                        {
                            Dispatcher.Invoke(() =>
                            {
                                MessageBox.Show("pdf Download of warranty failed, please contact your administrator", "Print message", MessageBoxButton.OK, MessageBoxImage.Stop);
                                LogHelper.LogInfo($"file:[{this.model.ZhiBaoShu.DownloadUrl}]Download failed\r\n Error:\r\n{result.Message}");
                                // Error Return to Home Page
                                UtilHelper.BackToMain(this, mainPage.stpBG, () => { BackToMain(); }, null);
                            });
                        }
                        Thread.Sleep(1000);
                        _savePath = result.Result.ToString();
                        // 2: Print Download pdf file (python prints only one copy, and print style is not perfect, so use C#to call print)
                        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 Quality assurance printing failed, please contact your administrator", "Print message", MessageBoxButton.OK, MessageBoxImage.Stop);
                                LogHelper.LogInfo($"file:[{result.Result.ToString()}]Printing Failed\r\n Error:\r\n{result.Message}");
                                // Error Return to Home Page
                                UtilHelper.BackToMain(this, mainPage.stpBG, () => { BackToMain(); }, null);
                            });
                        }
                        Thread.Sleep(1000);
                        //// 3: Delete pdf file 
                        //result = PythonHelper.PdfDelete(_savePath);
                        //if (!result.Successed)
                        //{
                        //    //MessageBox.Show("pdf warranty deletion failed", "Print message", "MessageBoxButton.OK", MessageBoxImage.Stop);
                        //    LogHelper.LogInfo($"File: [this.model.ZhiBaoShu.DownloadUrl}] Delete failed\r\n Error: \r\n{result.Message}");
                        //    //Error Return to Home Page
                        //    //UtilHelper.BackToMain(this, mainPage.stpBG, () => { BackToMain(); }, null);
                        //    //Failure to delete file does not mean failure to print, so reset the result here
                        //    result.Successed = true;
                        //}

                    }
                    catch (Exception e)
                    {

 
                    }

 

pythonhelper.cs file (code not optimized)

    /// <summary>
    ///Execute python file
    /// </summary>
    public static class PythonHelper
    {
        /// <summary>
        ///Program debug directory file path 
        /// </summary>
        private static string _binPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

        /// <summary>
        ///Save local pdf file name 
        /// </summary>
        private static string _pdfName = DateTime.Now.ToString("HHmmss") + ".pdf";

        /// <summary>
        ///File Download Save Local Address+File Name 
        /// </summary>
        private static string _savePath = _binPath + "file\\" + _pdfName;

        /// <summary>
        /// pdf download
        /// </summary>
        /// <param name="download url">pdf download address</param>
        /// <returns>Return to save file address</returns>
        public static HandlingResult PdfDownload(string downloadurl)
        {
            // Python file address, the path to the python file to be processed, in this case under the debug folder
            string _pdfDownloadPy = _binPath + "python\\pdfdownload.py";
            var result = new HandlingResult() { Successed = false };
            try
            {
                // Stitching Execution Command (Method Pass-Through)
                ArrayList arrayList = new ArrayList();
                arrayList.Add(downloadurl);
                arrayList.Add(_savePath);
                foreach (var param in arrayList)//Add parameters 
                    _pdfDownloadPy += " " + param;

                // Execution Settings
                ProcessStartInfo start = new ProcessStartInfo();
                start.FileName = "python";//Execute python.exe
                                          //Commands to execute python scripts
                start.Arguments = _pdfDownloadPy;
                //Set the initial directory to run the python script Note: If your Python script has file operations, you must set the initial directory, where the python script is located
                start.WorkingDirectory = _binPath + "python\\";
                start.UseShellExecute = false;
                start.CreateNoWindow = true;
                start.RedirectStandardOutput = true;
                start.RedirectStandardError = true;
                using (Process process = Process.Start(start))
                {
                    // Get command line content asynchronously
                    process.BeginOutputReadLine();
                    // Get subscription events asynchronously
                    process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                    {
                        // Print information from python scripts
                        LogHelper.LogInfo(e.Data);
                        //MessageBox.Show(e.Data);//e.Data is the last line of information printed on the command line
                    });
                }
                result.Successed = true;
                result.Result = _savePath;
            }
            catch (Exception e)
            {
                result.Successed = false;
                result.Message = e.Message;
                LogHelper.LogError(e);

            }

            return result;
        }

        /// <summary>
        ///Delete pdf file
        /// </summary>
        /// <param name="path">full path of local pdf file </param>
        public static HandlingResult PdfDelete(string path)
        {
            string _pdfDeletePy = _binPath + "python\\pdfdelete.py";
            var result = new HandlingResult() { Successed = true };
            try
            {
                // Stitching Execution Command (Method Pass-Through)
                ArrayList arrayList = new ArrayList();
                arrayList.Add(path);
                foreach (var param in arrayList)//Add parameters 
                    _pdfDeletePy += " " + param;

                // Execution Settings
                ProcessStartInfo start = new ProcessStartInfo();
                start.FileName = "python";//Execute python.exe
                                          //Commands to execute python scripts
                start.Arguments = _pdfDeletePy;
                //Set the initial directory to run the python script Note: If your Python script has file operations, you must set the initial directory, where the python script is located
                start.WorkingDirectory = _binPath + "python\\";
                start.UseShellExecute = false;
                start.CreateNoWindow = true;
                start.RedirectStandardOutput = true;
                start.RedirectStandardError = true;
                using (Process process = Process.Start(start))
                {

                    // Get command line content asynchronously
                    process.BeginOutputReadLine();
                    // Get subscription events asynchronously
                    process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                    {
                        // Print information from python scripts
                        LogHelper.LogInfo(e.Data);
                        //MessageBox.Show(e.Data);//e.Data is the last line of information printed on the command line
                    });
                }

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

        /// <summary>
        ///Print pdf
        /// </summary>
        /// <param name="printPath">File full path</param>
        /// <param name="printName">printer name</param>
        public static HandlingResult PdfPrint(string printPath, string printName)
        {
            string _pdfPrint = _binPath + "python\\pdfprint.py";
            var result = new HandlingResult() { Successed = true };
            try
            {
                // Stitching Execution Command (Method Pass-Through)
                ArrayList arrayList = new ArrayList();
                arrayList.Add(printPath);
                arrayList.Add(printName);
                foreach (var param in arrayList)//Add parameters 
                    _pdfPrint += " " + param;

                // Execution Settings
                ProcessStartInfo start = new ProcessStartInfo();
                start.FileName = "python";//Execute python.exe 
                start.Arguments = _pdfPrint;//Commands to execute python scripts
                //Set the initial directory to run the python script Note: If your Python script has file operations, you must set the initial directory, where the python script is located
                start.WorkingDirectory = _binPath + "python\\";
                start.UseShellExecute = false;
                start.CreateNoWindow = true;
                start.RedirectStandardOutput = true;
                start.RedirectStandardError = true;
                using (Process process = Process.Start(start))
                {
                    // Get command line content asynchronously
                    process.BeginOutputReadLine();
                    // Get subscription events asynchronously
                    process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                    {
                        // Print information from python scripts
                        LogHelper.LogInfo(e.Data);
                        //MessageBox.Show(e.Data);//e.Data is the last line of information printed on the command line
                    });
                }
            }
            catch (Exception e)
            {
                LogHelper.LogError(e);
                result.Successed = false;
                result.Message = e.Message;
            }
            return result;
        }

    }

 

The second way to call a printer is to useThird party O2S.Components.PDFRender4NET.dll file calls printer print pdf

        /// <summary>
        ///Print pdf file
        /// </summary>
        /// <param name="pdfPath">File full path</param>
        /// <param name="printName">printer name</param>
        /// <param name="copies">number of copies printed</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)"; //Printer Name
                settings.PrintToFile = false;

                //Set paper size (default setting, optional) 3.90 in, 8.65 in
                PaperSize ps = new PaperSize("test", 4, 9);
                ps.RawKind = 9; //For custom paper, it should be greater than 118. (A4 value is 9, see http://msdn.microsoft.com/zh-tw/library/system.drawing.printing.papersize.rawtype (v=vs.85). aspx) for a comparison of detailed paper type and value.
                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}---Printing Successful");
            }

            return result;
        }

  

That's part of the C# code, so the following python script is simpler.

Note: In fact, you can only write one method of printing. In order to see the process clearly, you can operate on one method file.

 

1: Download pdf file pdfdownload.py from address

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

# Declarative character encoding
# coding:utf-8
import os, sys
from requests import get
def dwnloadpfd(file_path, save_path):
    '''
    //Download files from file_path address to save_path path path
    :param file_path:Download Address
    :param save_path: Save Address
    :return:True or 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--Download Successful'%(save_path))
        return save_path
    except Exception as e:
        print(e)
        return None

if __name__ == "__main__":
    #url = ""
    #dwnloadpfd(url, "musics/1.pdf")
    # Receive parameters
    dwnloadpfd(sys.argv[1], sys.argv[2])

  

2: Print pdf file: pdfprint.py

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

# Declarative character encoding
# coding:utf-8
import os,sys 
import win32api
import win32print 
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()):
    '''
    //Print pdf file according to specified printer
    :param full_file_name:File Full Path
    :param print_name:Printer name (default printer)
    :return:
    ''' 
    try:
        win32api.ShellExecute(
            0,
            'open',
            GSPRINT_PATH,
            '-ghostscript "' + GHOSTSCRIPT_PATH + '" -printer "' + print_name + '" "' + full_file_name + '"',
            '.',
            0
        )
        print('%s---Printing Successful' % (full_file_name))
    except Exception as e:
        print('%s---Print exception:\n' % (full_file_name))
        print(str(e)) 
if __name__ == "__main__": 
    # path = "E:\Development Project\Learning Project\\\Python\\MusicDownLoad\\Musicics\\1.pdf"
    # name = win32print.GetDefaultPrinter()  # "NPI84FFAF (HP LaserJet MFP M436)" #
    # pdfprint(path, name)
    len(sys.argv) 
    print(sys.argv[1]) # File Path
    print(sys.argv[2:])# Printer name
    name = ' '.join(sys.argv[2:])
    print(name)
    # There may be a space in the printer name 
    pdfprint(sys.argv[1], name)
         

 

  

3: Delete file pdfdelete.py after printing

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

# Declarative character encoding
# coding:utf-8
import os, sys
def pdfdelete(full_path):
    '''
    //Delete based on the full path address of the file
    :param full_path:File Path
    :return:True or False
    '''
    try:
        if (os.path.exists(full_path)):
            os.remove(full_path)
            print(full_path + '---Delete succeeded')
            return True
        else:
            print(full_path + '---Delete file does not exist')
            return False
    except Exception as e:
        print(str(e))
        return False

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

  

Note: The effect of python calling the printer above for printing needs to be adjusted and the number of copies to be printed. These settings need to be improved in the future.

Posted by intermediate on Sat, 11 May 2019 15:57:24 -0700