VB.NET - source code for exporting to .pdf,.doc,... and printing crystal reports in vb.net

Asked By muthu kumar
17-Nov-08 11:26 PM
end of post

re  re

17-Nov-08 11:36 PM
u can export and print.
Imports CrystalDecisions.Shared
Imports System.IO

Public Class WebForm1
    Inherits System.Web.UI.Page

    Dim crReportDocument As CrystalReport2 = New CrystalReport2

    Protected WithEvents DropDownList1 As System.Web.UI.WebControls.DropDownList
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button
    Protected WithEvents Label1 As System.Web.UI.WebControls.Label
    Protected WithEvents CrystalReportViewer1 As _
                             CrystalDecisions.Web.CrystalReportViewer
    Protected WithEvents Button2 As System.Web.UI.WebControls.Button

#Region " Web Form Designer Generated Code "
    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> 
    Private Sub InitializeComponent()

    End Sub

    'NOTE: The following placeholder declaration is required 
    'by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object,_ 
                        ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()


        ' this is the most IMPORTANT line of code
        ' if this line is not writen the 
        ' " LOGON FAILED" error starts displaying
        crReportDocument.SetDatabaseLogon("username",_ 
                                    "password", "sql-server", "database")

        ' the Above line works even if only username 
        ' and password is supplied as below

        'crReportDocument.SetDatabaseLogon("username",_
                                 "password") ', "sql-server", "database")

        ' this will hide the group tree
        CrystalReportViewer1.DisplayGroupTree = False

        CrystalReportViewer1.ReportSource = crReportDocument

        ' IF REPORT Uses Parameter's
        ' Pass Paramaters As Follows
        crReportDocument.SetParameterValue("city", "Mumbai")


        ' city = Parameter Name
        ' Mumbai = Parameter Value

        ' :-) thats ALL your Report Will Be displayed 
        ' now Without Logon Failed Error

        With DropDownList1.Items
            .Add("Rich Text (RTF)")
            .Add("Portable Document (PDF)")
            .Add("MS Word (DOC)")
            .Add("MS Excel (XLS)")
        End With
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object,_ 
                ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
    End Sub

    Sub ExportReport()

        Dim oStream As New MemoryStream ' // using System.IO

        'this contains the value of the selected export format.
        Select Case DropDownList1.SelectedItem.Text 

            Case "Rich Text (RTF)"
                '-----------------------------------------------------------

                oStream = crReportDocument.ExportToStream(_
                    CrystalDecisions.Shared.ExportFormatType.WordForWindows)
                Response.Clear()
                Response.Buffer = True
                Response.ContentType = "application/rtf"
                '------------------------------------------------------------

                '------------------------------------------------------------
            Case "Portable Document (PDF)"

                oStream = crReportDocument.ExportToStream(_
                    CrystalDecisions.Shared.ExportFormatType.PortableDocFormat)
                Response.Clear()
                Response.Buffer = True
                Response.ContentType = "application/pdf"
                '--------------------------------------------------------------

                '--------------------------------------------------------------
            Case "MS Word (DOC)"

                oStream = crReportDocument.ExportToStream(_
                        CrystalDecisions.Shared.ExportFormatType.WordForWindows)
                Response.Clear()
                Response.Buffer = True
                Response.ContentType = "application/doc"
                '---------------------------------------------------------------

                '---------------------------------------------------------------
            Case "MS Excel (XLS)"

                oStream = crReportDocument.ExportToStream(_
                                 CrystalDecisions.Shared.ExportFormatType.Excel)
                Response.Clear()
                Response.Buffer = True
                Response.ContentType = "application/vnd.ms-excel"
                '---------------------------------------------------------------
        End Select 'export format
        Try
            Response.BinaryWrite(oStream.ToArray())
            Response.End()
        Catch err As Exception
            Response.Write("< BR >")
            Response.Write(err.Message.ToString)
        End Try
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) Handles Button2.Click
        ExportReport()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) Handles Button1.Click
        crReportDocument.SetDatabaseLogon("USER", _
                                "PASSWORD", "SQL-SERVER", "DATABASE")
        crReportDocument.PrintToPrinter(1, False, 0, 0)
    End Sub
