如何在Windows应用程序中打印PDF文件. [英] How can i print a PDF file in windows application.

查看:101
本文介绍了如何在Windows应用程序中打印PDF文件.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我实现通过Windows应用程序打印PDF文件.

Kindly help me to achieve to print a PDF file thro windows applicatoin.

推荐答案

尝试iText
http://itextpdf.com/itext.php [ http://itextpdf.com/book/examples.php [
Try iText
http://itextpdf.com/itext.php[^]
http://itextpdf.com/book/examples.php[^]


导入System.IO
导入System.Drawing.Printing
进口MODI
导入DocumentProcessing
''导入Microsoft.Office.Interop.Word
导入Microsoft.Office.Core
导入System.Runtime.InteropServices

导入PrinterQueueWatch
公共课程表格1

私人打印字体为字体
私有streamToPrint作为StreamReader
私有共享filePath为字符串
私有_MODIDocument作为MODI.Document = Nothing
Dim Proc作为新的System.Diagnostics.Process



私有子Button1_Click(ByVal发送者为System.Object,ByVal e为System.EventArgs)处理Button1.Click

filePath ="E:\ Personal \ Personal \ BackButtonDisable.txt"
''打印()

''PrintDialog1.PrinterSettings.PrintFileName = filePath

''PrintDialog1.Document = PrintDocument1
''PrintDialog1.ShowDialog()
''PrintFile()
printdoc()
''PrintMyExcelFile()
" PrintPDF("E:\ Personal \ Personal \ Credit Card \ PNR IOHPTI \ frmViewPassportPage1.pdf")

结束子


''打印文件.
公共子印刷()
试试
streamToPrint =新的StreamReader(filePath)
试试
printFont =新字体("Arial",10)
昏暗的pd作为新的PrintDocument()
AddHandler pd.PrintPage,AddressOf pd_PrintPage
''打印文档.
pd.Print()
终于
streamToPrint.Close()
结束尝试
异常捕获
MessageBox.Show(ex.Message)
结束尝试
结束子''打印

私人Sub pd_PrintPage(ByVal发送者为对象,ByVal ev为PrintPageEventArgs)
Dim linesPerPage如单个= 0
昏暗的yPos单身= 0
昏暗计数为整数= 0
Dim leftMargin为Single = ev.MarginBounds.Left
Dim topMargin As Single = ev.MarginBounds.Top
暗线作为字符串=什么都没有



''计算每页的行数.
linesPerPage = ev.MarginBounds.Height/printFont.GetHeight(ev.Graphics)

''打印文件的每一行.
计数< linesPerPage
行= streamToPrint.ReadLine()
如果线路什么都没有,那么
While While
如果结束
yPos = topMargin + count * printFont.GetHeight(ev.Graphics)
ev.Graphics.DrawString(line,printFont,Brushes.Black,leftMargin,yPos,New StringFormat())
计数+ = 1
结束时

''如果存在更多行,请打印另一页.
如果(行不是空行)则
ev.HasMorePages = True
其他
ev.HasMorePages = False
如果结束
结束子





''Private Sub PrintDocument1_PrintPage(ByVal sender as Object,ByVal e System.Drawing.Printing.PrintPageEventArgs)处理PrintDocument1.PrintPage

''''把linesPerPage设为昏暗= 0
''''将yPos设置为Single = 0
''''昏暗计数为整数= 0
''''将leftMargin设置为Single = e.MarginBounds.Left
''''将topMargin设置为Single = e.MarginBounds.Top
''''将行作为字符串调暗=无

''''''计算每页的行数.
''''linesPerPage = e.MarginBounds.Height/printFont.GetHeight(e.Graphics)

''''遍历文件,打印每一行.
''虽然计数< linesPerPage
''''line = streamToPrint.ReadLine()
''''如果行什么都没有,那么
''''While While
退出 ''''如果结束
''''yPos = topMargin +计数* printFont.GetHeight(e.Graphics)
''''e.Graphics.DrawString(line,printFont,Brushes.Black,leftMargin,_
''''yPos,新的StringFormat())
''数+ = 1
''''结束而

''''如果存在更多行,请打印另一页.
''''如果不是(行什么都不是)那么
''''e.HasMorePages = True
''''其他
''''e.HasMorePages = False
''''如果结束
''Dim Image As System.Drawing.Image = pictureBox1.Image
''e.Graphics.DrawImage(Image,New Point(0,0))


''结束子

私有子PrintFile()
''_filename =文件名;
_MODIDocument =新的MODI.Document()

