asp net core pdf

Долго ли, коротко ли, вместе с новой Visual Studio 2017 в релиз вышел ASP.NET Core. Тулинг лишился приставки preview, как и все инфраструктурные сборки, поставляемые Microsoft’ом. На мой взгляд, фреймворк получился отличным, а история с cjproj=>xproj=>project.json=>csproj и поломанная совместимость при переходе с RC1 на RC2 — это всё же разумная плата за скорость развития. Ну да ладно, опустим дела минувших дней, и вернёмся к текущим реалиям.

А реалии таковы, что есть задачи, и есть инструменты которые их решают. В частности, передо мной встала задача генерирования PDF-документов средствами ASP.NET Core. «Хмм… Наверняка уже есть что-то готовое. », — подумал я. Как бы не так. Вернее готовые библиотеки для этого есть, но платные, а вот чего-то OpenSource’ного нет. «А как же iText?», — спросите вы. «AGPL», — ответит вам страничка с лицензией на гитхабе. Для OpenSource проектов бесплатно, а для коммерческого использования, извольте заплатить. Ну что ж, раз нет инструмента, решающего мою задачу, значит я сделаю его сам.

В области генерирования PDF самым железобетонным вариантом для меня является wkhtmltopdf. Алгоритм в данном случае простой — делаем HTML страницу с необходимыми данными — конвертируем её в PDF — Profit! Таким образом родилась обёртка над wkhtmltopdf. Всё что ей требуется для работы — это указать путь к исполняемому файлу wkhtmltopdf. В простейшем варианте это выглядит вот так:

Для конвертирования используется поточный вариант работы. Данные передаются в stdin и забираются из stdout. Никаких временных файлов. Прекрасно работает в связке с ASP.NET Core. Опционально можно указать дополнительные параметры в виде формата и ориентации листа, отступов, максимального времени выполнения, ч/б режима, времени выполнения JavaScript’а, необходимости загрузки изображений. С полным списком параметров можно ознакомиться на GitHub.

Если хотя бы один человек решит свою проблему с помощью этого инструмента, значит он был создан не зря. Да пребудет с вами MIT.

Данная статья не подлежит комментированию, поскольку её автор ещё не является полноправным участником сообщества. Вы сможете связаться с автором только после того, как он получит приглашение от кого-либо из участников сообщества. До этого момента его username будет скрыт псевдонимом.

I created the Wep API in ASP.Net core to return the PDF. Here is my code:

But it returns only the JSON response:

Am I doing anything wrong here?

3 Answers 3

As explained in ASP.NET Core HTTPRequestMessage returns strange JSON message, ASP.NET Core does not support returning an HttpResponseMessage (what package did you install to get access to that type?).

Because of this, the serializer is simply writing all public properties of the HttpResponseMessage to the output, as it would with any other unsupported response type.

To support custom responses, you must return an IActionResult -implementing type. There’s plenty of those. In your case, I’d look into the FileStreamResult :

Or simply use a PhysicalFileResult , where the stream is handled for you:

Of course all of this can be simplified using helper methods, such as Controller.File() :

This simply abstracts the creation of a FileContentResult or FileStreamResult (for this overload, the latter).

Or if you’re converting an older MVC or Web API application and don’t want to convert all your code at once, add a reference to WebApiCompatShim (NuGet) and wrap your current code in a ResponseMessageResult :

If you don’t want to use return File(fileName, contentType, fileDownloadName) , then the FileStreamResult doesn’t support setting the content-disposition header from the constructor or through properties.

In that case you’ll have to add that response header to the response yourself before returning the file result:

Posted by Marinko Spasojevic | Jun 18, 2018 | 77

Let’s imagine that we have a .NET Core Web API project in which we need to generate a PDF report. Even though it shouldn’t suppose to be too hard to do something like that, we could end up losing too much time if we don’t know how to do it properly.

In this article, we are going to show how to use the DinkToPDF library to easily generate PDF documents while working on the .NET Core Web API project.

So, without further ado, let’s dive right into the fun part.

You can download the source code for this article at Creating PDF Document Source Code.

In this post, we are going to cover:

Basic Project Preparations

Let’s start, by creating a brand new .NET Core 3.0 Web API project named PDF_Generator :

After the project creation, we are going to modify the launchSettings.json file to disable our browser to start automatically:

DinkToPdf Library Configuration

DinkToPdf is a cross-platform oriented library which is the wrapper for the Webkit HTML to PDF library. It uses the WebKit engine to convert HTML to PDF.

It will allow us to create a PDF document from our HTML string that we generate in the .NET Core project, or to create a PDF document from an existing HTML page. Furthermore, we can download the created PDF document or save it on a certain location or return a new HTML page with the PDF content.

We are going to cover all these features in this article.

So, let’s install the DinkToPdf library first:

Or search for DinkToPdf inside the Nuget Package window:

After the installation completes, we need to import native library files to our root project. We can find those files in our source project in the NativeLibrary folder. Inside we will find two folders 32bit and 64bit , so we need to choose the appropriate library for our OS. We are going to choose the files from the 64bit folder:

Finally, we need to register this library with our IoC container in the StartUp >

Оцените статью