如何在服务器上保存Rotativa PDF

时间:2014-10-28 12:45:28

标签: asp.net-mvc-5 rotativa

我正在使用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 个答案:

答案 0 :(得分:15)

你可以尝试一下

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

如果那样做不起作用,你可以按照here

的答案

只要确保你这样做就不要让PRVRequestPdf作为PDF视图返回,而不是像上面那样普通的视图(只提到我自己犯了很多错误)

答案 1 :(得分:8)

另一个有用的答案:

我找到了解决方案here

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

这是原始thread

答案 2 :(得分: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;
    }
}

答案 3 :(得分:0)

您可以尝试以下操作:

var fileName = string.Format("my_file_{0}.pdf", id);
var path = Server.MapPath("~/App_Data/" + fileName);
System.IO.File.WriteAllBytes(path, pdfByteArray );