Convert PowerPoint to HTML

Hello friends,

This post is explain about how to convert ppt file in html pages by asp.net application. A requirement comes like when user will provide ppt with attached set of images and asp.net application needs to convert it in html pages where images needs to find from ppt and save in one folder and attached with html pages, so html page desing looks like same as ppt.

To implement this I have used MS office atomization tool (DCOM). I have added below dll from .net references.
Microsfot.Office.Core
Microsfot.Office.Interop.PowerPoint

In MS Power Point has inbuild functionality available to : File> Save as Web Pages. So I have used the same functionality by .net code from Powerpoint compenent.

Below are the code I have implemented to achieve this.

string strSourceFile = @"D:\PPT_Presentation.pptx";
            //Give the name and path of the HTML file to be generated
            string strDestinationFile = @"D:\HTML_Presentation.htm";
            //Create a PowerPoint Application Object

            Microsoft.Office.Interop.PowerPoint.Application oApplication = new Microsoft.Office.Interop.PowerPoint.Application();

            //Create a PowerPoint Presentation object

            Microsoft.Office.Interop.PowerPoint.Presentation oPresentation = oApplication.Presentations.Open(strSourceFile);
            //Call the SaveAs method of Presentaion object and specify the format as HTML
            oPresentation.SaveAs(strDestinationFile, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML);

            //Close the Presentation object
            oPresentation.Close();
            //Close the Application object
            oApplication.Quit();

So once you will run the application there will be one html file created which you provided as destination file and one folder created with same name at same location with all required supported files.

Requirement to run this code:
Microsoft office should be installed on the system
Microsoft office Power Point DCOM configured with application user with proper access.

Note: Use direct component is not suggested by Microsoft, due to performance and reliability issue.
http://support.microsoft.com/kb/257757/en-us
So to achieve this scenario Microsoft suggests Office open xml format.
http://msdn.microsoft.com/en-us/library/bb332059(v=office.12).aspx

Please contact me at amitpatel.it@gmail.com for more any other information.

Thanks,
Amit Patel
“Enjoy Programming”

Prototype.js and jquery conflicts

This post contains information about how to use prototype.js and jquery in same page by resolving conflicts.

Problem:
In my current project prototype.js used on very huge number of places so that is not easy to remove that and also per new client’s requirement we have to use jquery but when we have import jquery below protype.js then all prototype.js related script was not working.

<script type="text/javascript" src="js/prototype.js"></script>
    
    <script src="js/jquery-1.5.1.js" type="text/javascript"></script>

And I have writen below script and that is not working
<script type="text/javascript" src="js/prototype.js"></script>
         <script>
         jQuery.noConflict();
     </script> 

Also when I have change the passion of the both file and first add jquery and then add prototype.js then jquery related part was not working.

The problem is that in query in standard format $ we are getting any variable like $(‘Myclassname”) that is not working due to these conflicts.

Solution
To resolve this issue I have added below script in my page.

    <script type="text/javascript" src="js/prototype.js"></script>
    <script src="js/jquery-1.5.1.js" type="text/javascript"></script>
     <script>
         jQuery.noConflict();

         // Use jQuery via jQuery(...)
         jQuery(document).ready(function() {
             
         });
     </script> 

In this script also I have override $ with Jquery so every very we need to use query just use Jquery rather then $ and things was working fine.
$(".panel").hide();  // Replace with below
jQuery(".panel").hide();

So by this solution we can access both the solution.
Let me know for further information.

Thanks,
Amit Patel
“Enjoy Programming”

Embed images in email by dynamic template

In general .net mail sending we are using image as url but this is not good if image is delete from server and path as been changed then our email comes with image not found.
So to avoid this we can embed image with email and then create cid and that cid we can use anywhere in email by image tag.

But if we have used email template and used images on that template then how can we handle, by generic class.
So for solution of this is that we can create add predefine image tags in email template and that will be passed by image class as below.

public class EmbedImages
    {
        public EmbedImages(string _ImagePlaceHolde, string _ImagePath, string _width, string _height)
        {
            this.ImagePlaceHolde = _ImagePlaceHolde;
            this.ImagePath = _ImagePath;
            this.width = _width;
            this.height = _height;
        }
        public string ImagePlaceHolde { get; set; }
        public string ImagePath { get; set; }
        public string width { get; set; }
        public string height { get; set; }
    }

This List of object of “EmbedImages” will be used in email send mail class where we are fetching the value and preparing image tag and replacing.

