开发者

Print Pdf in C# [closed]

开发者 https://www.devze.com 2023-02-22 16:52 出处:网络
Closed. This question needs to be more focused. It is not currently accepting answers. 开发者_Go百科
Closed. This question needs to be more focused. It is not currently accepting answers. 开发者_Go百科

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 2 years ago.

Improve this question

I'm new to c#. I was looking all over the net for tutorials on how to print pdf, but couldn't find one.

Then I thought, is it possible to read it using itextpdf, like mentioned here

Reading PDF content with itextsharp dll in VB.NET or C#

then print it. If so, how?


A very straight forward approach is to use an installed Adobe Reader or any other PDF viewer capable of printing:

Process p = new Process( );
p.StartInfo = new ProcessStartInfo( )
{
    CreateNoWindow = true,
    Verb = "print",
    FileName = path //put the correct path here
};
p.Start( );

Another way is to use a third party component, e.g. PDFView4NET


I wrote a little helper method around the adobereader to bulk-print pdf from c#...:

  public static bool Print(string file, string printer) {
     try {
        Process.Start(
           Registry.LocalMachine.OpenSubKey(
                @"SOFTWARE\Microsoft\Windows\CurrentVersion" +
                @"\App Paths\AcroRd32.exe").GetValue("").ToString(),
           string.Format("/h /t \"{0}\" \"{1}\"", file, printer));
        return true;
     } catch { }
     return false;
  }

One cannot rely on the return-value of the method btw...


Another approach, if you simply wish to print a PDF file programmatically, is to use the LPR command: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/lpr

LPR is available on newer versions of Windows too (e.g. Vista/7), but you need to enable it in the Optional Windows Components.

For example:

Process.Start("LPR -S printerdnsalias -P raw C:\files\file.pdf");

You can also use the printer IP address instead of the alias.

This assumes that your printer supports PDF Direct Printing otherwise this will only work for PostScript and ASCII files. Also, the printer needs to have a network interface installed and you need to know it's IP address or alias.


Use PDFiumViewer. I searched for a long time till I came up with a similar solution, then I found this clean piece of code that does not rely on sending raw files to the printer (which is bad if they get interpreted as text files..) or using Acrobat or Ghostscript as a helper (both would need to be installed, which is a hassle):

https://stackoverflow.com/a/41751184/586754

PDFiumViewer comes via nuget, the code example above is complete. Pass in null values for using the default printer.


I had the same problem on printing a PDF file. There's a nuget package called Spire.Pdf that's very simple to use. The free version has a limit of 10 pages although, however, in my case it was the best solution once I don't want to depend on Adobe Reader and I don't want to install any other components.

https://www.nuget.org/packages/Spire.PDF/

PdfDocument pdfdocument = new PdfDocument();
pdfdocument.LoadFromFile(pdfPathAndFileName);
pdfdocument.PrinterName = "My Printer";
pdfdocument.PrintDocument.PrinterSettings.Copies = 2;
pdfdocument.PrintDocument.Print();
pdfdocument.Dispose();


You can create the PDF document using PdfSharp. It is an open source .NET library.

When trying to print the document it get worse. I have looked allover for a open source way of doing it. There are some ways do do it using AcroRd32.exe but it all depends on the version, and it cannot be done without acrobat reader staying open.

I finally ended up using VintaSoftImaging.NET SDK. It costs some money but is much cheaper than the alternative and it solves the problem really easy.

var doc = new Vintasoft.Imaging.Print.ImagePrintDocument { DocumentName = @"C:\Test.pdf" };
doc.Print();

That just prints to the default printer without showing. There are several alternatives and options.


The best way to print pdf automatically from C# is using printer's "direct pdf". You just need to copy the pdf file to printer's network sharename. The rest will be taken care by printer itself.

The speed is 10 times faster than any other methods. However, the requirements are the printer model supporting for direct pdf printing and having at least 128 MB Dram which is easy for any modern printer.


