2014-02-01 14 views
3

Im работает в проекте, который требует текущей HTML-страницы для преобразования в pdf и что файл pdf будет автоматически сохранен при нажатии кнопки на сервере, и его ссылка будет сохранена в базе данных. Я могу преобразовать просмотрите, если его данные поступают из базы данных, но данные в этой форме являются статическими, что означает, что в представлении есть так много переключателей и текстового поля, в которых я могу написать подробную информацию и установить флажок после нажатия кнопки сохранения, это сэкономит на сервере, и его ссылка будет сохранена в базе данных.Преобразование HTML в PDF в ASP.NET MVC

Причина в том, что im не сохраняет данные в базе данных, так это то, что отчет меньше используется для клиента, но если я сохраню данные в базе данных, тогда база данных станет очень огромной и станет сложной для обработки. потому что отчет содержит около 100 полей. , пожалуйста, если кто-нибудь может мне помочь.

ответ

2

Существует специальный пакет nuget RazorPDF. Это простые работы. RazorPDF site

1

Существует ряд конвертеров html в pdf для .NET, доступных там. Я могу рекомендовать ExpertPdf (www.html-to-pdf.net).

код выглядит примерно так:

PdfConverter pdfConverter = new PdfConverter(); 

pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; 
byte[] downloadBytes = pdfConverter.GetPdfFromUrlBytes(url); 

Там есть онлайн демо здесь: http://www.html-to-pdf.net/free-online-pdf-converter.aspx

+2

$ 550 лицензии разработчика – Junto

3

Короче:

HTML Renderer for PDF using PdfSharp

public static Byte[] PdfSharpConvert(String html) 
    { 
     Byte[] res = null; 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4); 
      pdf.Save(ms); 
      res = ms.ToArray(); 
     } 
     return res; 
    } 

More Detailed Answer

2

Код C#, приведенный ниже, может использоваться в приложении MVC для преобразования текущего представления в PDF и создания PDF-файла в буфере, который может быть сохранен на сервере или отправлен в браузер для загрузки. Код используется evopdf library for .net для выполнения HTML для преобразования PDF:

[HttpPost] 
public ActionResult ConvertCurrentPageToPdf(FormCollection collection) 
{ 
    object model = null; 
    ViewDataDictionary viewData = new ViewDataDictionary(model); 

    // The string writer where to render the HTML code of the view 
    StringWriter stringWriter = new StringWriter(); 

    // Render the Index view in a HTML string 
    ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, "Index", null); 
    ViewContext viewContext = new ViewContext(
      ControllerContext, 
      viewResult.View, 
      viewData, 
      new TempDataDictionary(), 
      stringWriter 
      ); 
    viewResult.View.Render(viewContext, stringWriter); 

    // Get the view HTML string 
    string htmlToConvert = stringWriter.ToString(); 

    // Get the base URL 
    String currentPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri; 
    String baseUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Convert_Current_Page/ConvertCurrentPageToPdf".Length); 

    // Create a HTML to PDF converter object with default settings 
    HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); 

    // Convert the HTML string to a PDF document in a memory buffer 
    byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlToConvert, baseUrl); 

    // Send the PDF file to browser 
    FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf"); 
    fileResult.FileDownloadName = "Convert_Current_Page.pdf"; 

    return fileResult; 
} 
4

Вы можете использовать Free HTML в PDF конвертер из SelectPdf (http://selectpdf.com/community-edition/).

код для MVC выглядит следующим образом:

[HttpPost] 
public ActionResult Convert(FormCollection collection) 
{ 
    // read parameters from the webpage 
    string url = collection["TxtUrl"]; 

    string pdf_page_size = collection["DdlPageSize"]; 
    PdfPageSize pageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), pdf_page_size, true); 

    string pdf_orientation = collection["DdlPageOrientation"]; 
    PdfPageOrientation pdfOrientation = (PdfPageOrientation)Enum.Parse(
     typeof(PdfPageOrientation), pdf_orientation, true); 

    int webPageWidth = 1024; 
    try 
    { 
     webPageWidth = System.Convert.ToInt32(collection["TxtWidth"]); 
    } 
    catch { } 

    int webPageHeight = 0; 
    try 
    { 
     webPageHeight = System.Convert.ToInt32(collection["TxtHeight"]); 
    } 
    catch { } 

    // instantiate a html to pdf converter object 
    HtmlToPdf converter = new HtmlToPdf(); 

    // set converter options 
    converter.Options.PdfPageSize = pageSize; 
    converter.Options.PdfPageOrientation = pdfOrientation; 
    converter.Options.WebPageWidth = webPageWidth; 
    converter.Options.WebPageHeight = webPageHeight; 

    // create a new pdf document converting an url 
    PdfDocument doc = converter.ConvertUrl(url); 

    // save pdf document 
    byte[] pdf = doc.Save(); 

    // close pdf document 
    doc.Close(); 

    // return resulted pdf document 
    FileResult fileResult = new FileContentResult(pdf, "application/pdf"); 
    fileResult.FileDownloadName = "Document.pdf"; 
    return fileResult; 
} 