Actually we need to put any of the placeholder in email template and that will be replace by image tag.
As per below logic by embedding images.

 if (this.ImageParamers != null && this.ImageParamers.Count > 0)
 {
                    AlternateView View;
                    LinkedResource resource;
                    View = AlternateView.CreateAlternateViewFromString(message.Body, null, "text/html");
                    foreach (EmbedImages item in this.ImageParamers)
                    {
                        resource = new LinkedResource(item.ImagePath);
                        resource.ContentId = item.ImagePlaceHolde;
                        View.LinkedResources.Add(resource);
                        string ImageTag = "<img src=cid:" + item.ImagePlaceHolde + "width='" + item.width + "' and height='" + item.height + "px'/></p>";
                        message.Body = message.Body.Replace(item.ImagePlaceHolde, ImageTag);
                    }                    
                    message.AlternateViews.Add(View);
  }

We can actually fit this login in our common class for send an email with all other facilities.

public class SentMail
    {
        public SentMail()
        {

        }
        private string _SMTPAddress;
        public string SMTPAddress 
        {
            get
            {
                if(string.IsNullOrEmpty(_SMTPAddress))
                    return ConfigurationManager.AppSettings["SMTPSERVER"].ToString();
                else
                    return _SMTPAddress;
            }
            set
            {
                _SMTPAddress = value;
            }
        }
        public bool isMailSent {get;set;}
        private string _FromDisplayName;
        public string FromDisplayName
        {
            get
            {
                if (string.IsNullOrEmpty(_FromDisplayName))
                    return ConfigurationManager.AppSettings["FROMDISPLAY"].ToString();
                else
                    return _FromDisplayName;
            }
            set
            {
                _FromDisplayName = value;
            }
        }
        private string _FromAddress;
        public string FromAddress
        {
            get
            {
                if (string.IsNullOrEmpty(_FromAddress))
                    return ConfigurationManager.AppSettings["FROMADDRESS"].ToString();
                else
                    return _FromAddress;
            }
            set
            {
                _FromAddress = value;
            }
        }
        /// <summary>
        /// To Address if multiple then add ; in between each address
        /// </summary>
        public string ToDisplayName { get; set; }
        public string ToAddress { get; set; }
        /// <summary>
        /// CC Address if multiple then add ; in between each address
        /// </summary>
        public string CCAddress { get; set; }
        /// <summary>
        /// BCC Address if multiple then add ; in between each address
        /// </summary>
        public string BCCAddress { get; set; }
        public string Body { get; set; }
        public string Subject { get; set; }
        public List<string> SubjectParameter { get; set; }
        public List<string> Attachment { get; set; }
        public bool HighPriority { get; set; }
        public List<string> DynamicParameter { get; set; }
        public string TemplateFile { get; set; }
        public List ImageParamers { get; set; }

        public bool Sent()
        {
            bool bReturn = true;
            try
            {
                string user = System.Configuration.ConfigurationManager.AppSettings["SMTP_USERNAME"];
                string pass = System.Configuration.ConfigurationManager.AppSettings["SMTP_PASSWORD"];

                SmtpClient oSMTLClient = new SmtpClient();
                oSMTLClient.Host = this.SMTPAddress;
                
                oSMTLClient.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SMTP_PORT"]);
                oSMTLClient.UseDefaultCredentials = false;
                oSMTLClient.Credentials = new System.Net.NetworkCredential(user, pass);
                oSMTLClient.DeliveryMethod = SmtpDeliveryMethod.Network;


                MailMessage message = new MailMessage();
                message.From = new MailAddress(this.FromAddress, this.FromDisplayName);
                if (!string.IsNullOrEmpty(this.ToAddress))
                {
                    string[] ToAddress = this.ToAddress.Trim().Split(";".ToCharArray());
                    foreach (string itemTo in ToAddress)
                    {
                        message.To.Add(itemTo);
                    }
                }
                // CC address
                if (!string.IsNullOrEmpty(this.CCAddress))
                {
                    string[] CCAddress = this.CCAddress.Trim().Split(";".ToCharArray());
                    foreach (string itemCC in CCAddress)
                    {
                        message.CC.Add(itemCC);
                    }
                }
                
                // BCC address
                if (!string.IsNullOrEmpty(this.BCCAddress))
                {
                    string[] BCCAddress = this.BCCAddress.Trim().Split(";".ToCharArray());
                    foreach (string itemBCC in BCCAddress)
                    {
                        message.Bcc.Add(itemBCC);
                    }
                }

                if (this.DynamicParameter != null && DynamicParameter.Count > 0)
                    message.Body = string.Format(this.MailBodystring(), this.DynamicParameter.ToArray());
                else
                    message.Body = this.MailBodystring();
                
                
                message.IsBodyHtml=true;
                if (this.HighPriority)
                {
                    message.Priority = MailPriority.High;
                }

                if (this.Attachment != null && this.Attachment.Count > 0)
                {
                    
                    foreach (string itemAttachFile in this.Attachment)
	                {
                        System.Net.Mail.Attachment oAttachment = new Attachment(itemAttachFile);
                        message.Attachments.Add(oAttachment);
	                }

                    
                }
                if (this.SubjectParameter != null && SubjectParameter.Count > 0)
                    message.Subject = string.Format(this.Subject, this.SubjectParameter.ToArray());
                else
                    message.Subject = this.Subject;
                //oSMTLClient.SendCompleted += SendCompletedCallback;
                if (this.ImageParamers != null && this.ImageParamers.Count > 0)
                {
                    AlternateView View;
                    LinkedResource resource;
                    View = AlternateView.CreateAlternateViewFromString(message.Body, null, "text/html");
                    foreach (EmbedImages item in this.ImageParamers)
                    {
                        resource = new LinkedResource(item.ImagePath);
                        resource.ContentId = item.ImagePlaceHolde;
                        View.LinkedResources.Add(resource);
                        string ImageTag = "<img src=cid:" + item.ImagePlaceHolde + "width='" + item.width + "' and height='" + item.height + "px'/></p>";
                        message.Body = message.Body.Replace(item.ImagePlaceHolde, ImageTag);
                    }                    
                    message.AlternateViews.Add(View);
                }


                
                var userState = message;
                oSMTLClient.Send(message);

                bReturn = true;
            }
            catch (Exception ex)
            {
                bReturn = false;
            }

            return bReturn;
           
            //message.CC = this.CCAddress

        }
        private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            this.isMailSent=true;
        }
        private string MailBodystring()
        {
            string MailBody = "";
            if (File.Exists(this.TemplateFile))
            {
                StreamReader SR = new StreamReader(this.TemplateFile);
                MailBody = SR.ReadToEnd();
                SR.Close();
                SR.Dispose();
            }
            return MailBody;
        }
    }

