I want to create reports in my ASP.NET MVC 5 application. I found this code (Hello world example in http://report.sourceforge.net/):
Report report = new Report(new PdfFormatter());
FontDef fd = new FontDef(report, "Helvetica");
FontProp fp = new FontPropMM(fd, 25);
Page page = new Page(report);
page.AddCB_MM(80, new RepString(fp, "Hello World!"));
RT.ViewPDF(report, "HelloWorld.pdf");
When I put this code inside a main in a console application, it creates and opens a PDF file that writes "Hello World".
But when I put the same code inside a controller in ASP.NET like this, I get nothing, no PDF opens or no PDF is saved in the server (I click mywebsite/Person/Print) :
public ActionResult Print(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person= db.Person.Find(id);
if (person== null)
{
Report report = new Report(new PdfFormatter());
FontDef fd = new FontDef(report, "Helvetica");
FontProp fp = new FontPropMM(fd, 25);
Page page = new Page(report);
page.AddCB_MM(80, new RepString(fp, "Hello World!"));
RT.ViewPDF(report, "HelloWorld.pdf");
}
return View(person);
}
How can I modify my ASP.NET application to let user get PDFs using this code? (I will also appreciate if you know any cool-free reporting tools for ASP.NET MVC 5.) Thanks.
Not sure what libraries you are using there but the general flow of your action should be like:
prepare report object
obtain byte array representing the content of the PDF file
return a File from your action using the File method: Controller.File
The result on the client would be a file download prompt
Related
I want to export the power bi report to pdf, to do that I have followed the below article
https://learn.microsoft.com/en-us/power-bi/developer/embedded/export-to
Here I'm able to export the report but without data.
So to see the data in the report I have to set the date slicer filter first.
because to see the data there is a dependency on the date slicer filter.
I have tried below code snippets for applying the filter, but nothing worked
//urlFilter = "%2FReportSection%3Ffilter%3DTable%2Fdate%20ge%202021-02-26%20and%20Table%2Fdate%20le%202021-03-02";//not working
//urlFilter = "/ReportSection?filter=DateTable/date ge 2022-05-07 and DateTable/date le 2022-06-07";//not working
//urlFilter = "?filter=DateTable/date ge 2022-05-07 and DateTable/date le 2022-06-07"; //not working
//urlFilter = #"?filter=DateTable/date ge 2022-05-07 and DateTable/date le 2022-06-07";
var powerBIReportExportConfiguration = new PowerBIReportExportConfiguration
{
Settings = new ExportReportSettings
{
Locale = "en-us",
},
Pages = new List<ExportReportPage>(),
ReportLevelFilters = !string.IsNullOrEmpty(urlFilter) ? new List<ExportFilter>() { new ExportFilter(urlFilter) } : null,
};
I really appreciate any help done.
Thank You
Query String filtering doesn't work with Publish to web or Export to PDF. But You can capture the filters in bookmark and then export the report to pdf.
// Capture the Bookmark state
const capturedBookmark = await report.bookmarksManager.capture();
The captured state (which is just a string) is then passed to the PowerBI .NET SDK method ExportToFileInGroupAsync as part of the PowerBIReportExportConfiguration that is necessary.
References:
https://learn.microsoft.com/power-bi/developer/embedded/export-to
https://learn.microsoft.com/power-bi/collaborate-share/service-url-filters
https://learn.microsoft.com/javascript/api/overview/powerbi/report-bookmarks
I have following problem: I wrote a HTML-Code which shows a variable List as table when I press the Button. I did so far, that the table get showed in PDF in a Print Service. But the table has some sort functions and on a PDF one can't use them. So I try to show the HTML as a Website in Webview in the App, where one can use the function. The code for the code behind is the following:
public ICommand PrintCommand => new AsyncCommand(Print);
private async Task Print()
{
// New up the Razor template and set the model property
var printTemplate = new ListPrintTemplate
{
Model = FilteredList,
};
// Generate the HTML
var htmlString = printTemplate.GenerateString();
// Create a source for the webview
var htmlSource = new HtmlWebViewSource{ Html = htmlString };
// Create and populate the Xamarin.Forms.WebView
var browser = new WebView { Source = htmlSource };
var printService = Xamarin.Forms.DependencyService.Get<IPrintService>();
printService.Print(browser, $"{Res.Probe}-{FilteredList}");
}
I have still the printService in the last lines. I looked over the libraries and the Microsoft documentation but can't help myself.
I am trying to generate a pdf using rotativa in asp.net. My view has multiple partial views rendered on it. I am able to create a pdf of single partial views but when i am combine all the partial views and trying to generate the pdf. It generates the pdf before loading the data in the pdf. please suggest how to hold the process until the loading of data in the pdf.
Thanks in advance.
public ActionResult Followers()
{
MediaAPIController mac = new MediaAPIController();
JsonResult jR = mac.getUserInfo("", "", "", "201");
MediaLibrary.User u = (MediaLibrary.User)jR.Data;
System.Threading.Tasks.Task.Run(async delegate
{
await Task.Delay(5000);
return 42;
}).Wait();
return new Rotativa.ActionAsPdf("PreviewPdf", u)
{
FileName = "MyDoc.pdf",
PageSize = Rotativa.Options.Size.A4,
PageOrientation = Rotativa.Options.Orientation.Portrait,
PageMargins = { Left = 10, Right = 10 }
};
}
You can use ViewAsPdf method instead of ActionAsPdf and pass the model that are bind in partial views. In this way the view will be bind before rendering and problem will be solved.
Small problem here with an MVC app that I'm not sure how to figure out a way around.
Basically, I'm adding additional functionality to a system that was originally created by someone else (c#). For a reporting system, the results were only ever displayed on screen. Now I am building in the functionality to allow the user the ability to download their report as an Excel document.
So basically, I have a view that displays the date ranges, and some other search refinement options to the user. I have introduced a radio button that if selected will download the report as opposed to displaying it on screen.
Here are my three actions within the ReportController:
public ActionResult Index()
{
return View();
}
public ActionResult ProductReport(AdminReportRequest reportRequest, FormCollection formVariables)
{
AdminEngine re = new AdminEngine();
if (!reportRequest.Download)
{
AdminReport report = re.GetCompleteAdminReport(reportRequest);
return View(report);
}
Stream ExcelReport = re.GetExcelAdminReport(reportRequest);
TempData["excelReport"] = ExcelReport;
return RedirectToAction("ExcelProductReport");
}
public FileResult ExcelReport()
{
var ExcelReport = TempData["excelReport"] as Stream;
return new FileStreamResult(ExcelReport, "application/ms-excel")
{
FileDownloadName = "Report" + DateTime.Now.ToString("MMMM d, yyy") + ".xls"
};
}
I've debugged through the AdminEngine, and everything looks fine. However, in the ExcelReport action, when it comes to returning the file - it doesn't. What I see is a lot of characters on screen (in the 'panelReport' div - see below), mixed in with what would be the data in the excel file.
I think I have established that the reason it is being displayed on screen is as a result of some code
that was written in the Index view:
<% using (Ajax.BeginForm("ProductReport", "Report", null,
new AjaxOptions
{
UpdateTargetId = "panelReport",
InsertionMode = InsertionMode.Replace,
OnSuccess = "pageLoaded",
OnBegin = "pageLoading",
OnFailure = "pageFailed",
LoadingElementId = ""
},
new { id = "SearchForm" })) %>
As you can see, the Ajax.BeginForm statement states that it should update to the panelReport div - which is what it's doing (through the Product Report partial view). While this is perfect for when the reports need to be displayed on screen, it is obviously not going to work with an excel file.
Is there a way of working around this issue without changing the existing code too much?
Here is the class where I do the workings for the excel file in case it's required to shed light on the situation:
Report Class:
public Stream GetExcelAdminReport(AdminReportRequest reportRequest)
{
AdminReport report = new AdminReport();
string dateRange = null;
List<ProductSale> productSales = GetSortedListOfProducts(reportRequest, out dateRange);
report.DateRange = dateRange;
if (productSales.Count > 0)
{
report.HasData = true;
CustomisedSalesReport CustSalesRep = new CustomisedSalesReport();
Stream SalesReport = CustSalesRep.GenerateCustomisedSalesFile(productSales);
return SalesReport;
}
}
Workings Class:
public class CustomisedSalesReport
{
public Stream GenerateCustomisedSalesFile(List<ProductSale> productSales)
{
MemoryStream ms = new MemoryStream();
HSSFWorkbook templateWorkbook = new HSSFWorkbook();
HSSFSheet sheet = templateWorkbook.CreateSheet("Sales Report");
//Workings
templateWorkbook.Write(ms);
ms.Position = 0;
return ms;
}
}
The problem is pretty obvious that you are using an Ajax Form to download a file. On top you are using the built-in Microsoft Ajax libraries, which seem to be not intelligent enough.
I can provide 2 solutions:
The easiest solution (which I have used in the past) is that instead of streaming a file yourself, create an excel file and save it on the server and then send the download link to the user. It won't require a lot of change to the code.
You could handle the OnSubmit event of the AjaxForm, see if you it's a file to download. If yes, then make a full postback request (using $.post()). This way the browser will automatically pop-up the dialog asking for where to download.
Hope it makes sense.
I'm not sure if this has even been done before, but what I am trying to accomplish can't be explained in any great detail, but basically, what I am trying to do is Process PHP scripts from within my C# Windows Forms Application.
I have already created a HTTP server, which works just fine. But now I need to be able to process PHP scripts aswell. We're working on a new privatised language over here, purely for learning and fun.
(Just a little background, not completely related):
We are now able to create a webpage like so:
Using System.Core,
System.Http,
System.Graphics and System.IO;
protected void -> Webpage(object homepage)
{
// Set Webpage properties.
homepage.Name = "Home";
homepage.Size = new Size(960[px], 100[%]);
homepage.Alignment = new AlignmentType.Vertical;
homepage.Alignment = new AlignmentType.Horizontal;
// This is a comment.
// Create objects to be rendered on the page.
Text text = new Text();
FormElements formElements = new FormElements();
private void -> Webpage.Load(object homepage)
{
text.Text = "Please enter your name below:";
text.Style = new Style(
Alignment = new AlignmentType.Horizontal,
Alignment = new AlignmentType.ManualAlignment(15[Y, px]),
Font = new Font(
Font.Family("Arial"),
Font.Size = new Size(9[pt], LineHeight(4[px])),
Font.Color = new Color.FromArgb(15, 15, 15))
);
formElements.CreateElements(TextField["textField"], SubmitButton["submitButton"], Form["form"]);
textField.Name = "name";
submitButton.Name = "submit";
form.Encapsulate(name, submit);
form.Alignment = new AlignmentType.RelativeTo(text.Bottom);
Elements[] elements = new Elements[]
{
text, form;
};
homepage.Display.Element.ElementCollection(elements);
}
private void -> Webpage.FormSubmission(object form)
{
form.Element(name).OmitSpecialCharacters();
if(form.Value is not Empty)
{
text.Text = "Hello, " + form.Element(name).Value;
}
}
}
The above sample demonstrates the ability to create a whole webpage, style it, and process form input in a nice, clean way. However, we've come to a complete dead end (trying to support PHP) and we do not wish to delve too far into server-side languages (lack of experience in that area is the main reason), so we would like to be able to "support" PHP scripts from within our WinForms app.
Anyone know of any way to process PHP scripts from within a C# winforms app?
Here is a simple http server that supports PHP:
MiniHttpd: an HTTP web server library
And here is Phalanger - The PHP Language Compiler for the .NET Framework
Use an HttpWebRequest, and request the url to the PHP page like you would to run the PHP page in your browser.
See here for more info: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx