UFO ET IT

파일 문서를 프린터로 보내고 인쇄하려면 어떻게해야합니까?

ufoet 2020. 12. 2. 22:18
반응형

파일 문서를 프린터로 보내고 인쇄하려면 어떻게해야합니까?


기본 전제는 다음과 같습니다.

내 사용자가 일부 기즈모를 클릭하면 PDF 파일이 데스크탑으로 튀어 나옵니다. 이 파일을 프린터 대기열로 보내고 로컬로 연결된 프린터로 인쇄 할 수있는 방법이 있습니까?

string filePath = "filepathisalreadysethere";
SendToPrinter(filePath); //Something like this?

그는이 과정을 여러 번 할 것입니다. 교실에있는 각 학생에게 작은 성적표를 인쇄해야합니다. 그래서 저는 각 학생에 대해 PDF를 생성하고 사용자가 pdf를 생성하고 인쇄하고 pdf를 생성하고 인쇄하고 pdf를 생성하고 인쇄하는 대신 인쇄 프로세스를 자동화하고 싶습니다.

이에 접근하는 방법에 대한 제안이 있습니까? Windows Forms .NET 4가 설치된 Windows XP에서 실행하고 있습니다.

수락 된 답변이 제안하는 StackOverflow 질문을 찾았습니다 .

파일을 생성 한 후에는 명령 줄을 통해 인쇄 할 수 있습니다 (System.Diagnostics 네임 스페이스에있는 Command 클래스를 사용할 수 있음).

어떻게해야합니까?


Acrobat Reader에 '인쇄'동사를 사용하여 파일을 인쇄하도록 지시 할 수 있습니다. 그 후에도 프로그래밍 방식으로 Acrobat Reader를 닫아야합니다.

private void SendToPrinter()
{
   ProcessStartInfo info = new ProcessStartInfo();
   info.Verb = "print";
   info.FileName = @"c:\output.pdf";
   info.CreateNoWindow = true;
   info.WindowStyle = ProcessWindowStyle.Hidden;

   Process p = new Process();
   p.StartInfo = info;
   p.Start();

   p.WaitForInputIdle();
   System.Threading.Thread.Sleep(3000);
   if (false == p.CloseMainWindow())
      p.Kill();
}

이렇게하면 Acrobat Reader가 열리고 PDF를 기본 프린터로 보낸 다음 3 초 후에 Acrobat이 종료됩니다.

응용 프로그램과 함께 다른 제품을 제공하려는 경우 GhostScript (무료) 또는 http://www.commandlinepdf.com/ (상용) 과 같은 명령 줄 PDF 프린터를 사용할 수 있습니다 .

