开发者

Generating HTML Programmatically in C#, Targeting Printed Reports

开发者 https://www.devze.com 2023-01-02 22:03 出处:网络
I\'ve taken over a C# (2.0) code base that has the ability to print information.The code to do this is insanely tedious.Elements are drawn onto each page, with magic constants representing positioning

I've taken over a C# (2.0) code base that has the ability to print information. The code to do this is insanely tedious. Elements are drawn onto each page, with magic constants representing positioning. I imagine the programmer sitting with a ruler, designing each page by measuring and typing in the positions. And yes, one could certainly come up with some nice abstractions to make this approach rational. But I am looking at a different method.

The idea is that I'll replace the current code that prints with code that generates static HTML pages, saves them to a file, and then launches the web browser on that file. The most obvious benefit is that I don't have to deal with formatting-- I can let the web browser do that for me with tags and CSS.

So what I am looking for is a very lightweight set of classes that I can use to help generate HTML. I don't need anything as heavyweight as HTMLTextWriter. What I'm looking for is something to avoid fragments like this:

String.Format("<tr><td>{0}</td><td>{1}</td></tr>", foo, bar);

And instead take have this kind of feel:

...
table().
    tr().
        td(foo).
        td(bar)

Or something like that. I've seen lightweight classes like that for other languages but can't find the equivalent (or better) for C#. I can certainly write it myself开发者_开发技巧, but I'm a firm believer in not reinventing wheels.

Know anything like this? Know anything better than this?


Just as an idea: why do you want to assemble the HTML in your applications code? Sounds a bit tedious to me. You could aggregate the data needed for the report and pass this on to one of the template engines (that are "normally" used for web apps) existing for C#. Then you save the result of the template engine to a html file.

The main benefits I see with this approach:

  • separates view from business logic
  • html templates can be edited by non-C# developers, html/css knowledge is enough
  • no need to recompile the application if the html changes

I havent used it yet, but I heard that the Spark View Engine is OK: http://sparkviewengine.com/ (not sure if it is for C# 2.0 though)

Some time ago I experimented (in PHP) with Gagawa ( http://code.google.com/p/gagawa/ ), where you can do stuff like:

$div = new Div();
$div->setId("mydiv")->setCSSClass("myclass");

$link = new A();
$link->setHref("http://www.example.com")->setTarget("_blank");

$div->appendChild( $link );

But soon dropped such an approach in favor of an template engine.


Another approach is converting the data to XML and applying an XSL stylesheet. In order to change the HTML formating you just need to replace the stylesheet.

0

精彩评论

暂无评论...
验证码 换一张
取 消