_MODIDocument.Create("E:\ Personal \ Personal \ Medical \ Saravana_Nov_Activities.doc")
如果_MODIDocument什么都没有,那么
昏暗的新PrintDialog()
d.AllowSomePages = True
d.AllowSelection = False
d.PrintToFile = False
昏暗的ps作为新的PrinterSettings()
ps.MinimumPage = 0
ps.MaximumPage = _MODIDocument.Images.Count-1
ps.FromPage = 0
ps.ToPage = _MODIDocument.Images.Count-1

d.PrinterSettings = ps
如果d.ShowDialog()= DialogResult.OK然后

_MODIDocument.PrintOut(d.PrinterSettings.FromPage,d.PrinterSettings.ToPage,d.PrinterSettings.Copies,d.PrinterSettings.PrinterName,",False,_
MODI.MiPRINT_FITMODES.miPRINT_ACTUALSIZE)
如果结束
如果结束
结束子


公共子printdoc()

昏暗的ac作为新的Microsoft.Office.Interop.Word.Application

昏暗的应用程序作为Microsoft.Office.Interop.Word.Application = ac.Application
昏暗的lsPriterName作为字符串
''我正在尝试将所有警报设置为关闭
''这将在后台打印
app.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone

''打开文档进行打印...
昏暗的文件名作为对象="E:\ Personal \ Personal \ Medical \ Saravana_Nov_Activities.docx"
昏暗的缺少值(作为对象)= Type.Missing
''使用OpenOld以便与Word的其他版本兼容 昏暗的文档为Microsoft.Office.Interop.Word.Document = app.Documents.Open(文件名,missingValue,missingValue,missingValue,missingValue,missingValue,_
missingValue,missingValue,missingValue,missingValue)

''设置活动打印机
昏暗的新PrintDialog()
如果d.ShowDialog()= DialogResult.OK然后
lsPriterName = d.PrinterSettings.PrinterName
其他
退出子
如果结束

app.ActivePrinter = lsPriterName
Dim myTrue As Object = True
''在后台打印
Dim myFalse As Object = False
''使用PrintOutOld来实现版本独立性
app.ActiveDocument.PrintOut(myTrue,myFalse,missingValue,missingValue,missingValue,missingValue,_
missingValue,missingValue,missingValue,missingValue,myFalse,missingValue,_
missingValue,missingValue)

document.Close(missingValue,missingValue,missingValue)

''确保所有文档都已从队列中移出
而app.BackgroundPrintingStatus> 0
System.Threading.Thread.Sleep(250)
结束时

''清理:
GC.Collect()
GC.WaitForPendingFinalizers()
元帅.FinalReleaseComObject(app)
元帅.FinalReleaseComObject(ac)
文档=没什么

结束子

''私有子InvokePrint(ByVal发送者作为对象,ByVal e作为RoutedEventArgs)
''''创建打印对话框对象并设置选项
''将pDialog设为新的PrintDialog()
''pDialog.PageRangeSelection = PageRangeSelection.AllPages
''pDialog.UserPageRangeEnabled = True
''''显示对话框.如果用户按下打印"按钮,则返回true.
''Dim print As Nullable(Of [Boolean])= pDialog.ShowDialog()
''如果print = True则
"将xpsDocument设置为新的XpsDocument("C:\ FixedDocumentSequence.xps",FileAccess.ReadWrite)
''Dim fixedDocSeq As FixedDocumentSequence = xpsDocument.GetFixedDocumentSequence()
" pDialog.PrintDocument(fixedDocSeq.DocumentPaginator,测试打印作业")
''结束如果
''结束子

私人子PrintMyExcelFile()
将excelApp变暗为新的Microsoft.Office.Interop.Excel.Application()
''打开工作簿:
如Microsoft.Office.Interop.Excel.Workbook = excelApp.Workbooks.Open("E:\ Personal \ Personal \ Medical \ Card.xlsx",Type.Missing,Type.Missing,Type.Missing,Type.Missing,缺少类型,_
Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,_
Type.Missing,Type.Missing,Type.Missing)
''获取第一个工作表.
''(Excel使用基于1的索引,而不是基于0的索引.)
作为Microsoft.Office.Interop.Excel.Worksheet的Dim ws = DirectCast(wb.Worksheets(1),Microsoft.Office.Interop.Excel.Worksheet)
''将1份副本打印到默认打印机:


''将App设为Microsoft.Office.Interop.Excel.Application = excelApp.Application
''将lsPriterName设为字符串
''将Dim d作为新的PrintDialog()
''如果d.ShowDialog()= DialogResult.OK然后
''lsPriterName = d.PrinterSettings.PrinterName
''其他
''退出子
''如果结束

