【问题标题】:How to convert a part of a Html Page build using asp.net to PDF如何将使用 asp.net 构建的 Html 页面的一部分转换为 PDF
【发布时间】:2015-08-05 14:11:32
【问题描述】:

我想将此 RED BOX 区域转换为 pdf 文档,以便在我的系统中将其用作报告。我该怎么做,我应该使用什么样的 pdf 转换器以及如何使用? (我正在使用引导程序

【问题讨论】:

  • 投票结束您的问题,因为它要求我们推荐一个图书馆,这是不允许的。相反,您应该进行自己的研究。谷歌搜索“c# create PDF”给了我很多方便的结果。

标签: c# asp.net pdf


【解决方案1】:

你可以试试这个工具,它非常适合 HTML 到 pdf 的转换 http://wkhtmltopdf.org/

这里是将 HTML 字符串转换为 PDF 字节的代码。

public byte[] Convert(string source, string commandLocation)
        {
            Process p;
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = commandLocation;
            psi.WorkingDirectory = @"D:\" ;// Path.GetDirectoryName(psi.FileName);

            // run the conversion utility
            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.RedirectStandardInput = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;

            // note: that we tell wkhtmltopdf to be quiet and not run scripts
            string args = "-q -n ";
            args += "--disable-smart-shrinking ";
            args += "";
            args += "--outline-depth 0 ";
            args += "--page-size A4 ";
            args += " - -";

            psi.Arguments = args;

            p = Process.Start(psi);

            try
            {
                using (StreamWriter stdin = p.StandardInput)
                {
                    stdin.AutoFlush = true;
                    stdin.Write(source);
                }

                //read output
                byte[] buffer = new byte[32768];
                byte[] file;
                using (var ms = new MemoryStream())
                {
                    while (true)
                    {
                        int read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);
                        if (read <= 0)
                            break;
                        ms.Write(buffer, 0, read);
                    }
                    file = ms.ToArray();
                }

                p.StandardOutput.Close();
                // wait or exit
                p.WaitForExit(60000);

                // read the exit code, close process
                int returnCode = p.ExitCode;
                p.Close();

                if (returnCode == 0)
                    return file;
                else
                    LogManager.Log("Could not create PDF, returnCode:" + returnCode);
            }
            catch (Exception ex)
            {
                LogManager.Log("Could not create PDF", ex);
            }
            finally
            {
                p.Close();
                p.Dispose();
            }
            return null;
        }

这里的“source”是 HTML 代码,而 commandLocation 是 wkhtmltopdf.exe 的完整文件路径,您可以从上面的链接下载。 此函数返回 byte[] 即 pdf 文件,您可以将其保存在磁盘上或通过编写 Response.Write(byte); 返回到浏览器 并更改 MIMIE 类型。

【讨论】:

  • Thax,我会努力做到的。
  • 当我调试代码时,当涉及到 ' p = Process.Start(psi); ' 它发送的代码行和错误“系统找不到指定的文件”。
  • 基本上你需要下载wkhtmltopdf.exe并在这里设置这个exe的文件。好像没有找到wkhtmltopdf.exe文件
  • 我刚刚发现了一篇很棒的文章,你可以在这里看到。codeproject.com/Articles/884204/HTML-to-PDF-in-ASP-Net
  • 我应该如何将返回的字节 [] 作为 pdf 文件保存在磁盘上?
【解决方案2】:

如果为解决方案付费不会破坏交易,那么我建议使用ABCPdf,您可以使用 API 甚至从视图发送 HTML,如下所示:

public static byte[] PdfForHtml(string html)
{
    // Create ABCpdf Doc object
    var doc = new Doc();

    // Add passed in HTML to ABCpdf Doc object
    int theID = doc.AddImageHtml(html);

    // Loop through document to create, potentially, multi-page PDF
    while (true)
    {
        if (!doc.Chainable(theID))
        {
            break;
        }

        doc.Page = doc.AddPage();
        theID = doc.AddImageToChain(theID);
    }

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

    // Get PDF as byte array to eventually pass back 
    // in controller action method
    var pdfbytes = doc.GetData();

    doc.Clear();

    return pdfbytes;
}

现在您需要一种方法来生成 HTML,该 HTML 将作为原始视图返回,如下所示:

public static string RenderViewToString(Controller controller, 
                                        string viewName, 
                                        object model, 
                                        string masterName)
{
    controller.ViewData.Model = model;

    using (StringWriter sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, 
                         viewName, 
                         masterName);

        var viewContext = new ViewContext(controller.ControllerContext, 
                                          viewResult.View, 
                                          controller.ViewData, 
                                          controller.TempData, 
                                          sw);

        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

最后,您需要创建一个控制器操作方法来使用上述两种方法,如下所示:

public ActionResult BuildPdf(YourModel model)
{
    // Return view if there is an error
    if (!ModelState.IsValid)
    {
        return View(model);
    }


    // Render view output to string
    var report = RenderViewToString(this, "BuildPdf", model, "BuildPdf");

    // Convert string to PDF using ABCpdf
    var pdfBytes = PdfForHtml(report);

    // Return file result
    return File(pdfBytes, 
                System.Net.Mime.MediaTypeNames.Application.Pdf,     
                "Your_PDF_File_Name_Here.pdf");
    }
}

【讨论】:

  • 谢谢很多朋友,我会试试这个
【解决方案3】:

将其发送到虚拟打印机或使用转换器库,例如iTextSharp

【讨论】:

    猜你喜欢
    • 2011-07-01
    • 2014-07-09
    • 2011-10-12
    • 1970-01-01
    • 2016-06-07
    • 2011-01-13
    • 2012-05-11
    • 1970-01-01
    相关资源
    最近更新 更多