【问题标题】:MVC ASP .NET - Generating PDF fileMVC ASP .NET - 生成 PDF 文件
【发布时间】:2015-07-08 18:00:36
【问题描述】:

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

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

我已经尝试在谷歌上找到这方面的例子。出现很多的东西是 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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我认为您的要求是单击按钮以返回具有不同字体、自己的样式并需要定义徽标的 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
    

    【讨论】:

      猜你喜欢
      • 2017-02-07
      • 1970-01-01
      • 2018-05-12
      • 2010-12-18
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 2010-11-17
      • 2015-05-08
      相关资源
      最近更新 更多