如何将视图中的数据提取到pdf文件asp.net mvc

时间:2017-10-30 14:01:37

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

我遇到了这个问题;我有一个视图,我希望信息在pdf文件上。我写了一个存储过程和一个函数;但是,视图上的数据未显示在pdf文件中。除了编写存储过程,我如何在pdf文件上显示数据。

查看

 <dt>
        @Html.DisplayNameFor(model => model.docType)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.docType)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.requisitionNumber)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.requisitionNumber)
    </dd>

生成pdf的功能

public ActionResult ReceiptPrint(Issue issue)
    {
        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.unpostedtransactionList();
        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>       
                 <M

arginBottom>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"));
            return File(bytes, "application/pdf");

        }


    public DataSet GetReceipt(string req_num)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand command = new SqlCommand();
            command.CommandText = "issue_sp_getreceipt";
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("@reqnum", SqlDbType.VarChar).Value = req_num;
            command.Connection = connection;
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            DataSet ds = new DataSet("Receipt");

            try
            {
                connection.Open();
                adapter.Fill(ds);
            }
            catch (Exception ex)
            {

                throw ex;
            }


            return ds;
        }


    ALTER PROCEDURE [dbo].[issue_sp_getreceipt] 

    @reqnum varchar (16)
    AS
    BEGIN
    SET NOCOUNT ON;

    SELECT empiitem.*, b.ACTNUMBR_1+ '-' +b.ACTNUMBR_2 + '/' + b.ACTDESCR [Expense_Account], c.ACTNUMBR_1+ '-' +c.ACTNUMBR_2 + '/' + c.ACTDESCR [Inventory_Account], 
                empiitem.CURRCOST*quantity [extended_Cost]
    FROM 
        (
            SELECT empdata.*, b.ITEMDESC  from
            (   
                Select *
                from 
                (Select Right(a.doc_num,12) [receipt_num], a.requisition_num, a.department, ab.expense_acc, a.inventory_acc_indx, a.issuer_id, ab.itemnum, ab.quantity, a.trans_date,
                        b.emp_firstname as [deptrepfname], b.emp_lastname [deptreplname], c.emp_firstname [Issuerfname],c.emp_lastname [Issurelname], ab.cost [CURRCOST], ab.uofm 
                    from [dbo].Issue a Inner Join dbo.IssueItem ab
                    on a.doc_num= ab.doc_num Left Outer Join [dbo].[Employee] b
                             on cast(a.dept_rep_id as int) = b.employee_id
                             Left join Employee c
                             on cast(a.issuer_id as int)= c.employee_id
                             where doc_type = 'Issue'
                ) as emp
            ) empdata 
            Inner Join [TWCL].[dbo].[IV00101] b
                on empdata.itemnum = b.ITEMNMBR
        ) empiitem 
        Inner Join [TWCL].[dbo].[GL00100] b
            on empiitem.expense_acc = b.ACTINDX
        Inner Join [TWCL].[dbo].[GL00100] c 
            on empiitem.inventory_acc_indx = c.ACTINDX
    WHERE requisition_num  = @reqnum



END 

1 个答案:

答案 0 :(得分:0)

不幸的是,没有内置的方法可以轻松地将项目插入到文档中。我开发了许多具有类似要求的项目(将值插入PDF)。最简单的方法是通过Nuget包管理器使用Aspose框架。将Aspose添加到项目后,您只需用PDF替换PDF中的书签即可。

        Aspose.Words.License awLic = new Aspose.Words.License();
        Document doc = new Aspose.Words.Document(templateLocation);

        foreach (Bookmark bk in doc.Range.Bookmarks)
        {
            if(bk.exists())
            {                    
                bk.Text = q.answer;
            }
        }

        doc.Save(outPutLocation, SaveFormat.PDF);