Programmatically set Custom Paper Size for Crystal Report - vb.net

I have created custom paper Size "SUPP 15 x 14" in Setting - Printers - File - Server Properties. Now I’m trying to set custom Paper Size for Crystal Report using VB.net 2005.
When I run report from VB.net, the Crystal report viewer shows the correct preview for custom paper size but when I give print command it prints with the default printer paper size. (e.g Letter)
Here's the code I'm using to print:
Public Sub ...
'...
Dim ObjCrReport as new ReportDocument
'...
ObjCrReport.SetDataSource(ObjPrintDataSet.Tables("PrintData"))
SetReportPageSize("SUPP 15 x 14", 1)
'...
End Sub
Private Sub BtnPrintDoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPrintDoc.Click
Try
'Print command
ObjCrReport.PrintToPrinter(1, False, 0, 0)
Catch ex As Exception
MessageBox.Show(ex.Message, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Public Sub SetReportPageSize(ByVal mPaperSize As String, ByVal PaperOrientation As Integer)
Try
Dim ObjPrinterSetting As New System.Drawing.Printing.PrinterSettings
Dim PkSize As New System.Drawing.Printing.PaperSize
ObjPrinterSetting.PrinterName = "Epson FX1170"
For i As Integer = 0 To ObjPrinterSetting.PaperSizes.Count - 1
If ObjPrinterSetting.PaperSizes.Item(i).PaperName = mPaperSize.Trim Then
PkSize = ObjPrinterSetting.PaperSizes.Item(i)
Exit For
End If
Next
If PkSize IsNot Nothing Then
Dim myAppPrintOptions As CrystalDecisions.CrystalReports.Engine.PrintOptions = ObjCrReport.PrintOptions
myAppPrintOptions.PrinterName = "Epson FX1170"
myAppPrintOptions.PaperSize = CType(PkSize.RawKind, CrystalDecisions.Shared.PaperSize)
ObjCrReport.PrintOptions.PaperOrientation = IIf(PaperOrientation = 1, _
CrystalDecisions.Shared.PaperOrientation.Portrait, _
CrystalDecisions.Shared.PaperOrientation.Landscape)
End If
PkSize = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
If I use myAppPrintOptions.PaperSize = PaperSize.PaperLegal, then Print Preview & Printing appear correct, but I want to set custom paper size which is not showing in the PaperSize class.
What’s wrong with above code? Why is it printing Letter Size where Crystal report preview otherwise shows custom paper in the size preview? Is there a better way to accomplish my goal?

This Method works with an Epson LX-300+ ii Dot-Matrix Printer and later models
If you are using a Printer especially for Printing Receipts
here are the steps on how to set your printer for desired paper size
First Set up Printer to be used:
Go to Devices and Printers
in Printers select the Printer you are going to use and click - right click Printer Properties
Click Preferences... Button. Under Main Tab - Change Document Size to User Defined
a new New Window will appear.
in Paper Size Name specify the name (i.e. OR Paper)
and change paper width and height as desired
Click Save then OK
then set your printer by Pressing right click then set as Default Printer
Add these line of code for your printing. You can still use parameters and datasets.
Dim c As Integer
Dim doctoprint As New System.Drawing.Printing.PrintDocument()
doctoprint.PrinterSettings.PrinterName = "EPSON L1300 Series"
Dim rawKind As Integer
For c = 0 To doctoprint.PrinterSettings.PaperSizes.Count - 1
If doctoprint.PrinterSettings.PaperSizes(c).PaperName = "OR Receipts" Then
rawKind = CInt(doctoprint.PrinterSettings.PaperSizes(c).GetType().GetField("kind", Reflection.BindingFlags.Instance Or
Reflection.BindingFlags.NonPublic).GetValue(doctoprint.PrinterSettings.PaperSizes(c)))
Exit For
End If
Next
Report1.PrintOptions.PaperSize = CType(rawKind, CrystalDecisions.Shared.PaperSize)
frmPreview.CrystalReportViewer1.ReportSource = Report1
Report1.PrintToPrinter(1, False, 1, 1)

you can do as this
var rep = new YursCrystalReport();
var printerSettings = new System.Drawing.Printing.PrinterSettings();
var pSettings = new System.Drawing.Printing.PageSettings(printerSettings);
pSettings.PaperSize = new System.Drawing.Printing.PaperSize("newsize", 3000, 3000);//custom size hundredths (100=1 inch)
pSettings.Margins = new System.Drawing.Printing.Margins(0, 0, 0, 0);
rep.PrintOptions.DissociatePageSizeAndPrinterPaperSize = true;
rep.PrintOptions.CopyFrom(printerSettings, pSettings);

Related

How to select a tray on a printer thorugh code when printing from a word document in VB (VS2019)

Hi I'm trying to create a word document and then print it with VB in visual studio 2019.
Creation works ok, the document saves fine, and prints fine to the general tray but I cannot get the application to send the print job to a specified tray. the prints will just come out of the default paper try
the customers have an array of different printer makes and models
ive tried printing the document through word, ive also tried changing the printer itself on the computer to set the tray then change it back after
TRY 1
Dim intTray As Integer = varibleNumber
If intTray = 1 Then
oWord.ActiveDocument.PageSetup.FirstPageTray = Word.WdPaperTray.wdPrinterUpperBin
oWord.ActiveDocument.PageSetup.OtherPagesTray = Word.WdPaperTray.wdPrinterUpperBin
ElseIf intTray = 2 Then
oWord.ActiveDocument.PageSetup.FirstPageTray = Word.WdPaperTray.wdPrinterMiddleBin
oWord.ActiveDocument.PageSetup.OtherPagesTray = Word.WdPaperTray.wdPrinterMiddleBin
ElseIf intTray = 3 Then
oWord.ActiveDocument.PageSetup.FirstPageTray = Word.WdPaperTray.wdPrinterLowerBin
oWord.ActiveDocument.PageSetup.OtherPagesTray = Word.WdPaperTray.wdPrinterLowerBin
Else
'else print default tray
oWord.ActiveDocument.p.PageSetup.FirstPageTray = Word.WdPaperTray.wdPrinterDefaultBin
oWord.ActiveDocument.PageSetup.OtherPagesTray = Word.WdPaperTray.wdPrinterDefaultBin
End If
TRY 2
Dim intTray As Integer = varibleNumber
Dim oPS As New System.Drawing.Printing.PrinterSettings
If intTray = 1 Then
oPS.DefaultPageSettings.PaperSource = oPS.DefaultPageSettings.PrinterSettings.PaperSources.Item("Tray 1")
oWord.ActiveDocument.PageSetup.FirstPageTray = "Tray 1"
oWord.ActiveDocument.PageSetup.OtherPagesTray = "Tray 1"
ElseIf intTray = 2 Then
oPS.DefaultPageSettings.PaperSource = oPS.DefaultPageSettings.PrinterSettings.PaperSources.Item("Tray 2")
oWord.ActiveDocument.PageSetup.FirstPageTray = "Tray 2"
oWord.ActiveDocument.PageSetup.OtherPagesTray = "Tray 2"
ElseIf intTray = 3 Then
oPS.DefaultPageSettings.PaperSource = oPS.DefaultPageSettings.PrinterSettings.PaperSources.Item("Tray 3")
oWord.ActiveDocument.PageSetup.FirstPageTray = "Tray 3"
oWord.ActiveDocument.PageSetup.OtherPagesTray = "Tray 3"
Else
'else print default tray
oPS.DefaultPageSettings.PaperSource = oPS.DefaultPageSettings.PrinterSettings.PaperSources.Item("Automatically Select")
End If
modPrint.printWordDoc(oWord)
Pages just come out of the main printer tray.
Any help much appreciated
One quick solution that pops to my mind is to use VBA Printer Setup Dialog to change the Tray on your printer settings. Try executing this line of code and change the options on the printer you're using:
Application.Dialogs(xlDialogPrinterSetup).Show
Edit:
Try using this code specific to VB framework. It's a valid starting point, since it allows you to select which print to use:
Public Sub Printing(printer As String)
Try
streamToPrint = New StreamReader(filePath)
Try
printFont = New Font("Arial", 10)
Dim pd As New PrintDocument()
AddHandler pd.PrintPage, AddressOf pd_PrintPage
' Specify the printer to use.
pd.PrinterSettings.PrinterName = printer
If pd.PrinterSettings.IsValid then
pd.Print()
Else
MessageBox.Show("Printer is invalid.")
End If
Finally
streamToPrint.Close()
End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
You can find more info here on Microsoft Documentation.
Hope this helps.
Managed to resolve the issue finally :) each printer has its own tray numbers for every tray, even if they are labelled Tray1 Tray2 etc.
so had to look through the papersources find when the source name equalled the tray number I wanted then grab the rawkind value of that source and use that as the tray number when allocating to the word firstpagetray
Dim intTray As Integer = <tray number i'm looking for>
Dim oPS As New System.Drawing.Printing.PrinterSettings
Dim paper_Source As PaperSource = New PaperSource
Dim i As Integer = 0
For Each ps As PaperSource In oPS.PaperSources
If ps.SourceName.Contains(intTray.ToString) Then
i = ps.RawKind
Exit For
End If
Next
oWord.ActiveDocument.PageSetup.FirstPageTray = i
Hope this helps others with the same issue