참고 : 샘플 코드는 PDF 를 인쇄하기 위해 현재 등록 된 응용 프로그램 에서 PDF를 엽니 다. 이는 대부분의 사용자 컴퓨터에서 Adobe Acrobat Reader입니다. 그러나 Foxit ( http://www.foxitsoftware.com/pdf/reader/ ) 과 같은 다른 PDF 뷰어를 사용할 수 있습니다 . 하지만 샘플 코드는 여전히 작동합니다.


.net에서 PDF를 인쇄하는 문제로 이것에 대한 새로운 답변을 추가하는 것은 오랫동안 존재했으며 대부분의 답변은 현재 .net 래퍼가있는 Google Pdfium 라이브러리보다 이전입니다. 저를 위해 저는이 문제를 직접 조사하고 있었고 계속 공백이되었고 Acrobat 또는 다른 PDF 리더를 생성하거나 비용이 많이 들고 라이센스 조건이 호환되지 않는 상용 라이브러리를 실행하는 것과 같은 해키 솔루션을 시도했습니다. 그러나 Google Pdfium 라이브러리와 PdfiumViewer .net 래퍼는 오픈 소스이므로 저를 포함하여 많은 개발자에게 훌륭한 솔루션입니다. PdfiumViewer는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다.

여기에서 NuGet 패키지를 얻을 수 있습니다.

https://www.nuget.org/packages/PdfiumViewer/

여기에서 소스 코드를 찾을 수 있습니다.

https://github.com/pvginkel/PdfiumViewer

다음은 파일 이름에서 PDF 파일의 사본 수에 관계없이 자동으로 인쇄하는 간단한 코드입니다. 스트림에서 PDF를로드 할 수도 있습니다 (일반적으로 수행하는 방식). 코드 나 예제를 보면 쉽게 파악할 수 있습니다. 또한 WinForm PDF 파일보기가 있으므로 PDF 파일을보기로 렌더링하거나 인쇄 미리보기를 수행 할 수도 있습니다. 우리에게는 요청에 따라 PDF 파일을 특정 프린터로 자동으로 인쇄하는 방법이 필요했습니다.

public bool PrintPDF(
    string printer,
    string paperName,
    string filename,
    int copies)
{
    try {
        // Create the printer settings for our printer
        var printerSettings = new PrinterSettings {
            PrinterName = printer,
            Copies = (short)copies,
        };

        // Create our page settings for the paper size selected
        var pageSettings = new PageSettings(printerSettings) {
            Margins = new Margins(0, 0, 0, 0),
        };
        foreach (PaperSize paperSize in printerSettings.PaperSizes) {
            if (paperSize.PaperName == paperName) {
                pageSettings.PaperSize = paperSize;
                break;
            }
        }

        // Now print the PDF document
        using (var document = PdfDocument.Load(filename)) {
            using (var printDocument = document.CreatePrintDocument()) {
                printDocument.PrinterSettings = printerSettings;
                printDocument.DefaultPageSettings = pageSettings;
                printDocument.PrintController = new StandardPrintController();
                printDocument.Print();
            }
        }
        return true;
    } catch {
        return false;
    }
}

나는 태그가 Windows Forms... 라고 말하는 것을 알고 있지만, 누군가 WPF신청 방법에 관심이 있다면 System.Printing매력처럼 작동합니다.

var file = File.ReadAllBytes(pdfFilePath);
var printQueue = LocalPrintServer.GetDefaultPrintQueue();

using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
    stream.Write(file, 0, file.Length);
}

System.Printing아직 포함되지 않은 경우 참조 를 포함 하는 것을 잊지 마십시오. 이제이 방법은 ASP.NET또는 에서 잘 작동하지 않습니다 Windows Service. Windows Forms같이 사용하면 안됩니다 System.Drawing.Printing. 위 코드를 사용하여 PDF를 인쇄하는 데 단 하나의 문제가 없습니다.

그러나 프린터가 PDF 파일 형식에 대해 Direct Print를 지원하지 않는 경우이 방법을 사용하면 운이 좋지 않습니다.


이것은 약간 수정 된 솔루션입니다. 프로세스는 1 초 이상 유휴 상태 일 때 종료됩니다. X 초의 시간을 추가하고 별도의 스레드에서 함수를 호출해야 할 수도 있습니다.

private void SendToPrinter()
{
  ProcessStartInfo info = new ProcessStartInfo();
  info.Verb = "print";
  info.FileName = @"c:\output.pdf";
  info.CreateNoWindow = true;
  info.WindowStyle = ProcessWindowStyle.Hidden;

  Process p = new Process();
  p.StartInfo = info;
  p.Start();

  long ticks = -1;
  while (ticks != p.TotalProcessorTime.Ticks)
  {
    ticks = p.TotalProcessorTime.Ticks;
    Thread.Sleep(1000);
  }

  if (false == p.CloseMainWindow())
    p.Kill();
}

다음 코드 조각은 PdfiumViewer 라이브러리를 사용하여 pdf 파일을 인쇄하기위한 Kendall Bennett의 코드를 수정 한 것입니다 . 가장 큰 차이점은 파일이 아닌 스트림이 사용된다는 것입니다.

