What is the best way to generate a PDF and Excel file from ASP.Net MVC - asp.net-mvc

I need to generate a PDF and an Excel file from my ASP.net MVC application.
Any ideas on the best way to implement this?

Use iTextSharp to create the PDF and return it with a FileContentResult.

I recommend writing a reporting services report (RDLC), deploying it with the web application, and using the report viewer control to render the output.
Bringing reporting services in may seem like a steep learning curve, but it is not too bad. You get the added benefit of a solid solution that supports other formats. You don't need a report server for this deployment scenario - not even SQL Server.

Create a PDFActionResult and an ExcelActionResult
EDIT
Example for an excelactionresult: http://stephenwalther.com/blog/archive/2008/06/16/asp-net-mvc-tip-2-create-a-custom-action-result-that-returns-microsoft-excel-documents.aspx

something like abcpdf is cool for creating the PDF, as for excel you just need to create a datatable from your dataset
var grid = new System.Web.UI.WebControls.DataGrid();
grid.HeaderStyle.Font.Bold = true;
grid.DataSource = yourdatahere;
grid.DataMember = yourdatahere.Stats.TableName;
grid.DataBind();
// render the DataGrid control to a file
using (var sw = new StreamWriter("c:\\test.xls"))
{
using (var hw = new HtmlTextWriter(sw))
{
grid.RenderControl(hw);
}
}
as for doing it with a pdf, that would depend on what route you take!