''ws.ActivePrinter = lsPriterName

''ws.ActiveDocument.PrintOutOld(Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,_
''Type.Missing,Type.Missing)
ws.PrintOut(Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,_
Type.Missing,Type.Missing)
''清理:
GC.Collect()
GC.WaitForPendingFinalizers()
元帅.FinalReleaseComObject(ws)
wb.Close(False,Type.Missing,Type.Missing)
元帅.FinalReleaseComObject(wb)
excelApp.Quit()
元帅.FinalReleaseComObject(excelApp)
结束子

公共函数PrintPDF(ByVal PDFFile作为字符串,ByVal PrinterName作为字符串,ByVal超时作为整数)作为整数

昏暗的新PrintDialog()
如果d.ShowDialog()= DialogResult.OK然后
PrinterName = d.PrinterSettings.PrinterName
其他
退出功能
如果结束

如果PrinterName.Trim.Length = 0则
PrinterName =(新System.Drawing.Printing.PrinterSettings).PrinterName
如果结束

''Dim Proc作为新System.Diagnostics.Process

Proc.EnableRaisingEvents = True
Proc.StartInfo.FileName = PDFFile
Proc.StartInfo.Arguments = Chr(34)+ PrinterName + Chr(34)
Proc.StartInfo.Verb =打印到"
Proc.StartInfo.WindowStyle = ProcessWindowStyle.Minimized
Proc.StartInfo.CreateNoWindow = True

''现在开始监视打印机队列.
昏暗的监视器作为新的PrinterQueueWatch.PrinterMonitorComponent
Monitor.MonitorJobAddedEvent = False
Monitor.MonitorJobDeletedEvent = False
Monitor.MonitorJobSetEvent = True
Monitor.MonitorJobWrittenEvent = False
Monitor.MonitorPrinterChangeEvent = False
AddHandler Monitor.JobSet,AddressOf SetPrintJob
Monitor.DeviceName =打印机名称

''现在我正在观看,请启动Acrobat.
Proc.Start()

超时时执行> 0还不存在已退出
System.Threading.Thread.Sleep(1000)
超时-= 1
循环

''停止监视.
RemoveHandler Monitor.JobSet,AddressOf SetPrintJob
监视器=什么都没有