So now when we want to use this class we use by below way.


 SentMail oMail = new SentMail();
            oMail.DynamicParameter = new List<string> { "Amit", "Password" };

            oMail.HighPriority = false;
            oMail.ToAddress = "amitpatel.it@gmail.com";
            oMail.Subject = "Password change";

            oMail.TemplateFile = System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplate/ChangePassord.htm");
	    List lstImage = new List()
	    lstImage.add("ComapnyLogo","<path>","100","50") // for dynamic apporach we can fetch this details from database and ser can attach each placeholder in email template by any WYSWYG editor.
	    oMail.ImageParamers = lstImage
            
            oMail.Sent();

So in this way we can send an email with dynamically embed images.

Please feel free to contact me for any other assistance at amitpatel.it@gmail.com

Thanks,
“Enjoy Programming”
amitpatel.it@gmail.com

Get Date & Time based on time zone in SQL Server

Problem:
SQL server is running in another time zone and application is launching for different time zone, like SQL server is established in USA, and Application is lunched for Indian user so we need to maintain all data in Indian times only. So all current date and time consider Indian time rather then consider USA time zone.
Also in some case SQL server moved to USA to Canada then also system is always consider proper Indian time. Or based on user’s demanded time zone’s time.

Also in some case SQL server moved to USA to Canada then also system is always consider proper Indian time. Or based on user’s demanded time zone’s time.

Solution:
So below are the sql function for that.

GO
/****** Object:  UserDefinedFunction [dbo].[GetLocalDateTime]    Script Date: 02/10/2012 15:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By : Amit Patel
Created Date : 11-Feb-2012
*/
------------------------------How to Executes--------------------------------------------------
-- select [dbo].[TimeZoneWiseTime](+5)
CREATE FUNCTION [dbo].[GetDateTimeByTimeZone]
(
	@TimeZoneDiff decimal(4,2)
)
RETURNS datetime
AS
BEGIN
	declare @utcdiff decimal(5,2)
set @utcdiff =  datediff(hh,GetUtcDate(), getdate())
declare @currDate datetime
set @currDate = DATEADD(Hour,@utcdiff,getdate())

