将 iTextSharp 与淘汰赛 JavaScript 或其他 MVC/MVVM 框架一起使用? [英] Using iTextSharp with knockout JavaScript or other MVC / MVVM framework?

查看:29
本文介绍了将 iTextSharp 与淘汰赛 JavaScript 或其他 MVC/MVVM 框架一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,因为我确实发现我可以使用 iTextSharp 生成 PDF,所以我选择了这条路线.

Ok, since I did find out that I can use iTextSharp to generate a PDF, I went that route.

我已经把它保存到可以将带有基本格式的 HTML 保存为 PDF 的位置.这不是问题.

I've got it to where it will save HTML with basic formatting to a PDF. That's not the problem.

我现在需要做的是使用 knockout 进行标记,并使用 resultant HTML(即 DOM)作为我的字符串传递到创建 PDF 的方法.

What I'm needing to do now is take markup with knockout in it, and use the resultant HTML (i.e. the DOM) as my string to pass into the method that creates the PDF.

例如,我有一个使用淘汰赛生成的表格.我需要将敲除生成的 DOM 作为字符串传递到我的 C# 控制器中,以便我可以构建 PDF.

So, for instance, I have a table that's generated with knockout. I need to pass the DOM that was generated by knockout, as a string, into my C# controller, so that I can build the PDF.

基本上,如果您查看此处生成的内容:

Basically, if you look at what's generated here:

http://knockoutjs.com/documentation/foreach-binding.html

如果您通读示例 2(它生成三个要点),它说明了我正在谈论的一代.就我而言,我希望将生成的项目符号作为字符串传递到我的控制器(HTML 和所有内容)中,以便我可以保存它们.

And if you read through Example 2 (it generates three bullet points), it illustrates the generation I'm talking about. In my case, I would want to take the generated bullet points and pass them into my controller -- HTML and all -- as a string, so that I can save them.

有什么想法吗?老实说,我什至不确定从哪里开始.

Any thoughts? I'm not even sure where to begin here, honestly.

推荐答案

该问题适用于任何执行 MVCMVVM 的 JavaScript 框架.上面提到:

The question applies to any JavaScript Framework that does MVC or MVVM. Mentioned above:

我需要将淘汰赛生成的 DOM 作为字符串传递,进入我的 C# 控制器,以便我可以构建 PDF.

I need to pass the DOM that was generated by knockout, as a string, into my C# controller, so that I can build the PDF.

所以我将使用一个简单的工作示例在 ASP.NET MVC 中完成这项工作.之前从未使用过 knockout.js,因此将获取 DOM 元素并使用 jQuery 发送 Ajax 请求.

So am going to go with a simple working example to get this done in ASP.NET MVC. Never used knockout.js before, so going to get the DOM element and send Ajax request with jQuery.

视图,基于您上面引用的示例:1. 获取 ulouterHTML2. 向控制器发送一个 Ajax 请求:

The view, based on the example you referenced above: 1. Gets outerHTML of ul; 2. sends an Ajax request to the controller:

<h4>People</h4>
<ul id='wanted' data-bind="foreach: people">
    <li>
        Name at position <span data-bind="text: $index"> </span>:
        <span data-bind="text: name"> </span>
        <a href="#" data-bind="click: $parent.removePerson">Remove</a>
    </li>
</ul>
<button data-bind="click: addPerson">Add</button>
<button data-bind="click: getPdf">Get PDF</button>

@section scripts
{
<script src="~/Scripts/libs/knockout-3.4.0.js"></script>
<script src="~/Scripts/ajax/FileSaver.js"></script>
<script src="~/Scripts/ajax/jquery.binarytransport.js"></script>
<script src="~/Scripts/ajax/jquery-binary.js"></script>
<script type="text/javascript">
    function AppViewModel() {
        var self = this;

        self.getPdf = function (data, event) {
            $(this).downloadFile(
                '@Url.Action("Index", "DomToPdf")',
                { xHtml: $('#wanted').prop('outerHTML') }
            );
        }

        self.people = ko.observableArray([
            { name: 'Bert' },
            { name: 'Charles' },
            { name: 'Denise' }
        ]);
        self.addPerson = function () {
            self.people.push({ name: "New at " + new Date() });
        };
        self.removePerson = function () {
            self.people.remove(this);
        }
    }
    ko.applyBindings(new AppViewModel());
</script>
}

注意事项:

  1. FileSaver.js 在技术上不是必需的,但可以节省大量时间处理不同的浏览器实现.参考 浏览器兼容性.
  2. BinaryTransport 如果使用jQuery - 遗憾的是框架不支持此功能我最后检查的框.AngularJS 等其他框架确实支持二进制.参考 发送和接收二进制数据.
  1. FileSaver.js isn't technically required, but saves a great deal of time not having to deal with different browser implementations. Reference Browser compatibility.
  2. BinaryTransport is required if using jQuery - sadly the framework doesn't support this feature out of the box last I checked. Other frameworks like AngularJS do support binary. Reference Sending and Receiving Binary Data.

jquery-binary.js 是我为几个内部项目编写的简单 jQuery 插件:

jquery-binary.js is a simple jQuery Plugin I wrote for a couple of internal projects:

(function ($) {
    $.fn.downloadFile = function(url, data, requestType) {
        $.ajax({
            url: url,
            data: data,
            type: requestType || 'POST',
            dataType: 'binary'
        })
        .done(function(data, textStatus, jqXHR) {
            var type = jqXHR.getResponseHeader('Content-Type');
            var filename = jqXHR.getResponseHeader('Content-Disposition');
            filename = filename && filename.indexOf('attachment') > -1
                ? filename.replace(/(?:[^=])+=/, '')
                : 'file.bin';
            var blob = new Blob([data], { type: type });
            saveAs(blob, filename);
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
        })
        ;
        return false;
    };
}(jQuery));

和控制器:1. 使用 XMLWorkerHelper 解析 HTML 字符串;2. 返回 PDF.

And the controller: 1. parses the HTML string with XMLWorkerHelper; 2. returns the PDF.

[HttpPost]  // some browsers have URL length limits
[ValidateInput(false)] // or throws HttpRequestValidationException
public ActionResult Index(string xHtml)
{
    Response.ContentType = "application/pdf";
    Response.AppendHeader(
        "Content-Disposition", "attachment; filename=test.pdf"
    );
    using (var stringReader = new StringReader(xHtml))
    {
        using (Document document = new Document())
        {
            PdfWriter writer = PdfWriter.GetInstance(
                document, Response.OutputStream
            );
            document.Open();
            XMLWorkerHelper.GetInstance().ParseXHtml(
                writer, document, stringReader
            );
        }
    }

    return new EmptyResult();
}

会让你决定如何处理内联样式.;)

Will let you decide how to deal with the inline styles. ;)

这篇关于将 iTextSharp 与淘汰赛 JavaScript 或其他 MVC/MVVM 框架一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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