如果没有Proc.HasExited然后
Debug.Print(杀死进程")
Proc.Kill()
如果结束

Debug.WriteLine(关闭过程")
Proc.Close()

返回0
最终功能
公共函数PrintPDF(以字符串形式ByByVal PDFFile)作为整数
返回PrintPDF(PDFFile,",60)
最终功能
公共函数PrintPDF(ByVal PDFFile为字符串,ByVal超时为整数)为整数
返回PrintPDF(PDFFile,",超时)
最终功能

Private Sub SetPrintJob(ByVal发送者为对象,ByVal e为System.EventArgs)
''打印作业已设置为打印.
System.Threading.Thread.Sleep(500)
Proc.Kill()
结束子

结束类
Imports System.IO
Imports System.Drawing.Printing
Imports MODI
Imports DocumentProcessing
''Imports Microsoft.Office.Interop.Word
Imports Microsoft.Office.Core
Imports System.Runtime.InteropServices

Imports PrinterQueueWatch
Public Class Form1

Private printFont As Font
Private streamToPrint As StreamReader
Private Shared filePath As String
Private _MODIDocument As MODI.Document = Nothing
Dim Proc As New System.Diagnostics.Process



Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

filePath = "E:\Personal\Personal\BackButtonDisable.txt"
''Printing()

''PrintDialog1.PrinterSettings.PrintFileName = filePath

''PrintDialog1.Document = PrintDocument1
''PrintDialog1.ShowDialog()
''PrintFile()
printdoc()
''PrintMyExcelFile()
''PrintPDF("E:\Personal\Personal\Credit Card\PNR IOHPTI\frmViewPassportPage1.pdf")

End Sub


''Print the file.
Public Sub Printing()
Try
streamToPrint = New StreamReader(filePath)
Try
printFont = New Font("Arial", 10)
Dim pd As New PrintDocument()
AddHandler pd.PrintPage, AddressOf pd_PrintPage
''Print the document.
pd.Print()
Finally
streamToPrint.Close()
End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub ''Printing

Private Sub pd_PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
Dim linesPerPage As Single = 0
Dim yPos As Single = 0
Dim count As Integer = 0
Dim leftMargin As Single = ev.MarginBounds.Left
Dim topMargin As Single = ev.MarginBounds.Top
Dim line As String = Nothing



'' Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics)

'' Print each line of the file.
While count < linesPerPage
line = streamToPrint.ReadLine()
If line Is Nothing Then
Exit While
End If
yPos = topMargin + count * printFont.GetHeight(ev.Graphics)
ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, New StringFormat())
count += 1
End While

'' If more lines exist, print another page.
If (line IsNot Nothing) Then
ev.HasMorePages = True
Else
ev.HasMorePages = False
End If
End Sub





''Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

'' ''Dim linesPerPage As Single = 0
'' ''Dim yPos As Single = 0
'' ''Dim count As Integer = 0
'' ''Dim leftMargin As Single = e.MarginBounds.Left
'' ''Dim topMargin As Single = e.MarginBounds.Top
'' ''Dim line As String = Nothing

'' '''' Calculate the number of lines per page.
'' ''linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics)

'' '''' Iterate over the file, printing each line.
'' ''While count < linesPerPage
'' '' line = streamToPrint.ReadLine()
'' '' If line Is Nothing Then
'' '' Exit While
'' '' End If
'' '' yPos = topMargin + count * printFont.GetHeight(e.Graphics)
'' '' e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, _
'' '' yPos, New StringFormat())
'' '' count += 1
'' ''End While

'' '''' If more lines exist, print another page.
'' ''If Not (line Is Nothing) Then
'' '' e.HasMorePages = True
'' ''Else
'' '' e.HasMorePages = False
'' ''End If
'' Dim Image As System.Drawing.Image = pictureBox1.Image
'' e.Graphics.DrawImage(Image, New Point(0, 0))


''End Sub

Private Sub PrintFile()
''_filename = filename;
_MODIDocument = New MODI.Document()

_MODIDocument.Create("E:\Personal\Personal\Medical\Saravana_Nov_Activities.doc")
If _MODIDocument IsNot Nothing Then
Dim d As New PrintDialog()
d.AllowSomePages = True
d.AllowSelection = False
d.PrintToFile = False
Dim ps As New PrinterSettings()
ps.MinimumPage = 0
ps.MaximumPage = _MODIDocument.Images.Count - 1
ps.FromPage = 0
ps.ToPage = _MODIDocument.Images.Count - 1

d.PrinterSettings = ps
If d.ShowDialog() = DialogResult.OK Then

_MODIDocument.PrintOut(d.PrinterSettings.FromPage, d.PrinterSettings.ToPage, d.PrinterSettings.Copies, d.PrinterSettings.PrinterName, "", False, _
MODI.MiPRINT_FITMODES.miPRINT_ACTUALSIZE)
End If
End If
End Sub


Public Sub printdoc()

Dim ac As New Microsoft.Office.Interop.Word.Application

Dim app As Microsoft.Office.Interop.Word.Application = ac.Application
Dim lsPriterName As String
'' I''m setting all of the alerts to be off as I am trying to get
'' this to print in the background
app.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone

'' Open the document to print...
Dim filename As Object = "E:\Personal\Personal\Medical\Saravana_Nov_Activities.docx"
Dim missingValue As Object = Type.Missing
'' Using OpenOld so as to be compatible with other versions of Word
Dim document As Microsoft.Office.Interop.Word.Document = app.Documents.Open(filename, missingValue, missingValue, missingValue, missingValue, missingValue, _
missingValue, missingValue, missingValue, missingValue)

'' Set the active printer
Dim d As New PrintDialog()
If d.ShowDialog() = DialogResult.OK Then
lsPriterName = d.PrinterSettings.PrinterName
Else
Exit Sub
End If

app.ActivePrinter = lsPriterName
Dim myTrue As Object = True
'' Print in background
Dim myFalse As Object = False
'' Using PrintOutOld to be version independent
app.ActiveDocument.PrintOut(myTrue, myFalse, missingValue, missingValue, missingValue, missingValue, _
missingValue, missingValue, missingValue, missingValue, myFalse, missingValue, _
missingValue, missingValue)

document.Close(missingValue, missingValue, missingValue)

'' Make sure all of the documents are gone from the queue
While app.BackgroundPrintingStatus > 0
System.Threading.Thread.Sleep(250)
End While

'' Cleanup:
GC.Collect()
GC.WaitForPendingFinalizers()
Marshal.FinalReleaseComObject(app)
Marshal.FinalReleaseComObject(ac)
document = Nothing

End Sub

''Private Sub InvokePrint(ByVal sender As Object, ByVal e As RoutedEventArgs)
'' '' Create the print dialog object and set options
'' Dim pDialog As New PrintDialog()
'' pDialog.PageRangeSelection = PageRangeSelection.AllPages
'' pDialog.UserPageRangeEnabled = True
'' '' Display the dialog. This returns true if the user presses the Print button.
'' Dim print As Nullable(Of [Boolean]) = pDialog.ShowDialog()
'' If print = True Then
'' Dim xpsDocument As New XpsDocument("C:\FixedDocumentSequence.xps", FileAccess.ReadWrite)
'' Dim fixedDocSeq As FixedDocumentSequence = xpsDocument.GetFixedDocumentSequence()
'' pDialog.PrintDocument(fixedDocSeq.DocumentPaginator, "Test print job")
'' End If
''End Sub

Private Sub PrintMyExcelFile()
Dim excelApp As New Microsoft.Office.Interop.Excel.Application()
'' Open the Workbook:
Dim wb As Microsoft.Office.Interop.Excel.Workbook = excelApp.Workbooks.Open("E:\Personal\Personal\Medical\Card.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing)
'' Get the first worksheet.
'' (Excel uses base 1 indexing, not base 0.)
Dim ws As Microsoft.Office.Interop.Excel.Worksheet = DirectCast(wb.Worksheets(1), Microsoft.Office.Interop.Excel.Worksheet)
'' Print out 1 copy to the default printer:


''Dim app As Microsoft.Office.Interop.Excel.Application = excelApp.Application
''Dim lsPriterName As String
''Dim d As New PrintDialog()
''If d.ShowDialog() = DialogResult.OK Then
'' lsPriterName = d.PrinterSettings.PrinterName
''Else
'' Exit Sub
''End If

''ws.ActivePrinter = lsPriterName

''ws.ActiveDocument.PrintOutOld(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
'' Type.Missing, Type.Missing)
ws.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Type.Missing, Type.Missing)
'' Cleanup:
GC.Collect()
GC.WaitForPendingFinalizers()
Marshal.FinalReleaseComObject(ws)
wb.Close(False, Type.Missing, Type.Missing)
Marshal.FinalReleaseComObject(wb)
excelApp.Quit()
Marshal.FinalReleaseComObject(excelApp)
End Sub

Public Function PrintPDF(ByVal PDFFile As String, ByVal PrinterName As String, ByVal Timeout As Integer) As Integer

Dim d As New PrintDialog()
If d.ShowDialog() = DialogResult.OK Then
PrinterName = d.PrinterSettings.PrinterName
Else
Exit Function
End If

If PrinterName.Trim.Length = 0 Then
PrinterName = (New System.Drawing.Printing.PrinterSettings).PrinterName
End If

'' Dim Proc As New System.Diagnostics.Process

Proc.EnableRaisingEvents = True
Proc.StartInfo.FileName = PDFFile
Proc.StartInfo.Arguments = Chr(34) + PrinterName + Chr(34)
Proc.StartInfo.Verb = "PrintTo"
Proc.StartInfo.WindowStyle = ProcessWindowStyle.Minimized
Proc.StartInfo.CreateNoWindow = True

'' Now start monitoring the printer''s queue.
Dim Monitor As New PrinterQueueWatch.PrinterMonitorComponent
Monitor.MonitorJobAddedEvent = False
Monitor.MonitorJobDeletedEvent = False
Monitor.MonitorJobSetEvent = True
Monitor.MonitorJobWrittenEvent = False
Monitor.MonitorPrinterChangeEvent = False
AddHandler Monitor.JobSet, AddressOf SetPrintJob
Monitor.DeviceName = PrinterName

'' Now that I am watching, start up Acrobat.
Proc.Start()

Do While Timeout > 0 AndAlso Not Proc.HasExited
System.Threading.Thread.Sleep(1000)
Timeout -= 1
Loop

'' Stop monitoring.
RemoveHandler Monitor.JobSet, AddressOf SetPrintJob
Monitor = Nothing

If Not Proc.HasExited Then
Debug.Print("Killing process")
Proc.Kill()
End If

Debug.WriteLine("Closing process")
Proc.Close()

Return 0
End Function
Public Function PrintPDF(ByVal PDFFile As String) As Integer
Return PrintPDF(PDFFile, "", 60)
End Function
Public Function PrintPDF(ByVal PDFFile As String, ByVal Timeout As Integer) As Integer
Return PrintPDF(PDFFile, "", Timeout)
End Function

Private Sub SetPrintJob(ByVal sender As Object, ByVal e As System.EventArgs)
'' Print job is set to print.
System.Threading.Thread.Sleep(500)
Proc.Kill()
End Sub

End Class


这篇关于如何在Windows应用程序中打印PDF文件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