Giter Site home page Giter Site logo

rdvojmoc / dinktopdf Goto Github PK

View Code? Open in Web Editor NEW
1.0K 44.0 393.0 88.71 MB

C# .NET Core wrapper for wkhtmltopdf library that uses Webkit engine to convert HTML pages to PDF.

License: MIT License

C# 100.00%
net-standard wkhtmltopdf html pdf net-core pdf-converter

dinktopdf's People

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

dinktopdf's Issues

libwkhtmltox.dll could not be opened in MVC Core 2 projects

Hi,

I created new web Mvc Core 2 project and installed DintoPdf from NuGet. Then I copied the libwkhtmltox.dll on the root folder and also on the path of nuget packages in system driver.

When I run the application, the following problem is issued:

Metadata file 'C:\Users\a.fetouh.nuget\packages\dinktopdf/1.0.8\lib/netstandard1.6/libwkhtmltox.dll' could not be opened -- PE image doesn't contain managed metadata.

Any body can help me?

Authentication Problem

Hi,

When trying to print a view putting [Authorization] attribute on its action, DinkToPdf doesn't have the authentication ticket when printing the page. It is redirected to Login page and print it.
Objects = {
new ObjectSettings()
{
Page = $"http://{Request.Host}/TestPage/TestAction",
},
}

    [Authorization]
    public IActionResult TestAction()
    {

Is there any solution for this issue?

Unable to load wkhtmltopdf dll

I am using this in an ASP.NET Core project that builds against the .NET Framework 4.7. It is running in Kestrel behind IIS.

If I try to load the 32 bit version I get this exception:

Managed Debugging Assistant 'PInvokeStackImbalance' occurred
Message=Managed Debugging Assistant 'PInvokeStackImbalance' : 'A call to PInvoke function 'DinkToPdf!DinkToPdf.WkHtmlToXBindings::wkhtmltopdf_init' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.'

If I try to load the 64 bit version I get this exception instead:

An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

First Call from .Net core 2 Web API works, next one hangs

I'm using this on Windows 10 with a .Net core 2 web api.

The first call works fine, but subsequent calls hang. Any ideas?

private byte[] GeneratePDFFromHtml(string html)
        {
            var converter = new SynchronizedConverter(new PdfTools());

            var doc = new HtmlToPdfDocument()
            {
                GlobalSettings =
                {
                    ColorMode = ColorMode.Color,
                    Orientation = Orientation.Landscape,
                    PaperSize = PaperKind.A4Plus
                },
                Objects =
                {
                    new ObjectSettings()
                    {
                        PagesCount = true,
                        HtmlContent = html,
                        WebSettings =
                        {
                            DefaultEncoding = "utf-8"
                        },
                        HeaderSettings =
                        {
                            FontSize = 9,
                            Right = "Page [page] of [toPage]",
                            Line = true,
                            Spacing = 2.812
                        }
                    }
                }
            };

            var bytes = converter.Convert(doc);

            return bytes;
        }

Native library not loaded on Linux

Hi I'm having some serious issues with this package.
I added the package to my project and copied the native .so file to the root of my ASP.NET Core project. Now when I start the application and try to convert HTML to PDF I get the following error:

(Exception from HRESULT: 0x8007007E)) ---> System.DllNotFoundException: Unable to load DLL 'libwkhtmltox': The specified module could not be found.

I've tried setting up LD_LIBRARY_PATH to my app folder. I even copied the .so file to /usr/lib but it doesn't work at all.

Any ideas what to do here?

[NO ISSUE] "Library was NOT tested with IIS" -> It works !

Hello,
I noticed the "Library was NOT tested with IIS." in README.

For the record, the package works under IIS.

  • Package 1.0.8 with libwkhtmltox.dll v0.12.4
  • IIS Version 8.5.9600.16384
  • Project is almost a raw ASP.NET CORE 2.1 API template, targeting core
  • Published as self contained
  • I had to use the CustomAssemblyLoadContext issue resolution here

Regards,

viewport-size

The documentation for the GlobalSettings.ViewportSize says "Set viewport size. Not supported in wkhtmltopdf API since v0.12.2.4".

The wkhtmltopdf cli version can take that parameter as an option, and it's an option that I need to fix an issue with Bootstrap.

Is there a wat to set the viewport other than using GlobalSettings.ViewportSize?

It appears that V0.12.5 fixes the problem by exposing it via the C API.

Having looked through the DinkToPdf code I can see that the settings are handled in a generic way.
So if I understand it correctly then simply updating the libwkhtmltox.dll to v0.12.5 should be enough to cause the setting to be used.

I downloaded the DinkToPdf source and ran it with the updated libwkhtmltox.dll and it ran fine.
Setting some breakpoints I could see it applying the viewportSize setting.

Unfortunately that still didn't solve the root issue I'm having, which is bootstrap 4 not using the correct layout for the width available.

I think that's because the viewportSize wasn't being used, but at the point I'm not sure how to move further forward with the investigation of the issue.

System.DllNotFoundException: Unable to load DLL 'libwkhtmltox' when deploying on Windows 2016

Hi,

I saw this use case was already mentioned in other issues but I found a strange workaround.