File is in Use VB.NET

I am using VB.NET (VS-2012), I use to scan documents in my applicant software. When i scan document i resize the scanned image and save it over the original file. When the user scan all the required documents then the use click the save button. After clicking the save button the application upload the images to database and try to delete the locally created files but stuck with the error that the file is in use.
I am using the following code...
Tw.Init(Me.Handle)
If (Not msgfilter) Then
Me.Enabled = False
msgfilter = True
Application.AddMessageFilter(Me)
End If
If SelectScanner Then
Tw.Select()
SelectScanner = False
End If
Tw.Acquire(chkScanner.Checked)
This function listens the event triggered by tw.acquire()
Public Function PreFilterMessage(ByRef m As Message) As Boolean Implements IMessageFilter.PreFilterMessage
Try
Dim cmd As TwainCommand = Tw.PassMessage(m)
If (cmd = TwainCommand.Not) Then
Return False
End If
Select Case cmd
Case TwainCommand.CloseRequest
EndingScan()
Tw.CloseSrc()
Case TwainCommand.CloseOk
EndingScan()
Tw.CloseSrc()
Case TwainCommand.DeviceEvent
Case TwainCommand.TransferReady
Dim pics As ArrayList = Tw.TransferPictures()
EndingScan()
Tw.CloseSrc()
For i = 0 To pics.Count - 1 Step 1
flName = TempPath & "\" & GetNextFileName(TempPath, lstDocType.Items(cboDocTypes.SelectedIndex).ToString)
Dim img As IntPtr = CType(pics(i), IntPtr)
SaveImage(img)
lstDocuments.Items.Add(flName)
lstDocType.Items.Add(GetDocType(cboDocTypes.SelectedIndex))
SetItemData(lstDocuments, lstDocuments.Items.Count - 1, GetItemData(lstApplicants, lstApplicants.SelectedIndex))
Try
lstDocuments.SelectedIndex = lstDocuments.Items.Count - 1
Catch ex As Exception
End Try
Dim Original As Image = Image.FromFile(flName)
Dim Resized As Image = ResizeImage(Original, New Size(1024, 1407), False)
Original.Dispose()
Resized.Save(flName, ImageFormat.Jpeg)
Resized.Dispose()
img = Nothing
pics = Nothing
Next
Tw.Dispose()
Case 0
Return False
End Select
Return True
Catch ex As Exception
Return False
MsgBox(ex.Message)
End Try
End Function
In this given function you can see that the image is resized and the original image is replaced with the resized one. And then the resize object is disposed but when the software try to delete the image after uploading it to database, an error occurs.
I don't know whats the problem.

