HTML 到 PDF 解决方案(处理内容、页眉和页脚)

发布于 2024-12-07 13:34:20 字数 1048 浏览 0 评论 0原文

我正在尝试通过生成基于 HTML 的 PDF 来创建“报告”。

起初,我只是尝试将原始编码的 HTML 写入文档,然后使用 Javascript 打印该文档。然而,这让我几乎无法控制页眉和页脚。

我尝试使用 theadtfoot 元素,它们在大多数浏览器中运行得相当好,但是我无法获得我正在寻找的格式。

目前 - 我正在尝试在 MVC3 中使用 iTextSharp 来开发服务器端解决方案,但是我对如何继续感到有点迷失,因为我没有太多地使用 iTextSharp。

输出的输入和描述:

创建报告时将使用 4 个项目:

  • 报告内容 (当前是编码的 HTML,因为我不确定解码是否会更改任何格式)
  • 报告标题 (将只是生成的 PDF 的名称)
  • 报告标题 (将是显示在每页左上角)
  • 报表页脚 (将显示在每页的左下角)

控制器操作:

//This will be accessed by a jQuery Post
[HttpPost]
public FileStreamResult GeneratePDF(string id)
{
      //Grab Report Item
      ReportClass report = reportingAgent.GetReportById(id);

      Document doc = new Document();

      //Do I need to decode the HTML or is it possible to use the encoded HTML?

      //Adding Headers / Footers

      //Best method of returning the PDF?
}

I'm trying to create a "report" by generating a PDF based on HTML.

At first, I simply attempted to write raw encoded HTML to a document and then print that document using Javascript. However, this gave me little to no control involving headers and footers.

I attempted using thead and tfoot elements, which worked reasonably well in most browsers, however I wasn't able to get the formatting that I was looking for.

Currently - I am trying to work on a server-side solution using iTextSharp in MVC3, however I am a bit lost as to how to proceed, having not worked with iTextSharp much.

Input and Description of Output:

There will be 4 items used in creating the Report:

  • Report Content (which is currently encoded HTML, as I am unsure if decoding will change any formatting)
  • Report Title (will simply be the name of the PDF generated)
  • Report Header (will be displayed at the upper-left of each page)
  • Report Footer (will be displayed at the lower-left of each page)

Controller Action:

//This will be accessed by a jQuery Post
[HttpPost]
public FileStreamResult GeneratePDF(string id)
{
      //Grab Report Item
      ReportClass report = reportingAgent.GetReportById(id);

      Document doc = new Document();

      //Do I need to decode the HTML or is it possible to use the encoded HTML?

      //Adding Headers / Footers

      //Best method of returning the PDF?
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清欢 2024-12-14 13:34:20

iTextSharp 无法将 HTML 转换为 PDF。这不是它设计的目的。它旨在从头开始创建 PDF 文件,而不是在各种格式之间转换为 PDF。如果您想将 HTML 转换为 PDF,您可以使用 flying-saucer基于iText的库。我有 博客 关于如何使用 IKVM.NET 字节码编译器在 .NET 中完成此操作(ikvmc.exe)

因此,您的控制器操作可能看起来类似于:

[HttpPost]
public FileStreamResult GeneratePDF(string id)
{
    ReportClass report = reportingAgent.GetReportById(id);
    return PdfResult(report.Html);
}

其中 PdfResult 可以是自定义操作结果,采用原始 HTML 并将 PDF 输出到响应流中:

public class PdfResult : ActionResult
{
    private readonly string _html;
    public PdfResult(string html)
    {
        _html = html;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = "application/pdf";
        var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        using (var bais = new ByteArrayInputStream(Encoding.UTF8.GetBytes(_html)))
        using (var bao = new ByteArrayOutputStream())
        {
            var doc = builder.parse(bais);
            var renderer = new ITextRenderer();
            renderer.setDocument(doc, null);
            renderer.layout();
            renderer.createPDF(bao);
            var buffer = bao.toByteArray();
            response.OutputStream.Write(buffer, 0, buffer.Length);
        }
    }
}

iTextSharp cannot convert HTML to PDF. It's not what it was designed to do. It was designed to create PDF files from scratch, not converting between various formats into PDF. If you want to convert HTML into PDF you could for example use the the flying-saucer library which is based on iText. I have blogged about how this could be done in .NET using IKVM.NET Bytecode Compiler (ikvmc.exe).

So your controller action might look something along the lines of:

[HttpPost]
public FileStreamResult GeneratePDF(string id)
{
    ReportClass report = reportingAgent.GetReportById(id);
    return PdfResult(report.Html);
}

where PdfResult could be a custom action result taking the raw HTML and outputting the PDF into the response stream:

public class PdfResult : ActionResult
{
    private readonly string _html;
    public PdfResult(string html)
    {
        _html = html;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = "application/pdf";
        var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        using (var bais = new ByteArrayInputStream(Encoding.UTF8.GetBytes(_html)))
        using (var bao = new ByteArrayOutputStream())
        {
            var doc = builder.parse(bais);
            var renderer = new ITextRenderer();
            renderer.setDocument(doc, null);
            renderer.layout();
            renderer.createPDF(bao);
            var buffer = bao.toByteArray();
            response.OutputStream.Write(buffer, 0, buffer.Length);
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文