So first some information about my environment : I'm using DinkToPdf along with some fixes provided by #18 . Everything work natively with VS2017 in a .net core 2.0 (AspNet core), I can generate any PDF I want without any problem, any errors (and without loading explicitly any DLL).

I deployed it on a Windows 2016 Server and I got the infamous System.DllNotFoundException. I tried a lot of things but finally I added in the root of my project the libwkhtmltox.dll coming from the 0.12.3.2 windows 64bits package. And it worked perfectly fine. Swapping it with 0.12.4 does not work at all (DllNotFoundException). I tried to use the latest alpha and even if I did not have a System.DllNotFoundException, I didn't get any PDF output (did not spend any time debugging it).

If I read wkhtmltox changelog they switched from VS2013 to VS2015 with 0.12.4.

Can somebody with access to Windows server 2016 test and confirm ?

PDF is empty after download over ajax

I am using ASP.NET CORE 2.0 and I was successfully to show a PDF from the Controller directly (with new FileContentResult(pdf, "application/pdf");). But if I try to show OR download the PDF from an ajax request, I get an empty PDF back on client side and also a scarry title.

My Web API Code

var doc = new HtmlToPdfDocument()
                {
                    GlobalSettings = {
                        ColorMode = ColorMode.Color,
                        Orientation = Orientation.Portrait,
                        PaperSize = PaperKind.A4Plus,
                    },
                    Objects = {
                    new ObjectSettings() {
                        PagesCount = true,
                        HtmlContent = "<h1>Hello World!</h1>",
                        WebSettings = { DefaultEncoding = "utf-8" },
                        HeaderSettings = { FontSize = 9, Right = "Page [page] of [toPage]", Line = true, Spacing = 2.812 }
                    }
                        }

                };

                byte[] pdf = _converter.Convert(doc);

                using (FileStream stream = new System.IO.FileStream(@"./" + DateTime.UtcNow.Ticks.ToString() + ".pdf", FileMode.Create))
                {
                    stream.Write(pdf, 0, pdf.Length);
                }
                return new FileContentResult(pdf, "application/pdf");`

and my Ajax Code:

          $.ajax({
                url: apiHelper.getPdfApiUrl(),
                method: 'post',
                headers: {
                    "Authorization": "Bearer " + jsCookie.get('token'),
                    "Content-Type": "application/json; charset=utf-8",
                },
                contentType: "application/json",
                data: json,
                success: function (data) {

                    console.log('***********************');
                    console.log(data);

                    var blob=new Blob([data]);
                    var link=document.createElement('a');
                    link.href=window.URL.createObjectURL(blob);
                    link.download="test.pdf";
                    link.click();
                }
            })

The downloaded PDF (left in the image) is empty on client side.

For testing, I tried also to "write" or "create" the pdf directly on the server/localhost. The write was also successfully AND the pdf is successfully created. What am I doing wrong ?
screen shot 2018-03-15 at 17 53 43

Cannot make it work - issues with wkhtmltopdf library

I'm having issues with the library, as in that I can't make it work; I tried both 32 and 64 bit versions of wkhtmltopdf (v.0.12.4 downloaded from this git), with the following results:
64bit: I get a BadImageFormatException
32bit: I get that "a call to PInvoke function 'DinkToPdf!DinkToPdf.WkHtmlToXBindings::wkhtmltopdf_init' unbalanced the stack. This could happen when the managed PInvoke signature doesn't correspond to the unmanaged signature"

using VS2017 professional 15.5.7
on Windows 10 64 bit (v.1803)
.net standard 2.0 library loaded from a .net 4.6.1 project

Any help?

[EDIT]
I just noticed issue #38, and I'm thinking that might be my case - as in, the library only works from .net Core and not from the full framework. Can anyone confirm?

seems like img tag not working

.net core version: 1.0.4
dinktopdf: 1.0.8

I am trying to add an <img> but it seems it does not work.
I already have app.UseStaticFiles();
I added the image in my wwwroot folder

I also tried it on 2.0.2 version of dotnet
I already have the .dlls in my root folder

A snippet of my code

public IActionResult Pdf()
{
    var converter = new SynchronizedConverter(new PdfTools());
    var doc = new DinkToPdf.HtmlToPdfDocument()
    {
        GlobalSettings =
        {
            ColorMode = DinkToPdf.ColorMode.Color,
            Orientation = DinkToPdf.Orientation.Landscape,
            PaperSize = DinkToPdf.PaperKind.A4Plus,
        },
        Objects =
        {
            new DinkToPdf.ObjectSettings()
            {
                HtmlContent = "<img src='~/long.JPG' asp-append-version='true' />",
                WebSettings = { DefaultEncoding = "utf-8" },
             }
            }
        };

    var pdf = converter.Convert(doc);
    return File(pdf, "application/pdf");
}

How can I add an image to my page then convert it to pdf?

Cheers

Converter.convert works exactly twice

I have an api, that just passes an html string, which is then passed to this

        static public byte[] HtmlToPdf(string html)
        {
            var converter = new BasicConverter(new PdfTools());
            var doc = new HtmlToPdfDocument()
            {
                GlobalSettings = {
                    ColorMode = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    PaperSize = PaperKind.A4Plus
                }, 
                Objects = {
                    new ObjectSettings()
                    {
                        PagesCount = true,
                        HtmlContent = html,
                        WebSettings = {DefaultEncoding = "utf-8"}
                    }
                }
            };
            return converter.Convert(doc); // <--- hangs here on 3rd time called
        }

This call only works twice though?? After the second time this method has been invoked it will just hangs on the converter.Convert() call. Any idea's? Thanks.

Setting PagesCount to false causes crash

If I set PagesCount to false it crashes. The error messages says pdftools not found and a divide by 0 error.

I can get around it with the following:

new ObjectSettings()
{
PagesCount = true,
HtmlContent = html,
WebSettings =
{
DefaultEncoding = "utf-8"
},
HeaderSettings =
{
FontSize = 9,
//Right = "Page [page] of [toPage]",
Right = "",
Line = false,
Spacing = 0
}
}

PDF generation reaches up to 100% and prints after 4~5 minutes

ASP.NET core version: 1.1.2.

On other machines this code works normally.
I've restarted and tried various configurations without success.
I also printed an empty document, with no header and footer.

Startup.cs

services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));

Class that generates the report

//On constructor
_converter = new SynchronizedConverter(new PdfTools());


//On the method
var  _diarioDeOperacao = new HtmlToPdfDocument()
{
    GlobalSettings = {
        ColorMode = ColorMode.Color,
        Orientation = Orientation.Portrait,
        PaperSize = PaperKind.A4Plus
    }
};

_diarioDeOperacao.Objects.Add(new ObjectSettings()
{
        PagesCount = true,
        HtmlContent = "Teste",
        WebSettings = { DefaultEncoding = "utf-8", LoadImages = false },
        UseExternalLinks = false
});
_converter.Error += (sender, args) => _logger.LogError("Erro no relatório: Diário de operações\n" + args.Message);
_converter.Warning += (sender, args) => _logger.LogWarning("Warning no relatório: Diário de operações\n" + args.Message);
_converter.ProgressChanged += (sender, args) => _logger.LogWarning(args.Description);
_converter.Finished += (sender, args) => _logger.LogWarning("Sucesso " + args.Success);

//when debugging, here is where it hangs
byte[] pdfBytes = _converter.Convert(_diarioDeOperacao);


Response.ContentType = "Application/pdf";
Response.Headers.Remove("Content-Disposition");
Response.Headers.Add("Content-Disposition", $@"attachment; filename=Diario de Operacoes {DateTime.Now.ToString()}.pdf");
var buffer = pdfBytes;
Response.StatusCode = 200;

Response.Body.Write(buffer, 0, buffer.Length);
Response.Body.Flush();
Response.Body.Dispose();

Console output

#when the method is called it produces
Qt: Could not initialize OLE (error 80010106) 
warn: PortoImbituba.Controllers.AccountController[0] 0%
warn: PortoImbituba.Controllers.AccountController[0] 10%
warn: PortoImbituba.Controllers.AccountController[0] 50% 
warn: PortoImbituba.Controllers.AccountController[0] 100%
   
#after 4 minutes and 8 seconds

warn: PortoImbituba.Controllers.AccountController[0] Object 1 of 1
warn: PortoImbituba.Controllers.AccountController[0] Object 1 of 1
warn: PortoImbituba.Controllers.AccountController[0] Preparing
warn: PortoImbituba.Controllers.AccountController[0] Page 1 of 1
warn: PortoImbituba.Controllers.AccountController[0] Sucesso True   

Azure web app not working as expected??

Hi. I cannot seem to get the correct configuration for getting this to work on an azure web app. The web app is configured to run under 64bit and the library I am using is the 64 bit one. It works flawlessly on my local through localhost. I have included the the three libwkhtmltox files needing to be present in the root of the directory where startup.cs is located. I have done that.
From Kudu I can see this....
image

my appsettings in my web app are this:
image

my vs .net core website looks like this
image

My error is this
image

AggregateException: One or more errors occurred. (An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B))
DinkToPdf.SynchronizedConverter.Invoke(Func delegate)
DinkToPdf.SynchronizedConverter.Convert(IDocument document)

Any advice would be totally appreciated.

Unable to read DLL

I tried making my own project to test this out. I downloaded the 64 bit dll from your link and tried putting it in three different places

  • The root folder (with the .csproj file)
  • The folder with the solution file (One above root folder)
  • The folder with the debug dll in it (bin\Debug\netcoreapp1.1)

I am still getting the same error:
dllnotfound
Is there somewhere else I should be putting the DLL? Thanks!

Edit: Here are the error details:

System.DllNotFoundException occurred
  HResult=0x80131524
  Message=Unable to load DLL 'libwkhtmltox': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
  Source=DinkToPdf
  StackTrace:
   at DinkToPdf.WkHtmlToXBindings.wkhtmltopdf_init(Int32 useGraphics)
   at DinkToPdf.PdfTools.Load() in C:\Users\admin\Documents\DinkToPdf\src\DinkToPdf\PdfTools.cs:line 27
   at DinkToPdf.BasicConverter.Convert(IDocument document) in C:\Users\admin\Documents\DinkToPdf\src\DinkToPdf\BasicConverter.cs:line 42
   at DinkToPdf.SynchronizedConverter.<>n__0(IDocument document)
   at DinkToPdf.SynchronizedConverter.<>c__DisplayClass5_0.<Convert>b__0() in C:\Users\admin\Documents\DinkToPdf\src\DinkToPdf\SynchronizedConverter.cs:line 27
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()

Subsequent PdfTools instances yield wrong PDF output

Hi! I'm trying to write some automated tests.

If I:

using (var tools = new PdfTools())
{
 var converter = new SynchronizedConverter(tools);
 // do the stuff, many times over
}

..then everything works fine.

However, if I:

using (var tools = new PdfTools())
{
 var converter = new SynchronizedConverter(tools);
 // do the stuff
}
using (var tools = new PdfTools())
{
 var converter = new SynchronizedConverter(tools);
 // do the stuff
}

The "stuff" being done is a randomly-named temp folder being set up, a HTML file and CSS file being copied in and the HTML being converted. I've put breakpoints and verified that for each conversion, the HTML and CSS are all valid. It's the PDF conversion bit which has the issue, for some reason!

..then only the first PDF is correct. Strangely, all of the subsequent PDFs simply have text in the source document dumped out.

The tests don't run in parallel, it seems that using a second (or rather, non-first) PdfTools instance is the issue.

Anything I can do to help diagnose?

Text slightly blurry

Love this tool but after installing it on server and converting some html to PDF the text is slightly blurry. It's not terrible but just enough to hurt your eyes when read. I'm comparing it to another PDF report that I created with the same font and there is a noticeable difference in quality. Any idea what could cause that?

charset configuration not works

Regardless of configuration the charset not change

1 - below it's my html that I'm trying to convert

<html>
<head>
	<meta http-equiv=Content-Type content="text/html; charset=us-ascii">
</head>
<body>
	Todo mundo é com acento.
</body>
</html>

2- below it's my code to do the conversion

Controller Code

        [HttpGet("PrintTests")]
        public object PrintTests()
        {
            PDFDocument x = new PDFDocument();
            x.teste();
            return null;
        }

x.teste() Function Code

    public void teste()
    {
        string _content = string.Empty;
        using (System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Temp\teste.html"))
        {
            _content = file.ReadToEnd();
            file.Close();
        }
        


        var globalSettings = new GlobalSettings
        {
            ColorMode = ColorMode.Color,
            Orientation = Orientation.Portrait,
            PaperSize = PaperKind.A4,
            Margins = new MarginSettings { Top = 10 },
            DocumentTitle = "PDF Report",
            Out = @"C:\Temp\teste_1.pdf",
              
            
        };


        ObjectSettings _obsettings = new ObjectSettings();
        _obsettings.HtmlContent = _content;
        _obsettings.WebSettings.DefaultEncoding = "us-ascii";
        _obsettings.WebSettings.LoadImages = true;
        _obsettings.IncludeInOutline = true;

        var pdf = new HtmlToPdfDocument()
        {
            GlobalSettings = globalSettings,
            Objects = { _obsettings }
        };

        var _converter = new BasicConverter(new PdfTools());
        _converter.Convert(pdf);
        _converter.Tools.Dispose();
    }

3 - below it's my pdf file converted
teste_1.pdf

Error CGI azure font and img

I have application working right on local machine with kestrel.
Usage azure service returns error CGI aplication.
With simple writing text generates squares.
With absolute path css font family returns CGI error.
Img tag also returns CGI error.
Error: The specified CGI application encountered an error and the server terminated the process.
Here's an example.

 string  cssPath = @"file:///" + _environment.ContentRootPath + @"\wwwroot\font.css";

            var doc = new HtmlToPdfDocument()
            {
                GlobalSettings =
                {
                    ColorMode = ColorMode.Color,
                    Orientation = Orientation.Landscape,
                    PaperSize = PaperKind.A4
                },
                Objects =
                {
                    new ObjectSettings()
                    {
                        PagesCount = true,
                        HtmlContent = @"<html>
                                        <head>
                                            <meta charset='UTF-8' \>
                                            <link href=' "+ cssPath + @"' rel='stylesheet' type ='text/css' media='screen'>
                                        </head>
                                        <body>
                                            <img class='qrcode img-fluid pb-2' src='https://chart.googleapis.com/chart?chs=500x500&cht=qr&&chld=L|0&chl=12345678'>
                                            <h2>Imagem</h2>
                                        </body>
                                        </html>",
                        WebSettings =
                        {
                            DefaultEncoding = "utf-8"
                        },
                        HeaderSettings =
                        {
                            FontSize = 9,
                            Spacing = 2.812
                        }
                    }
                }
            };
          
            byte[] pdf = _converter.Convert(doc);

Bottom overlapping onto header of next page

I have an issue where the bottom of the page overlaps onto the next page into the header. The amount is variable, some pages overlap more than others.

Below are the settings I use and screenshots attached. Any help would be appreciated.

var doc = new HtmlToPdfDocument()
{
GlobalSettings =
{
ColorMode = ColorMode.Color,
Orientation = DinkToPdf.Orientation.Landscape,
PaperSize = PaperKind.A4
},
Objects =
{
new ObjectSettings()
{
PagesCount = true,
HtmlContent = html,
WebSettings =
{
DefaultEncoding = "utf-8"
},
HeaderSettings =
{
FontSize = 9,
//Right = "Page [page] of [toPage]",
Right = "",
Line = false,
Spacing = 0
}
}
}
};
overlapping

Javascript is not working

With the below code javascript is not enable? could pleae advice on it?
sb.AppendFormat(@"


<style>
.header {
text-align: center;
color: green;
padding-bottom: 35px;
}

                            table {
                                width: 80%;
                                border-collapse: collapse;
                            }

                            td, th {
                                border: 1px solid gray;
                                padding: 15px;
                                font-size: 22px;
                                text-align: center;
                            }

                            table th {
                                background-color: green;
                                color: white;
                            }
                                            </style>            
                                <script src='{0}\\js\\Chart.js'></script>                               
                        </head>

                        <body>
                            <div class='header'><h1>This is the generated PDF report!!!</h1></div>
                            <table align='center'>
                                <tr>
                                    <th>Name</th>
                                    <th>LastName</th>
                                    <th>Age</th>
                                    <th>Gender</th>
                                </tr>", webpath);

        foreach (var emp in employees)
        {
            sb.AppendFormat(@"<tr>
                                <td>{0}</td>
                                <td>{1}</td>
                                <td>{2}</td>
                                <td>{3}</td>
                              </tr>", emp.Name, emp.LastName, emp.Age, emp.Gender);
        }

        sb.Append(@"
                            </table>
                            <canvas id='myChart'></canvas>
                             <script>
                            var ctx = document.getElementById('myChart').getContext('2d');
                            var chart = new Chart(ctx, {
                                // The type of chart we want to create
                                type: 'line',

                                // The data for our dataset
                                data: {
                                    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
                                    datasets: [{
                                            label: 'My First dataset',
                                        backgroundColor: 'rgb(255, 99, 132)',
                                        borderColor: 'rgb(255, 99, 132)',
                                        data: [0, 10, 5, 2, 20, 30, 45],
                                    }]
                                },

                                // Configuration options go here
                                options: {}
                            });
                            </script>
                        </body>
                    </html>");

Text not displayed correctly in Azure instance

Hello, the library is working fine locally when debugging with IIS, but when deployed to Azure the text is displayed as black boxes. I've tried to manually set a font face and it made no difference.
Any ideas?

image

Korean and Hindi font not rendered properly on Windows 10

I tried to create a PDF with some korean and hindy words but result pdf shows squares (tofu).
I modified basic sample test in order to output different languages for test.
Here's my code:

Objects = {
		new ObjectSettings() {
				PagesCount = true,
				HtmlContent = @"<!DOCTYPE html>
<html>
<head>
<meta charset=""utf-8"" />
</head>
<body>
<h1>Latin</h1><p>Lorem ipsum dolor sit amet</p>
<h1>Japanese</h1><p>欧州でのテロ等に対する注意喚起(再々更新</p>
<h1>Chinese</h1><p>2018年1月10日,国家主席***在人民大会堂集体会见北欧和波罗的海国家议会领导人。芬兰议长洛赫拉、挪威议长托马森、冰岛议长西格富松、爱沙尼亚议长内斯托尔、拉脱维...</p>
<h1>Arabic</h1><p>استقبل فخامة رئيس الجمهورية الإيطالية سيرجو ماتاريلا في قاعة الفرسان بقصر الكويرينالي في روما رؤساء البعثا</p>
<h1>Persian</h1><p>اسیمو دالما نخست وزیر و وزیر خارجه اسبق ایتالیا که برای شرکت در کنفرانس امنیتی تهران در کشورمان بسر می برد، عصر امروز با وزیر امور خ</p>
<h1>Hindi</h1><p>डिप्टी सेक्रेटरी ऑफ स्टेट जॉन जे. सुल्लीवान जार्ज सी. मार्शल सेंटर वाशिंगटन, डीसी डिप्टी सेक्रेटरी सुल्लिवानः </p>
<h1>Korean</h1><p>안보리 비상임 이사국 지위를 1년씩 나눠 맡기로 합의했습니다. 이에 따라서 이탈리아는 올해 1월 1일을 기준으로 유엔 안보리 비상임 이사국의 일원이 되었습니다. </p>
<h1>Greek</h1><p>Σε όλη την Ομογένεια, σε όλες τις Ελληνίδες και τους Έλληνες όπου γης, στέλνω τις πιο θερμές ευχές μου για το 2018. Να είναι μια χρονιά που να αποδεικνύει για μια ακόμα φορά ότι η ελληνική ψυχή,</p>
<h1>Russian</h1><p>О встрече спецпредставителя Президента Российской Федерации по Ближнему Востоку и странам Африки, заместителя Министра иностранных дел России М.Л.Богданова с Послом Палестины в Москве А.Нофалом(Открывает новое окно)</p>
<h1>Hebrew</h1><p>שלום וברוכים הבאים לאתר הבית של שגרירות ישראל בניו דלהי, להודו וסרי לנקה. שגרירות ישראל בניו דלהי אמונה על הקשרים הדיפלומטיים בין המדינות בתחומים שונים ביניהן התחום המדיני, כלכלי, התרבותי, </p>
<h1>Armenian</h1><p>ԹՊԻՀ-ի անչափահասների արդարադատությանը ուղղված «Իրավական կրթություն և ակտիվ մասնակցություն» ծրագիրը Հ</p>
</body>
</html>",
				WebSettings = { DefaultEncoding = "utf-8" },
				HeaderSettings = { FontSize = 9, Right = "Page [page] of [toPage]", Line = true, Spacing = 2.812 }
		}   
}

This is how the resulting PDF looks like:

Image of bad pdf

HTML is rendered properly both by Firefox and Chrome

Process quits

Hey, I have the following code:

                _converter = new SynchronizedConverter(new PdfTools());

                var doc = new HtmlToPdfDocument()
                {
                    GlobalSettings =
                    {
                        PaperSize = PaperKind.A4,
                        ColorMode = ColorMode.Color,
                        Orientation = Orientation.Portrait,
                    },
                    Objects =
                    {
                        new ObjectSettings()
                        {
                            PagesCount = false,
                            HtmlContent = html,
                            WebSettings = { DefaultEncoding = "utf-8" },
                            HeaderSettings = { },
                            FooterSettings = { },
                        }
                    }
                };

                return _converter.Convert(doc);

The program exits without any error or exit code on line:

return _converter.Convert(doc);

The input html is:

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

</body>
</html>

Any ideas what may be wrong? The 3rd party library files are in bin via Target:

    <Target Name="CopyCustomContent" AfterTargets="AfterBuild">
        <Copy SourceFiles="..\..\lib\libwkhtmltox.so" DestinationFolder="$(OutDir)" />
        <Copy SourceFiles="..\..\lib\libwkhtmltox.dll" DestinationFolder="$(OutDir)" />
        <Copy SourceFiles="..\..\lib\libwkhtmltox.dylib" DestinationFolder="$(OutDir)" />
    </Target>

I'm running dotnet core 2.1 on OSX.

PS. Multithreading is a non-issue as this is a single unit test.

Header/Footer Html

Is it possible to directly put Html for HeaderSettings, FooterSettings as-well? now it is only possible to link via HtmUrl.

using font-face

I am trying to include a font from a ttf file.
I put the ttf file in the wwwroot folder of my project and i have this in my css in my html file:
@font-face {
font-family: 'MICR';
src: url("micrenc.ttf") format("truetype");
font-weight: normal;
font-style: normal;
}
and this on the line that needs the font:
style="font-family: 'MICR'; font-size: 30px;

The pdf file does that is created does even not include the text that is supposed to be in that font.
(when i render this file in my browser, i do see the text and in the specified font)

base64 images not breaking correctly?

Hi. I have the following in my css:
.photo-inspection--photo-preview, img {
page-break-inside: avoid;
}
i then have in my html a basic img tag looking like the following:
<img crossorigin="Anonymous" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCAHCAlgDASIAAhEBAxEB/8QAHQAAAgIDAQEBAAAAAAAAAAAABQYEBwACAwEICf/EAEcQAAIBAwMCBAQFAgMHAwMBCQECAwQFEQASI..." /> (truncated for readability).
My code looks like this:
` var ss = Path.Combine(Environment.CurrentDirectory.ToString(), "wwwroot", "css", "pdfoutput.css");

        var ws = new WebSettings()
        {
            UserStyleSheet = ss,
            DefaultEncoding = "utf-8"
        };
        var margin = new MarginSettings()
        {
            Bottom = .75,
            Top = .5,
            Left = .5,
            Right = .5,
            Unit = Unit.Inches

        };

        var doc = new HtmlToPdfDocument()
        {

            GlobalSettings = {
                ColorMode = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize = PaperKind.Letter,
                Margins = margin,
            },
            Objects = {
                new ObjectSettings() {

                    PagesCount = true,
                    HtmlContent = htmlContent,
                    WebSettings = ws,
             //       HeaderSettings = { FontSize = 9, Right = "Page [page] of [toPage]", Line = false, Spacing = 1},
                    FooterSettings = { FontSize = 9, Right = "Page [page] of [toPage]", Spacing = 4}
                }
            }
        };`

The output however keeps breaking across the image. Any ideas?

Multiple pages

Is it possible to create several dynamic pages? Placing a foreach inside objects?

Doesn't work inside docker

Hi,
I would appreciate if the above same code is once tested in docker and if it works pls upload the steps. I get unable to shared library every time.
"One or more errors occurred. (Unable to load shared library 'libwkhtmltox' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: liblibwkhtmltox: cannot open shared object file: No such file or directory)"
but the libraries exist at the current directory.

Small contents in PDF for macOS

I am using DinkToPdf to convert my html to pdf and got a great result in windows.
But in macOS I am facing a problem: I put html file and the pdf that it produced became very small on A4 size paper.
I was testing on different websites and it had similar result. Like the following picture
a1
Any advise for me to fix the problems?

NuGet package does not link native libs

Rather than have to copy the libwk*.* native libs into the output folder, you can set up the NuGet package to include them automatically. They just need to be linked like so in the NuSpec:

<file src="..\..\v0.12.4\64 bit\libwkhtmltox.dll" target="runtimes\win7-x64\native" />
<file src="..\..\v0.12.4\64 bit\libwkhtmltox.so" target="runtimes\linux-x64\native" />
<file src="..\..\v0.12.4\64 bit\libwkhtmltox.dylib" target="runtimes\osx-x64\native" />

same goes for x86...

I'm happy to create a pull request if you'd like.

Thanks!

Pdf cannot view

After I have run the server then it show this error, but it still run.
error1

Here is my code in the API, I scared it have problem with async/await so I used .Result

[HttpGet("booking-preview/{bookingId}")]
public IActionResult GetBookingPreview(long bookingId)
{
	if (!ModelState.IsValid)
		return Ok(ModelState);

	var doc = new HtmlToPdfDocument()
	{
		GlobalSettings = {
			PaperSize = PaperKind.A3,
			Orientation = Orientation.Landscape,
		},

		Objects = {
			new ObjectSettings()
			{
				Page = "http://google.com/",
			},
			new ObjectSettings()
			{
				Page = "https://github.com/",

			}
		}
	};
	byte[] pdf = _converter.Convert(doc);
	return new FileContentResult(pdf, "application/pdf");
}

But after have called the API and then return the pdf file, I opened it by browser withBlob or using Pdf reader but it appeared blank/ not support.

error2

image

Thanks.

Images are not shown

Hi
I'm creating a PDF from Html file and the images are not shown. How can I convert an html file with images?

Table Header is Repeated on each page

When I generate PDF from Razor View in .Net Core which contains an Html table, the table header is repeated on each page of the PDF generated Document.
the Repeated header on the second page and down overwrite the table content, while it's fixed right only in the first page.

Endless progress after first generated

After my first generate, when i have tried to generate pdf again i get endless process. If i have restarted project it work good again. But just for first generate. As i understand it have stopped at this string
bool converted = Tools.DoConversion(converter);
or sometimes happens next - The PDF report that is created is just html code and not a readable report

ViewModel

i am trying to pass viewmodel data to my html rendered view i got null reference exception

PdfViewModel vm = new PdfViewModel { PdfText = "some pdf text" };
string documentContent = await _printservice.RenderTemplateAsync("DemoPrinter/View", vm);

Custom path to libraries

I see that there are many issues with the path to the libraries. Maybe it is not a bad idea to allow customization of this path. (For example as a property in converters). This could allow us to remove the libraries from the solution, which is a lot cleaner...

Not have support google charts ?

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

      // Load the Visualization API and the corechart package.
      google.charts.load('current', {'packages':['corechart']});

      // Set a callback to run when the Google Visualization API is loaded.
      google.charts.setOnLoadCallback(drawChart);

      // Callback that creates and populates a data table,
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart() {

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
        data.addRows([
          ['Mushrooms', 3],
          ['Onions', 1],
          ['Olives', 1],
          ['Zucchini', 1],
          ['Pepperoni', 2]
        ]);

        // Set chart options
        var options = {'title':'How Much Pizza I Ate Last Night',
                       'width':400,
                       'height':300};

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

Docker + .NET Core 2.0 + Https Images

I'm currently running DinkToPdf on my macOS without any problem.

My webpages use external HTTPS ressources such as

  • two images
  • 1 CSS file

In Docker, using a asp-net-2.0 base image (along with added-dependencies

apt-get install -y --no-install-recommends zlib1g fontconfig libfreetype6 libx11-6 libxext6 libxrender1

For some reason, the PDF rendered has no image, and no CSS.

How can I fix this?

Continuation of #5: Unable to load DLL 'libwkhtmltox': The specified module could not be found.

I have followed timfisher's comments at the end of closed issue #5 but still am unable to load the dll. I am using Visual Studio 2017 Net Core 2.0 on a Windows 10 PC. It works fine using the localhost IIS express web server, however, when I publish to the IIS 10 server, it cannot find the 'libwkhtmltox'.dll. I have verified that the files have been copied correctly, and have even tried manual placing of the dll file in every conceivable location.

I guess first up, two questions need answering:

Does it work with Net Core 2.0?
Does it work on IIS 10 (Windows Server 2016)
Could some one please help me here.

Many thanks in advance

Unable to load DLL 'libwkhtmltox': The specified module could not be found. When using Nuget package

When using the DinkToPdf Nuget package I get the error message below because it is looking for the libwkhtmltox DLL in the same folder the Nuget package DLL is in. For me using VS 2017 on Windows 10 this is:

%UserProfile%\.nuget\packages\dinktopdf\1.0.8\lib\netstandard1.6

When I either manually copy the correct libwkhtmltox DLL to this folder or include the source of the DinkToPdf project into my solution I no longer get this error. By including the project source into my solution the DinkToPdf DLL is then compiled into my output folder where it then also successfully finds the libwkhtmltox DLL.

Is it possible to resolve this issue without having to use the project source or regsvr32.exe? I see that TuesPechkin has an IDeployment interface to address this issue (see: tuespetre/TuesPechkin#57). Is it possible to do something similar in DinkToPdf?

System.AggregateException: One or more errors occurred. (Unable to load DLL 'libwkhtmltox': The specified module could not be found. (Exception from HRESULT: 0x8007007E)) ---> System.DllNotFoundException: Unable to load DLL 'libwkhtmltox': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
   at DinkToPdf.WkHtmlToXBindings.wkhtmltopdf_init(Int32 useGraphics)
   at DinkToPdf.PdfTools.Load() in C:\Users\admin\Documents\DinkToPdf\src\DinkToPdf\PdfTools.cs:line 27
   at DinkToPdf.BasicConverter.Convert(IDocument document) in C:\Users\admin\Documents\DinkToPdf\src\DinkToPdf\BasicConverter.cs:line 42
   at DinkToPdf.SynchronizedConverter.<>n__0(IDocument document)
   at DinkToPdf.SynchronizedConverter.<>c__DisplayClass5_0.<Convert>b__0() in C:\Users\admin\Documents\DinkToPdf\src\DinkToPdf\SynchronizedConverter.cs:line 27
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
   --- End of inner exception stack trace ---
   at DinkToPdf.SynchronizedConverter.Invoke[TResult](Func`1 delegate) in C:\Users\admin\Documents\DinkToPdf\src\DinkToPdf\SynchronizedConverter.cs:line 51
   at DinkToPdf.SynchronizedConverter.Convert(IDocument document) in C:\Users\admin\Documents\DinkToPdf\src\DinkToPdf\SynchronizedConverter.cs:line 27