For PDF, you can use PdfSharp. For Excel, I think Aspose.Cells will be good (although I've never used it, I have used their Word component and it rocks).

PDF - use NFOP, PdfSharp or iSharpText
Excel - if you need plain data as a spreedshet, then render as plain-text CSV file. If you need formatting and all the whistles, then use GBSpreadsheet.

Related

Swagger-Swashbuckle include xmlcomments from dependent dlls

I need to document an asp.net core web api and I m using swagger and swashbuckle.
I have looked around and I have found this link but it's old and does not work
https://github.com/domaindrivendev/Swashbuckle/issues/93
Can somebody show/point me how i can include xml comments from another dll?
thanks
There are two versions of swashbuckle:
https://github.com/domaindrivendev/Swashbuckle
https://github.com/domaindrivendev/Swashbuckle.AspNetCore
If the tags on this question are correct, your link is not to the version you are using, but still the solution offered should give you a good idea what you need to do.
You can include as many xml comments as you want with IncludeXmlComments that is still available on Swashbuckle.AspNetCore, see here:
Swashbuckle.AspNetCore.SwaggerGen/Application/SwaggerGenOptions.cs#L259
First you need to make sure that the xml comments you need are making it to the server as part of your deployment, otherwise Swashbuckle will not show what it is not there...
A solution could be to recursively loop looking for XML files and add them using the IncludeXmlComments, something like this:
public void IncludeAllXmlComments(string folder)
{
if (!string.IsNullOrEmpty(folder))
{
foreach (var name in Directory.GetFiles(folder, "*.XML", SearchOption.AllDirectories))
{
IncludeXmlComments(filePath: name);
}
}
}
This sample code is just to give you an idea, not for copy/pasta

open source controls to convert rich text formatted code to html markup

I am working on asp.net mvc. I am trying to display the rich text formatted content like,
{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\
fcharset0 Times New Roman;}{\f2\fcharset0 Tahoma;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hi
ch\dbch\pard\plain\ltrpar\itap0{\lang1033\fs24\f2\cf0 \cf
0\ql{\f2 {\ltrch AMANDA WITH RC CALLED AND WANTED TO
VERIFY THAT WE WERE AFFILIATED WITH SHAUN # JAGGYS. LET HER KNOW WE
WERE, SHAUN CALLED RC AS WELL TO VERIFY STATUS OF BD}\li0\ri0\sa0\sb0\fi0\ql\par}
}
}
in the view. Actually this data could come from database table and i need to display it in the editor type control. so is there any open source controls that are able to display rich text format.
Well, I just got done writing a RTF to HTML converter that maintains all embedded media, and creates a MIME multipart message out of it. This is close to what you want to do. Essentially if you aren't interested in writing your own converter, you can look at this CodeProject and use his: http://www.codeproject.com/Articles/27431/Writing-Your-Own-RTF-Converter
There is also descriptions as to how to reach his solution.
On my project we just started ripping apart the RTF document and parsing its contents. Open source and 3rd-Party Libraries weren't an option for me.

How do you create an EditorTemplate in a Plugin for nopCommerce v2.20

I'm trying to create a plugin for nopCommerce v2.20 that allows the user to request a quote for goods and services by describing the requirements and attaching any relevant documents.
I have started by using http://blog.csharpwebdeveloper.com/2011/09/10/writing-a-plugin-for-nopcommerce-2-x/ as a guide, this has been very good so far. My project is almost identical to the one in the blog post so I'll only add code snippets as I think they are required, so please ask me to expand and provide details if I have left anything important out.
Now I want to add a facility to upload multiple files using uploadify and have decided based on the existing code that I should create an EditorTemplate for attachments.
My problem is I can't work out how to setup my template in a way that can be located by the MVC framework when I use the following line of code to get the template.
#Html.EditorFor(m => m.Attachment)
In my model I’m using the UIHintAttribute("Attachments") on the Attachment property to identify the template with no noticeable effect.
I have created a folder below the "Views" folder called "EditorTemplates" and added a file called "Attachments.cshtml" with the build action set to "Embedded Resource", contents below:
#model int
#using Nop.Core;
#{
var randomNumber = CommonHelper.GenerateRandomInteger();
var clientId = "download" + randomNumber;
var downloadService = EngineContext.Current.Resolve();
var download = downloadService.GetDownloadById(Model);
}
<div>This is a download control #string.Format("randomNumber = {0}, clientId = {1}, download = {2}", randomNumber, clientId, download);</div>
I intend to implement the template once I can get the MVC framework to resolve its location.
So is it possible to have an editor template in a plugin (a separate class library from the main project) and if so what do I need to do to enable the MVC framework to resolve my template location?
I'd also like to add I'm quite new to MVC, Razor, and nopCommerce, sorry in advance if I missed something obvious.
As a side, could you suggest a better title for my question as stackoverflow tells me that it appears subjective?
thanks
If you are trying to supply an editor template without pre-compilation (which is probably the best way until you get into some more advanced scenarios) you will want to set the BuildAction as "Content" - not "EmbeddedResource".
Also, make sure your editor template is in one of the following directory structures (you mentioned it was under "Views" which is incorrect):
/Views/{ControllerName}/EditorTemplates/Attachments.cshtml
/Views/Shared/EditorTemplates/Attachments.cshtml
/Areas/{AreaName}/Views/{ControllerName}/EditorTemplates/Attachments.cshtml
/Areas/{AreaName}/Views/Shared/EditorTemplates/Attachments.cshtml
If you do want to embed the templates as part of a separate library, I suggest you look at this post from Chris Van De Steeg.

ASP.net MVC Export To Excel