return DATEADD(Hour,-(@TimeZoneDiff),@currDate )
END

In this example I have give example of select [dbo].[TimeZoneWiseTime](+5)
to consider Indian standard time (IST) as +5. So we can set it to take any country’s time.

In above logic I am first considering GetUtcDate() to get central time and based on that find difference of server’s date with central time, and finally after all I am adding uses requested timezone’s hours.

Let me know if you have any questions or feedback on this.

Thanks,
Amit Patel
Enjoy Programing

Redirection by AJAX request in MVC application.

This article is basically for MVC developer whom is using AJAX in their application.

Problem:
In my application I have created common login control (partial view) that I have used in various places but when I was submitting the form that is redirecting to different URL based on loaded controller so where I need to write login logic in common place. So to resolve this I have used AJAX so that form is on same place always use only one action method. I have used on div for updatedtargedid to update on each request.

But in this case, I am also facing an issue when I am redirecting to another page (after success login) that is open all redirected page in my login div (mean targeted id). So I need to resolve it, if any validation error and control back to login then thing is working fine because control is loaded in updatedtarged id.

This article is basically covers below three scenarios/problems

  • AJAX in MVC
  • How to update current div or form
  • Redirection by AJAX request in MVC application.

Below are the my code for this.

<div id="loginControl">
@using (Ajax.BeginForm("Login", new AjaxOptions { UpdateTargetId = "loginControl", InsertionMode=InsertionMode.Replace }))
{
    
        <div class="login_pannel">
            @if (Html.ValidationSummary(true) != null && Html.ValidationSummary(true).ToString() != string.Empty)
            {
                @Html.ValidationMessage("", new { @class = "reqtext" })            
            }
Your User ID
            <br />
            @Html.TextBoxFor(m => m.UserName, new { @class = "login_box" })
            <br />
            @Html.ValidationMessageFor(m => m.UserName, null, new { @class = "reqtext" })<br />
Your Password
            <br />
            @Html.PasswordFor(m => m.Password, new { @class = "login_box" })
           <br />
            @Html.ValidationMessageFor(m => m.Password, null, new { @class = "reqtext" })
<input name="login" type="submit" value="Login" class="button" />
}
</div>

In this above code I have used Ajax.BeginForm so that will be responsible set ajax request to the controller’s post method. And Once response back that will update only “loginControl” id, Which is specified as Div id. (you can see in code).

Once you submit form that will executes controllers login action method.

public ActionResult Login(LogOn Model)
        {
            if (ModelState.IsValid)
            {
			LogOnservices dbLoginService = new LogOnservices();
                Users LogedInUser = dbLoginService.LogOn(Model);

                    if (LogedInUser != null && LogedInUser.Status == Convert.ToInt32(CommonEnums.UserStatus.Inactive))
                    {
                        ModelState.AddModelError("", “In Active User”);
                    }
                    else
                    {
                          string returnUrl = Url.Action("Index", "MyAccount");
                    		ViewBag.returnUrl = returnUrl;
                    			return PartialView("_Login", model);

                    }
                }
            }
            return PartialView("_Login", Model);
}

So if any error then return “_login” view by partialView. And replace div id with returned div.
Here I have faced one problem is that when I am returning to current div then that is overlapping on another div mean each time that is rendered another div so that results changed UI or give JavaScript errors.

So I have added this property in Ajax form to resolve this issue :

InsertionMode=InsertionMode.Replace

Now I am facing one another problem is that when user succesfull login and redirecting to another page then also system open new window in targeted div id rather than in full page.

Previously I have added code like below. That is redirect but open page in targeted id, with very strange UI.

return RedirectToAction("Index", " MyAccount");

This is because of returned partial view is loading in targeted div id due to AJAX Request.

So This need to handle in JavaScript. So I have created one ViewBag with return url and if that has some value then javascript is redirecting to provided url.
Below are the code is helpful to me to resolve this issue.

Created Viewbag :

string returnUrl = Url.Action("Index", "CDashBoard");
                    		ViewBag.returnUrl = returnUrl;
                    			return PartialView("_Login", model);

Redirection by Javascript:

<script language="javascript">

    function Redirect() {
        var returnUrl = "@ViewBag.returnUrl";
        if (returnUrl) {
            window.location.href = returnUrl;
        }
    }
    Redirect();
</script>

So With this code now my redirection and login control is works fine in all senario with code/ui reusablities.

Thanks
Amit Patel
"Enjoy Programming"

Create SQL Users and Role by sql script