VB.NET MVC версию кода можно найти здесь: http://selectpdf.com/convert-from-html-to-pdf-in-asp-net-mvc-csharp-and-vb-net/

1

Используйте ABCpdf DLL, здесь в текстовой области, мы можем написать код и на кнопке щелкните соответствующий pdf-файл. ABCpdf след версии легко доступны для Downloding, добавив linlk загрузить DLL ABCpdfhttps://www.websupergoo.com/download.htm

index.cshtml

 @using (Html.BeginForm("covertopdf", "simple", FormMethod.Post)) 
{ 
     <p style="margin-top:50px"> 
      Input Html: @Html.TextArea("Htmlcontent", new { @class = "form-control",@cols="160" , @rows="20"})<br /> 
      <input type="submit" class="btn-primary" value="Convertopdf" /> 
     </p> 
} 

SimpleController.cs

public class SimpleController : Controller 
    { 
     public class FileViewModel 
     { 
      public byte[] Content { get; set; } 
      public string Extension { get; set; } 
      public string FileName { get; set; } 
     } 

     [HttpPost] 
     [ValidateInput(false)] 
     public FileStreamResult covertopdf(string Htmlcontent) 
     //public FileStreamResult covertopdf(file fo) 
     { 
      var result = ExecuteAction(() => 
      { 
       var fileViewmodel = new FileViewModel 
       { 
        Content = ConvertHtmlToPdf(Htmlcontent), 
        //Content= ConvertHtmlToPdf(fo.cont), 
        Extension = "application/pdf", 
        FileName = "Policy Information.pdf" 
       }; 
       return fileViewmodel; 
      }, "covertopdf"); 
      // return result; 
      HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); 
      // Content is the file 
      Stream stream = new MemoryStream(result.Content); 
      return new FileStreamResult(stream, "application/pdf") 
      { 

      }; 
     } 



     public T ExecuteAction<T>(Func<T> action, string method) 
     { 
      try 
      { 
       return action.Invoke(); 
      } 
      catch (Exception ex) 
      { 
       return default(T); 
      } 
     } 



     protected byte[] ConvertHtmlToPdf(string html, string header = null, string footer = null, bool isPageNumberInFooter = false) 
     { 
      // Create ABCpdf Doc object 
      var doc = new Doc(); 
      if (header == null && footer == null) 
       doc.Rect.Inset(20, 20); 
      else 
       doc.Rect.String = "0 70 600 760"; /*padding from left, padding from bottom, width from left, height from bottom*/ 
      // Add html to Doc 
      //html = "<html><head></head><body></body></html>"; 
      int theId = doc.AddImageHtml(html); 

      // Loop through document to create multi-page PDF 
      while (true) 
      { 
       if (!doc.Chainable(theId)) 
        break; 
       doc.Page = doc.AddPage(); 
       theId = doc.AddImageToChain(theId); 
      } 
      var count = doc.PageCount; 

      /*****************Footer area******************/ 
      if (footer != null) 
      { 
       var newfooter = ""; 
       doc.Rect.String = "40 20 580 50"; 
       for (int i = 1; i <= count; i++) 
       { 

        doc.PageNumber = i; 
        if (isPageNumberInFooter) 
        { 
         newfooter = footer.Replace("PageNumber", "Page " + i.ToString() + " of " + count.ToString()); 
         int id = doc.AddImageHtml(newfooter); 

         while (true) 
         { 
          if (!doc.Chainable(id)) 
           break; 
          id = doc.AddImageToChain(id); 
         } 
        } 
        else 
         doc.AddText(footer); 
       } 
      } 
      /*****************Footer area******************/ 


      // Flatten the PDF 
      for (int i = 1; i <= doc.PageCount; i++) 
      { 
       doc.PageNumber = i; 
       doc.Flatten(); 
      } 

      var pdf = doc.GetData(); 
      doc.Clear(); 
      // Get PDF as byte array. Couls also use .Save() to save to disk 
      return pdf; 
     } 
    } 
Смежные вопросы