0

How can I specify the download location of the converted pdf in the server?

When I run in the server I want to save the pdf in server files but I don't know how can I manipulate the memory stream or how to do it.

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
using System.IO;
using Microsoft.AspNetCore.Hosting;

namespace HospitalQR.Web.Controllers
{
    public class FormController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        public FormController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
        public IActionResult Index()
        {
            return View("PreForm");
        }

        public IActionResult PdfConverter()
        {
            HtmlToPdfConverter converter = new HtmlToPdfConverter();

            WebKitConverterSettings settings = new WebKitConverterSettings();
            settings.WebKitPath = Path.Combine(_hostingEnvironment.ContentRootPath, "QtBinariesWindows");
            converter.ConverterSettings = settings;

            PdfDocument document = converter.Convert("https://localhost:44334/form");

            MemoryStream ms = new MemoryStream();
            document.Save(ms);
            document.Close(true);

            ms.Position = 0;

            FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
            fileStreamResult.FileDownloadName = "PreForm.pdf";

            return fileStreamResult;
        }
    }
}

1 Answers1

0

By default, it will automatically save the downloaded file in your browser location. We could not able set the defined path in an ASP NET Core Web application and download it from the browser. If you want the save the pdf in a defined path, please change the browser path setting to that predefined path.

However, if you want to save the PDF document in your “wwwroot” location, please refer the below code snippet,

//Initialize HTML to PDF converter with WebKit rendering engine
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.WebKit);
WebKitConverterSettings settings = new WebKitConverterSettings();
//Set the QtBinaries folder path 
settings.WebKitPath= Path.Combine(_hostingEnvironment.ContentRootPath, "QtBinariesWindows");
//Assign WebKit settings to HTML converter
htmlConverter.ConverterSettings = settings;
//Convert URL to PDF
PdfDocument document = htmlConverter.Convert("https://www.google.com");
string path = _hostingEnvironment.ContentRootPath+ "\\wwwroot\\output.pdf";
FileStream file = new FileStream(path,FileMode.Create, FileAccess.Write);
document.Save(file);
document.Close(true);

Please try the above solution on your end and let us know if it suits your requirement.

Note: I work for Syncfusion.

Dharman
  • 30,962
  • 25
  • 85
  • 135
gowtham raj
  • 187
  • 2