End Class

Re :: Export Crystal Report to PDF, .DOC  Re :: Export Crystal Report to PDF, .DOC

18-Nov-08 01:44 AM

To PDF ::

There are so many sources available on internet,

See one of them

Visual Studio .NET comes with a useful version of Crystal Reports which allows you to create Crystal Reports (.rpt files) and then bind them to your database to produce PDF files on a web page, all from within the Visual Studio .NET GUI without ever even getting into the code. As easy as this is, you can have a lot more control over the process if you do it yourself.

This code shows you how to create and bind a DataSet and a Crystal Report file (.rpt) without even using Visual Studio at all (I used Web Matrix). It is assumed, however, that you have access to the Crystal Reports .dlls which came with Visual Studio .NET and that you have the ability to create .rpt files (I used Crystal Reports 9.0).

Here are the steps:

  1. Copy the file "EmployeeReport" into an ASP.NET web folder.
  2. Important: Make SURE that that folder is a WEB folder and not just a sub-directory of another ASP.NET web folder. This is necessary for the \bin directory to function.
  3. Create a \bin directory and copy the two .dll files "CrystalDecisions.CrystalReports.Engine.dll" and "CrystalDecisions.Shared.dll" to your bin directory (I found the .dlls here: C:\Program Files\Common Files\Crystal Decisions\1.1\Managed)
  4. Point your browser to your .aspx file, e.g. http://localhost/... This will create your schema file (Employees.xsd).
  5. In Crystal Reports, create a report from a ADO.NET XML data source. When you are asked for an XML file, point it to your .XSD file. Create the report just as you would any other report from the fields in the table provided.
  6. Important: click on FILE and turn OFF the option "Save Report with Data". This will allow your .rpt file to use information coming from a DataSet at run-time, otherwise it will ignore the DataSet and always be empty.
  7. Save your report as "Employees.rpt" in your web folder.
  8. Now in your .aspx file, change the action variable to "CreatePdf" and reload the page in your browser. You should see a link to "Employees.pdf". Click on it and you will see your PDF file which was created by combining your DataSet with your RPT file. Note that the line "dt.TableName = "Table";" is very important. If you change this name, then you table won't get through to your report. I believe you can rename your table but it has to have the same name when you create the schema as when you run the report.

 

 

