How to print PDF in ASP.NET MVC

Creating PDF docs in Asp.Net MVC is a fairly common functionality. Usually either for reporting or, more often, for having printable friendly documents.

I have tried the itextSharp with XMlWorkker but latest version is not free. We have to purchase it for commercial use.

After some research I have found the excellent wkhtmltopdf tool to convert html content to PDF. It uses the WebKit engine (used by browsers like Chrome and Safari) to render HTML. Its also fast.

With Rotativa, (It is using wkhtmltopdf) we can print the all things in pdf:

Steps to use Rotativa:

Install using the Nuget package manager or, more conveniently, with the package manager console, typing:

Install-Package Rotativa

Writing a controller action to return a view representing the desired PDF output.  Replace it with ActionAsPDF. Such as:

public ActionResult Test()        {
return new ActionAsPdf("Index", new { name = "Giorgio" }) { FileName = "Test.pdf" };
}

More formats:

public ActionResult Test()
{
return new ActionAsPdf("Index", new { name = "Giorgio" }) { FileName = "Test.pdf" };
}

public ActionResult TestExternalUrl()
{
return new UrlAsPdf("http://www.google.com")
{
FileName = "TestExternalUrl.pdf",
PageMargins = new Margins(0, 0, 0, 0)
};
}

public ActionResult TestView()
{
ViewBag.Message = string.Format("Hello {0} to ASP.NET MVC!", "Giorgio III.");
return new ViewAsPdf("Index")
{
FileName = "TestView.pdf",
PageSize = Size.A4,
PageOrientation = Orientation.Landscape,
PageMargins = { Left = 0, Right = 0 }
};
}

public ActionResult TestSaveOnServer(string fileName)
{
var filePath = Path.Combine(Server.MapPath("/App_Data"), fileName);
ViewBag.Message = string.Format("Hello {0} to ASP.NET MVC!", "Giorgio III.");
return new ViewAsPdf("Index")
{
FileName = fileName,
PageSize = Size.A3,
PageOrientation = Orientation.Landscape,
PageMargins = { Left = 0, Right = 0 },
SaveOnServerPath = filePath
};
}

public ActionResult TestViewWithModel(string id)
{
var model = new TestViewModel { DocTitle = id, DocContent = "This is a test" };
return new ViewAsPdf(model);
}

public ActionResult TestPartialViewWithModel(string id)
{
var model = new TestViewModel { DocTitle = id, DocContent = "This is a test with a partial view" };
return new PartialViewAsPdf(model);
}

Entity Framework – How to supply a connection string to constructor

If you are using Entity Framework in your projects or websites. You are about to add clients which will have other databases with other connection strings. Database schema is same for all.

For this you are to pass client connection string in EF constructor, this will override the base connection string and use the connection string database.

Basic connection string will not works with EF so you have to use same format of connection string which was created while creating the EDMX file i.e with meta info.

There are two ways to use connection string in constructor:

1. EntityConnectionStringBuilder : Create a connection string format real time with all details.

2. Connection String from config file.

using (MyEntity myent= new MyEntity("name=client2_connectionstring"))
{
}

using (MyEntity myent= new MyEntity("name=client2_connectionstring"))
{
}

How to cast MSSQL Datetime in MYSQL

If any one mograte MSSQl data to MYSQl then there will be issue related to datetime column. SQL management studio generate script export the datetime value to hex value and MYSQL doesn’t recognized it.

To solve this issue just create a function and called it where required.

create function sp_ConvertSQLServerDate(dttm binary(16))
returns datetime
return CAST(
’1900-01-01 00:00:00′ +
INTERVAL CAST(CONV(substr(HEX(dttm),1,8), 16, 10) AS SIGNED) DAY +
INTERVAL CAST(CONV(substr(HEX(dttm),9,8), 16, 10) AS SIGNED)* 10000/3 MICROSECOND
AS DATETIME);

and how to use it in MYSQL:

SELECT sp_ConvertSQLServerDate(0x00009E3000C98FF6) AS BinaryData

How to list all tables which was updated in last days

– Method to list all tables which was updated in current month
SELECT TABLENAME,LASTUPDATED FROM
(
SELECT B.NAME AS ‘TABLENAME’, MAX(STATS_DATE (ID,INDID)) AS LASTUPDATED,
CONVERT(VARCHAR, MAX(STATS_DATE (ID,INDID)), 103) as Date
FROM SYS.SYSINDEXES AS A
INNER JOIN SYS.OBJECTS AS B ON A.ID = B.OBJECT_ID
WHERE B.TYPE = ‘U’ AND STATS_DATE (ID,INDID) IS NOT NULL
GROUP BY B.NAME
) AS A
WHERE LASTUPDATED>=(select DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0)) AND LASTUPDATED<=(select DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0)))
ORDER BY LASTUPDATED DESC

-- Method to list all tables which was updated in date range
SELECT TABLENAME,LASTUPDATED FROM
(
SELECT B.NAME AS 'TABLENAME', MAX(STATS_DATE (ID,INDID)) AS LASTUPDATED,
CONVERT(VARCHAR, MAX(STATS_DATE (ID,INDID)), 103) as Date
FROM SYS.SYSINDEXES AS A
INNER JOIN SYS.OBJECTS AS B ON A.ID = B.OBJECT_ID
WHERE B.TYPE = 'U' AND STATS_DATE (ID,INDID) IS NOT NULL
GROUP BY B.NAME
) AS A
WHERE LASTUPDATED>=’2013-05-01′ AND LASTUPDATED<=’2013-05-31′
ORDER BY LASTUPDATED DESC

How To Automatically Logon To Windows

Press the Windows key + R on your keyboard to launch the “Run” dialog box.

Type in control userpasswords2 or netplwiz

Press Enter. The User Accounts window will display.

Uncheck the option “Users must enter a user name and password to use this computer”

Click “OK”

You will then be prompted to enter the password and confirm it.

After doing so, you will no longer be prompted to enter your password upon login.

From now on, when your PC starts up, Windows will log on automatically.