Hi again,
For my project i need to generate some dynamic pdf files, so the user can download them. I dont want to store them on disk, so i put code like this in my HomeController:
public class HomeController : MySpaControllerBase
{
IMyEntryAppService _myEntryService;
public HomeController(IMyEntryAppService myEntryService)
{
_myEntryService= myEntryService;
}
public void GetFile(long id)
{
EntryDto entry= _myEntryService.GetEntry(id);
using (MemoryStream workStream = new MemoryStream())
{
PdfDocument doc = new PdfDocument();
doc.Info.Title = "Created with PDFsharp";
// Create an empty page
PdfPage page = doc.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
// Draw the text
gfx.DrawString(entry.SomeProperty, font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
doc.Save(workStream);
byte[] byteInfo = workStream.ToArray();
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "attachment; filename= " + Server.HtmlEncode("MyGeneratedFile.pdf"));
Response.ContentType = "APPLICATION/pdf";
Response.BinaryWrite(byteInfo);
doc.Close();
}
}
}
I feel this code doesnt belong there and would fit better in the MyEntryAppService. Is there a way to manipulate the ResponseHeader of the AppService response like in the controller or is there even a cleaner solution to achieve the dynamic file generation/download?
Kind Regards, Sebastian
4 Answer(s)
-
0
Hi,
I prefer to generate PDF/EXCEL on application service. Thus, it become re-usable and independed from UI frameworks. I generate it and save it to harddisk, then return a token (say name of the file as a guid) to client. Then client makes a second request to a generic file download controller with this token and downloads file (this file controller deletes file after download). If you definetely dont want to even temporary use harddisk, you can hold file in memory temporary in a cache.
-
0
So, related to previous answer; Is it best to use a separate file controller to manage files to download a zip file like your previous response, or create an webAPI whith a custom http response ? (if it's even possible)
thks !
my goal is to click, create file, and give it to download on frontend. I can store it temporary on disk if necessary, but i'll go for the memory only solution.
-
0
I'm trying to generate a dynamic pdf file and returns a HttpResponseMessage, but the ABP don't return all informations(i.e. content)
How to return a dynamic pdf like using only HttpResponseMessage without any hard disck thecnique?
-
0
You can create an MVC controller action and return FileResult.