Passing Parameter to Crystal Reports XI from Visual Studio 2015

I am running into problems with the passing of parameters to an externally created Crystal Reports XI report from the WinForms application I'm building in Visual Studio 2015 Community Edition. No matter what I try to do, the report doesn't seem to get the value unless I manually select it at the prompt (which shouldn't even be popping up) when the report is being displayed. I'm using the same code I've used in a previous application (although that one was built in VS2008), but I've tried a number of "alternate" versions of the code in my attempts to get this working. Here's the code that I'm currently using:
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Module modReports
Private WithEvents DocumentToPrint As New Printing.PrintDocument
Private Sub ShowReport(ByVal LID As Integer, ByVal InHouse As Boolean)
Dim Report As New ReportDocument
Dim ReportParameters As ParameterFieldDefinitions = Nothing
Dim Parameter As ParameterFieldDefinition = Nothing
Dim ApplicationValue As ParameterDiscreteValue = Nothing
Dim ReportValues As ParameterValues = Nothing
Dim ReportViewer As New frmReport
Dim Response As DialogResult = DialogResult.Cancel
PrintingReport = True
Report.Load(CRYSTAL_REPORT_FILE_PATH & "ExampleReport.rpt")
Report.Refresh()
Report.VerifyDatabase()
ReportParameters = Report.DataDefinition.ParameterFields
Parameter = ReportParameters.Item("PrintAll")
ReportValues = New ParameterValues
ApplicationValue = New ParameterDiscreteValue
'Parameter.CurrentValues.Clear()
'ReportValues.Clear()
ReportValues = Parameter.CurrentValues
If LID = 7777 Then
ApplicationValue.Value = True
Else
ApplicationValue.Value = False
End If
ReportValues.Add(ApplicationValue)
Parameter.ApplyCurrentValues(ReportValues)
Response = MessageBox.Show("Do you want to send this report directly to the printer?", "SEND TO PRINTER", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
If Response = DialogResult.No Then
With ReportViewer
.rptViewer.ReportSource = Nothing
.rptViewer.ReportSource = Report
.WindowState = FormWindowState.Maximized
.rptViewer.RefreshReport()
' Set zoom level: 1 = Page Width, 2 = Whole Page, 25-100 = zoom %
.rptViewer.Zoom(1)
.rptViewer.Show()
.ShowDialog()
End With
ElseIf Response = DialogResult.Yes Then
Dim SelectPrinter As New PrintDialog
Dim PrinterSelected As DialogResult = DialogResult.Cancel
With SelectPrinter
.Document = DocumentToPrint
.AllowPrintToFile = False
.AllowSelection = False
.AllowCurrentPage = False
.AllowSomePages = False
.PrintToFile = False
End With
PrinterSelected = SelectPrinter.ShowDialog
If PrinterSelected = DialogResult.OK Then
Dim Copies As Integer = DocumentToPrint.PrinterSettings.Copies
Dim PrinterName As String = DocumentToPrint.PrinterSettings.PrinterName
Dim LastPageNumber As Integer = 1
Dim PrintBuffer As String = String.Empty
LastPageNumber = Report.FormatEngine.GetLastPageNumber(New ReportPageRequestContext)
Report.PrintOptions.PrinterName = PrinterName
Report.PrintOptions.PrinterDuplex = DocumentToPrint.PrinterSettings.Duplex
Report.PrintToPrinter(Copies, True, 1, LastPageNumber)
If Copies = 1 Then
PrintBuffer = "Printed " & Copies & " copy of "
Else
PrintBuffer = "Printed " & Copies & " copies of "
End If
If LastPageNumber = 1 Then
PrintBuffer += LastPageNumber.ToString & " page."
Else
PrintBuffer += LastPageNumber.ToString & " pages."
End If
MessageBox.Show("The report was sent to the following printer:" & vbCrLf & " • " & PrinterName & vbCrLf & PrintBuffer, "REPORT PRINTED", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End If
PrintingReport = False
End Sub
End Module
The report itself is built to use an XML file as the data source, which is dynamically created by this application. All of that works normally, and oddly enough, if I send the report directly to the printer, it seems to print correctly without prompting me. It's only a problem when I try to display the report through the CrystalReportViewer object.
Some of the things I've tried without success:
I've tried with and without calling the Clear() methods on the
Parameter.CurrentValues and ReportValues objects.
I've tried moving all of the parameter setting logic to after I set the
ReportSource of the CrystalReportViewer control (rptViewer.ReportSource)
I've tried using alternate Crystal Reports objects (ParameterFields instead of ParameterFieldDefinitions and ParameterField instead of ParameterFieldDefinition).
I've tried removing all of the "complicated" code and just using the SetParameterValue method (i.e., Report.SetParameterValue("PrintAll", True)
I've even tried creating different types of parameter fields in the report itself (String, Boolean, Number) and passing appropriate values for those datatypes.
If I walk through the code, it doesn't appear to error out anywhere, and everything looks like it's working just great until I get to the .rptViewer.RefreshReport() line in the With ReportViewer block. I've verified that all of the parameters and values have only the value I am "selecting" via the application by checking them every step up to that point, and it all looks exactly as I expect it to look.
But the application (via Crystal Reports) continues to prompt me for the value I just passed in the code. If I select the value in that prompt, the report does generate correctly based on the value I select, but no matter what I "pass" in the programming, the prompt always defaults to True.
Does anyone have any suggestions that I may have overlooked for how to get this parameter to correctly pass to the CrystalReportViewer control? Please let me know if you need any additional information or have any questions about what I've set up so far here. Thank you in advance.
Okay, so based on the information I found over on http://www.it-sideways.com/2011/10/how-to-disable-parameter-prompt-for.html, it seems that the RefreshReport method for the CrystalReportViewer control basically wipes out any parameters and/or log on information:
1. ) Do not invoke CrystalReportViewer.RefreshReport Method
This method will refresh the data for the report currently displayed
in the CrystalReportViewer control. The report will prompt for
parameters or logon info is necessary.
So, this method is not needed unless the same
CrystalDecisions.CrystalReports.Engine.ReportDocument object is
reused.
By commenting out that line of the code, I was able to prevent the parameter prompt from being displayed. The only issue I have after making that change is that, even though the zoom level is being set to 1 (page width), and when I run the project the CrystalReportViewer control even shows that it's correctly set in the status bar ('Zoom Factor: Page Width' is displayed), the report itself is not actually zoomed in to the page width.
With the RefreshReport method uncommented, if I manually provided the value for my parameter, it would display the report properly zoomed. If I add the zoom button to the control (.rptViewer.ShowZoomButton = True), I can manually choose the Page Width option, which then correctly "re-zooms" the report to the desired level, but it won't immediately display that way if the RefreshReport method is not called.
Regardless, I can spend some time trying to fight that now, but I finally have it properly setting, passing and displaying the results of my parameter. I hope this helps someone else running into this issue.

Printing an external PDF document in VB.net

I know this question has been asked before, but my situation is a bit wonky.
Basically, I'm trying to print a PDF file that I've generated using a previous Windows Form. I can find the file no problem, and I used the following code which I found off MSDN's help forums:
Dim p As New System.Diagnostics.ProcessStartInfo()
p.Verb = "print"
p.WindowStyle = ProcessWindowStyle.Hidden
p.FileName = "C:\534679.pdf" 'This is the file name
p.UseShellExecute = True
System.Diagnostics.Process.Start(p)
So far so good, but everytime I press the button to run this code, it keeps asking me to save it as a PDF file instead, as shown below:
I've also tried adding a PrintDialog to the Windows Form, getting it to pop up, and I can select the printer I want to use from there, but even after selecting the printer it still asks me to print to PDF Document instead.
What am I doing wrong?
To print massive PDF documents with VB.Net you can use LVBPrint and run it via command line:
http://www.lvbprint.de/html/gsbatchprint1.html
For Example:
C:\temp\gsbatchprint64\gsbatchprintc.exe -P \\server\printer -N A3 -O Port -F C:\temp\gsbatchprint64\Test*.pdf -I Tray3
I use the following function in my application:
' print a pdf with lvbrint
Private Function UseLvbPrint(ByVal oPrinter As tb_Printer, fileName As String, portrait As Boolean, sTray As String) As String
Dim lvbArguments As String
Dim lvbProcessInfo As ProcessStartInfo
Dim lvbProcess As Process
Try
Dim sPrinterName As String
If portrait Then
lvbArguments = String.Format(" -P ""{0}"" -O Port -N A4 -F ""{1}"" -I ""{2}"" ", sPrinterName, fileName, sTray)
Else
lvbArguments = String.Format(" -P ""{0}"" -O Land -N A4 -F ""{1}"" -I ""{2}"" ", sPrinterName, fileName, sTray)
End If
lvbProcessInfo = New ProcessStartInfo()
lvbProcessInfo.WindowStyle = ProcessWindowStyle.Hidden
' location of gsbatchprintc.exe
lvbProcessInfo.FileName = LvbLocation
lvbProcessInfo.Arguments = lvbArguments
lvbProcessInfo.UseShellExecute = False
lvbProcessInfo.RedirectStandardOutput = True
lvbProcessInfo.RedirectStandardError = True
lvbProcessInfo.CreateNoWindow = False
lvbProcess = Process.Start(lvbProcessInfo)
'
' Read in all the text from the process with the StreamReader.
'
Using reader As StreamReader = lvbProcess.StandardOutput
Dim result As String = reader.ReadToEnd()
WriteLog(result)
End Using
Using readerErr As StreamReader = lvbProcess.StandardError
Dim resultErr As String = readerErr.ReadToEnd()
If resultErr.Trim() > "" Then
WriteLog(resultErr)
lvbProcess.Close()
Return resultErr
End If
End Using
If lvbProcess.HasExited = False Then
lvbProcess.WaitForExit(3000)
End If
lvbProcess.Close()
Return ""
Catch ex As Exception
Return ex.Message
End Try
End Function
I discourage on using AcrRd32.exe as it doesn't work with massive printings.
First, to be able to select a Printer, you'll have to use a PrintDialog and PrintDocument to send graphics to print to the selected printer.
Imports System.Drawing.Printing
Private WithEvents p_Document As PrintDocument = Nothing
Private Sub SelectPrinterThenPrint()
Dim PrintersDialog As New PrintDialog()
If PrintersDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then
Try
p_Document = New PrintDocument()
PrintersDialog.Document = p_Document
AddHandler p_Document.PrintPage, AddressOf HandleOnPrintPage
Catch CurrentException As Exception
End Try
End If
End Sub
Private Sub HandleOnPrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs) Handles p_Document.PrintPage
Dim MorePagesPending As Boolean = False
'e.Graphics.Draw...(....)
'e.Graphics.DrawString(....)
' Draw everything...
If MorePagesPending Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
End Sub
That's what I'm doing since I usually have custom objects to print.
But to print PDF Files, you must understand that PDF means absolutely nothing to dotNet. Unlike common images like Bitmaps (.bmp) or Ping images (.png) the dotNet doesn't seem to have any inbuilt parser/decoder for reading, displaying and printing PDF files.
So you must use a third party application, thrid party library or your own custom PDF parser/layout generator in order to be able to send pages to print to your printer.
That's why you can't launch a hidden (not visible) process of Acrobat Reader with the command "print". You won't be able to select a printer but will direct to the default one instead !
You can however launch the Acrobat Reader process just to open the file, and do the printing manipulations (select a printer) inside Acrobat Reader (you're outside dotNet coding now)
A workaround for your may aslo to select another default printer by opening Acrobat Reader, and print one blank page on an actual working printer. This should deselect your FoxIt thing in favour of an actual printer..
This code will help you to print in a specific printer.
The sample print a file using a ProcessStartInfo and a specific printer you can change the printer to use in the process.
If the print process is not finished after 10 seconds we kill the print process.
'Declare a printerSettings
Dim defaultPrinterSetting As System.Drawing.Printing.PrinterSettings = Nothing
Private Sub cmdPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPrint.Click
Try
dim fileName As String = "C:\534679.pdf"
'Get de the default printer in the system
defaultPrinterSetting = DocumentPrinter.GetDefaultPrinterSetting
'uncomment if you want to change the default printer before print
'DocumentPrinter.ChangePrinterSettings(defaultPrinterSetting)
'print your file
If PrintFile(fileName, defaultPrinterSetting) then
msgbox ("your print file success message")
else
msgbox ("your print file failed message")
end if
Catch ex As Exception
mssbox(ex.Message.toString)
End Try
End Sub
Public NotInheritable Class DocumentPrinter
Shared Sub New()
End Sub
Public Shared Function PrintFile(ByVal fileName As String, printerSetting As System.Drawing.Printing.PrinterSettings) As Boolean
Dim printProcess As System.Diagnostics.Process = Nothing
Dim printed As Boolean = False
Try
If PrinterSetting IsNot Nothing Then
Dim startInfo As New ProcessStartInfo()
startInfo.Verb = "Print"
startInfo.Arguments = defaultPrinterSetting.PrinterName ' <----printer to use----
startInfo.FileName = fileName
startInfo.UseShellExecute = True
startInfo.CreateNoWindow = True
startInfo.WindowStyle = ProcessWindowStyle.Hidden
Using print As System.Diagnostics.Process = Process.Start(startInfo)
'Close the application after X milliseconds with WaitForExit(X)
print.WaitForExit(10000)
If print.HasExited = False Then
If print.CloseMainWindow() Then
printed = True
Else
printed = True
End If
Else
printed = True
End If
print.Close()
End Using
Else
Throw New Exception("Printers not found in the system...")
End If
Catch ex As Exception
Throw
End Try
Return printed
End Function
''' <summary>
''' Change the default printer using a print dialog Box
''' </summary>
''' <param name="defaultPrinterSetting"></param>
''' <remarks></remarks>
Public Shared Sub ChangePrinterSettings(ByRef defaultPrinterSetting As System.Drawing.Printing.PrinterSettings)
Dim printDialogBox As New PrintDialog
If printDialogBox.ShowDialog = Windows.Forms.DialogResult.OK Then
If printDialogBox.PrinterSettings.IsValid Then
defaultPrinterSetting = printDialogBox.PrinterSettings
End If
End If
End Sub
''' <summary>
''' Get the default printer settings in the system
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function GetDefaultPrinterSetting() As System.Drawing.Printing.PrinterSettings
Dim defaultPrinterSetting As System.Drawing.Printing.PrinterSettings = Nothing
For Each printer As String In System.Drawing.Printing.PrinterSettings.InstalledPrinters
defaultPrinterSetting = New System.Drawing.Printing.PrinterSettings
defaultPrinterSetting.PrinterName = printer
If defaultPrinterSetting.IsDefaultPrinter Then
Return defaultPrinterSetting
End If
Next
Return defaultPrinterSetting
End Function
End Class
I used this code to print my PDF files on VB NET:
Dim PrintPDF As New ProcessStartInfo
PrintPDF.UseShellExecute = True
PrintPDF.Verb = "print"
PrintPDF.WindowStyle = ProcessWindowStyle.Hidden
PrintPDF.FileName = dirName & fileName 'fileName is a string parameter
Process.Start(PrintPDF)
When you do this, process remains open with a adobe reader window that users have to close manually. I wanted to avoid user's interaction, just want them to get their documents. So, I added a few code lines to kill process:
Private Sub killProcess(ByVal processName As String)
Dim procesos As Process()
procesos = Process.GetProcessesByName(processName) 'I used "AcroRd32" as parameter
If procesos.Length > 0 Then
For i = procesos.Length - 1 To 0 Step -1
procesos(i).Kill()
Next
End If
End Sub
If you put the kill process method right after the print method you won't get your document printed (I guess this is because process is killed before it is sent to printer). So, between these 2 methods, I added this line:
Threading.Thread.Sleep(10000) ' 10000 is the milisecs after the next code line is executed
And with this my code worked as I wanted. Hope it helps you!

Print report directly, without print dialogue box and report viewer

I need to print my reports directly to printer:
1) Without showing print dialogue box
2) Without showing the Reportviewer
I was suggested the following code:
Dim printerSettings As New PrinterSettings()
Dim printDialog As New PrintDialog()
printDialog.PrinterSettings = printerSettings
printDialog.AllowPrintToFile = False
printDialog.AllowSomePages = True
printDialog.UseEXDialog = True
Dim result As DialogResult = printDialog.ShowDialog()
If result = DialogResult.Cancel Then
Return
End If
Me.rptSalesReport.PrintOptions.PrinterName = printerSettings.PrinterName
Me.rptSalesReport.PrintToPrinter(printerSettings.Copies, False, 0, 0)
But I am receiving error on the last two lines, where I put the name of my reports,
rptSalesReport. It says:
rptSalesReport is not defined.
While the rptSalesReport is there in my project and I can view it through report viewer.
Please advise.
Thanks