使用ASP.NET生成.pdf [英] Using ASP.NET generate .pdf

查看:131
本文介绍了使用ASP.NET生成.pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如何在asp.net里面生成pdf文件pdf添加表格数据



我有什么试过:




how to generate pdf file in asp.net inside pdf add table with data

What I have tried:

Document pdfDoc = new Document();
          PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
          pdfDoc.Open();
          string strHTML = @" <div style='text-align: center; width: 80%'>
              ABC
          </div>
          <table border='1' style='border-spacing: 0; border-style: solid; border-width: thin; padding: 0; width: 80%; height: 100%'>
              <tr>
                  <td colspan='6' rowspan='2'>
                      <table>
                          <tr>
                              <td>@@@@@</td>
                          </tr>
                          <tr>
                              <td>@@@@@</td>
                          </tr>
                      </table>

                  </td>
                  <td colspan='2'>*************</td>
                  <td colspan='2'>*************</td>
              </tr>
              <tr>
                  <td colspan='2'>***</td>
                  <td colspan='2'>***</td>
              </tr>
              <tr>
                  <td colspan='6' rowspan='2'>
                      <table>
                          <tr>
                              <td>@@@@@</td>
                          </tr>
                          <tr>
                              <td>@@@@@</td>
                          </tr>
                      </table>
                  </td>
                  <td colspan='2'>***</td>
                  <td colspan='2'>***</td>
              </tr>
              <tr>
                  <td colspan='2'>***</td>
                  <td colspan='2'>***</td>
              </tr>
              <tr>
                  <td colspan='6'>***</td>
                  <td>***</td>
                  <td>***</td>
                  <td>***</td>
                  <td>***</td>
              </tr>
              <tr>
                  <td colspan='6' rowspan='5'>
                      <table>
                          <tr>
                              <td>@@@@@</td>
                          </tr>
                          <tr>
                              <td>@@@@@</td>
                          </tr>
                          <tr>
                              <td>@@@@@</td>
                          </tr>
                          <tr>
                              <td>@@@@@</td>
                          </tr>
                          <tr>
                              <td>@@@@@</td>
                          </tr>
                      </table>
                  </td>
                  <td>***</td>
                  <td>***</td>
                  <td>***</td>
                  <td>***</td>
              </tr>
              <tr>

                  <td>***</td>
                  <td>***</td>
                  <td>***</td>
                  <td>***</td>
              </tr>
              <tr>

                  <td>***</td>
                  <td>***</td>
                  <td>***</td>
                  <td>***</td>
              </tr>
              <tr>

                  <td>***</td>
                  <td>***</td>
                  <td>***</td>
                  <td>***</td>
              </tr>
              <tr>

                  <td>***</td>
                  <td>***</td>
                  <td>***</td>
                  <td>***</td>
              </tr>
              <tr>
                  <td colspan='6'>***</td>
                  <td colspan='3'>***</td>
                  <td>***</td>
              </tr>
              <tr>
                  <td colspan='10' rowspan='1'>***</td>
              </tr>
              <tr>
                  <td colspan='8' rowspan='4'>***</td>
              </tr>
              <tr>
                  <td colspan='2'>***</td>
              </tr>
          </table>
          <div style='text-align: center; width: 80%'>
              ABC
              <br />
              ABC
          </div>";
          HTMLWorker htmlWorker = new HTMLWorker(pdfDoc);
          htmlWorker.Parse(new StringReader(strHTML));
          pdfWriter.CloseStream = false;
          pdfDoc.Close();
          Response.Buffer = true;
          Response.ContentType = "application/pdf";
          Response.AddHeader("content-disposition", "attachment;filename=Test.pdf");
          Response.Cache.SetCacheability(HttpCacheability.NoCache);
          Response.Write(pdfDoc);
          Response.Flush();
          Response.End();

推荐答案

假设我有一个方法返回发票清单的业务层

Suppose I have a method in Business layer which returns invoice list
public DoctorInvoiceViewModel DoctorDisplayInvoice(int visitId)
{
    VisitDA visit = new VisitDA();
    DoctorInvoiceViewModel doctorInvoiceViewModel = new DoctorInvoiceViewModel();
    doctorInvoiceViewModel = visit.DoctorInvoiceDetails(visitId);
    return doctorInvoiceViewModel;
}





然后我们需要将此列表转换为PDF

In控制器我将这样写:



Then we need to convert this list to PDF
In controller I will write like this:

public ActionResult GeneratePdf()
        {
            try
            {
                int userId;
                int.TryParse((Session["userId"]).ToString(), out userId);
                VisitBL patient = new VisitBL();
                return View(patient.PatientDisplayVisit(userId));
            }
            catch (Exception)
            {
                return RedirectToAction("Error", "Home", new { area = "Main" });
            }      
        } 



在View中我们将编写用于生成PDF的代码。我正在使用iTextSharp生成PDF。




In View we will write the code for generating the PDF.Here I am using iTextSharp for generating PDF.

@model IEnumerable<Patient.Models.PatientVisitViewModel>
@using iTextSharp.text;
    @using iTextSharp.text.pdf;
@{
        Layout = null;
        
        Response.AddHeader("Content-disposition", "attachment; filename=report.pdf");
        Response.ContentType = "application/octet-stream";
        var doc = new Document();
        
        PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
        doc.SetPageSize(PageSize.A4.Rotate());
        var arial = FontFactory.GetFont("Arial", 12, Color.BLACK);
        var arialBold = FontFactory.GetFont("Arial", 14, Font.BOLD, Color.BLACK);
        doc.Open();
        try
        {
            PdfContentByte cb = writer.DirectContent;
            string imageURL = Server.MapPath(".") + "/image2.jpg";
            cb.BeginText();
            try
            {                
                cb.SetFontAndSize(BaseFont.CreateFont(), 14);
                cb.SetTextMatrix(200,350);
                var table = new PdfPTable(5)
                {
                    TotalWidth = 700f,
                    SpacingAfter = 12f,
                    LockedWidth = true,                    
                   SpacingBefore = 400f
                };
                PdfPCell cell = new PdfPCell(new Phrase("Your Visit Details are here! \n You can take a print out of this. Get Well Soon !!",
                        new Font(Font.HELVETICA, 18F)));
                cell.Colspan = 5;
                cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                //Style
                
                cell.Border = Rectangle.BOTTOM_BORDER; // | Rectangle.TOP_BORDER;
                cell.BorderWidthBottom = 3f;
                cell.PaddingBottom = 10f;
                table.AddCell(cell);
                
                table.HorizontalAlignment = 1;              
                
              
                    table.AddCell(new Phrase("Visit Name", arialBold));
                    table.AddCell(new Phrase("Visit Date", arialBold));
                    table.AddCell(new Phrase("Doctor Name", arialBold));
                    table.AddCell(new Phrase("Visit Details", arialBold));
                    table.AddCell(new Phrase("Total Amount", arialBold));
               
                foreach (var item in Model)
                {
                    table.AddCell(new Phrase(item.VisitName.ToString(), arial));
                    table.AddCell(new Phrase(item.VisitDate.ToString(), arial));
                    table.AddCell(new Phrase(item.DoctorName, arial));
                    table.AddCell(new Phrase(item.VisitDetails.ToString(), arial));
                    table.AddCell(new Phrase("₹ " + item.TotalAmount.ToString(), arial));
                  
                }
             
                doc.Add(table);
                
            }
            finally
            {
                cb.EndText();
            }

        }
        finally
        {
            doc.Close();
            writer.Close();
           
        }
           

    }


我创建pdf输出文件的方式是首先创建MS Word模板文件,然后以编程方式使用数据填充它并将其另存为pdf。



Word模板文件包含数据的所有必要格式和placehoders。在运行时,这个模板充满了数据。



幕后我正在使用第三方库。准备好模板文件后,.NET应用程序会引入数据(作为.NET对象)。



在两行代码中创建pdf文档:< br $>


The way that I am creating pdf output files is by creating MS Word template file first and then populating it programmatically with data and saving it as pdf.

Word template file contains all the necessary formatting and placehoders for the data. At runtime this template is filled with data.

Behind the scenes I am using a 3rd party library. Once the template file is prepared then a .NET application brings in the data (as .NET objects).

In two lines of code the pdf document is created:

DocumentGenerator dg = new DocumentGenerator(customer);
DocumentGenerationResult result = dg.GenerateDocument("MyTemplate.docx", "MyReport.pdf");





如果我想要一个docx或xps文档,我只是使用该文件扩展名,输出文档将分别采用该格式。



该库基于OpenXML,文档生成可以可以在服务器上完成,无需安装MS Office或安装某种PDF编写器。如果您觉得这很有趣,请参阅此处的更多示例。


这篇关于使用ASP.NET生成.pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