Welcome Guest Search | Active Topics | Sign In | Register

How to return the PDF file from C# Web API Options
OJB1
Posted: Friday, October 7, 2022 9:13:13 AM
Rank: Newbie
Groups: Member

Joined: 10/6/2022
Posts: 9
Hello,

I'm struggling with your documentation because there doesnt appear to be much information regarding the conversion to System.IO.Stream

When using the following line of code below, the library assumes I want to save the pdf document to disk. In my case it's saving in the root of my .NET Core project's bin folder:

var result = EO.Pdf.HtmlToPdf.ConvertHtml(html, "Test Report.pdf");

I need to be able to use the following return type shown below in my Web API in order to return the file back to the calling client, which also provides a download link in Swagger:

var doc = await _logsQueryRepo.GetLogsReportPdf(response!); // my C# interface
return File(new MemoryStream(doc.BinaryData), "application/pdf", name); // This part i can't figure out

The above code was used when I was trialling IronPdf, but I since have moved away from that library due to cost.

It looks to be I need a code sample in how to get the binary data stream from the ConvertHtml method.

Thanks
eo_support
Posted: Friday, October 7, 2022 9:40:01 AM
Rank: Administration
Groups: Administration

Joined: 5/27/2007
Posts: 24,217
Hi,

You would do something like this:

Code: C#
//Convert the result to a MemoryStream
MemoryStream ms = new MemoryStream();
EO.Pdf.HtmlToPdf.ConvertHtml(html, ms);

//Important: Set the current position to the begining of the stream
ms.Seek(0, SeekOrigin.Begin);

//Pass the memory stream to File method
return File(ms, ....);


Hope this helps.

Thanks!
OJB1
Posted: Friday, October 7, 2022 9:57:02 AM
Rank: Newbie
Groups: Member

Joined: 10/6/2022
Posts: 9
Hi,

I had more or less come to the same soluton, then I saw your mesage.

I did however have to convert the memory stream to an array.

// create memory stream to save PDF
using var pdfStream = new MemoryStream();

EO.Pdf.HtmlToPdf.ConvertHtml(html, pdfStream);

// Reset stream position
pdfStream.Seek(0, SeekOrigin.Begin);

return File(memoryStream.ToArray(), "application/pdf", name); // To Array, otherwise I got a server error.

Many thanks
eo_support
Posted: Friday, October 7, 2022 10:56:43 AM
Rank: Administration
Groups: Administration

Joined: 5/27/2007
Posts: 24,217
Great. If you do it that way then you do not need to call pdfStream.Seek to reset the stream position.


You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.