Cannot add headers & footers

It is possible to put some content on each page as describe here once the number of pages is known and when having an empty document initially. However, when having a big html, I would like to add headers and footers to the pages afterwards. I do not know the exact number of pages, I just want to ensure that once the pdf is generated each page has a header and a footer. This is a problem.
The normal content is presented correctly. It is just about adding headers and footers to each page afterwards. This html & css should solve it but it is not working.

How to deal with pagination when lines don't have a standard height

I was wondering about that, if there is any know solution/workaround.
It could happen when the cell text gets wrapped because it has to be shown entirely. So it will affect the height of the rows (making it variable), therefore the number of rows that can fit in a page.

Is there a way to detect dynamically the height of the rows?

Thanks

PDF font size growing up after creating the pdf [.NET CORE 2.0]

I am preparing some PDF Layouts. But at some point I get confused. If I run the .net core application on DEBUG Mode, I get the size that I want. If I run the the application in Release (Production) Mode I get a total different pdf (with a bigger font size) back. Is this an issue? I included the CSS (both templates are using the same css) and the pdf can load successfully the font (RNS Sanz) but no luck with the font size. I tried it also without my css, plain example code. But there is the same situation. Is there a setting for that? thanks.

I am using this code

Controller

            string html = "<!DOCTYPE html>" +
                    "<html lang = \"en\">" +
                         "<head>" +
                             "<meta charset = \"UTF-8\">" +
                             "<title> Check </title>" +
                        // "<link href='" + cssPath + "' rel='stylesheet' type='text/css' media='screen'>" +

                        "</head>" +
                        "<body>" +
                            "<div style = \"text-align: center; margin-top:16px;\">" +
                "<p style=\"font-family: 'RNS Sanz'; font-size: 70px;\"> Hi! I am RNS Sanz font. (70px, Release)</p>" +

                            "</div>" +
                            "<div style = \"text-align: center; margin-top:16px;\">" +
                "<p style =\"font-family: 'Roboto'; font-size: 30px;\"> This is roboto font. (30px, Release)</p>" +
                            "</div>" +
                        "</body>" +
                    "</html>";

            var pdf = new HtmlToPdfConverterService(_converter, _env).Convert(html);
            var path = Path.Combine(_env.WebRootPath, "micr.pdf");
            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                fs.Write(pdf, 0, pdf.Length);
            }

            return new FileContentResult(pdf, "application/pdf");`

HtmlToPdfConverterService

public class HtmlToPdfConverterService
    {
        private IConverter _converter;
        readonly IHostingEnvironment _env;

        public HtmlToPdfConverterService(IConverter converter, IHostingEnvironment env)
        {
            _converter = converter;
            _env = env;

        }

        public byte[] Convert(string html)
        {

            string cssPath = Path.Combine(_env.WebRootPath, "static/css/app.css");

            HtmlToPdfDocument doc = new HtmlToPdfDocument()
            {
                GlobalSettings = {
                    Orientation = Orientation.Portrait,
                    PaperSize = PaperKind.Letter,
                    Margins = new MarginSettings() { Top = 10 , Bottom = 0, Left = 10, Right = 10},
                },
                Objects = {
                        new ObjectSettings() {
                                 HtmlContent = html,
                                 WebSettings = new WebSettings { MinimumFontSize = 12, UserStyleSheet = cssPath }

                            }
                        }
            };

            return _converter.Convert(doc);
        }


    }

I followed this ticket here: #24
The PDF can Read the font "RNS Sanz" but the font size is growing automatically up in Release.

If I don't use any css, I get the same result. Also with this example:

var doc = new HtmlToPdfDocument()
{
    GlobalSettings = {
        ColorMode = ColorMode.Color,
        Orientation = Orientation.Landscape,
        PaperSize = PaperKind.A4Plus,
    },
    Objects = {
        new ObjectSettings() {
            PagesCount = true,
            HtmlContent = "<h1>Hello World</h1>",
            WebSettings = { DefaultEncoding = "utf-8" },
            HeaderSettings = { FontSize = 9, Right = "Page [page] of [toPage]", Line = true, Spacing = 2.812 }
        }
    }
};

pdf font issue

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.