Return pdf to browser in a C# razor page using itext7
Sample code to return a PDF file to the browser in a Razor c# page using itext7.
using System; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using iText.Kernel.Pdf; using iText.Layout; using iText.Layout.Element; using System.IO; public IActionResult OnPostManipulatePdf(String dest) { MemoryStream ms = new MemoryStream(); PdfWriter writer = new PdfWriter(ms); PdfDocument pdfDoc = new PdfDocument(writer); Document doc = new Document(pdfDoc); writer.SetCloseStream(false); Paragraph header = new Paragraph("header"); doc.Add(header); doc.Close(); byte[] byteInfo = ms.ToArray(); ms.Write(byteInfo, 0, byteInfo.Length); ms.Position = 0; FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf"); //Uncomment this to return the file as a download //fileStreamResult.FileDownloadName = "Output.pdf"; return fileStreamResult; }
Source:
https://stackoverflow.com/questions/1510451/how-to-return-pdf-to-browser-in-mvc
Leave a Reply