在 C# 中打印现有的 PDF(或其他文件)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/273675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print existing PDF (or other files) in C#
提问by
From an application I'm building I need to print existing PDFs (created by another app). How can I do this in C# and provide a mechanism so the user can select a different printer or other properties.
从我正在构建的应用程序中,我需要打印现有的 PDF(由另一个应用程序创建)。如何在 C# 中执行此操作并提供一种机制,以便用户可以选择不同的打印机或其他属性。
I've looked at the PrintDialog but not sure what file it is attempting to print, if any, b/c the output is always a blank page. Maybe I'm just missing something there.
我查看了 PrintDialog 但不确定它正在尝试打印什么文件,如果有的话,b/c 输出总是一个空白页。也许我只是在那里错过了一些东西。
Do I need to use "iTextSharp" (as suggested else where)? That seems odd to me since I can "send the the file to the printer" I just don't have any nice dialog before hand to set the printer etc. and I don't really want to write a printing dialog from the ground up but it seems like a lot of examples I found by searching did just that.
我是否需要使用“iTextSharp”(如其他地方所建议的那样)?这对我来说似乎很奇怪,因为我可以“将文件发送到打印机”我只是没有任何好的对话框来设置打印机等,而且我真的不想从头开始编写打印对话框但似乎我通过搜索找到的很多例子就是这样做的。
Any advice, examples or sample code would be great!
任何建议、示例或示例代码都会很棒!
Also if PDF is the issue the files could be created by the other app in a diff format such as bitmap or png if that makes things easier.
此外,如果 PDF 是问题,则其他应用程序可以以 diff 格式(例如位图或 png)创建文件,如果这使事情变得更容易。
回答by plinth
You will need Acrobat or some other application that can print the PDF. From there you P/Invoke to ShellExecuteto print the document.
您将需要 Acrobat 或其他一些可以打印 PDF 的应用程序。从那里你 P/Invoke 到ShellExecute来打印文档。
回答by Nicholas Piasecki
Display a little dialog with a combobox that has its Items set to the string collection returned by PrinterSettings.InstalledPrinters
.
显示一个带有组合框的小对话框,该组合框的 Items 设置为由 返回的字符串集合PrinterSettings.InstalledPrinters
。
If you can make it a requirement that GSViewbe installed on the machine, you can then silently print the PDF. It's a little slow and roundabout but at least you don't have to pop up Acrobat.
如果您可以要求在机器上安装GSView,则您可以静默打印 PDF。它有点缓慢和迂回,但至少你不必弹出 Acrobat。
Here's some code I use to print out some PDFs that I get back from a UPS Web service:
下面是我用来打印从 UPS Web 服务返回的一些 PDF 的一些代码:
private void PrintFormPdfData(byte[] formPdfData)
{
string tempFile;
tempFile = Path.GetTempFileName();
using (FileStream fs = new FileStream(tempFile, FileMode.Create))
{
fs.Write(formPdfData, 0, formPdfData.Length);
fs.Flush();
}
try
{
string gsArguments;
string gsLocation;
ProcessStartInfo gsProcessInfo;
Process gsProcess;
gsArguments = string.Format("-grey -noquery -printer \"HP LaserJet 5M\" \"{0}\"", tempFile);
gsLocation = @"C:\Program Files\Ghostgum\gsview\gsprint.exe";
gsProcessInfo = new ProcessStartInfo();
gsProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
gsProcessInfo.FileName = gsLocation;
gsProcessInfo.Arguments = gsArguments;
gsProcess = Process.Start(gsProcessInfo);
gsProcess.WaitForExit();
}
finally
{
File.Delete(tempFile);
}
}
As you can see, it takes the PDF data as a byte array, writes it to a temp file, and launches gsprint.exe to print the file silently to the named printer ("HP Laserjet 5M"). You could replace the printer name with whatever the user chose in your dialog box.
如您所见,它将 PDF 数据作为字节数组,将其写入临时文件,然后启动 gsprint.exe 以静默方式将文件打印到指定的打印机(“HP Laserjet 5M”)。您可以使用用户在对话框中选择的任何名称替换打印机名称。
Printing a PNG or GIF would be much easier -- just extend the PrintDocument class and use the normal print dialog provided by Windows Forms.
打印 PNG 或 GIF 会容易得多——只需扩展 PrintDocument 类并使用 Windows 窗体提供的普通打印对话框。
Good luck!
祝你好运!
回答by Nicholas Piasecki
Although this is VB you can easily translate it. By the way Adobe does not pop up, it only prints the pdf and then goes away.
虽然这是 VB,但您可以轻松翻译它。顺便说一下,Adobe 不会弹出,它只会打印 pdf 文件然后消失。
''' <summary>
''' Start Adobe Process to print document
''' </summary>
''' <param name="p"></param>
''' <remarks></remarks>
Private Function printDoc(ByVal p As PrintObj) As PrintObj
Dim myProcess As New Process()
Dim myProcessStartInfo As New ProcessStartInfo(adobePath)
Dim errMsg As String = String.Empty
Dim outFile As String = String.Empty
myProcessStartInfo.UseShellExecute = False
myProcessStartInfo.RedirectStandardOutput = True
myProcessStartInfo.RedirectStandardError = True
Try
If canIprintFile(p.sourceFolder & p.sourceFileName) Then
isAdobeRunning(p)'Make sure Adobe is not running; wait till it's done
Try
myProcessStartInfo.Arguments = " /t " & """" & p.sourceFolder & p.sourceFileName & """" & " " & """" & p.destination & """"
myProcess.StartInfo = myProcessStartInfo
myProcess.Start()
myProcess.CloseMainWindow()
isAdobeRunning(p)
myProcess.Dispose()
Catch ex As Exception
End Try
p.result = "OK"
Else
p.result = "The file that the Document Printer is tryng to print is missing."
sendMailNotification("The file that the Document Printer is tryng to print" & vbCrLf & _
"is missing. The file in question is: " & vbCrLf & _
p.sourceFolder & p.sourceFileName, p)
End If
Catch ex As Exception
p.result = ex.Message
sendMailNotification(ex.Message, p)
Finally
myProcess.Dispose()
End Try
Return p
End Function
回答by David Duffett
You could also use PDFsharp - it's an open source library for creating and manipulating PDFs. http://www.pdfsharp.net/
您也可以使用 PDFsharp - 它是一个用于创建和操作 PDF 的开源库。 http://www.pdfsharp.net/
回答by Parvej Solkar
I'm doing the same thing for my project and it worked for me
我正在为我的项目做同样的事情,它对我有用
See if it can help you...
看看能不能帮到你...
Process p = new Process();
p.EnableRaisingEvents = true; //Important line of code
p.StartInfo = new ProcessStartInfo()
{
CreateNoWindow = true,
Verb = "print",
FileName = file,
Arguments = "/d:"+printDialog1.PrinterSettings.PrinterName
};
try
{
p.Start();
}
catch
{
/* your fallback code */
}
You can also play with different options of windows
您还可以使用不同的窗口选项
PRINT command to get desired output...Reference link
PRINT 命令以获得所需的输出...参考链接
回答by Marko
After much research and googling about this task Microsoft has released a great KB to print a pdf without any other applications necessary. No need to call adobe or ghostprint. It can print without saving a file to the disk makes life very easy.
在对这项任务进行大量研究和谷歌搜索之后,微软发布了一个很棒的知识库,可以在不需要任何其他应用程序的情况下打印 pdf。无需调用 adobe 或 ghostprint。它可以在不将文件保存到磁盘的情况下进行打印,这让生活变得非常轻松。