Print report directly, without print dialogue box and report viewer - vb.net

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

Related

Programmatically printing WebBrowser and setting its PrinterSettings in VB

I am trying to find a way to set PrinterSettings when printing contents of WebBrowser similar to the following code
Dim doc As PrintDocument = New PrintDocument()
With doc
.PrinterSettings = New PrinterSettings()
With .PrinterSettings
.PrinterName = "PrinterName"
.PrintToFile = True
.PrintFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "test.pdf")
End With
End With
doc.Print()
I converted this from a C# code I've found that tells how to set PrinterSettings programmatically.
Is there a way to combine the code above with WebBrowser.Print() in order to print HTML and set PrinterSettings programmatically
I have tried doing it like this thinking that this code might set default printer to Microsoft Print to PDF
Dim doc As PrintDocument = New PrintDocument()
With doc
.PrinterSettings = New PrinterSettings()
With .PrinterSettings
.PrinterName = "Microsoft Print to PDF"
.PrintToFile = True
.PrintFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "test.pdf")
End With
End With
WebBrowser.Print()
But it prints on the default printer and not on Microsoft Print to PDF
Edit: The WebBrowser contains the document I'm trying to print in HTML Format and some inline CSS. The WebBrowser don't have a UI, It is a plain code Declared as Private WithEvents WebBrowser As WebBrowser. Hope this helps clear my problem, thanks.
Edit(2): Setting the Default Printer have been problematic to me because of the printer setting "let windows manage my printers." Unchecking this allow the application to set the default printer. credits to K J
Try This :
Vote for me if I've helped you.
Dim doc As New PrintDocument()
With doc
With .PrinterSettings
.PrinterName = "PrinterName" ' exam: Fax
.PrintToFile = True
.PrintFileName = "The location of the file you want to print with the formula" ' exam -> C:\CV.pdf
End With
End With
doc.Print()

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

Select Printer to Print PDF file in vb.net

I have to select a printer and print a PDF file.
here i used, this code prints ONLY in the default printer.. i tired for searching and didn't find a solution.
Dim PrintPDF As New ProcessStartInfo
PrintPDF.UseShellExecute = True
PrintPDF.Verb = "print"
PrintPDF.WindowStyle = ProcessWindowStyle.Hidden
PrintPDF.FileName = "temp.pdf" 'fileName is a string parameter
Process.Start(PrintPDF)
i had done another part to find the printers in dropdown list
this code to find printer
Dim pkInstalledPrinters As String
For Each pkInstalledPrinters In PrinterSettings.InstalledPrinters
ComboBox1.Items.Add(pkInstalledPrinters)
Next pkInstalledPrinters
ComboBox1.SelectedIndex = ComboBox1.Items.Count - 1
Is there any Suggestions?
Thanks.
Try this,
I have added a web browser control in form.
add file file name of your pdf filename as follows:
WebBrowser1.naviagte(YourFileName)
Try
WebBrowser1.Print()
Catch ex As Exception
MsgBox(ex.Message)
End Try
While Doing this your app show print dialog with inbuilt option with which printer to you need to print.

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.

Programmatically set Custom Paper Size for Crystal Report

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);