如何指定pdf的下载位置?

问题描述

如何指定转换后的pdf在服务器中的下载位置?

当我在服务器中运行时,我想将 pdf 保存在服务器文件中,但我不知道如何操作内存流或如何操作。

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;
        }
    }
}

解决方法

默认情况下,它会自动将下载的文件保存在您的浏览器位置。我们无法在 ASP NET Core Web 应用程序中设置定义的路径并从浏览器下载它。如果要将pdf保存在定义的路径中,请将浏览器路径设置更改为该预定义路径。

但是,如果您想将 PDF 文档保存在您的“wwwroot”位置,请参考以下代码片段,

//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);

请在您的一端尝试上述解决方案,并告诉我们它是否符合您的要求。

注意:我为 Syncfusion 工作。

问候,

高谭

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...