10

我在一个项目中工作,该项目需要将当前的 html 页面转换为 pdf,并且该 pdf 将自动保存在服务器上的按钮单击上,并且它的引用将保存在数据库中。如果视图的数据来自数据库但数据在此表单是静态的,这意味着在视图上它有很多单选按钮和文本框,我可以在其中编写详细信息并在单击保存按钮后选中复选框,它将保存在服务器上,并且它的引用将保存在数据中根据。

原因是我没有将数据保存在数据库中是因为报告对客户端的使用较少,但是如果我将数据保存在数据库中,那么数据库会变得非常庞大并且处理起来变得复杂。因为该报告有大约 100 个字段。所以请如果有人可以帮助我。

4

9 回答 9

5

您可以使用来自 SelectPdf ( http://selectpdf.com/community-edition/ ) 的免费 Html 到 Pdf 转换器。

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/

于 2016-11-16T14:56:42.323 回答
4

简而言之:

使用 PdfSharp 的 PDF 的 HTML 渲染器

    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;
    }

更详细的答案

于 2015-08-11T15:06:54.613 回答
3

下面的 C# 代码可用于 MVC 应用程序将当前视图转换为 PDF 并在缓冲区中生成 PDF,该缓冲区可以保存在服务器上或发送到浏览器以供下载。该代码使用.net 的 evopdf 库 执行 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;
}
于 2016-09-28T09:16:48.320 回答
2

有特殊的 nuget 包 RazorPDF。它很简单。RazorPDF 网站

于 2014-02-06T07:42:53.167 回答
2

使用ABCpdfdll,在文本区域我们可以编写 html 代码,然后单击按钮会显示相应的 pdf。ABCpdftrail 版本很容易下载,添加 linlk 以下载ABCpdfdll https://www.websupergoo.com/download.htm

索引.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>
}

简单控制器.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;
        }
    }
于 2017-05-22T07:10:50.097 回答
2

我已经使用 Canvas 转换为 PDF,这对我来说非常有用。这是相同的完美教程:https ://www.freakyjolly.com/jspdf-multipage-example-generate-multipage-pdf-using-single-canvas-of-html-document-using-jspdf/

谢谢大家。

于 2020-01-24T06:40:34.193 回答
1

有许多 .NET 的 html 到 pdf 转换器可用。我可以推荐 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

于 2014-11-19T09:16:20.303 回答
1

我使用 iDiTect.Converter 在 asp.net mvc https://www.iditect.com/tutorial/html-to-pdf/中将 html 转换为 pdf ,但简而言之它不是免费代码

public static Byte[] ConvertToBytes()
{
HtmlToPdfConverter converter = new HtmlToPdfConverter();

converter.DefaultStyleSheet = ".para{font-size: 24px; color: #FF0000;}";

string htmlContent = "<p class=\"para\">Content with special style.</p><p>Content without style</p>";
converter.Load(htmlContent);

return converter.SaveAsBytes();
}
于 2018-11-16T06:54:00.957 回答
1

Canvas to PDF 是正确的选择

function getPDF(){

    var HTML_Width = $(".canvas_div_pdf").width();
    var HTML_Height = $(".canvas_div_pdf").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width+(top_left_margin*2);
    var PDF_Height = (PDF_Width*1.5)+(top_left_margin*2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;
    
    var totalPDFPages = Math.ceil(HTML_Height/PDF_Height)-1;
    

    html2canvas($(".canvas_div_pdf")[0],{allowTaint:true}).then(function(canvas) {
        canvas.getContext('2d');
        
        console.log(canvas.height+"  "+canvas.width);
        
        
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt',  [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin,canvas_image_width,canvas_image_height);
        
        
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        
        pdf.save("HTML-Document.pdf");
    });
};
于 2021-04-21T06:59:38.647 回答