<%@ Page Language="C#" Debug="true" %>
<%@ import Namespace="CrystalDecisions.CrystalReports.Engine" %>
<%@ import Namespace="CrystalDecisions.Shared" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.IO" %>
<%@ import Namespace="System.Xml" %>
<%@ import Namespace="System.Text" %>
<script runat="server">
    public void Page_Load(Object sender, EventArgs E) {
        //*** INSTRUCTIONS:
        //define action for this program
        //1. set action to "CreateSchemaFile"
        //2. run program which creates your .xsd schema file
        //3. create crystal report based on that file
        //4. then set action permanently to "CreatePdf"
        //the command
        string action = "CreatePdf";
        //variables
        string tableName = "fin";
        string rptFile = "fin.rpt";
        string xsdFile = "fin.xml";
        string pdfFile = "fin.pdf";
        //either create the schema (first time only) or the pdf file
        if(action.ToUpper() == "CREATESCHEMAFILE") {
            DataTable dt = new DataTable();
            dt = DummyTable();
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            CreateSchemaFile(xsdFile,ds);
            Response.Write("Your schema file has been created:<br/><br/> <b>" + Server.MapPath(xsdFile) + "</b><br/><br/>");
            Response.Write("Use it to create your Crystal Reports report file named:<br/><br/> <b>" + Server.MapPath(pdfFile) + "</b>");
        } else {
            //create the report document
            ReportDocument doc = new ReportDocument();
            string fileName = Server.MapPath(rptFile);
            doc.Load(fileName);
            DataTable dt = DummyTable();
            dt.TableName = tableName;
            DataSet ds = new DataSet();
            dt.TableName    = "Table";
            ds.Tables.Add(dt);
            doc.SetDataSource(ds);
            ExportOptions exportOpts = doc.ExportOptions;
            exportOpts.ExportFormatType = ExportFormatType.PortableDocFormat;
            exportOpts.ExportDestinationType = ExportDestinationType.DiskFile;
            exportOpts.DestinationOptions = new DiskFileDestinationOptions();
            // Set the disk file options.
            DiskFileDestinationOptions diskOpts = new DiskFileDestinationOptions();
            ( ( DiskFileDestinationOptions )doc.ExportOptions.DestinationOptions ).DiskFileName = Server.MapPath("fin.pdf");
            doc.Export();
            Response.Write(dt.Rows.Count);
            Response.Write("<a href=\"" + pdfFile + "\">" + pdfFile + "</a>");
        }

    }
    private void CreateSchemaFile(string fileName, DataSet ds) {
        string absoluteFileName = HttpContext.Current.Server.MapPath(fileName);
        FileStream myFileStream = new FileStream (absoluteFileName, FileMode.Create);
        XmlTextWriter myXmlWriter = new XmlTextWriter(myFileStream, Encoding.Unicode);
        ds.WriteXml( myXmlWriter,XmlWriteMode.WriteSchema );
        myXmlWriter.Close();
    }
    private DataTable GetTheData() {
        //get datatable
        DataTable dt = qs.GetDataTable("SELECT * FROM fin");
        DataTable d2 = dt.Copy();
        return d2;
    }
    private DataTable DummyTable()    {
        //create table
        DataTable dt = new DataTable("Employees");
        dt.Columns.Add("id",Type.GetType("System.Int32"));
        dt.Columns.Add("FirstName",Type.GetType("System.String"));
        dt.Columns.Add("LastName",Type.GetType("System.String"));
        dt.Columns.Add("HireDate",Type.GetType("System.DateTime"));
        //fill rows
        DataRow dr;
        for(int x=1;x<=10;x++) {
            dr = dt.NewRow();
            dr["id"] = x;
            dr["FirstName"] = "Joe" + x;
            dr["LastName"] = "Smith" + x;
            dr["HireDate"] = DateTime.Now;
            dt.Rows.Add(dr);
        }
        return dt;
    }
</script>
<!--#include file="qs.aspx" -->

Also see the following articles for exporting Crystal Report to doc and printing it.

http://www.codeproject.com/KB/aspnet/crCode.aspx (Complete Article)

http://forums.asp.net/t/728315.aspx

http://www.experts-exchange.com/Programming/Languages/.NET/Q_22759698.html

Hope this helps.

Converting DOC to PDF  Converting DOC to PDF