I am currently exporting to Excel using the old HTML trick, where I set the MIME type to application/ms-excel. This gives the added benefit of nicely formatted tables, however the negative of the excel document not being native Excel format.
I could export it as CSV, but then this would not be formatted.
I have read brief snippets that you can export it as XML to create the Excel document, but cannot find too much information on this. Does anybody know of any tutorials and/or benefits of this? Can it be formatted tables using this method?
Thanks.
Easiest way, you could parse your table and export it in Excel XML format, see this for example: http://blogs.msdn.com/b/brian_jones/archive/2005/06/27/433152.aspx
It allows you to format the table as you whish (borders, fonts,colors, I think even formulas), and Excel will recognize it as native excel format. As a plus, you can use other programs that can import Excel XML (ie.Open office, Excel viewer,etc) and you do not need to have Office components installed on the server.
Check out ExcelXmlWriter.
We've been using it for some time and it works well. There are some downsides to the xml format however. Since it's unlikely your end users will have the .xml extension associated with Excel, you end up having to download files as .xls with an Excel mime type. When a user opens a file downloaded in this way they get a warning that the file is not in xls format. If they click through it, the file opens normally.
The only alternative is a paid library to generate native Excel files. That's certainly the best solution but last time we looked there were no good, free libraries (may have changed)
Bill Sternberger has blogged a very simple solution here:
export to excel or csv from asp.net mvc
Just today I had to write a routine that exported data to excel in an MVC application. Here's the details so someone may benefit in the future, first the user had to select some date ranges and areas for the report. On the post back, this method was in place, with TheModelTypeList containing the data from LINQ/Entity Framework/SQL Query returning strong types:
if (ExportToExcel) {
var stream = new MemoryStream();
var serializer = new XmlSerializer(typeof(List<SomeModelType>));
serializer.Serialize(stream, TheModelTypeList);
stream.Position = 0;
FSR = new FileStreamResult(stream, "application/vnd.ms-excel");
}
The only catch on this one was the file type was not known when opening so the system prompted for the application to open it... this is a result of the content being XML.... I'm still working on that.
I am using Spreadsheet Light, an Open-Source library that provides ridiculously easy creation, manipulation and saving of an Excel sheet from C#. You can have an MVC / WebAPI Controller do the work of creating the file and either
Return a URL link to the saved Excel file to the page and invoke Excel to open it with an ActiveX object
Return a Data Content Stream to the page
Return a URL link to the calling page to force an Open / Save As dialog
http://spreadsheetlight.com/

Saving a picture from a browser canvas

I'm currently developing a website in ASP .NET MVC and I require functionality for a user to be able to draw a picture on a canvas which can be saved in a database. What is the best method for doing this? preferably a very lightweight solution. I was thinking flash would be the most accessible platform and there may be some good free solutions.
Thanks
Flash can do it pretty easily, though you'll have to get your back-end set up to enable it. Basically you can draw anything on your stage to a bytearray of pixel data, then encode that bytearray to comply with for instance the .PNG specification. Then you send the whole package over to your back end as a byte array and make sure that your server-side scripts know to write it as a .png file to your server, then save the location in your database. Does that make sense?
A broad example can be found here on the Flex Cookbook: http://cookbooks.adobe.com/post_Creating_a__png_file_from_a_webcam_image-12732.html
You can do this in DotNet using the canvas.
canvas.SaveAs(dstfile, "Quality=high");
Here is the tutorial: http://www.websupergoo.com/helpig6net/source/3-examples/1-drawimage.htm
No need to use Flash.
An excellent way of saving an image is to use the native toDataURL method.
var element = document.getElementById('drawingCanvas');
var data = element.toDataURL();
// data holds the base64 encoded image of the canvas
From there you can post it asynchronously to the server
$.ajax({
'type': 'post',
'dataType': 'json',
'data': {'image': data},
'url': '/json/image_converter.php'
});
and convert it to an image using ImageMagick:
list($header, $data) = explode(',', $_POST['image']);
$image = base64_decode($data);
$magick = new Imagick();
$magick->setFormat('png');
$magick->readImageBlob($image);
$magick->writeImage('/home/dude/imagefile.png');
Edit: Oh, and of course I forgot to say that IE doesn't support canvas, hence no toDataURL method. Even with explorer canvas workaround.
You should be able to do something like this in Silverlight... Silverlight should be able to, without difficulty, translate the mouse movements into line strokes. I don't know if there is a pure JavaScript solution too.
User MouseUp,mouseDown and MouceMove events along with LintTo,MoveTO events of canvas (all javascript) to draw a picture and then use canvas.toDataURL() to save this picture in a base64 string in yr database.

Resources