Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

winforms - How to print a PDF with C#

I′ve trying to solve this problem for nearly 2 days. There are a lot of more or fewer good solutions on the net, but not a single one fits my task perfectly.

Task:

  • Print a PDF programmatically
  • Do it with a fixed printer
  • Don′t let the user do more than one Button_Click
  • Do it silent - the more, the better
  • Do it client side

First Solutions:

Do it with a Forms.WebBrowser

If we have Adobe Reader installed, there is a plugin to show PDF′s in the webbrowser. With this solution we have a nice preview and with webbrowserControlName.Print() we can trigger the control to print its content.

Problem - we still have a PrintDialog.


Start the AcroRd32.exe with start arguments

The following CMD command let us use Adobe Reader to print our PDF.

InsertPathTo..AcroRd32.exe /t "C:sample.pdf" "printerNetworkprinterName"

Problems - we need the absolute path to AcroRd32.exe | there is an Adobe Reader Window opening and it has to be opened until the print task is ready.


Use windows presets

Process process = new Process();

process.StartInfo.FileName = pathToPdf; 
process.StartInfo.Verb = "printto";
process.StartInfo.Arguments = """ + printerName + """; 
process.Start();

process.WaitForInputIdle();
process.Kill();

Problem - there is still an Adobe Reader window popping up, but after the printing is done it closes itself usually.

Solution - convince the client to use Foxit Reader (don′t use last two lines of code).


Convert PDF pages to Drawing.Image

I′ve no idea how to do it with code, but when I get this to work the rest is just a piece of cake. Printing.PrintDocument can fulfill all demands.


Anyone an idea to get some Drawing.Image′s out of those PDF′s or another approach how to do it?

Best Regards, Max

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The most flexible, easiest and best performing method I could find was using GhostScript. It can print to windows printers directly by printer name.

"C:Program Filesgsgs9.07ingswin64c.exe" -dPrinted -dBATCH -dNOPAUSE -sDEVICE=mswinpr2 -dNoCancel -sOutputFile="%printer%printer name" "pdfdocument.pdf"

Add these switches to shrink the document to an A4 page.

-sPAPERSIZE=a4 -dPDFFitPage


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...