search
Japanese Chinese Nederlands Espanol Italiano Deutsch Francais Twitter Rss Feeds
MicrosoftArticlesForumsFAQs
C# .NET
VB.NET
Visual Studio .NET
ADO.NET
Xml / Xslt
VB 6.0
.NET CF
GDI+
LINQ
Deployment
Security
FoxPro
Silverlight / WPF
Entity Framework
RIA Services

Web ProgrammingArticlesForumsFAQs
JavaScript
ASP
ASP.NET
Web Services

Non-MicrosoftArticlesForumsFAQs
NHibernate
Perl
PHP
Ruby
Java
Linux / Unix
Apple
Open Source

DatabasesArticlesForumsFAQs
SQL Server
Access
Oracle
MySQL
Other Databases

OfficeArticlesForumsFAQs
Excel
Word
Powerpoint
Outlook
Publisher
Money

Operating SystemsArticlesForumsFAQs
Windows 7
Windows Server
Windows Vista
Windows XP
Windows Update
MAC
Linux / UNIX

Server PlatformsArticlesForumsFAQs
BizTalk
Site Server
Exhange Server
IIS

Graphic DesignArticlesForumsFAQs
Macromedia Flash
Adobe PhotoShop
Expression Blend
Expression Design
Expression Web

OtherArticlesForumsFAQs
Subversion / CVS
Ask Dr. Dotnetsky
Active Directory
Networking
Uninstall Virus
Job Openings
Product Reviews
Search Engines
Resumes

 

View Other VB.NET Posts   Ask New Question 
source code for exporting to .pdf,.doc,... and printing crystal reports in vb.net
muthu kumar posted at Monday, November 17, 2008 11:26 PM
end of post

 
  re
Web star replied to muthu kumar at Monday, November 17, 2008 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
Sanjay Verma replied to muthu kumar at Tuesday, November 18, 2008 1: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
Binny ch replied to muthu kumar at Tuesday, November 18, 2008 1: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
Binny ch replied to muthu kumar at Tuesday, November 18, 2008 1: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
nARESH kUMAR replied to muthu kumar at Friday, April 24, 2009 9:54 AM
HI MUTHKUMAR PLAS POST VB.NET SOURCE OF EXPORT CRYSTAL REPORT IN pdf SHORTLY