If some time required to create SQL Role with readonly permission  and then created sql user and that need to attach with new created role.

So below script is performated all operation just by passing
below parameter.

  1. User Name
  2. Password
  3. Database Name
  4. Role Name


GO
/****** Object:  StoredProcedure [dbo].[SetPermission]    Script Date: 10/04/2011 17:28:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Amit Patel
-- Create date: 30-Sep-2011
-- Description:	Set Permission for readonly for created user
-- exec SetPermission 'Permission','ap77',amit@@07','AP_Permission'
-- =============================================
CREATE PROCEDURE [dbo].[SetPermission]
	-- Add the parameters for the stored procedure here
	@DataBase nvarchar(50),
    @UserName nvarchar(50),
    @Password nvarchar(50),
    @RoleName nvarchar(50)
AS
BEGIN
declare @sql nvarchar(max)
set @sql = ''


set @sql = @sql +  ' USE [master] '
declare @CreateLogin nvarchar(200)
set @CreateLogin=''
set @sql = @sql + ' CREATE LOGIN [' + @UserName + '] WITH PASSWORD=N''' + @Password + ''', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF; ';

---------------------------------
---------------------------------
set @sql = @sql + ' Use '+ @DataBase;

DECLARE @CreateRole nvarchar(100)
set @sql = @sql + ' CREATE ROLE [' + @RoleName + ']; ';



set @sql = @sql + ' CREATE USER ['+ @UserName + '] FOR LOGIN [' + @UserName + ']; ';


DECLARE @sqltbl as NVARCHAR(MAX) 
SET @sqltbl = '' 
 
SELECT @sqltbl = @sqltbl + ' 
 GRANT SELECT ON OBJECT::['+TABLE_SCHEMA+'].['+TABLE_NAME+'] TO '+ '[' + @RoleName +']'+'; ' 
FROM INFORMATION_SCHEMA.TABLES
set @sql = @sql + @sqltbl


DECLARE @sqlProc as NVARCHAR(MAX) 
SET @sqlProc = '' 
 
SELECT @sqlProc = @sqlProc + ' 
 GRANT EXECUTE ON OBJECT::['+ROUTINE_SCHEMA+'].['+ROUTINE_NAME+'] TO '+ '[' + @RoleName +']'+'; ' 
FROM INFORMATION_SCHEMA.ROUTINES 
 
set @sql = @sql + @sqlProc;

declare @AssingRole nvarchar(50)
set @AssingRole=''
set @sql = @sql + ' EXEC sp_addrolemember ' +   @RoleName + ',' +  @UserName
--print @sql
exec(@sql)
END

Save PDF file from RDLC Reports

When developer need to generate PDF file based on report without any Report viewer in UI.
Below is the code window application to generate PDF file on specific location as well as save dialog box in window or web application. (Note: This code I have added code for window application for save dialog box code).

Microsoft.Reporting.WinForms.ReportViewer reportViewer1 = new Microsoft.Reporting.WinForms.ReportViewer();
            
            Microsoft.Reporting.WinForms.LocalReport objRDLC = new Microsoft.Reporting.WinForms.LocalReport();
            reportViewer1.LocalReport.ReportEmbeddedResource = "OrderDetails.rdlc";
            
            
            ReportData oReportData = new ReportData();
            DataTable oReportDataTable = oReportData. OrderDetails (OrderID, UserID).Tables[0]; // Fetch data from database
            objRDLC.DataSources.Clear();
            reportViewer1.LocalReport.EnableHyperlinks = true;
            reportViewer1.LocalReport.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", oReportDataTable));
            //objRDLC.Refresh();
            reportViewer1.RefreshReport(); 
            byte[] byteViewer = reportViewer1.LocalReport.Render("PDF");

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "*PDF files (*.pdf)|*.pdf";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileStream newFile = new FileStream(saveFileDialog1.FileName, FileMode.Create);
                newFile.Write(byteViewer, 0, byteViewer.Length);
                newFile.Close();
            }

This code is helpfull when requirement comes for create a PDF and sent an email to specified id from RDLC reports.
Let me ask a if you need more information by adding comments.

“Enjoy Programming”
Thanks
Amit Patel

Add any customize text in crystal reports by .net code

In my requirement I have to show few search parameter in crystal reports which is passed from aspx page.
And that is not hard coded fixed because I have 10-15 parameters and I want to place it dynamically if whatever parameter’s value available that only needs to be attach in reports.

So I have implemented this by below approaches.
In Crystal reports rpt file I have take one default fields with “SearchTextRight” and “SearchTextLeft” to display value left and right side corner.

This both fields “CanGrouw” property set as “True” and attach each of the search parameter by “\n” so automatically new line added and text object’s height will increased.
Below are the code we have used for that.

 ReportClass rptH = GenerateReportClasss(Server.MapPath("~/Reports/GetReortData.rpt"));
            
            /// Attach serarch fields

            SearchDraw oSearchDrow = AttachCustomerHours(collection);
            if (oSearchDrow.SearchingStringLeft != string.Empty)
            {
                TextObject SeachTextLeft = (TextObject)rptH.ReportDefinition.ReportObjects["SearchTextLeft"];
                SeachTextLeft.Text = oSearchDrow.SearchingStringLeft;
            }
            if (oSearchDrow.SearchingStringRight != string.Empty)
            {
                TextObject SeachTextRight = (TextObject)rptH.ReportDefinition.ReportObjects["SearchTextRight"];
                SeachTextRight.Text = oSearchDrow.SearchingStringRight;
            }
            AttachLocalizationCustomerHours(rptH);
            rptH.Refresh();

            rptH.SetDataSource(Ds.Tables[0]);

Now all text will attached in reports’ PDF or excel file.

Let me know for more details

Thanks,
Amit Patel
amitpatel.it@gmail.com
“Enjoy Programming”

HTML to PDF Converter

In any of the business application a scenario comes when html file is available
and we need to covert that html file in PDF format

i.e.  if we have provided invoice template to user for modification and we need to create a final PDF as final result based on that provided html template then we need to required logic/code to convert html file or string in PDF file

So below code main targeting to resolve above problem
statement. I have implemented below code which is convert html file in PDF by
iTextSharp.

Below are the code for this. (VB.NET)

Private Sub CovertHTMLTOPDF()
        Dim htmlstr As StreamReader = New StreamReader("Enter your html files physical path")
        Dim strline As String

        strline = htmlstr.ReadToEnd
        htmlstr.Close()

        ' Code to convert to pdf
        Dim doc As New Document(PageSize.A4, 8, 80, 50, 30, 65)
        Dim fsNew As New StringReader(strline)
        Dim document As New Document(PageSize.A4, 80, 50, 30, 65)

        Using ofilestream As New FileStream(Request.PhysicalApplicationPath + "Output related PDF file", FileMode.Create)
            PdfWriter.GetInstance(document, ofilestream)
            Using stringReader As New StringReader(strline)
                Dim parsedList As New ArrayList()
                parsedList = html.simpleparser.HTMLWorker.ParseToList(stringReader, Nothing)
                document.Open()
                ' parse each html object and add it to the pdf document
                For Each item As Object In parsedList
                    document.Add(DirectCast(item, IElement))
                Next

                document.Close()

            End Using

        End Using
    End Sub

Please insert a comment if you required any more clarification.

Thanks,
Amit Patel
“Enjoy Programming”
amitpatel.it@gmail.com

Implement Multi Lingual support in Crystal Reports by .net code

This article is targeting to .net developer whom they are dealing with crystal reports.
Generally we are working multi language supported application where we are using resource file to fetch value different language and they are loaded in UI based on users culture.

But this structure is not working in crystal reports. In crystal reports generally we are filling all data from database but what about headers and title information, if client requires that all available in based on selected language.

So for this handle we need to fill each text objects in crystal reports. So we have to provided appropriate name of all headers and title related text object in rtp file.
Below are the code for find that find and update all objects.

ReportClass reortptH = new ReportClass();
            rptH.FileName = Server.MapPath("~/Reports/ReportData.rpt");

reortptH.Load();


            
TextObject EmployeeName = (TextObject)reortptH.ReportDefinition.ReportObjects["hdEmployeeName"];
EmployeeName.Text = ResourceManager.GetObject(“EmployeeName”); // EmployeeName is resource key 

TextObject Department = (TextObject)reortptH.ReportDefinition.ReportObjects["hdDepartment"];
Department.Text = ResourceManager.GetObject(“Department”); // Department is resource key 

//……Need to update all text objects with resource key value.
reortptH.Refresh();

So in this way we can update available header and title related static information reports by value from resource file. We can create a report in multi-language supported.

Please add comments if you have any suggestion/questions.

Thanks,
Amit Patel
amitpatel.it@gmail.com
“Enjoy Programming”

Follow

Get every new post delivered to your Inbox.