0

如何在服务器中指定转换后的 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;
        }
    }
}
4

1 回答 1

0

默认情况下,它会自动将下载的文件保存在您的浏览器位置。我们无法在 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 工作。

于 2021-03-29T10:22:01.473 回答