public bool PrintPDF(
    string printer,
    string paperName,
    int copies, Stream stream)
        {
            try
            {
                // Create the printer settings for our printer
                var printerSettings = new PrinterSettings
                {
                    PrinterName = printer,
                    Copies = (short)copies,
                };

            // Create our page settings for the paper size selected
            var pageSettings = new PageSettings(printerSettings)
            {
                Margins = new Margins(0, 0, 0, 0),
            };
            foreach (PaperSize paperSize in printerSettings.PaperSizes)
            {
                if (paperSize.PaperName == paperName)
                {
                    pageSettings.PaperSize = paperSize;
                    break;
                }
            }

            // Now print the PDF document
            using (var document = PdfiumViewer.PdfDocument.Load(stream))
            {
                using (var printDocument = document.CreatePrintDocument())
                {
                    printDocument.PrinterSettings = printerSettings;
                    printDocument.DefaultPageSettings = pageSettings;
                    printDocument.PrintController = new StandardPrintController();
                    printDocument.Print();
                }
            }
            return true;
        }
        catch (System.Exception e)
        {
            return false;
        }
    }

In my case I am generating the PDF file using a library called PdfSharp and then saving the document to a Stream like so:

        PdfDocument pdf = PdfGenerator.GeneratePdf(printRequest.html, PageSize.A4);
        pdf.AddPage();

        MemoryStream stream = new MemoryStream();
        pdf.Save(stream);
        MemoryStream stream2 = new MemoryStream(stream.ToArray());

One thing that I want to point out that might be helpful to other developers is that I had to install the 32 bit version of the pdfuim native dll in order for the printing to work even though I am running Windows 10 64 bit. I installed the following two NuGet packages using the NuGet package manager in Visual Studio:

  • PdfiumViewer
  • PdfiumViewer.Native.x86.v8-xfa

System.Diagnostics.Process.Start can be used to print a document. Set UseShellExecute to True and set the Verb to "print".


The easy way:

var pi=new ProcessStartInfo("C:\file.docx");
pi.UseShellExecute = true;
pi.Verb = "print";
var process =  System.Diagnostics.Process.Start(pi);

You can try with GhostScript like in this post:

How to print PDF on default network printer using GhostScript (gswin32c.exe) shell command


this is a late answer, but you could also use the File.Copy method of the System.IO namespace top send a file to the printer:

System.IO.File.Copy(filename, printerName);

This works fine


I know Edwin answered it above but his only prints one document. I use this code to print all files from a given directory.

public void PrintAllFiles()
{
    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
    info.Verb = "print";
    System.Diagnostics.Process p = new System.Diagnostics.Process();
    //Load Files in Selected Folder
    string[] allFiles = System.IO.Directory.GetFiles(Directory);
    foreach (string file in allFiles)
    {
        info.FileName = @file;
        info.CreateNoWindow = true;
        info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
         p.StartInfo = info;
        p.Start();
    }
    //p.Kill(); Can Create A Kill Statement Here... but I found I don't need one
    MessageBox.Show("Print Complete");
}

It essentually cycles through each file in the given directory variable Directory - > for me it was @"C:\Users\Owner\Documents\SalesVaultTesting\" and prints off those files to your default printer.


You can use the DevExpress PdfDocumentProcessor.Print(PdfPrinterSettings) Method.

public void Print(string pdfFilePath)
{
      if (!File.Exists(pdfFilePath))
          throw new FileNotFoundException("No such file exists!", pdfFilePath);

      // Create a Pdf Document Processor instance and load a PDF into it.
      PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor();
      documentProcessor.LoadDocument(pdfFilePath);

      if (documentProcessor != null)
      {
          PrinterSettings settings = new PrinterSettings();

          //var paperSizes = settings.PaperSizes.Cast<PaperSize>().ToList();
          //PaperSize sizeCustom = paperSizes.FirstOrDefault<PaperSize>(size => size.Kind == PaperKind.Custom); // finding paper size

          settings.DefaultPageSettings.PaperSize = new PaperSize("Label", 400, 600);

          // Print pdf
          documentProcessor.Print(settings);
      }
}

참고URL : https://stackoverflow.com/questions/6103705/how-can-i-send-a-file-document-to-the-printer-and-have-it-print

반응형