[MVC ASP .NET-生成PDF文件

问题描述 投票:1回答:2

我在MVC 4和ASP.NET中有一个C#应用程序。

我想做的是在剃刀视图中按下一个按钮,将模型发送到控制器。在这里,我想创建一个pdf文件并将其返回到视图。然后,用户可以在其浏览器中保存或打开pdf。我不想仅将文件保存在服务器上。

我已经尝试过google来查找此示例。 iTextSharp带来了很多东西。但是我找不到任何能很好地说明我需要的代码示例。

将根据模型中的数据创建pdf。我将需要更改字体和字体大小,并将它们恰好放在我想要的pdf文件中。我还需要在顶部或底部放置一些照片(徽标)。

也将有一个按钮将文件发送到此人的电子邮件。如果我可以重用一些代码,那就太好了。

任何人都没有任何库或执行此操作的示例吗?

预先谢谢。

编辑:经过大量的搜索,我找到了一个可以简化为我可以使用的示例。我只尝试了一行文本,但是我认为我可以在此基础上获得所需的东西。我至少能够更改字体。现在,我必须查看是否可以将内容准确放置在想要的位置。这是创建用户可以保存在设备上的文件的代码:

    public ActionResult CreatePdf()
    {
        MemoryStream workStream = new MemoryStream();
        Document doc = new Document(PageSize.A4);
        PdfWriter.GetInstance(doc, workStream).CloseStream = false;
        doc.Open();

        Paragraph p = new Paragraph("This is a text in my file");

        doc.Add(p);
        doc.Close();

        byte[] byteInfo = workStream.ToArray();
        workStream.Write(byteInfo, 0, byteInfo.Length);
        workStream.Position = 0;

        return File(byteInfo, "application/pdf", "file.pdf");
    }
asp.net-mvc pdf-generation itextsharp
2个回答
0
投票

我不清楚您实际上想要实现什么,但是我要做的是使用表进行格式化,并相应地在单元格中添加内容。如果桌子不可见,那么我就隐藏了边框。您可以在此处找到有关此内容的教程:http://www.mikesdotnetting.com/article/86/itextsharp-introducing-tables


0
投票

[我认为您的要求是单击按钮,您想返回具有不同字体,自己的样式并需要定义徽标的PDF(无需保存在服务器中的创建/打开PDF文件)。[在此处输入图像描述] [1]如果要定义徽标,请使用徽标块。

    The best solution is using iTextSharp pdf tools.Its a free tool.
    1)First initialize nuget packages.
     itextsharp and itextsharp.xmlworker.
    2)Define namespaces 
    using System.Text.RegularExpressions;
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    3)Start creating PDF file coding.
     public ActionResult GetEmployeeListPDF()
            {
                MemoryStream workStream = new MemoryStream();
                //file name to be created   
                string PDFFileName = string.Format("EmployesList.pdf");
                Document doc = new Document();
                //Create PDF Table with 4 columns  
                PdfPTable tableLayout = new PdfPTable(4);
                //Create PDF Table  
                //file will created in this path  
                PdfWriter writerms = PdfWriter.GetInstance(doc, workStream);
                writerms.CloseStream = false;
                doc.Open();
                //We have option to assign titles logos /images any thing
                BaseFont f_cb = BaseFont.CreateFont("c:\\windows\\fonts\\calibrib.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                PdfContentByte cb = writerms.DirectContent;
                cb.BeginText();
                cb.SetFontAndSize(f_cb, 16);
                string text = "XYZ PVT. LTD";
                cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, text, 280, 770, 0);
                cb.EndText();
                cb.SetLineWidth(0.5f);   // Make a bit thicker than 1.0 default
                cb.MoveTo(0, 755);
                cb.LineTo(750, 755);
                cb.SetRGBColorStroke(0, 0, 0);
                cb.Stroke();
                //Here if we want to define logo ,use this block
                //var logoPath = Server.MapPath("~/logo.jpg");
                //iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(logoPath);
                //png.SetAbsolutePosition(150, 950);
                //png.ScaleAbsolute(250, 70);
                //png.PaddingTop = 0;
                //doc.Add(png);
                //Add Content to PDF   
                doc.Add(Add_Content_To_PDF(tableLayout));
                // Closing the document  
                doc.Close();
                byte[] byteInfo = workStream.ToArray();
                workStream.Write(byteInfo, 0, byteInfo.Length);
                workStream.Position = 0;
                return File(workStream, "application/pdf", PDFFileName);
            }
            protected PdfPTable Add_Content_To_PDF(PdfPTable tableLayout)
            {
                float[] headers = { 30, 30, 30, 15 }; //Header Widths  
                tableLayout.SetWidths(headers); //Set the pdf headers  
                tableLayout.WidthPercentage = 100; //Set the PDF File witdh percentage  
                //Add Title to the PDF file at the top
                tableLayout.AddCell(new PdfPCell(new Phrase(" ", new Font(Font.FontFamily.HELVETICA, 10, 1, new iTextSharp.text.BaseColor(153, 51, 0)))) { Colspan = 6, Border = 0, PaddingBottom = 0, PaddingTop = 45, HorizontalAlignment = Element.ALIGN_CENTER });
                ////Add header  
                //tableLayout.SpacingBefore = 250f;
                //If you want add any spaces ,margings or padding any styles before header you can add here.
                //AddCellHeader function defining for common styles we written methos other wise you candefine heades directly here it self like
                AddCellToHeader(tableLayout, "Name");
                AddCellToHeader(tableLayout, "Phone No");
                AddCellToHeader(tableLayout, "Gender");
                AddCellToHeader(tableLayout, "Sal");

                var date = DateTime.Now.ToString("dd-MM-yyyy");
                ////Add body  
                //List<EmployeeList> EmployeeList = GetEmployeeList();Fetch list of employees from database then pass that list in layout body.
                //foreach (var emp in EmployeeList)
                //{
                //    AddCellToBody(tableLayout, emp.Name);
                //    AddCellToBody(tableLayout, emp.Phone);
                //    AddCellToBody(tableLayout, emp.Gender);
                //    AddCellToBody(tableLayout, emp.Sal);
                //}
                //Just for understanding I AMBModular hardcoding 
                AddCellToBody(tableLayout,"ABC");
                AddCellToBody(tableLayout, "9999999999");
                AddCellToBody(tableLayout, "Male");
                AddCellToBody(tableLayout, "20000");
                AddCellToBody(tableLayout, "def");
                AddCellToBody(tableLayout, "9999999999");
                AddCellToBody(tableLayout, "Male");
                AddCellToBody(tableLayout, "35000");
                AddCellToBody(tableLayout, "xys");
                AddCellToBody(tableLayout, "9999999999");
                AddCellToBody(tableLayout, "Female");
                AddCellToBody(tableLayout, "50000");
                tableLayout.AddCell(new PdfPCell(new Phrase("Total Sal Amount", new Font(Font.FontFamily.HELVETICA, 7, 1, iTextSharp.text.BaseColor.BLACK))) { HorizontalAlignment = Element.ALIGN_CENTER, Padding = 3, BackgroundColor = new iTextSharp.text.BaseColor(211, 211, 211),Colspan=3 });
                tableLayout.AddCell(new PdfPCell(new Phrase("1,05,000", new Font(Font.FontFamily.HELVETICA, 7, 1, iTextSharp.text.BaseColor.BLACK))) { HorizontalAlignment = Element.ALIGN_CENTER, Padding = 3, BackgroundColor = new iTextSharp.text.BaseColor(211, 211, 211) });
                return tableLayout;
            }

            // Method to add single cell to the Header  
            private static void AddCellToHeader(PdfPTable tableLayout, string cellText)
            {
                tableLayout.AddCell(new PdfPCell(new Phrase(cellText, new Font(Font.FontFamily.HELVETICA, 7, 1, iTextSharp.text.BaseColor.BLACK))) { HorizontalAlignment = Element.ALIGN_CENTER, Padding = 3, BackgroundColor = new iTextSharp.text.BaseColor(211, 211, 211) });//if you want to define any colspan to our table.we need to write same methos with different name and define colspan or row span anything.
            }
            // Method to add single cell to the body  
            private static void AddCellToBody(PdfPTable tableLayout, string cellText)
            {
                tableLayout.AddCell(new PdfPCell(new Phrase(cellText, new Font(Font.FontFamily.HELVETICA, 7, 1, iTextSharp.text.BaseColor.BLACK))) { HorizontalAlignment = Element.ALIGN_CENTER, Padding = 3, BackgroundColor = iTextSharp.text.BaseColor.WHITE });//if you want to define any colspan to our table.we need to write same methos with different name and define colspan or row span anything.
            }



  [1]: https://i.stack.imgur.com/Io2lO.jpg
© www.soinside.com 2019 - 2024. All rights reserved.