【问题标题】:Printing pdf from asp.net mvc project从 asp.net mvc 项目打印 pdf
【发布时间】:2017-10-18 13:56:20
【问题描述】:

当我尝试生成 pdf 时;我得到了 pdf,但输入的数据没有显示在 pdf 文件中,而相同的信息被发送到数据库。我看到了该信息,但我不确定与 pdf 文件有关的问题可能是什么。而且我在不同的浏览器上都试过了,还是一样的。

更新

IssueDAO dbdata = new IssueDAO();
        dbdata.connectionString = ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ConnectionString;
        getIssue.transactionDate = DateTime.Now; //Sets the transaction date to current date
        getIssue.status = -1;
        Item item = new Item();
        try
        {
            dbdata.createIssue(getIssue, item);//Creates the issue in the database
        }
        catch (Exception ex)
        {
            LogWrite logWriter = new LogWrite(ex.ToString());
            ViewBag.errorMessage = "Unable to complete the Issue. Please see Log file for more Information";
            return View("IssueItem", getIssue);

        }


        DataSet ds = dbdata.GetReceipt(getIssue.requisitionNumber);
        LocalReport localreport = new LocalReport();
        localreport.ReportPath = Request.MapPath(Request.ApplicationPath) + @"Reports\Reciept.rdlc";
        localreport.DataSources.Add(new ReportDataSource("Receipt_Data", ds.Tables[0]));
        localreport.SetParameters(new ReportParameter("Req_num", getIssue.requisitionNumber));
        string reporttype = "PDF";
        string mimeType;
        string encoding;
        string fileNameExtension = "pdf";
        string deviceInfo = @"<DeviceInfo>              
                 <OutputFormat>PDF</OutputFormat>              
                 <PageWidth>8.5in</PageWidth>              
                 <PageHeight>11in</PageHeight>          
                 <MarginTop>0.25in</MarginTop>          
                 <MarginLeft>0.45in</MarginLeft>            
                 <MarginRight>0.45in</MarginRight>       
                 <MarginBottom>0.25in</MarginBottom></DeviceInfo>";
        Warning[] warnings;
        string[] streams;
        byte[] renderedBytes;
        renderedBytes = localreport.Render(
         reporttype, deviceInfo, out mimeType, out encoding, out fileNameExtension,
         out streams, out warnings);


        var doc = new iTextSharp.text.Document();
        var reader = new PdfReader(renderedBytes);
        using (FileStream fs = new FileStream(Server.MapPath("~/Receipt" +
             Convert.ToString(Session["CurrentUserName"]) + ".pdf"), FileMode.Create))
        {
            PdfStamper stamper = new PdfStamper(reader, fs);
            string Printer = "Xerox Phaser 3635MFP PCL6";
            // This is the script for automatically printing the pdf in acrobat viewer
            stamper.JavaScript = "var pp = getPrintParams();pp.interactive =pp.constants.interactionLevel.automatic; pp.printerName = " +
                           Printer + ";print(pp);\r";
            stamper.Close();
        }
        reader.Close();
        FileStream fss = new FileStream(Server.MapPath("~/Receipt.pdf"), FileMode.Open);
        byte[] bytes = new byte[fss.Length];
        fss.Read(bytes, 0, Convert.ToInt32(fss.Length));
        fss.Close();
        System.IO.File.Delete(Server.MapPath("~/Receipt.pdf"));

        //Here we returns the file result for view(PDF)
        ModelState.Clear();
        Session.Clear(); //Clears the session variable for reuse 
        return File(bytes, "application/pdf");
    }

【问题讨论】:

  • 你调试代码了吗?你检查ds.Tables[0]里面有没有数据?
  • 是的,它确实有数据。
  • 我已经停止使用 c# 来生成 excel 和 PDF ...客户端上的 JS 足以生成易于操作的文档..只需以某种方式将数据发送到客户端......然后做事跨度>
  • @Rohitas 最好举一些例子来说明在客户端使用什么来做到这一点。
  • @FarrukhSubhani 是的 :)

标签: c# asp.net asp.net-mvc pdf


【解决方案1】:

我对这个主题做了一些研究,我很好奇你为什么不为你在 using 语句中创建的 pdf 返回 FileStream。而不是尝试再次打开它然后发送字节?