18-Nov-08 01:56 AM
#region Converting DOC to PDF
                            try
                            {
                                string Source = f.FullName.Trim().ToString();

                                string Target = TxtFilePath.Text.Trim() + "\\" + dest_name + dest_ext.Trim();

                                string filename = @Source;
                                Word.Application app = new Word.ApplicationClass();
                                object nullobj = System.Reflection.Missing.Value;
                                object objfile = filename;
                                Word.Document doc = app.Documents.Open(ref objfile, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
                                doc.ActiveWindow.Selection.WholeStory();
                                doc.ActiveWindow.Selection.Copy();
                                IDataObject data = Clipboard.GetDataObject();
                                string text = data.GetData(DataFormats.Text).ToString();
                                doc.Close(ref nullobj, ref nullobj, ref nullobj);
                                app.Quit(ref nullobj, ref nullobj, ref nullobj);
                                text = text.TrimStart().ToString();
                                Document mydoc = new Document();
                                // string data = "Add This Data To PDf File";
                                PdfWriter.GetInstance(mydoc, new FileStream(@Target, FileMode.OpenOrCreate));
                                mydoc.AddTitle(@dest_name);
                                mydoc.Open();
                                mydoc.Add(new Paragraph(text));
                                mydoc.Close();
                                MessageBox.Show("Conversion from DOC to PDF Finished", "Conversion", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            catch (PdfException ex)
                            {
                                MessageBox.Show(ex.ToString());
                            }
                            #endregion
                        }



Print Crystal Report  Print Crystal Report
18-Nov-08 01:59 AM

Try this code:

report.PrintToPrinter(1, False, 0, 0)

here report is the object for crystal report

If you wish to print certain page range, change last two parameters From to To page number.

 If you want to set page margins, you need to create a PageMargin object and set PrintOptions of the ReportDocument.

 The following code sets page margins and printer name:

 Dim margins As PageMargins =  Report.PrintOptions.PageMargins

   margins.bottomMargin = 200

   margins.leftMargin = 200

   margins.rightMargin = 50

   margins.topMargin = 100

   Report.PrintOptions.ApplyPageMargins(margins)

    ' Select the printer name

   Report.PrintOptions.PrinterName = printerName
HI  HI
24-Apr-09 09:54 AM
HI MUTHKUMAR PLAS POST VB.NET SOURCE OF EXPORT CRYSTAL REPORT IN pdf SHORTLY
Create New Account
help
visual studio installation problem Actually, my OS is Windows Xp with service pack2.I added service pack3 to install visual studio2010.after that i tryed to installed, but am getting SETUP FAILED due to "Windows other are not processing. and am getting below one in log file as error cause: Microsoft Windows Installer 4.5 Update (x86) - Windows XP: [2] CGenericComponent::Install() expects the setup file for Microsoft Windows Installer 4.5 Update (x86) - Windows XP, but the file is not available. [08 ISetupManager::InternalInstallManager() with HRESULT -2147467259. [08 / 10 / 11, 14:26:00] VS70pgui: [2] DepCheck indicates Microsoft Windows Installer 4.5 Update (x86) - Windows XP is not installed. [08 / 10 / 11, 14:26:00] VS70pgui: [2] DepCheck indicates Microsoft Visual F# 2.0 Runtime was not attempted to be installed. [08 / 10 / 11, 14:26
Logging Service b9wt High Log retention limit reached. Log file 'C: \ Program Files \ Common Files \ Microsoft Shared \ Web Server Extensions \ 14 \ LOGS \ TRICOFLEX-20111030-0008.log' has been deleted. 11 / 13 e63e-4ee9-b396-3fc61e3e6b80 11 / 13 / 2011 00:08:31.87 w3wp.exe (0x0DB4) 0x0AB8 Excel Services Application Excel Calculation Services 8jg2 Medium ResourceManager.PerformCleanup: Memory Manager: CurrentSize = 536850432. 53fed7f1-b549-1a88-0000-000050f7b00c SharePoint Foundation Topology e5mc Medium WcfSendRequest: RemoteAddress: 'http: / / tricoflex:32843 / 7a4080d658ba42efa38ff6455cbc382b / BdcService.svc / http' Channel: 'Microsoft.SharePoint.BusinessData.SharedService.IBdcServiceApplication' Action: 'http: / / www.microsoft.com / Office / 2009 / BusinessDataCatalog / BusinessDataCatalogSharedService / GetLobSystemsLikeName' MessageId: 'urn:uuid:abbcffd4-6783-4121-86ca-a30f0afe866a' 5c243a60 hozetric.local:32843 / 7a4080d658ba42efa38ff6455cbc382b / bdcservice.svc / http' Channel: 'System.ServiceModel.Channels.ServiceChannel' Action: 'http: / / www.microsoft.com / Office / 2009 / BusinessDataCatalog / BusinessDataCatalogSharedService / GetLobSystemsLikeName' MessageId: 'urn:uuid:abbcffd4-6783-4121-86ca-a30f0afe866a' 5c243a60 SharePoint Foundation Topology e5mc Medium WcfSendRequest: RemoteAddress: 'http: / / tricoflex:32843 / 7a4080d658ba42efa38ff6455cbc382b / BdcService.svc / http' Channel: 'Microsoft.SharePoint.BusinessData.SharedService.IBdcServiceApplication' Action: 'http: / / www.microsoft.com / Office / 2009 / BusinessDataCatalog / BusinessDataCatalogSharedService / GetLobSystemsLikeName' MessageId: 'urn:uuid:677d0349-b6d5-40e5-81b0-44215e75a07a' 5c243a60
Interview Questions for .NET Framework This article is specially for the users those are in development or want to be a .net developer • To test a Web Service you must create a windows application or web application to consume this service? It is True / False? FALSE How many classes can a single.NET DLL contain? Answer1: As many Answer2: One or more What are good ADO.NET object(s) to replace the ADO Recordset object? The differences includes In ADO, the in memory representation of data is the recordset. In ADO.net, it is the dataset A recordset looks like a single table in ADO In contrast, a dataset is a collection of one or more tables in ADO.net ADO is designed primarily for connected access ADO net the disconnected access to the database is used In ADO you communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter
mistake, but currently I am reading the logfiles placed under "c: \ program files \ common files \ microsoft shared \ web server extensions \ 12 \ logs". I don't find any relavant information regarding authentication EXE (0x0980) 0x0988 Windows SharePoint Services Database 880i High . . .tem.Data.SqlClient.SqlConnection.Open() bei Microsoft.SharePoint.Utilities.SqlSession.OpenConnection() 03 / 04 / 2010 13:53:11.35 OWSTIMER.EXE (0x0980) 0x0988 von der Anmeldung angeforderte 'SharePoint_07_Config'-Datenbank kann nicht geöffnet werden. Fehler bei der Anmeldung.' Source: '.Net SqlClient Data Provider' Number: 4060 State: 1 Class: 11 Procedure: '' LineNumber: 65536 Server: 'd-it5 Services Database 880j High SqlError: 'Fehler bei der Anmeldung für den Benutzer 'SPTEST \ spadmin'.' Source: '.Net SqlClient Data Provider' Number: 18456 State: 1 Class: 14 Procedure: '' LineNumber: 65536 Server: 'd-it5 13:53:11.59 OWSTIMER.EXE (0x0980) 0x0988 Windows SharePoint Services Database 880k High bei Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand command, CommandBehavior behavior) bei Microsoft.SharePoint.Administration.SPConfigurationDatabase.FetchId(QualifiedObjectName qName) bei Microsoft.SharePoint.Administration.SPConfigurationDatabase.GetObject(String name, Guid parentId, Type type) bei Microsoft.SharePoint.Administration.SPConfigurationDatabase.get_Farm() bei Microsoft.SharePoint.Administration.SPFarm.FindLocal(SPFarm& farm, Boolean& isJoined) bei
2011 19:10:25.0731] [0] * ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** * [11 / 17 / 2011 19:10:25.0731] [0] Starting Microsoft Exchange Server 2010 Setup [11 / 17 / 2011 19:10:25.0731] [0] * ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** * [11 / 17 / 2011 Central Time (US & Canada). [11 / 17 / 2011 19:10:25.0731] [0] Operating System version: Microsoft Windows NT 6.1.7601 Service Pack 1. [11 / 17 / 2011 19:10:25.0731 17 / 2011 19:10:27.0135] [0] Exchange configuration container for the organization is 'CN = Microsoft Exchange, CN = Services, CN = Configuration, DC = mr238, DC = org'. [11 / 17 / 2011 19:10:27.0135] [0] Exchange organization container for the organization is 'CN = First Organization, CN = Microsoft Exchange, CN = Services, CN = Configuration, DC = mr238, DC = org'. [11 / 17 / 2011 19:10:27 EXCHANGE, CN = Servers, CN = Exchange Administrative Group (FYDIBOHF23SPDLT), CN = Administrative Groups, CN = First Organization, CN = Microsoft Exchange, CN = Services, CN = Configuration, DC = mr238, DC = org'. [11 / 17 / 2011 19:10:27 EXCHANGE, CN = Servers, CN = Exchange Administrative Group (FYDIBOHF23SPDLT), CN = Administrative Groups, CN = First Organization, CN = Microsoft Exchange, CN = Services, CN = Configuration, DC = mr238, DC = org'. [11 / 17 / 2011 19:10:27 15. [11 / 17 / 2011 19:11:17.0415] [0] Exchange Installation Directory : 'F: \ Program Files \ Microsoft \ Exchange Server \ V14'. [11 / 17 / 2011 19:11:17.0446] [0] Applying default role selection 17 / 2011 19:11:17.0477] [0] Setup will run from path 'F: \ Program Files \ Microsoft \ Exchange Server \ V14 \ '. [11 / 17 / 2011 19:11:17.0493] [0] InstallModeDataHandler has 0 DataHandlers