C # print PDF documents by calling WinApi, Server PDF printing, iis pdf printing,

Source: Internet
Author: User

C # print PDF documents by calling WinApi, Server PDF printing, iis pdf printing,

Download classes from other websites, which can be used for Winform and Asp. Net, and for server-side PDF or other file printing.

Directly run the Code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace CyServer.WinAPI
{
    public class RawPrinterHelper
    {
        // Structure and API declarions:
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        public class DOCINFOA
        {
            [MarshalAs(UnmanagedType.LPStr)]
            public string pDocName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pOutputFile;
            [MarshalAs(UnmanagedType.LPStr)]
            public string pDataType;
        }

        [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

        [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool ClosePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

        [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool EndDocPrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool StartPagePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool EndPagePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

        // SendBytesToPrinter()
        // When the function is given a printer name and an unmanaged array
        // of bytes, the function sends those bytes to the print queue.
        // Returns true on success, false on failure.
        public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
        {
            Int32 dwError = 0, dwWritten = 0;
            IntPtr hPrinter = new IntPtr(0);
            DOCINFOA di = new DOCINFOA();
            bool bSuccess = false; // Assume failure unless you specifically succeed.

            di.pDocName = "My C#.NET RAW Document";
            di.pDataType = "RAW";

            // Open the printer.
            if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
            {
                // Start a document.
                if (StartDocPrinter(hPrinter, 1, di))
                {
                    // Start a page.
                    if (StartPagePrinter(hPrinter))
                    {
                        // Write your bytes.
                        bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                        EndPagePrinter(hPrinter);
                    }
                    EndDocPrinter(hPrinter);
                }
                ClosePrinter(hPrinter);
            }
            // If you did not succeed, GetLastError may give more information
            // about why not.
            if (bSuccess == false)
            {
                dwError = Marshal.GetLastWin32Error();
            }
            return bSuccess;
        }

        public static bool SendFileToPrinter(string szPrinterName, string szFileName)
        {
            // Open the file.
            FileStream fs = new FileStream(szFileName, FileMode.Open);
            // Create a BinaryReader on the file.
            BinaryReader br = new BinaryReader(fs);
            // Dim an array of bytes big enough to hold the file's contents.
            Byte[] bytes = new Byte[fs.Length];
            bool bSuccess = false;
            // Your unmanaged pointer.
            IntPtr pUnmanagedBytes = new IntPtr(0);
            int nLength;

            nLength = Convert.ToInt32(fs.Length);
            // Read the contents of the file into the array.
            bytes = br.ReadBytes(nLength);
            // Allocate some unmanaged memory for those bytes.
            pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
            // Copy the managed byte array into the unmanaged array.
            Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
            // Send the unmanaged bytes to the printer.
            bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
            // Free the unmanaged memory that you allocated earlier.
            Marshal.FreeCoTaskMem(pUnmanagedBytes);
            return bSuccess;
        }

        public static bool SendStringToPrinter(string szPrinterName, string szString)
        {
            IntPtr pBytes;
            Int32 dwCount;
            // How many characters are in the string?
            dwCount = szString.Length;
            // Assume that the printer is expecting ANSI text, and then convert
            // the string to ANSI text.
            pBytes = Marshal.StringToCoTaskMemAnsi(szString);
            // Send the converted ANSI string to the printer.
            SendBytesToPrinter(szPrinterName, pBytes, dwCount);
            Marshal.FreeCoTaskMem(pBytes);
            return true;
        }
    }

}
Next we will Copy a bit of information:
Print Management Library Function Winspool.drv
Printer low-level driver package

Function name Description
AbortPrinter deletes spooled files from the printer
AddForm adds a format table that can be selected for a given printer
                              format
AddJob returns a complete path to a file that can be used to store print jobs
                              Path and file name
AddMonitor installs a local printer monitor and connects the profile
                              , Data files, and monitor files

AddPort adds a port name to the list of supported ports
AddPrinter adds a list of printers supported by the specified server
                              printer
AddPrinterConnection Add specified printer and connect for current user
AddPrinterDriver installs a local or remote printer and connects to cultivate files, data
                              Data files and driver files
AddPrintProcessor installs a print processor on the specified server, and
                             Name is added to the supported internal list
AddPrintProvidor installs a local printer provider and connects a profile,
                              Data files and provider files
AdvancedDocumentProperties displays a printer advanced configuration dialog for a given printer
                              Box to allow configuration
ClosePrinter closes the given printer object
ConfigurePort displays the configuration dialog for the given port on the specified server, starting with
                              Allow configuration
ConnectToPrinterDlg displays a dialog box for users to browse and connect the printer on the network
DeleteForm deletes a format name from a supported format table
DeleteMonitor deletes a printer monitor added by the AddMonitor function
                              Viewer
DeleteProt displays a dialog box to allow the user to delete a port name
DeletePrinter deletes the specified printer object
DeletePrinterConnection deletes the specified printer connection
DeletePrinterDriver deletes a pointer from a list of drive names supported by a given server
                              Printer driver
DeletePrintProcessor deletes the printer added by the AddPrintProcessor function
                              Handler
DeletePrintProvidor deletes a provider added by the AddPrintProvidor function
DeviceCapabilities get the capabilities required by the specified printer

DocumentProperties displays a printer configuration dialog for a given printer,
                              To allow configuration
EndDocPrinter terminates a print job for a given printer
EndPagePrinter indicates the end of one page and the beginning of the next page
EnumForms enumerates the formats supported by the specified printer
EnumJobs initializes a print job data describing the printer
                              JOB_INFO_1 or JOB_INFO_2 structure array for enumeration
                              Printing machine operation
EnumMonitors initializes one with the monitor data describing the given server
                             MONITOR_INFO_1 structure array to enumerate printer monitoring
                              Device
EnumPorts enumerates the ports available for printing on the specified server
EnumPrinterDrivers enumerate all printers installed on a given printer server
                              driver
EnumPrinters enumerates the printers available on the specified server
EnumPrintProcessorDatatypes enumerates the data types supported by the specified printer handler
EnumPrintProcessors enumerates the print processors installed on the specified server
FindClosePrinterChangeNotification is closed by calling
                              FindFirstPrinterChangeNotification function built
                              Change notification object
FindFirstPrinterChangeNotification creates a change notification object and returns a handle, using this
                              The handle checks the printer or printer during a call to a wait function.
                              Print server changes
FindNextPrinterChangeNotification communicates changes related to the specified printer or print server.
                              The object can retrieve the latest change notification notification information, which can also be used to
                              Reset the change notification object to no message state
FreePrinterNotifyInfo releases the system allocation
                              FindNextPrinterChangeNotification function returns
                              Buffer

GetForm initializes data with data describing the specified format for a given printer
                              FORM_INFO_1 structures
GetJob retrieves print job data for a specified printer
GetPrinter retrieves data for a given printer
GetPrinterData retrieves configuration data for a given printer
GetPrinterDriver retrieves driver data for a given printer
GetPrinterDriverDirectory retrieves the directory path of a given printer driver
GetPrintProcessDirectory retrieves the path of the printer handler on the specified server
OpenPrinter retrieves a handle identifying a specific printer or print server
                              And open
PrinterMessageBox displays a message box for notification of a printing application
                              User has a print job error
PrinterProperties displays a printer performance dialog for a given printer to allow
                              Allow to set
ReadPrinter retrieves data from a given printer
ResetPrinter allows the application to be set to submit with StartDocPrinter function
                              Data type and device mode values of the printed document
ScheduleJob notifies the spooler to schedule printing for a specified job
SetForm sets format information for a given printer
SetJob Pauses, resumes, cancels, or restarts the specified printer on a given printer
                              Print job
SetPrinter sets the assignments by pausing, resuming, or clearing all print jobs
                              Printer
SetPrinterData Set configuration data for a printer
StartDocPrinter notifies the spooler that a document will be printed on the spooler
                              files
StartPagePrinter notifies the spooler that a page will be printed on a given printer
WritePrinter notifies the spooler that the specified print should be written to the given printer
                              The data
Implement many commands with low-level communication commands 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.