gpt4 book ai didi

asp.net-mvc - RazorPDF将pdf文件保存到MVC4中的服务器目录

转载 作者:行者123 更新时间:2023-12-01 19:00:03 26 4
gpt4 key购买 nike

我目前正在 MVC4 中使用 RazorPDF 组装和显示 PDF,并希望在返回 View 的同时将 PDF 文件保存到文件系统。

Controller 操作中的以下代码行正在调用 View :

return new PdfResult(claims, "PDF");

最佳答案

通过更改 RazorPDF 渲染方法的代码库,我最终能够将 pdf 写入目录系统。 Rendor 方法创建一个与响应流关联的 PdfWriter 对象:

        // Associate output with response stream
var pdfWriter = PdfWriter.GetInstance(document, viewContext.HttpContext.Response.OutputStream);
pdfWriter.CloseStream = false;

解决方案是创建另一个与 FileStream 对象关联的 PdfWriter 对象,如下所示:

        // Create the pdf file in the directory system
var fileStream = new FileStream(myPdfFilePath, FileMode.Create);
var pdfWriter2 = PdfWriter.GetInstance(document, fileStream);

然后我关闭了对象:

        fileStream.Close();

pdfWriter.Close();
pdfWriter2.Close();

我必须将 RazorPDF 的 PdfResult 和 PdfView 类合并到我自己的项目中,并显着更改代码。原因是因为我还必须合并对将 pdf 发送给用户的电子邮件类的调用。

完整的渲染方法如下所示:

    public void Render(ViewContext viewContext, TextWriter writer)
{
// generate view into string
var sb = new System.Text.StringBuilder();
TextWriter tw = new System.IO.StringWriter(sb);
myResult.View.Render(viewContext, tw);
var resultCache = sb.ToString();

// detect itext (or html) format of response
XmlParser parser;
using (var reader = GetXmlReader(resultCache))
{
while (reader.Read() && reader.NodeType != XmlNodeType.Element)
{
// no-op
}

if (reader.NodeType == XmlNodeType.Element && reader.Name == "itext")
parser = new XmlParser();
else
parser = new HtmlParser();
}

// Create a document processing context
var document = new Document();
document.Open();

// Associate output with response stream
var pdfWriter = PdfWriter.GetInstance(document, viewContext.HttpContext.Response.OutputStream);
pdfWriter.CloseStream = false;

// Create the pdf file in the directory system
var fileStream = new FileStream(myPdfFilePath, FileMode.Create);
var pdfWriter2 = PdfWriter.GetInstance(document, fileStream);

// this is as close as we can get to being "success" before writing output
// so set the content type now
viewContext.HttpContext.Response.ContentType = "application/pdf";

// parse memory through document into output
using (var reader = GetXmlReader(resultCache))
{
parser.Go(document, reader);
}

fileStream.Close();

// Send an email to the claimant
Thread.Sleep(100);
if (File.Exists(myPdfFilePath))
{
var subject = "PDF Documents";

var body = Config.GetContent(ContentParams.CLAIM_DOCUMENT_EMAIL_BODY_TEXT);

bool success;
string errorMessage;

Email.Send(myEmailAddress, subject, body, out success, out errorMessage, myPdfFilePath);
}

pdfWriter.Close();
pdfWriter2.Close();

}

如果将此功能以某种方式合并到当前的 RazorPDF 项目中,那就太好了。

关于asp.net-mvc - RazorPDF将pdf文件保存到MVC4中的服务器目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18153340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com