首页 > 解决方案 > 在内存流中打开 PDF 时是否可以打印 PDF?

问题描述

当在 memorystram 中打开时,它可能打开打印对话框?实际上,我将 pdf 保存在“~/App_Data/Rep_PDF/”中,然后在 iframe 中显示 pdf,但我不能这样做,因为我收到一条消息:

“不允许加载本地资源:file:///C:/Users/andres.martinez/Documents/TFS%20Monterrey%20Gob/InterfaceMonterrey%20PROD/Interface%20Monterrey%20PROD/InterfaceMonterrey/App_Data/Rep_PDF/Copia_C_Administrativa%2030- 04-2019.pdf"

你能帮我如何在asp mvc中打印pdf吗?

这是我的代码的一部分:

 public ActionResult ImprimeReporte()
    {
        //Indicamos donde vamos a guardar el documento
        string directorioRaiz = "~/App_Data/Rep_PDF/";
        string NombreArchivoPDF = "C_Administrativa " + DateTime.Today.ToString("dd-MM-yyyy") + ".pdf";
        string path_Original=Server.MapPath(directorioRaiz+NombreArchivoPDF);
        string path_Copia = Server.MapPath(directorioRaiz + "Copia_"+NombreArchivoPDF);

        if (System.IO.File.Exists(path_Original))
        {
            //SI EXISTE EL ARCHIVO EN LA CARPETA, LO MANDA A IMPRIMIR
            Inicia_PrintScript(path_Original, path_Copia);
            ViewData["path_Copia"] = path_Copia;
            //Elimina los archivos , despues de que se imprimio
            // System.IO.File.Delete(path_Original);
            //System.IO.File.Delete(path_Copia);
        }
        else
        {
            //SI NO EXISTE MANDA LLAMAR AL METODO PARA DESCARGAR EL ARCHIVO Y DESPUES IMPRIMIRLO
            Genera_Pdf_Administrativo();
            Inicia_PrintScript(path_Original, path_Copia);
            ViewData["path_Copia"] = path_Copia;
            //Elimina los archivos , despues de que se imprimio
            //System.IO.File.Delete(path_Original);
            //System.IO.File.Delete(path_Copia);
        }
        return View();
    }

第二部分

public static void Inicia_PrintScript(string Original, string Copia)
    {
        PdfReader reader = new PdfReader(Original);
        PdfStamper stamper = new PdfStamper(reader, new FileStream(Copia, FileMode.Create));
        AcroFields fields = stamper.AcroFields;
        stamper.JavaScript = "this.print(true);\r";
        stamper.FormFlattening = true;
        stamper.Close();
        reader.Close();

看法

<iframe src="@ViewData["path_Copia"].ToString()" id="myFrame" frameborder="0" style="border:0;" width="700" height="300"></iframe>

标签: c#htmlasp.net-mvcpdfprinting

解决方案


好吧,可以在另一个选项卡中打开带有打印对话框的 PDF。

在您的控制器中,您需要在内存中获取文件以返回它,或者动态生成文件。

public FileResult PDFToReturn()
{
    string filePath = Server.MapPath("Path_to_PDF");
    return File(System.IO.File.ReadAllBytes(filePath), System.Web.MimeMapping.GetMimeMapping(filePath));
}

javascript 具有魔力。

function printPDF() {
    let link = 'javascript:w=window.open("/Controller/PDFToReturn"); w.print();';
    location.href = link;
}

推荐阅读