fpanaccia / wkhtmltopdf.netcore-deprecated Goto Github PK
View Code? Open in Web Editor NEWRotativa + Net Core
License: The Unlicense
Rotativa + Net Core
License: The Unlicense
The core functionality of this library does not require MVC at all, it makes me a bit sad to have to pull in all of AspNetCore.MVC anyway. (I want to use it in an old .NET Framework project that's still on MVC4). Happy to submit a pull request but it would probably consist of moving the MVC-dependent code into your example project or something, which seems a bit invasive for a drive-by PR to your project. :)
Good morning,
I'm trying to launch library on Azure WebApp. Unfortunately all the time I have an error:
System.ComponentModel.Win32Exception (13): Permission denied at Wkhtmltopdf.NetCore.GeneratePdf.GetByteArray[T](String View, T model)
For test purpose I injected also IRazorViewToStringRenderer class from the library to check is HTML rendered properly
await this.razorViewToStringRenderer.RenderViewToStringAsync("Views/Home/Index.cshtml", results);
At this moment everything working good, method is returning rendered HTML.
Problem is starting when I try to call
await generatePdf.GetByteArray("Views/Home/Index.cshtml", results);
About environment:
Everything is deployed by Azure Pipelines for sure I'm giving there 755 chmod for Linux/wkhtmltopdf and Windows/wkhtmltopdf.exe files.
WebApp is launched on App Service Plan S1 with Linux environment
When generating the pdf on linux it seems to ignore css and images.
Left was generated on linux, right was on windows
Convert Options
generate.SetConvertOptions(new ConvertOptions
{
PageSize = Wkhtmltopdf.NetCore.Options.Size.A7,
PageOrientation = Wkhtmltopdf.NetCore.Options.Orientation.Landscape,
PageMargins = new Wkhtmltopdf.NetCore.Options.Margins(0,0,0,0),
IsLowQuality = false,
});
I'm using the binaries provided in the repo.
Is this just a limitation of the linux version or is there a configuration issue?
Hi,
I tried to render a url ( https://echarts.apache.org/examples/en/editor.html?c=bar-gradient ) using HeaderPagingTest sample function. But it seems it could not handle delay and related resources properly.
I was wondering it could properly render pdf based on a url?
DefaultHttpContext holds empty HttpContext.Request information.
could you add it ?
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
IHttpContextAccessor _httpContextAccessor;
public class RazorViewToStringRenderer : IRazorViewToStringRenderer
{
private readonly IOptions<MvcViewOptions> _options;
private readonly ITempDataProvider _tempDataProvider;
private readonly IServiceProvider _serviceProvider;
private readonly IHttpContextAccessor _httpContextAccessor;
public RazorViewToStringRenderer(
IOptions<MvcViewOptions> options,
ITempDataProvider tempDataProvider,
IHttpContextAccessor httpContextAccessor)
{
_options = options;
_tempDataProvider = tempDataProvider;
_httpContextAccessor = httpContextAccessor;
}
private ActionContext GetActionContext()
{
return new ActionContext(_httpContextAccessor.HttpContext, new RouteData(), new ActionDescriptor());
}
}
Razor context request parameters , schema
@{ var a = Context; }
Good time!
I'd like to know if Wkhtmltopdf.NetCore
supports console app. In the description you mentioned only asp.net core. I wanna clarify it.
Thank you!
Hello
The following code works in dev, but not on production (deployed to IIS)
var viewAsPdf = new Wkhtmltopdf.NetCore.ViewAsPdf(_hostingEnvironment.ContentRootPath)
{
PageMargins = new Margins(0, 0, 0, 0),
PageSize = Size.A4,
IsLowQuality = false
};
return await viewAsPdf.GetByteArray("Views/Contract.cshtml", sale);
It apparently can't find the view, which makes sense, since the views are compiled into the dll.
I don't know however how to get it running.
In files like this:
https://github.com/fpanaccia/Wkhtmltopdf.NetCore/blob/master/Wkhtmltopdf.NetCore/Implementation/GeneratePdf.cs
Near the bottom, there are several catch(Exception e) { throw e; } statements. Throwing exceptions in this manner will reset the stack trace, making debugging difficult. If you are just going to rethrow, don't bother catching at all. If you need to log, or something, use the "e" you caught, but just use the statement "throw;" to rethrow it.
Hi @fpanaccia, firstly thanks for the library.
I am trying to use in my project where I have background task that suppose to generate pdfs for one or more data elements. I am having issues when I am trying to inject depenendencies using service provider. I am trying to do like this
var tempDataProvider = serviceScope.ServiceProvider.GetRequiredService<ITempDataProvider>();
var razorViewEngine = serviceScope.ServiceProvider.GetRequiredService<IRazorViewEngine>();
var razorViewStringRenderer = serviceScope.ServiceProvider.GetRequiredService<IRazorViewToStringRenderer>();
var pdfGenerator = serviceScope.ServiceProvider.GetRequiredService<IGeneratePdf>();
However when I run I am getting following exception
Any ideas how to this, am I missing some dependencies ?
We are getting an error when trying to access wkhtmltopdf.exe file. how can we give the file path?
Throws file not found exception '/app/59a1b217-811d-4723-a54b-....pdf on Linux Docker container.
A portion of the stack trace:
Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, string path, bool isDirectory, Func<ErrorInfo, ErrorInfo> errorRewriter)
Microsoft.Win32.SafeHandles.SafeFileHandle.Open(string path, OpenFlags flags, int mode)
System.IO.FileStream.OpenHandle(FileMode mode, FileShare share, FileOptions options)
System.IO.FileStream..ctor(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
Wkhtmltopdf.NetCore.WkhtmlDriver.Convert(string wkhtmlPath, string switches, string html)
Wkhtmltopdf.NetCore.GeneratePdf.GetPDF(string html)
Hi!
Just testing your tool in VS2019 ASP.Net Core 3.1 project.
Stuck in this message "Could not find an IRouter associated with the ActionContext..."
Works only with hard coded html string without any model added.
Any help is kindly appreciated!
Thank you in advance
RL
System.ComponentModel.Win32Exception (13): Permission denied
at Wkhtmltopdf.NetCore.WkhtmlDriver.Convert(String wkhtmlPath, String switches, String html)
at Wkhtmltopdf.NetCore.GeneratePdf.GetPDF(String html)
at BankSlip.Api.Models.Services.BankSlipService.GeneratePdf(IEnumerable`1 bankSlipsModels, Boolean paymentBooklet) in /var/lib/jenkins/workspace/Bankslip.Homol/src/BankSlip.Api/Models/Services/BankSlipService.cs:line 36
I try this example https://github.com/fpanaccia/Wkhtmltopdf.NetCore.Example with docker run on linux and got below error.
Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HLOHJ6AVNDMN", Request id "0HLOHJ6AVNDMN:00000001": An unhandled exception was thrown by the application.
System.ComponentModel.Win32Exception (2): No such file or directory
at Wkhtmltopdf.NetCore.WkhtmlDriver.Convert(String wkhtmlPath, String switches, String html)
at WebApplication1.Controllers.ValuesController.Get() in C:\Users\quxianyang\source\repos\ConsoleApp4\WebApplication1\Controllers\ValuesController.cs:line 38
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at System.Threading.Tasks.ValueTask1.get_Result() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync() at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication
1 application)
When I run the project on Linux I get this error:
System.IO.IOException: Broken pipe
at System.IO.FileStream.WriteNative(ReadOnlySpan`1 source)
at System.IO.FileStream.WriteSpan(ReadOnlySpan`1 source)
at System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count)
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.IO.StreamWriter.WriteLine(String value)
at Wkhtmltopdf.NetCore.WkhtmlDriver.Convert(String wkhtmlPath, String switches, String html)
at Wkhtmltopdf.NetCore.GeneratePdf.GetPDF(String html)
I've already ran chmod 755
in Rotativa folder. Works fine locally on my PC running Windows
I have a function in an project classlib, how can i using ?
Hi, thanks for creating this library, it works great in a .net core 2.1 project, but currently getting an error in a ASP.Net Core 3.0 project...
System.TypeLoadException: 'Could not load type 'Microsoft.AspNetCore.Hosting.Internal.HostingEnvironment' from assembly 'Microsoft.AspNetCore.Hosting, Version=3.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.'
Any ideas when you will be adding support for Core 3.0? I'm using preview 8 at the moment, but its only a few weeks until general release :)
Will this package be updated to .NET 6 or should we fork it and create a new one?
Hi,
I'm using this project and i testd linux stdout redirection.
If i'm running on Linux OS, this project wil write html on file and read from there to generated PDF file.
I believe it is because stdin/stdou redirection wont be working in the past.
But i'm test now, with the last .Net5, and that work fine.
I only remove the else clausule, and alow the program perform the same code to Windows and Linux OS.
On the WkhtmlDriver class, the else reference if clausule on line 40:
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
I think use stdin/stdou redirection are better then write and read from the disk.
Wath do you think about remove that "if" as i did?
Can i open pull request with this modification?
Hey,
I have that files included on my view
<head>
<title>test</title>
<meta http-equiv="x-ua-compatible" content="ie=edge">
<link rel="stylesheet" href="~/css/normalize/normalize.min.css" />
<script src="~/lib/jsbarcode/JsBarcode.itf.min.js"></script>
</head>
My pdf generated did not included css and js... I was using Rotativa like that and it worked there...
What am I doing wrong?
Hi,
I try to convert certificates to pdf. I need high quality background image for print. When i try to convert to pdf, background image dpi is changing. I am using .net Core 3.0.1 version. (https://www.nuget.org/packages/Wkhtmltopdf.NetCore/3.0.2/)
What can i do for this issur? Have you a solution?
Regards,
Hi, thanks for sharing this!
Can you please confirm which licence you'd like this to fall under and add it to the project?
When I use rotativa and wkhtmltopdf on linux ubuntu I get this error.
An unhandled exception occurred while processing the request.
Win32Exception: No such file or directory
System.IO.IOException: Pipe is broken.
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.IO.Pipes.PipeStream.CheckWriteOperations()
at System.IO.Pipes.PipeStream.Flush()
[10:02:34.268 ERR] [Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware] An unhandled exception has occurred while executing the request.
at System.IO.StreamWriter.Dispose(Boolean disposing)
at System.IO.TextWriter.Dispose()
at Wkhtmltopdf.NetCore.WkhtmlDriver.Convert(String wkhtmlPath, String switches, String html)
Hello, i'm trying to run the tool to generate pdf from razor view, but i am getting this error ;
Could not find an IRouter associated with the ActionContext. If your application is using endpoint routing then you can get a IUrlHelperFactory with dependency injection and use it to create a UrlHelper, or use Microsoft.AspNetCore.Routing.LinkGenerator.
PS: I am running this from a controller.
Please help.
I have that code to add footer.
_generatePdf.SetConvertOptions(new ConvertOptions { FooterHtml = "https://localhost:5001/footer.html", Replacements = new Dictionary<string, string> {{"ref", inspectionReportData.InspectionReference}}, });
And this is my footer
I was expecting footer to be in center but it seems like no style is added. Anyone can elaborate on this?
Like in the object,
in my asp.net core 3.1 application, normaly when i try to use "GetPdfViewInHtml" it's ok. Whereas if i modify html, in order to use a new field created in datamodel, i obtain this error:
"
2020-12-29 15:10:08.881 [Error] An unhandled exception has occurred while executing the request.
Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.CompilationFailedException: One or more compilation failures occurred:
/Views/FakeView.cshtml(230,45): error CS1061: 'ModuloConsegnaPdfViewModel' non contiene una definizione di 'Responsabile' e non è stato trovato alcun metodo di estensione accessibile 'Responsabile' che accetta un primo argomento di tipo 'ModuloConsegnaPdfViewModel'. Probabilmente manca una direttiva using o un riferimento all'assembly.
/Views/FakeView.cshtml(236,33): error CS1061: 'ModuloConsegnaPdfViewModel' non contiene una definizione di 'Responsabile' e non è stato trovato alcun metodo di estensione accessibile 'Responsabile' che accetta un primo argomento di tipo 'ModuloConsegnaPdfViewModel'. Probabilmente manca una direttiva using o un riferimento all'assembly.
at Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.RuntimeViewCompiler.CompileAndEmit(RazorCodeDocument codeDocument, String generatedCode)
at Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.RuntimeViewCompiler.CompileAndEmit(String relativePath)
at Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.RuntimeViewCompiler.OnCacheMiss(String normalizedPath)
"
Thank's
I put services.AddWkhtmltopdf(); in the ConfigureServices method in Startup.cs in my .NET Core project using Razor and I got this error when trying to access the login page:
InvalidOperationException: Session has not been configured for this application or request.
This one is my Startup class:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading.Tasks;
using Wkhtmltopdf.NetCore;
namespace Digibyte.Controle
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//Repositories and Services
...
//HTML to PDF Transformer, which we use to print slips
services.AddWkhtmltopdf();
services.AddDbContext<ApplicationDbContext>(options => options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 6;
options.User.RequireUniqueEmail = true;
})
.AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
When I comment out the services.AddWkhtmltopdf();
no more mistakes
Can anyone help me with this error?
Hello!
I have an application which creates PDF pages that contain images.
When I run it locally it works perfect.
Unfortunately, when I run it in docker images are not reflected in PDF files(css works fine).
Did you face such an issue?
Thank you!
Originally added to:
fpanaccia/Wkhtmltopdf.NetCore.Example-deprecated#22
I have some legal documents that I'm having to recreate in PDF from a .Net 5 (core) MVC application (using wkhtmltopdf.netcore 3.0.2). Obviously, I'm using your tool and for the most part, it's worked great. However, when it comes to footers, my legal docs have special conditions for footers. Like some pages not having paging and others resetting the starting page when a new section is encounters. With that being said, how do you use the "url" and special parameters that you've given us? How does using the "section" parameter work? I can't get it too. Section is always blank.
https://localhost:44342/footer.html?
page=1§ion=&sitepage=1&title=&subsection=&username=Veaer&url=google.com&frompage=1&subsubsection=&age=20&isodate=2022-02-
14&topage=20&doctitle=&sitepages=20&webpage=-&time=3:10:34%20PM&date=2/14/2022
I'm behind on a project due to this footer issue and we might have to bail on using this tool. Any help would be awesome!
Thanks
Update....
One thing I just noticed and I technically fixed in my original comment is the url. The "section" part of the url is coming out wrong. I'm just using your original code and pulling it out.
var url = window.location.href.replace(/#$/, ""); // Remove last # if exist
document.getElementById("url").innerHTML = url;
https://localhost:44342/footer.html?
page=2§ion=&sitepage=2&title=&subsection=&username=Veaer&url=google.com&frompage=1&subsubsection=&age=20&isodate=2022-02-
14&topage=20&doctitle=&sitepages=20&webpage=-&time=3:24:23%20PM&date=2/14/2022
Thanks
I get images and css by urls in the html, I use method GetByteArrayViewInHtml, when I run my application in localhost (windows) all is fine, but when I execute from container only show text in pdf without style and without images.
My dockerfile copy the binaries and I give permisions chmod 755 to this files.
RUN chmod 755 ./wkhtmltopdf/Linux/wkhtmltopdf
RUN chmod 755 ./wkhtmltopdf/Linux/wkhtmltoimage
I use asp.net core 3.1
My images and css are stored in Azure Storage.
Thank you for sharing the library with the community!
I was just playing around with the library and i tried to set the header for the PDF,
after looking at the code, i was able to do that by casting IGeneratePdf to the Implementation (GeneratePdf) , from there i can access the header.
is there another way to do it?
Hi (or ciao :) ) is it possibile to use it in a pure WEBAPI project ? without view? .... if yes how to replace the view params in the pdf method? thnx!
var options = new ConvertOptions();
if (isvalid)
{
options.HeaderHtml = $"https://localhost:12115/Areas/Controller/GetHeader?ID=106";
options.PageOrientation = Wkhtmltopdf.NetCore.Options.Orientation.Landscape;
_generatePdf.SetConvertOptions(options);
}
else
{
}
Result => Empty PDF
Would this work in a Xamarin forms projects?
Hi, i want to use the HeaderHTML option to add some headers.
My project is an API and i use razorViewToString to render my dynamic header in a string.
But it doesn't work if i place it in the header option.
It's normal ? It accept only string URL ?
After install Wkhtmltopdf.NetCore version 3.0.2 to using an project that depend of Wkhtmltopdf.NetCore version 1.1.3 the error happens below.
An exception of type 'System.TypeLoadException' occurred in BankSlip.Api.dll but was not handled in user code: 'Could not load type 'Wkhtmltopdf.NetCore.HtmlAsPdf' from assembly 'Wkhtmltopdf.NetCore, Version=3.0.1.0, Culture=neutral, PublicKeyToken=null'
EXCEPTION: System.ComponentModel.Win32Exception (13): Permission denied\n at Wkhtmltopdf.NetCore.GeneratePdf.GetByteArray[T](String View, T model)\n
I got below error code when I try to open project.
676 | ERROR | System.Exception: Exception of type 'System.Exception' was thrown. at Microsoft.Internal.VisualStudio.Shell.Interop.IVsSolutionBuildOrderPrivate.GetBuildOrderList(Boolean fForceRecalculation, UInt32 cProjects, VsProjectBuildOrder[] pBuildOrder, UInt32& pValidationId) at Microsoft.VisualStudio.ErrorListPkg.Shims.TaskListBase.RecalculateProjectRank() at Microsoft.VisualStudio.ErrorListPkg.Shims.TaskListBase.OnEntriesChanged(Object sender, EntriesChangedEventArgs e) at Microsoft.VisualStudio.Text.Utilities.GuardedOperations.RaiseEvent[TArgs](Object sender, EventHandler`1 eventHandlers, TArgs args) --- End of stack trace from previous location where exception was thrown --- at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject) | Editor or Editor Extension | 2020/02/06 06:47:44.596 |
---|
ALM (Arabic Letter Mark ) Character shows in Arabic language with the minus numbers In the pdf
I already added to <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
to the header, and ( lang='ar') to the html tag
If I run the code as (html page) in the browser, it works fine, but the issue happened when it convert to pdf
Hi,
On updating my code to run on .NET 5.0, the following error occurs:
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
An unhandled exception has occurred while executing the request.
System.Exception: QPainter::begin(): Returned false
Exit with code 1, due to unknown error.
at Wkhtmltopdf.NetCore.WkhtmlDriver.Convert(String wkhtmlPath, String switches, String html)
at Wkhtmltopdf.NetCore.GeneratePdf.GetPDF(String html)
The same code is working fine with dotnet 3.1.
Possibly related to this wkhtmltopdf/wkhtmltopdf#3119 in wkhtmltopdf itself, however it is the same version of wkhtmltopdf that works with 3.1 but not 5.0.
This issue happens with dotnet on Linux. Under Windows there is no issue with .NET 5.0
Hello, and thanks for your library !
Do you think its possible to expose te replace parameter of wkhtmltopdf ? (https://stackoverflow.com/questions/26985285/how-to-use-replace-in-wkhtmltopdf) it will allow to use custom variable in header and footer, otherwise we can only load static html on these part !
Thanks !
Having an issue running this package locally (command F5) on Mac, but the same .Net Core project generates PDFs with no issues on a PC.
I've followed the setup and example project you have posted, and looked at the OS check in your driver, but on Mac I always get this error:
[11:16:02 ERR] HTTP POST /api/registration/2 responded 500 in 12210.6616 ms
System.ComponentModel.Win32Exception (13): Permission denied
at Wkhtmltopdf.NetCore.WkhtmlDriver.Convert(String wkhtmlPath, String switches, String html)
at Wkhtmltopdf.NetCore.GeneratePdf.GetPDF(String html)
at Prime.Services.PdfService.Generate(String htmlContent)
I've configured the service, and provided a relative path to the wkhtmltopdf files that contains the /Linux, /Mac, and /Windows folders:
services.AddWkhtmltopdf("./Resources/wkhtmltopdf");
And added the item group to .csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RootNamespace>Prime</RootNamespace>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
... // Removed for brevity
<ItemGroup>
<None Update="Resources\wkhtmltopdf\Linux\wkhtmltopdf">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Resources\wkhtmltopdf\Mac\wkhtmltopdf">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Resources\wkhtmltopdf\Windows\wkhtmltopdf.exe">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
Version Number of Plugin: 3.0.2
Version of VS: Microsoft Visual Studio 2019 V. 16.6.5
Target Framework: .NET Core 3.1
services.AddWkhtmltopdf();
to startup.IGeneratePdf
to constructor.Calling GetByteArrayViewInHtml(view, model) should return the pdf generate in a byte array format.
Calling GetByteArrayViewInHtml(view, model) instead throws the below exception:
Could not find an IRouter associated with the ActionContext. If your application is using endpoint routing then you can get a IUrlHelperFactory with dependency injection and use it to create a UrlHelper, or use Microsoft.AspNetCore.Routing.LinkGenerator.
This is the snippet in my controller:
var resPDF = await _pdfGenerator.GetByteArrayViewInHtml<ReportInEditViewModel>("PDFTemplates/Report", model);
This is a section of my view:
@model ViewModels.ReportInEditViewModel
@{ Layout = null; }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="~/lib/fontawesome/css/all.min.css" />
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/lib/fontawesome/js/all.min.js"></script>
</head>
<body>
...
</body>
</html>
Any help would be greatly appreciated! 😉
Hi, thanks for the plugin, i'm already using it and i love it. Any chance this can be used to generate images as well?
Thank you for your time!
May I know how to fix the following error?
[03/01/2021 09:36:41] ErrorKind:Internal
System.Exception: /var/aspnetcore/viqcommunitystaging/Rotativa/Linux/wkhtmltopdf: error while loading shared libraries: libpng15.so.15: cannot open shared object file: No such file or directory
Also, may I know where do you get the latest wkhtmltopdf file?
Many thanks.
Is there any chance to use a system wide installed version of wkhtmltopdf?
Because my hoster already deploys an up to date version on theirs servers. I have multiple services which use pdf rendering with wkhtmltopdf and it would be very nice to use the version provided by the system, instead having every app it's own binary
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.