如何在服务器上保存 Rotativa PDF

10

我正在使用Rotativa在我的"MVC"应用程序中生成PDF。如何保存Rotativa生成的PDF?在所有过程完成后,我需要将文档保存在服务器上。

下面是代码:

public ActionResult PRVRequestPdf(string refnum,string emid)
{
    var prv = functions.getprvrequest(refnum, emid);            
    return View(prv);

}
public ActionResult PDFPRVRequest()
{
    var prv = Session["PRV"] as PRVRequestModel;
    byte[] pdfByteArray = Rotativa.WkhtmltopdfDriver.ConvertHtml("Rotativa", "Approver", "PRVRequestPdf");
    return new Rotativa.ViewAsPdf("PRVRequestPdf", new { refnum = prv.rheader.request.Referenceno });            

} 
4个回答

20

你可以试一试

var actionResult = new ActionAsPdf("PRVRequestPdf", new { refnum = prv.rheader.request.Referenceno, emid = "Whatever this is" });
var byteArray = actionResult.BuildPdf(ControllerContext);
var fileStream = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
fileStream.Write(byteArray, 0, byteArray.Length);
fileStream.Close();
如果这样做还不行,那么你可以按照这里的答案进行操作。只需确保以这种方式执行时,PRVRequestPdf不返回PDF视图,而是像上面一样返回普通视图(要注意,如果不这样做,可能会遇到麻烦)。

11

另一个有用的答案:

我在这里找到了解决方案(链接)

            var actionPDF = new Rotativa.ActionAsPdf("YOUR_ACTION_Method", new { id = ID, lang = strLang } //some route values)
            {
                //FileName = "TestView.pdf",
                PageSize = Size.A4,
                PageOrientation = Rotativa.Options.Orientation.Landscape,
                PageMargins = { Left = 1, Right = 1 }
            };
            byte[] applicationPDFData = actionPDF.BuildPdf(ControllerContext);

这是原始的帖子


此解决方案也使用了Daniel的答案。 - meJustAndrew
@meJustAndrew 是的,我知道,这就是为什么我在我的答案第一行引用了他的答案。 - Ibrahim Amer

3
您可以通过使用 ViewAsPdf 实现此功能。
[HttpGet]
public ActionResult SaveAsPdf(string refnum, string emid)
{
    try
    {
        var prv = functions.getprvrequest(refnum, emid);
        ViewAsPdf pdf = new Rotativa.ViewAsPdf("PRVRequestPdf", prv)
        {
            FileName = "Test.pdf",
            CustomSwitches = "--page-offset 0 --footer-center [page] --footer-font-size 8"
        };
        byte[] pdfData = pdf.BuildFile(ControllerContext);
        string fullPath = @"\\server\network\path\pdfs\" + pdf.FileName;
        using (var fileStream = new FileStream(fullPath, FileMode.Create, FileAccess.Write))
        {
            fileStream.Write(pdfData, 0, pdfData.Length);
        }
        return Json(new { isSuccessful = true }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        //TODO: ADD LOGGING
        return Json(new { isSuccessful = false, error  = "Uh oh!" }, JsonRequestBehavior.AllowGet);
        //throw;
    }
}

0
你可以简单地尝试这个:
var fileName = string.Format("my_file_{0}.pdf", id);
var path = Server.MapPath("~/App_Data/" + fileName);
System.IO.File.WriteAllBytes(path, pdfByteArray );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接