I am working on MVC 6 application(DNX Core 5.0 framework). Unfortunately, I don't find any library for pdf export.
Any help will be appreciated.
I finally figured out a way to generate pdf's from .NET Core (without any .NET framework dependencies) is using Node.js from within my .NET Core application.
The following example shows how to implementing a HTML to PDF converter in a clean ASP.NET Core Web Application project (Web API template).
Install the NuGet package Microsoft.AspNetCore.NodeServices
In Startup.cs add the line services.AddNodeServices() like this
public void ConfigureServices(IServiceCollection services)
{
// ... all your existing configuration is here ...
// Enable Node Services
services.AddNodeServices();
}
Now install the required Node.js packages:
From the command line change working directory to the root of the .NET Core project and run these commands.
npm init
and follow the instructions to create the package.json file
npm install jsreport-core --save
npm install jsreport-jsrender --save
npm install jsreport-phantom-pdf --save
Create a file pdf.js in the root of the project containing
module.exports = function (callback) {
var jsreport = require('jsreport-core')();
jsreport.init().then(function () {
return jsreport.render({
template: {
content: '<h1>Hello {{:foo}}</h1>',
engine: 'jsrender',
recipe: 'phantom-pdf'
},
data: {
foo: "world"
}
}).then(function (resp) {
callback(/* error */ null, resp.content.toJSON().data);
});
}).catch(function (e) {
callback(/* error */ e, null);
})
};
Have a look here for more explanation on jsreport-core.
Now create an action in an Mvc controller that calls this Node.js script
[HttpGet]
public async Task<IActionResult> MyAction([FromServices] INodeServices nodeServices)
{
var result = await nodeServices.InvokeAsync<byte[]>("./pdf");
HttpContext.Response.ContentType = "application/pdf";
string filename = #"report.pdf";
HttpContext.Response.Headers.Add("x-filename", filename);
HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "x-filename");
HttpContext.Response.Body.Write(result, 0, result.Length);
return new ContentResult();
}
Off course you can do whatever you want with the byte[] returned from nodeServices, in this example I'm just outputting it from a controller action so it can be viewed in the browser.
You could also exchange the data between Node.js and .NET Core by a base64 encoded string using resp.content.toString('base64') in pdf.js and use
var result = await nodeServices.InvokeAsync<byte[]>("./pdf"); in the action and then decode the base64 encoded string.
Alternatives
Most pdf generator solutions still depend on .NET 4.5/4.6 framework.
None of the two answers above (JsReport and RazorPDFCore) works for .NET Core yet.
There seems to be some paid alternatives available if you don't like to use Node.js:
NReco.PdfGenerator.LT
EVO HTML to PDF Converter Client for .NET Core
Winnovative HTML to PDF Converter Client for .NET Core
I haven't tried any of these though.
I hope we will soon see some open source progress in this area.
If you must rely on Core you'll have two options:
1 - Wait a bit
Core is still RC1, slowly moving to RC2, and you won't find much libs really soon. Since .NET Core is taking much attention, first libs should come out in a few months, but I'd guess you'll have to wait for at least RC2 release.
2 - Fork (or similar)
You can grab an open-source project that best fits your needs, fork (if on GitHub) or just download and start updating to .NET Core. I've just done that with DapperExtensions and it's working like a charm. You can even add some spicy just for you ;)
On the other hand, if you just need something that works but with no direct need of embedding into .NET Core, I've managed to make JsReport work fine. It will start it's very own server (embedded server) based on Node but integration is really easy (with AspNet Core very own Dependecy Injection system!) and PDF are created with no further issue.
If that interests you, here are some instructions:
1 - References
Add those to your project.json:
"jsreport.Embedded": "0.8.1",
"jsreport.Client": "0.8.1"
2 - AspNet integration
After, follow instructions from jsReport here. You can configure AspNet DI system as here:
public void ConfigureServices(IServiceCollection services)
{
// ...
var _server = new EmbeddedReportingServer();
_server.StartAsync().Wait();
services.AddInstance<IEmbeddedReportingServer>(_server);
services.AddSingleton<IReportingService>((s) => { return s.GetRequiredService<IEmbeddedReportingServer>().ReportingService; });
// ...
}
To use you'll just have to either receive an IReportingService or manually grab it from Resolver on your controller, for instance.
3 - Usage
public IActionResult SomeReport()
{
// This is <my> type of usage. It's a bit manual because I'm currently loading reports from DB. You can use it in a diferent way (check jsReport docs).
var service = Resolver.GetRequiredService<jsreport.Client.IReportingService>();
var phantomOptions = new jsreport.Client.Entities.Phantom()
{
format = "A4",
orientation = "portrait",
margin = "0cm"
};
phantomOptions.footer = "<h2>Some footer</h2>";
phantomOptions.footerHeight = "50px";
phantomOptions.header = "<h2>Some header</h2>";
phantomOptions.headerHeight = "50px";
var request = new jsreport.Client.RenderRequest()
{
template = new jsreport.Client.Entities.Template()
{
content = "<div>Some content for your report</div>",
recipe = "phantom-pdf",
name = "Your report name",
phantom = phantomOptions
}
};
var _report = service.RenderAsync(request).Result;
// Request file download.
return File(_report.Content, "application/pdf", "Some fancy name.pdf");
}
4 - Important: your server won't start (missing a zip file)
Due to changes from NuGet on AspNet projects, you have to manually move some content files which are not moved automatically.
First, find your dnx cache for the embedded server. Should be something like:
C:\Users\<name>\.dnx\packages\jsreport.Embedded\0.8.1.
You'll notice a folder called content there. Simply copy it's contents (two files: node.exe and jsreport-net-embedded.zip) into lib\net45.
So, to be plain simple and fool-proof: copy contents (files only) from
C:\Users\<name>\.dnx\packages\jsreport.Embedded\0.8.1\contents
into
C:\Users\<name>\.dnx\packages\jsreport.Embedded\0.8.1\lib\net45.
That should solve startup issues. Remember: first startup will extract files and should take a few minutes. After that, it will be much much faster.
I know that this question was asked a while ago, and I know that there have been several answers provided already that may well be right for certain projects. But I recently created a GitHub repository that allows for the creation of PDFs directly from your C# code without any requirement for nodejs, javascript, or razor. The feature set is a bit limited at the moment but it generates PDFs with images (.jpg only at this stage), shapes, and formatted text. The library works with .net core 2.0 and has no dependency on any other PDF generation tool.
Please note that this is my own repository: https://github.com/GZidar/CorePDF
I do plan to add functionality over time but at least for now this may provide the basis for others to include simple PDF capability in their own projects without the need for additional tooling.
I have amended the RazorAnt/RazorPDF which was working only for older MVC versions to work with ASP.NET Core. Its RazorPDFCore, available on nuget and github:
Example usage
class YourBaseController : RazorPDF.Controller {
// [...]
public IActionResult Pdf() {
var model = /* any model you wish */
return ViewPdf(model);
}
}
In your Startup.cs
add the following line before services.AddMVc();
services.AddSingleton<PdfResultExecutor>();
PLEASE NOTE:
You need to inhere RazorPDF.Controller from your base controller before using the ViewPdf() method
Necromancing.
Adding a dependency to NodeJS is subideal IMHO, especially considering .NET Core self-contained deployment.
As per 2017, you could use my port of PdfSharpCore to .NET Core 1.1
Resolves fonts, and it can use images. Comes with a nice sample application. You'll have to replace the DB part, however.
Credits go to:
https://github.com/groege/PdfSharpCore
which is a bit outdated, and doesn't contain a sample on how to use it with images.
Note that you need to register the font-resolver and the imageSource-Implementation before using the respective features:
PdfSharpCore.Fonts.GlobalFontSettings.FontResolver = new FontResolver();
MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel
.Shapes.ImageSource.ImageSourceImpl =
new PdfSharpCore.ImageSharp.ImageSharpImageSource();
Related
I'm using RDLC to create reports with my .NET Core Web API. I spent an entire week creating 3 reports using lots of expressions. Now after publishing the application on IIS every report fails with error
An error occurred during local report processing.;An unexpected error
occurred in Report Processing.Object reference not set to an instance
of an object
The report works fine in development. After lots of research I found the issue is with expressions. I have been struggling to find a solution for almost a day searching the entire web. Many people suggested that this is the limitation of RDLC and we can't use expressions. Without expressions there is no use of this tool for me. I can't afford to spend another week to re-create those reports using another tool. In fact I don't even know what else can I use instead of RDLC to create reports.
Any suggestion to fix these issues or an alternative to RDLC will be life saving for me....
It's been a pain to use this unstable tool, but unfortunately I'm stuck in this.
Thanks
Having .NET Core work with library from .NET framework is painful to say the least.
Thanks for the recompiled WinForms library provided by lkosson.
I managed to make this work but it looks like bandage fix more then anything.
Very Important Note!! This solution make use of WPF, WinForms version of RDLC. This limit the .NET 5 solution to Windows build only. (I can't make Web version to work, maybe someone else can)
1. Update .NET 5 project settings
Unload the .NET 5 project
Right click and Edit .csproj
Update/Add 3 lines in property group as following:
<PropertyGroup>
--><TargetFramework>net5.0-windows</TargetFramework>
<RootNamespace>Net_Core_5._0</RootNamespace>
--><UseWindowsForms>true</UseWindowsForms>
--><EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>
</PropertyGroup>
Reload the project
2. Add NuGet Packages
Add and install the following packages:
Microsoft.ReportViewer.Common
Microsoft.ReportViewer.WinForms
ReportViewerCore.WinForms
3. Use .NET version's function to generate Report
This is an example for your reference,
using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.Data;
namespace NET_4._8_RDLC_Lib
{
public class ReportGenerator
{
/// <summary>
/// .NET Core use this function to render reports
/// </summary>
public static byte[] RenderReport(String reportPath, Dictionary<string, DataTable> data, string format)
{
Microsoft.Reporting.WinForms.ReportViewer v1 = new Microsoft.Reporting.WinForms.ReportViewer();
v1.LocalReport.DataSources.Clear();
//Add all datasource to the Report
foreach (KeyValuePair<string, DataTable> pair in data)
{
Microsoft.Reporting.WinForms.ReportDataSource ds = new ReportDataSource(pair.Key, pair.Value);
v1.LocalReport.DataSources.Add(ds);
}
v1.LocalReport.EnableExternalImages = true;
v1.LocalReport.ReportPath = reportPath;
return v1.LocalReport.Render(format: format, deviceInfo: "");
}
}
}
The file is just inside the bytes array.
Very much an XY problem, but I'm interested in the underlying answer too.
See bottom for XY context.
I'm in a .NET Core 3 AzureFunctions (v3) App project.
This code makes my question fairly clear, I think:
namespace MyProj.Functions
{
internal class CustomStartup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
var isDevelopment = true; //Can I correctly populate this, such that it's true only for local Dev?
if(isDevelopment)
{
// Do stuff I wouldn't want to do in Prod, or on CI...
}
}
}
}
XY Context:
I have set up Swagger/Swashbuckle for my Function, and ideally I want it to auto-open the swagger page when I start the Function, locally.
On an API project this is trivial to do in Project Properties, but a Functions csproj doesn't have the option to start a web page "onDebug"; that whole page of project Properties is greyed out.
The above is the context in which I'm calling builder.AddSwashBuckle(Assembly.GetExecutingAssembly()); and I've added a call to Diagnostics.Process to start a webpage during Startup. This works just fine for me.
I've currently got that behind a [Conditional("DEBUG")] flag, but I'd like it to be more constrained if possible. Definitely open to other solutions, but I haven't been able to find any so ...
While I am not completely sure that it is possible in azure functions I think that setting the ASPNETCORE_ENVIRONMENT application setting as described in https://learn.microsoft.com/en-us/azure/azure-functions/functions-how-to-use-azure-function-app-settings should allow you to get whether the environment is set as production or development by injecting a IHostEnvironment dependency and checking
.IsDevelopment()
on the injected dependency.
I'm using Serilog with ASP.Net Core 2.0, writing to RollingFile using JsonFormatter. Followed the instructions here to configure: https://github.com/serilog/serilog-aspnetcore. Everything works great, but in every log entry I get the following properties that I did not log:
SourceContext
RequestId
RequestPath
I presume they are being added by the ASP.Net Core logging framework. How can I get rid of them?
This can be achieved by plugging an enricher into the logging pipeline:
.Enrich.With(new RemovePropertiesEnricher())
Where:
class RemovePropertiesEnricher : ILogEventEnricher
{
public void Enrich(LogEvent le, ILogEventPropertyFactory lepf)
{
le.RemovePropertyIfPresent("SourceContext");
le.RemovePropertyIfPresent("RequestId");
le.RemovePropertyIfPresent("RequestPath");
}
}
Yes, you can get rid of them. Try to use log template:
_loggerConfiguration.WriteTo.Console(LogLevel.Debug, "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {Message}{NewLine}{Exception}");
In this scenario, you won't see mentioned properties in your output.
When you are logging an object, Serilog has the concept of destructuring.
And if you want to remove(ignore) some properties in those objects for logging, there are two options.
You can use attributes. Take a look at this post.
Then there is by-ignoring. You need this Destructurama.ByIgnoring nuget.
Note you should not use both. Using both did not work for me.
I've been banging my head at this for about 8 hours now, and I just can't seem to find a simple explanation on how to change my custom bootstrapper for ninject (Last worked on the code back in v2.x.x.x) to the new v3.0.0.0 syntax.
I currently have the following:
public class NinjectCustomBootStrapper : NinjectNancyBootstrapper
{
protected override Ninject.IKernel GetApplicationContainer()
{
return Program.MyContainer;
}
}
in a septate class, and :
public static IKernel MyContainer
{
get { return _myContainer ?? (_myContainer = CreateKernel()); }
set { _myContainer = value; }
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<CardMonitorService>().ToSelf().InSingletonScope();
return kernel;
}
in my main program 'Program.c' in a command line app.
Iv'e since updated ninject to V3.0.0.0 only to find that there's been some breaking changes. I'll admit I don't use ninject very often (I usually use structuremap), and the only reason this project does is I didn't write it originally.
Since I've upgraded Ninject, now when the app is started up I get the following exception:
Method not found: 'Ninject.Syntax.IBindingWhenInNamedWithOrOnSyntax`1<!0>
Ninject.Syntax.IBindingToSyntax`1.ToConstant(!0)'.
After a ton of searching and researching, the closest I've been able to find is this:
http://sharpfellows.com/post/Ninject-Auto-registration-is-changing-in-version-3.aspx
Which while it points me in the right direction, still isn't quite a solution as I'm not using a custom binding generator.
So my question is this.
How do I rewrite the above so that my project once again works and the WCF service when called gets the correct singleton binding handed to it when a request comes in. Going back to ninject 2 is not an option, as other dependencies in the project that have been added have forced the v3 upgrade and these add new functionality that's been requested hence why I'm working on it.
For reference this is a .NET4 build, running on NancyFX with a self hosting WCF setup as a windows service using Topshelf to provide the SCM interface.
Cheers
Shawty
Addendum to clear things up a little
This is an existing project that was originally written sometime back, I've been asked to add some new features to the project.
As part of adding these new features I have been required to upgrade the version of Ninject being used from an earlier version to V3.0.0.0 as newer dependencies added to the project require the newer version of Ninject.
Under the previous V2 of Ninject the code I have given above worked fine, with no issues, since the project has had Ninject V3 added I now get the exception as described above.
I cannot go back to the earlier version of Ninject as that will mean not being able to add the new functionality that I'm adding.
From the research I've done so far the sharpfellows link above is the closest explanation of my issue that I've managed to find so far on the internet.
I don't use Ninject very often, so I've not got the background to know what's changed between V2 & V3 that (based on my research) is the cause of my issue.
I need to know how to change my code written under V2 (and shown above) so that it works under V3.
MissingMethodException is usually a deployment problem. You compile against a different assembly than you deploy. Check that you deployed the same version and same build.
So after a week or so it turns out that the problem was that the Nancy dev team broke binary comparability with the latest version of ninject (or vice versa) :-)
There is a GitHub pull request to fix this available at :
https://github.com/NancyFx/Nancy.Bootstrappers.Ninject/pull/6
However the next version 'Nancy.Bootstrapper.Ninject' 0.12 will be out on NuGet soon which will have the fix implemented.
Using Entity Framework Migrations (Beta1), using Update-Database command is all good during development.
But when the application is running on some customer's server somewhere, I really want my application to automatically update it's database schema to the latest version when it's started.
Is this possible? Documentation is scarce.
They aren't providing a way to do this until RTM, at which point they have promised a command line app and a msdeploy provider.
Source: http://blogs.msdn.com/b/adonet/archive/2011/11/29/code-first-migrations-beta-1-released.aspx
Of course not being satisfied with that, the powershell command is stored in the packages directory and is plain text, it appears to just load up an assembly called EntityFramework.Migrations.Commands stored in the same directory.
Tracing through that assembly I came up with the following
public class MyContext : DbContext
{
static MyContext()
{
DbMigrationsConfiguration configuration = new DbMigrationsConfiguration() {
MigrationsAssembly = typeof(MyContext).Assembly,
ContextType = typeof(MyContext),
AutomaticMigrationsEnabled = true,
};
DbMigrator dbMigrator = new DbMigrator(configuration);
dbMigrator.Update(null);
}
}
UPDATE: after a bit of experimentation I figured out a few more things
Performing an update in the static constructor for your context is bad as it breaks the powershell commands, much better off adding the code to application startup another way (Global.asax, WebActivator or Main method)
The above code only works when using AutomaticMigrations, you need to set the MigrationsNamespace for it to pickup on manually created migrations
The configuration class I was creating should already exist in your project (added when you install the migration nuget package), so just instantiate that instead.
Which means the code is simplified to
DbMigrator dbMigrator = new DbMigrator(new NAMESPACE.TO.MIGRATIONS.Configuration());
dbMigrator.Update(null);
Another options for this issue is to add
Database.SetInitializer<MyContext>(new MigrateDatabaseToLatestVersion<MyContext, NAMESPACE.TO.MIGRATIONS.Configuration>());
line to your Global.asax Application_Start method.