Giter Site home page Giter Site logo

wkhtmltopdf.netcore-deprecated's Introduction

Wkhtmltopdf.NetCore

NuGet Publish Packages

This project implements the library wkhtmltopdf for asp net core, working in Windows, Linux, macOS and docker.

For more information about how to use it, go to https://github.com/fpanaccia/Wkhtmltopdf.NetCore.Example

But i don't want to see another repository

You will need to put this files with this following structure, this need to be done because nuget cant copy those files, only puts a link with the full path and will only work on your computer.

The structure will need to be on the folder of your project

    .
    ├── Example
    |   ├── Example.csproj
    |   └── Rotativa
    |   |   ├── Linux
    |   |   |   └── wkhtmltopdf
    |   |   ├── Mac
    |   |   |   └── wkhtmltopdf
    |   |   └── Windows
    |   |       └── wkhtmltopdf.exe
    └── Example.sln

Those files will need to be included in your project with the propierty "Copy Always", then add to your Startup.cs in ConfigureServices method, this line "services.AddWkhtmltopdf();", like this

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {            
        services.AddControllers();
        services.AddWkhtmltopdf();
    }

If you are using the docker container for net core provided from microsoft, you need to add this line to the dockerfile "RUN apt-get update -qq && apt-get -y install libgdiplus libc6-dev", like this

    FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
    WORKDIR /app
    RUN apt-get update -qq && apt-get -y install libgdiplus libc6-dev
    EXPOSE 80

In linux you also need to install the same libraries used in the dockerfile, they are libgdiplus, libc6-dev

For more information, see the example project -> https://github.com/fpanaccia/Wkhtmltopdf.NetCore.Example

wkhtmltopdf.netcore-deprecated's People

Contributors

ayiadim avatar biggray avatar bl4y avatar fpanaccia avatar gurustron avatar yanchihuang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wkhtmltopdf.netcore-deprecated's Issues

Redirect stdin/stdou on linux container

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?

Use system wide installed wkhtmltopdf

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

Win32Exception: No such file or directory

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

Request - remove MVC dependency

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. :)

Xamarin

Would this work in a Xamarin forms projects?

'InvalidOperationException' error when using services.Add Wkhtmltopdf() in ASP.NET Razor project

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.

Screenshot_1

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?

Error Running Locally on Mac

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>

Exception while trying getting bytearray from view

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.

ALM Character Shows Near Minus Numbers In Arabic language

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

image

If I run the code as (html page) in the browser, it works fine, but the issue happened when it convert to pdf

header-html using MVC view is not working

 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

Injecting dependencies using scope

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

image

Any ideas how to this, am I missing some dependencies ?

How to set options like header?

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?

Error running under Linux

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

GetPdfViewInHtml generate "Razor.RuntimeCompilation.CompilationFailedException" error CS1061 on Centos 8

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

Win32Exception: Permission denied on Azure

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

File not found exception on Linux

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)

[BUG] GetByteArrayViewInHtml(view, model) not working.

Bug Information

Version Number of Plugin: 3.0.2
Version of VS: Microsoft Visual Studio 2019 V. 16.6.5
Target Framework: .NET Core 3.1

Steps to reproduce the Behavior

  1. Add services.AddWkhtmltopdf(); to startup.
  2. Add IGeneratePdf to constructor.
  3. Call GetByteArrayViewInHtml(view, model) and receive the respective value for the pdf generated.

Expected Behavior

Calling GetByteArrayViewInHtml(view, model) should return the pdf generate in a byte array format.

Actual Behavior

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.

Code snippet

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>

Final Comments

Any help would be greatly appreciated! 😉

Can't find view when running published release build

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.

Could not find an IRouter associated with the ActionContext

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

Failure on .NET 5.0

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

Error in Linux

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.

.NET 6 Docker error on GetPDF()

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)

WEB API

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!

Got error on linux

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](IHttpApplication1 application)

Not loading Css/Js from my Razor view

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?

.net core 3.0 support

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 :)

_generatePdf.GetByteArrayViewInHtml(htmlView,data) not working

  • I have two project: api and classlibary
  • In classlibary: I install nug Wkhtmltopdf.NetCore and write function printPdf call func: await _generatePdf.GetByteArrayViewInHtml(htmlView, data);
  • In Api project: Acction generate printPdf form classlib, throw excel
    Cannot find reference assembly 'Microsoft.AspNetCore.Antiforgery.dll' file for package Microsoft.AspNetCore.Antiforgery.Reference'
    But use _generatePdf.GetByteArray("Views/Test.cshtml", data) every working correc

Inconsistent Behavior between windows and linux.

When generating the pdf on linux it seems to ignore css and images.
Left was generated on linux, right was on windows
RmtdVMy7S0+7NLyqnWgpKg
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?

Error on run Ubuntu

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

Footer not respecting styles

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

image

I was expecting footer to be in center but it seems like no style is added. Anyone can elaborate on this?

Not render images and css in docker container with asp.net core 3.1

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.

.Net core console app support

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!

Footer issue and documentation on using 'default params'

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&section=&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

Missing information on Context in Razor

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; }

Could not load type 'Wkhtmltopdf.NetCore.HtmlAsPdf'

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'

Licence?

Hi, thanks for sharing this!

Can you please confirm which licence you'd like this to fall under and add it to the project?

It Gives editor error

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

.NET 6

Will this package be updated to .NET 6 or should we fork it and create a new one?

Error on run Docker

EXCEPTION: System.ComponentModel.Win32Exception (13): Permission denied\n at Wkhtmltopdf.NetCore.GeneratePdf.GetByteArray[T](String View, T model)\n

Using header with string HTML

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 ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.