pruiz / wkhtmltoxsharp Goto Github PK
View Code? Open in Web Editor NEWC# wrapper wrapper (using P/Invoke) for the excelent Html to PDF conversion library wkhtmltopdf library.
C# wrapper wrapper (using P/Invoke) for the excelent Html to PDF conversion library wkhtmltopdf library.
Recently I had to generate a pdf from html what contains images ( img tag) and the they are not shown in resulting pdf.
The result of running in x86 mode is as expected.
Could this be related with some missing dependencies?
Hi Pablo, I noticed this project hasn't been updated recently and wanted to know how much you intend to keep this project (and the associated NuGet package) up to date with the original library.
Hi!
We're trying to replace existing (buggy) WkHtml-integration with WkHtmlToXSharp. We're using it to generate reports of many different kinds, each report-generation running in a seperate thread with a prioritized queue in front.
I'm a bit confused, by the following (probably misunderstood) things, that maybe you can clear up:
Any input is appreciated - thanks!
Firstly, great library and with a the two interfaces (single and multi-thread) this seems to be the programmers choice for html > pdf.
That being said however, I am struggling to get this to work on a development machine. I get on run 'Exception has been thrown by the target of an invocation' ... DllNotFoundException, Unable to Load DLL 'wkhtmltox0'. Your documentation says this is automatically created on first conversion - perhaps this isn't happening? Or I need permissions on the bin or something? Can you offer any suggestions?
Thanks :)
I was wondering how do I set the page width/size?
WkhtmlToPDF (according to http://madalgo.au.dk/~jakobt/wkhtmltoxdoc/wkhtmltopdf-0.9.9-doc.html)
Exposes the option –-page-width
I was trying to add cookies and I noticed the original project has cookies in Load settings.
I tried to tackle it but failed when it came to passing values into the QList of QPairs that is the cookies in the original code.
Please help
When trying to install the nuget package for version 1.2.32 I get the following error:
Failed to add reference to 'wkhtmltox0'.
Please make sure that the file is accessible, and that it is a valid assembly or COM component.
Visual Studio 2019
Net 4.6 Vb.Net Project
I tried downloading and running example project to see how it works and I got the following message from my virus scanner.
/******************************/
Category: Trojan
Description: This program is dangerous and executes commands from an attacker.
Recommended action: Remove this software immediately.
Items:
file:C:\Users\name\Desktop\WkHtmlToXSharp-master\Packages\NuGet.CommandLine.1.6.0\tools\NuGet.exe
Get more information about this item online.
Hi,
We encounter an issue sometimes on our website with wkhtml when we restart Server Application or deploy news files.
To resolve this problem, we need to recycle pool after each deployment.
Thanks,
Log:
Message: Une exception a été levée par la cible d'un appel.
Exception type: System.Reflection.TargetInvocationException
Stack Trace:
at Sanford.Threading.DelegateQueue.EndInvoke(IAsyncResult result)
at Sanford.Threading.DelegateQueue.Invoke(Delegate method, Object[] args)
at WkHtmlToXSharp.MultiplexingConverter.Convert(String inputHtml)
at PrevifranceFront.Previfrance.Services.getFile.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Message: Tentative de lecture ou d'écriture de mémoire protégée. Cela indique souvent qu'une autre mémoire est endommagée.
Exception type: System.AccessViolationException
Stack Trace:
at WkHtmlToXSharp.NativeCalls.wkhtmltopdf_convert(IntPtr converter)
at WkHtmlToXSharp.WkHtmlToPdfConverter._Convert(String inputHtml)
at WkHtmlToXSharp.WkHtmlToPdfConverter.Convert(String inputHtml)
at WkHtmlToXSharp.MultiplexingConverter.b__9(String x)
I want to convert an HTML file to PDF file, and I was using "wkhtmltopdf.exe".
Then we moved this application to a shared hosting server. This server, wouldn't allow to run .exe files, so that I have to use the WkHtmlToXSharp.dll [wrapper for the above exe].
Its working fine but the problem is this it caching the output somewhere, so that every-time I create a new PDF, it always giving the first one.
I have called .Dispose() and setting the converter to null but no use.
Below is my code. every-time I pass a new html file[htmlFullPath] with different images in it.
Also I am setting the margins 0cm for all sides, but not working.
IHtmlToPdfConverter converter = new MultiplexingConverter();
converter.ObjectSettings.Page = htmlFullPath;
converter.ObjectSettings.Web.EnablePlugins = true;
converter.ObjectSettings.Web.EnableJavascript = true;
converter.ObjectSettings.Web.Background = true;
converter.ObjectSettings.Web.LoadImages = true;
converter.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.ignore;
converter.GlobalSettings.Orientation = (PdfOrientation)Enum.Parse(typeof(PdfOrientation), orientation);
if (!string.IsNullOrEmpty(pageSize))
converter.GlobalSettings.Size.PageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), pageSize);
converter.GlobalSettings.Margin.Top = "0cm";
converter.GlobalSettings.Margin.Bottom = "0cm";
converter.GlobalSettings.Margin.Left = "0cm";
converter.GlobalSettings.Margin.Right = "0cm";
Byte[] bufferPDF = converter.Convert();
System.IO.File.WriteAllBytes(pdfUrl, bufferPDF);
converter.Dispose();
converter = null;
Hi,
There is a problem in your latest nuget package 1.1.23.22. In this package's Dependencies it says and installs Common.Logging 2.0.0 but inside dll you are using 2.1.0. Can you update dependency please. Because any time someone downloads this package, they will get the same error.
Hello. I have list of strings . Each of them contains html. I want to merge them into one PDF. Could u provide me the best way for doing it ?
First-chance exception at 0x000007FEFDAF940D (KernelBase.dll) in w3wp.exe: 0xE0434352 (parameters: 0xFFFFFFFF80004003, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x000007FEF8D90000).
If there is a handler for this exception, the program may be safely continued.
I use WK in my project.The first convert is error,the second show this exception,How can I do?
Hi,
I encounter a poor perfomrance issue (1 minute for PDF generation of simple html page, no concurrent requests) while using WkHTMLToXSharp from whitin a ASP.NET MVC 3 application and .NET framework 4.0. I'm using a MultiplexingConverter like in the example below :
var wk = new MultiplexingConverter();
wk.GlobalSettings.Margin.Top = "0cm";
wk.GlobalSettings.Margin.Bottom = "0cm";
wk.GlobalSettings.Margin.Left = "0cm";
wk.GlobalSettings.Margin.Right = "0cm";
wk.ObjectSettings.Web.EnablePlugins = false;
wk.ObjectSettings.Web.EnableJavascript = false;
wk.ObjectSettings.Page = url;
wk.ObjectSettings.Load.Proxy = "none";
Do you have any hints, what's going on or how can I debug/improve it ?
Thanks,
Hello. Can you describe which tools and environment are you used to build wkhtmltopdf lib and its x64 version. What version of QT, with wkhtmltopdf patches or not. What toolchain - mingw or Visual Studio. Thank you.
Sometimes when a system is under heavy load CallbackOnCollectedDelegate occur and produce NullReferenceException. The reason is that in the method WkHtmlToPdfConverter._Convert native calls that are invoked in the finally block (wkhtmltopdf_set_error_callback (converter, null), etc.)
do not have time to work on the side of c ++ library before the garbage collector destroys corresponding delegates objects. In particular case it tries to call wkhtmltopdf_int_callback after completion of the WkHtmlToPdfConverter._Convert method that resulted in an error.
Please upgrade the wkhtml library from 0.12.5 to 0.12.6 so it works for 64-bit ARM.
Hi,
I'm trying to use the library on a mod_mono / apache project on debian linux 64 bits. But i ran into this error :
System.DllNotFoundException: wkhtmltox0
at (wrapper managed-to-native) WkHtmlToXSharp.NativeCalls:wkhtmltopdf_version ()
at WkHtmlToXSharp.NativeCalls.WkHtmlToPdfVersion () [0x00000] in :0
at WkHtmlToXSharp.WkHtmlToPdfConverter..ctor () [0x00000] in :0
at WebDevCore.PdfExport.GetPdfBytesFromHtml (System.String HTMLContent, Double margin) [0x00000] in :0
at JdV5AdminWeb.print.ProcessRequest (System.Web.HttpContext context) [0x00000] in :0
at System.Web.HttpApplication+c__Iterator6.MoveNext () [0x00000] in :0
at System.Web.HttpApplication.Tick () [0x00000] in :0
It works well on my development enviroment ( windows / visual studio dev. web server ), and the code for deploying the dll seems to be called correctly. i got this on the log :
Deploying embedded libwkhtmltox0.so to /tmp/www-data-temp-aspnet-0/84dd945b/assembly/shadow/fb474576/ba29ae1b_416eeb6d_00000001
and
Deployed /tmp/www-data-temp-aspnet-0/84dd945b/assembly/shadow/fb474576/ba29ae1b_416eeb6d_00000001/libwkhtmltox0.so with md5sum: 4F913853E31C3F4A9F3B6B1338E2AD8C.
The file does exists (is really created) in the above folder, and does have a +x flag on it.
Am i doing something wrong ?
When I pass a Page from the Internet, it works perfectly and converts the HTML exactly as the page looks. My requirements however mean I need to pass it a string of HTML so I'm using Convert(ValidHtmlString) instead of setting a Page and just calling Convert().
When I pass in my HTML string, it's outputting a PDF, but it's completely unformatted. It even outputs my CSS style declarations. For example, here's the beginning of one of my PDF outputs:
body { font-family: Arial; font-size: 14px; width: 796px; } #letterLeft { width: 45%; padding-left: 7%; float: left; } #letterRight { width: 34%;
float: left; padding-top: 20px; padding-left: 8%; } .GreenBox { margin-top: -8px; background-color: #D7E4BD; padding: 20px; width:
65%; border-radius: 10px; } .GreenBoxWide { margin-top: -8px; background-color: #D7E4BD; padding: 20px; width: 82%; borderradius:
10px; } .title { font-size: 1.2em; font-weight: bold; } .normal { font-size: 12px; font-weight: normal; } .subtext { font-size: 0.8em; }
.icon { float: left; padding-right: 15px; } .floatRight { float: right; } Working in partnership with
Does anyone have any idea why this may be happening? Have I missed a setting somewhere? Here is my code for the converter:
public class ConvertToPDF
{
private bool ConvertComplete { get; set; }
public byte[] HtmlToPdf(string html)
{
using (var toPdf = GetConverter())
{
toPdf.GlobalSettings.Margin.Top = "1cm";
toPdf.GlobalSettings.Margin.Bottom = "1cm";
toPdf.GlobalSettings.Margin.Left = "1cm";
toPdf.GlobalSettings.Margin.Right = "1cm";
toPdf.ObjectSettings.Web.EnablePlugins = false;
toPdf.ObjectSettings.Web.EnableJavascript = false;
toPdf.ObjectSettings.Load.Proxy = "none";
byte[] pdfBytes = toPdf.Convert(html);
if (pdfBytes != null && ConvertComplete)
{
return pdfBytes;
}
else
{
return null;
}
}
}
private MultiplexingConverter GetConverter()
{
var obj = new MultiplexingConverter();
obj.Finished += new EventHandler<EventArgs<bool>>(obj_Finished);
return obj;
}
void obj_Finished(object sender, EventArgs<bool> e)
{
ConvertComplete = true;
}
}
Thanks in advance.
Steps to Reproduce
WkHtmlToXSharp.Bundle
Nuget packageWkHtmlToXLibrariesManager.Register(new Linux32NativeBundle());
WkHtmlToXLibrariesManager.Register(new Linux64NativeBundle());
WkHtmlToXLibrariesManager.Register(new Win32NativeBundle());
WkHtmlToXLibrariesManager.Register(new Win64NativeBundle());
using (MultiplexingConverter converter = new MultiplexingConverter())
{
//WkHtmlToPdfConverter converter = new WkHtmlToPdfConverter();
converter.GlobalSettings.Size.PageSize = PdfPageSize.Letter;
byte[] data = converter.Convert(@"
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
");
File.WriteAllBytes("test.pdf", data);
}
Obviously the fix is to install System.Configuration.ConfigurationManager
but the dependencies of WkHtmlToXSharp
should probably include this so it gets installed automatically.
In the readme, you wrote that an x64 compile of WkHtmlToPdf 'worked pretty flawlessly'; was there anything broken/preventative from using this in a x64 environment if it worked?
Or was it just convenience, i.e., to be able to just drop in the WkHtmlToPdf lib as built rather than go off and recompile in x64.
It looks like version 1.2.9 of WkHtmlToXSharp didn't make it to nuget. Since that's a dependency of all of the other packages, they error out when trying to install them.
Now this test case is not run (ignored) with the following attribute:
//[Ignore("This test requires (still to be released) wkhtmltopdf v0.12+")]
I have a couple of questions:
Thank you all in advance.
This exception was thrown several times on Windows 7 SP1 or Windows 10...
at WkHtmlToXSharp.NativeCalls.wkhtmltopdf_deinit()
at WkHtmlToXSharp.WkHtmlToPdfConverter.Dispose(Boolean disposing)
at WkHtmlToXSharp.WkHtmlToPdfConverter.Finalize()
I could not reproduce it myself though.
"Unable to load DLL 'wkhtmltox0': The specified module could not be found. (Exception from HRESULT: 0x8007007E)"
I have added it on the bin file manually. I also have tried both x86 and 64 bit. And have build the project on either one or the other instead of the Any CPU. Any other suggestions?
in this line throw PlatformNotSupportedException (.net core, linux x64)
delegateThread.TrySetApartmentState(ApartmentState.STA);
Hi,
There is one small inconsistency that not allowing WkHtmlToXSharp
libraries be used in signed assemblies — WkHtmlToXSharp.Win32.dll
/ WkHtmlToXSharp.Win64.dll
not signed and cannot be loaded.
WkHtmlToXSharp.dll
is signed, can we also provide option for signed platform specific assemblies?
In issues #30 and #10, its stated that this project does not support IIS/ASP.net. This is because of of incompatibilities with the app pool recycling and the releasing of resources in non-managed code.
Is it feasible to update how those resources are managed in order to fix this issue? I'm willing to put in the effort to try and make this project compatible with the app pool recycling if I could be pointed in the direction of where these non-managed code resources are at.
Hi,
I read in an earlier issue that running this lib under IIS is not supported. What does this imply? I would like to use this library, and get rid of AbcPdf in my ASP.NET 4.0 project. Is it possible? I do not want to use any web service or windows service.
Can I use it on a 64bit OS with IIS7 app pool set to 32-bit? If yes (as per your readme) then why did you mention here that IIS is not supported: #8 (comment)
Thank you,
Vivek
Intermittently we're getting an exception from the queue thread that results in the entire IIS app pool shutting down. We're using the MultiplexingConverter
in response to an HTTP call.
Unfortunately, the exception is happening somewhere we can't wrap in a try {} catch{}
block so the information we can provide is limited. We were also unable to try catching the error by attaching the debugger to the source project.
Exception message:
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
mscorlib is microsoft dll
Thread: WkHtmlToPdf Queue Thread: 1
Any assistance or direction you can provide would be greatly appreciated.
Your readme states there is no support for 64-bit because of the upstream lib.
They now have a x64 binary on their download site
And your source got a x64 folder, does that mean the readme is outdatet?
Both screenshots is output from the same html report.
The only difference in the calling code is which class is new'ed up as the responsible IHtmlToPdfConverter
Seems to me like a bug in WkHtmlToPdfConverter?
I'm using MultiplexerConverter so no trouble for my, just wanted to report it since I saw it.
Thanks for making this!
Hi,Pruiz.thanks your project very mach!
WkHtmlToXSharp is very good!
I've got some problems on with WkHtmlToXSharp,
My HTML like the document:
<h1 style='font-family:Microsoft YaHei;'>I am Microsoft YaHei;...</h1>
The HTML font is “Microsoft YaHei”,but the PDF font is “SimSun”,eg:
I find some people discuss the problem on stackoverflow:use-custom-fonts-with-wkhtmltopdf.
Many people suggest use “@font-face”,eg:
<html>
<style type="text/css">
@font-face {
font-family: 'MSYH';
font-style: normal;
font-weight: normal;
src: url(http://7xrayk.com1.z0.glb.clouddn.com/MSYH.TTC) format('truetype');
}
</style>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<h1 style='font-family:MSYH;'>I am Microsoft YaHei;...</h1>
<h1 style='font-family:Microsoft YaHei;'>I am Microsoft YaHei;...</h1>
</html>
But Convert to pdf too slow because “Microsoft YaHei”(MSYH.TTC) more than 20M.
So,I want to add "Microsoft YaHei" to WkHtmlToXSharp project.
What should I do?
Thanks and Regards.
When I convert HTML to PDF the the letters are close and affect the reading.
Can I fix it?
If I wanted to use this in a commercial product, what am I allowed to do?
Please upgrade the wkhtml library from 0.12.4 to 0.12.5
Hey is there any commands to use multiple Links to be generated in multiple Pdfs?
Also anyway of printing without creating the PDF?
Hi,
running the library on linux it does not seems to have the wkhtmltox0 library embedded, since it produces the following error :
An unhandled exception has occurred while executing the request.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.DllNotFoundException: Unabl to load shared library 'wkhtmltox0' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG env ronment variable: libwkhtmltox0: cannot open shared object file: No such file or directory
at WkHtmlToXSharp.NativeCalls.wkhtmltopdf_version()
at WkHtmlToXSharp.WkHtmlToPdfConverter..ctor()
at WkHtmlToXSharp.MultiplexingConverter.<>c.<.ctor>b__26_0()
--- End of inner exception stack trace ---
at Sanford.Threading.DelegateQueue.EndInvoke(IAsyncResult result)
at Sanford.Threading.DelegateQueue.Invoke(Delegate method, Object[] args)
at WkHtmlToXSharp.MultiplexingConverter..ctor()
at HtmlToPdfCore.Web.Controllers.HomeController.GenerateTestPdf() in C:\Dev\OnitGit\OnTms\src\HtmlToPdf\HtmlToPdfCore.Web\Controllers\HomeC ntroller.cs:line 26
at lambda_method(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExec tor executor, Object controller, Object[] arguments)
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.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext context)
the nuget packages for WkHtmlToXSharp.Linux32 version 1.2.* are all very small (20k) i doubt it has the linux lib embedded, 1.1.latest it's 15+Mb instead, looks working.
Unfortunatly version 1.1.23.22 does not work on windows either :(
Can you point me to a solution ?
Valerio
Hi,
I'm trying to generate a PDF from a html string using the following code in an asp.net web application:
public static MemoryStream WkHtmlToXSharp_ConvertToPDF(string wHTML)
{
MemoryStream msOutput = new MemoryStream();
WkHtmlToXSharp.MultiplexingConverter htmlToPdfConverter = new MultiplexingConverter();
htmlToPdfConverter.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.ignore;
byte[] pBytes = htmlToPdfConverter.Convert(wHTML);
htmlToPdfConverter.Dispose();
msOutput.Write(pBytes, 0, pBytes.Length);
return msOutput;
}
I then return the stream to the browser to download. Anyway, it works great the first time, but the second time I run this the generated PDF is plain text (all images, styles and layout such as tables ect are missing).
Can you please help me?
Regards
Dean
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.