我找到了这篇文章,也许这会有所帮助,因为它消除了对阅读器和一切的需求。看第一个答案。

    DataSet ds = dbdata.GetReceipt(getIssue.requisitionNumber);
    ReportDataSource reportDataSource = new ReportDataSource();
    reportDataSource.Value = ds.Tables[0];
    reportDataSource.Name = "Receipt_Data";
    LocalReport localreport = new LocalReport();
    localreport.ReportPath = Request.MapPath(Request.ApplicationPath) + @"Reports\Reciept.rdlc";
    localreport.DataSources.Add(reportDataSource);
    localreport.SetParameters(new ReportParameter("Req_num", getIssue.requisitionNumber));
    string reporttype = "PDF";
    string mimeType;
    string encoding;
    string fileNameExtension = "pdf";
    string deviceInfo = @"<DeviceInfo>              
             <OutputFormat>PDF</OutputFormat>              
             <PageWidth>8.5in</PageWidth>              
             <PageHeight>11in</PageHeight>          
             <MarginTop>0.25in</MarginTop>          
             <MarginLeft>0.45in</MarginLeft>            
             <MarginRight>0.45in</MarginRight>       
             <MarginBottom>0.25in</MarginBottom></DeviceInfo>";
    Warning[] warnings;
    string[] streams;
    byte[] renderedBytes;
    renderedBytes = localreport.Render(
     reporttype, deviceInfo, out mimeType, out encoding, out fileNameExtension,
     out streams, out warnings);


    var doc = new iTextSharp.text.Document();
    var reader = new PdfReader(renderedBytes);
    using (FileStream fs = new FileStream(Server.MapPath("~/Receipt" +
         Convert.ToString(Session["CurrentUserName"]) + ".pdf"), FileMode.Create))
    {
        PdfStamper stamper = new PdfStamper(reader, fs);
        string Printer = "Xerox Phaser 3635MFP PCL6";
        // This is the script for automatically printing the pdf in acrobat viewer
        stamper.JavaScript = "var pp = getPrintParams();pp.interactive =pp.constants.interactionLevel.automatic; pp.printerName = " +
                       Printer + ";print(pp);\r";
        stamper.Close();
    }
    reader.Close();
    FileStream fss = new FileStream(Server.MapPath("~/Receipt.pdf"), FileMode.Open);
    byte[] bytes = new byte[fss.Length];
    fss.Read(bytes, 0, Convert.ToInt32(fss.Length));
    fss.Close();
    System.IO.File.Delete(Server.MapPath("~/Receipt.pdf"));

    //Here we returns the file result for view(PDF)
    ModelState.Clear();
    Session.Clear(); //Clears the session variable for reuse 
    return File(bytes, "application/pdf");
}

Creating a PDF from a RDLC Report in the Background

Other good examples

【讨论】:

  • 评论不用于扩展讨论;这个对话是moved to chat
  • 对我来说还有什么凯尔
  • @LeonCharles 你用过这篇文章吗? codeproject.com/Tips/569335/…
  • 不,我没有,但感谢分享,但我看不出我做了什么不同
  • 嘿凯尔我真的很感谢你的帮助,即使你最终不是这个问题。
【解决方案2】:

!st 以某种方式将数据发送到客户端... Ajax , viewbag , session ..whatever

jsPDF 可以使用插件。为了使它能够打印 HTML,您必须包含某些插件,因此必须执行以下操作:

Go to https://github.com/MrRio/jsPDF and download the latest Version.
Include the following Scripts in your project:
jspdf.js
jspdf.plugin.from_html.js
jspdf.plugin.split_text_to_size.js
jspdf.plugin.standard_fonts_metrics.js

如果你想忽略某些元素,你必须用一个 ID 标记它们,然后你可以在 jsPDF 的特殊元素处理程序中忽略它。因此,您的 HTML 应如下所示:

*

<!DOCTYPE html>
<html>
  <body>
    <p id="ignorePDF">don't print this to pdf</p>
    <div>
      <p><font size="3" color="red">print this to pdf</font></p>
    </div>
  </body>
</html>

*

然后您使用以下 JavaScript 代码在弹出窗口中打开创建的 PDF:

var doc = new jsPDF();          
var elementHandler = {
  '#ignorePDF': function (element, renderer) {
    return true;
  }
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
    source,
    15,
    15,
    {
      'width': 180,'elementHandlers': elementHandler
    });

doc.output("dataurlnewwindow");

对我来说,这创建了一个漂亮而整洁的 PDF,其中仅包含“将其打印为 pdf”这一行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    相关资源
    最近更新 更多