I wrote and released a small Nuget Package which can be used to print a PDF file to a printerdriver. It can also print to a XPS file or PDF file. Here is a link to it.


It is possible to use Ghostscript to read PDF files and print them to a named printer.


Looks like the usual suspects like pdfsharp and migradoc are not able to do that (pdfsharp only if you have Acrobat (Reader) installed).

I found here

https://vishalsbsinha.wordpress.com/2014/05/06/how-to-programmatically-c-net-print-a-pdf-file-directly-to-the-printer/

code ready for copy/paste. It uses the default printer and from what I can see it doesn't even use any libraries, directly sending the pdf bytes to the printer. So I assume the printer also needs to support it, on one 10 year old printer I tested this it worked flawlessly.

Most other approaches - without commercial libraries or applications - require you to draw yourself in the printing device context. Doable but will take a while to figure it out and make it work across printers.


The easiest way is to create C# Process and launch external tool to print your PDF file

private static void ExecuteRawFilePrinter() {
    Process process = new Process();
    process.StartInfo.FileName = "c:\\Program Files (x86)\\RawFilePrinter\\RawFilePrinter.exe";
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.StartInfo.Arguments = string.Format("-p \"c:\\Users\\Me\\Desktop\\mypdffile.pdf\" \"gdn02ptr006\"");
    process.Start();
    process.WaitForExit();
}

Code above launches RawFilePrinter.exe (similar to 2Printer.exe), but with better support. It is not free, but by making donation allow you to use it everywhere and redistribute with your application. Latest version to download: http://bigdotsoftware.pl/rawfileprinter


It depends on what you are trying to print. You need a third party pdf printer application or if you are printing data of your own you can use report viewer in visual studio. It can output reports to excel and pdf -files.


It is also possible to do it with an embedded web browser, note however that since this might be a local file, and also because it is not actually the browser directly and there is no DOM so there is no ready state.

Here is the code for the approach I worked out on a win form web browser control:

    private void button1_Click(object sender, EventArgs e)
    {
        webBrowser1.Navigate(@"path\to\file");
    }  

    private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
    {   
        //Progress Changed fires multiple times, however after the Navigated event it is fired only once,
        //and at this point it is ready to print
        webBrowser1.ProgressChanged += (o, args) => 
        {
            webBrowser1.Print();//Note this does not print only brings up the print preview dialog
            //Should be on a separate task to ensure the main thread 
            //can fully initialize the print dialog 
            Task.Factory.StartNew(() => 
            {
                Thread.Sleep(1000);//We need to wait before we can send enter
                //This assumes that the print preview is still in focus
                Action g = () =>
                {
                    SendKeys.SendWait("{ENTER}");
                };
                this.Invoke(g);
            });
        };
    }


I advice you to try 2Printer command line tool from: http://www.doc2prn.com/

Command line example to print all PDF files from folder "C:\Input" is below. You can simple call it from your C# code.

2Printer.exe -s "C:\Input*.PDF" -prn "Canon MP610 series Printer"


If you have Adobe Reader installed, then you should be able to just set it as the default printer. And VOILA! You can print to PDF!

printDocument1.PrinterSettings.PrinterName = "Adobe PDF";
printDocument1.Print();

Just as simple as that!!!


Open, import, edit, merge, convert Acrobat PDF documents with a few lines of code using the intuitive API of Ultimate PDF. By using 100% managed code written in C#, the component takes advantage of the numerous built-in features of the .NET Framework to enhance performance. Moreover, the library is CLS compliant, and it does not use any unsafe blocks for minimal permission requirements. The classes are fully documented with detailed example code which helps shorten your learning curve. If your development environment is Visual Studio, enjoy the full integration of the online documentation. Just mark or select a keyword and press F1 in your Visual Studio IDE, and the online documentation is represented instantly. A high-performance and reliable PDF library which lets you add PDF functionality to your .NET applications easily with a few lines of code.

PDF Component for NET

0

精彩评论

暂无评论...
验证码 换一张
取 消