Pike project – module stub creator
I recently began learning how to create Pike modules in C. The Pike module C API seems great and once you’ve sorted things out the modules are easy to build and install. Non the less, when creating a C module from scratch there’s a couple of files you need and some configurations of those before everything is set for go. And here comes “pike-project” into play.
Pike-project is a simple GTK program (works as command line tool also) written in Pike it self. The program will create the basics for a running Pike C module, or a plain installable Pike module. Then it’s just starting programming.
The program is available at my Github repository.
BTW! At the moment it only works on Linux I suppose.
Pingly – a Roxen module for automatic Twingly pinging
Twingly is a blog search engine that focus on indexing the “blogosphere” rather than being a generic search engine. Twingly has a ping service that let you ping Twingly when you have new content on your blog so that Twingly can head over there and index the new content asap.
Since Roxen CMS have event hooks this module listens for newly published files and when found automatically notifies Twingly about it.
The only thing needed is to set up a config file in the SiteBuilder’s workarea so that this module knows under which paths newly published content should notify Twingly and with which arguments. But all this is documented in the module.
One note! If you run a replicated environment install this module on one of the frontend servers, not the backend. If installed on a backend Twingly might head over to your site before the new content has been replicated.
JavaScript minifier filter module for Roxen
Nowadays web sites and web applications tend to be more and more JavaScript driven which results in humongous JavaScript files. It’s not uncommon to have several 100 of bytes of JavaScript on a site. Of course web browsers cache stuff like JavaScript so that it only is requested from the server once. But judging from the visitor logs at work most people only visit our site once a month or so which means that cache will expire and all those scripts has to be requested upon the first visit.
Now, there are several ways to compact JavaScripts: Packer, YUI Compressor, Shrink Safe, jsmin and many more. Some of these just remove redundant white space and comments, some obfuscates the code and shortens variable and function names and what not. Many of these scripts and programs are very fine but they require you to manually minify your scripts, and that’s just a hassle!
But since we use Roxen CMS at work things get much easier if you write your own Roxen filter module which automatically minifies JavaScripts on the fly, given they meet certain criteria. And so I did!
I ported the original jsmin code written in C to Pike. Then it was just a matter of creating a simple filter module for Roxen. And then it was all done.
You can use two criteria to determine if a script should be minified or not:
- Path glob: In the module settings you can specify any number of directory globs or full paths. If a requested JavaScript either is in a directory matching a glob or is a direct match it will be minified.
- Query string variable: In the module settings you can define a variable name that if exists as a query string variable in the request the JavaScript will be minified. So:
<script type="text/javascript" src="myscript.js?jsmin=1"></script>
will minify
myscript.js
And that’s that!
GTK hacking in Pike
I’ve found out that it’s great fun programming desktop applications and of course it gets more fun the more you learn. Now I’m doing a Twitter client in Pike – my favorite programming language – mostly because I wanted to try out GTK programming in Pike. I use the good Twitter client Pino – written in Vala – and I have borrowed the concept and layout from it. I call it Tweepi.
The only major difference between Tweepi and Pino – besides they are written in different programming languages – is that Pino uses WebKit to draw the status messages where I am using good old GTK widgets – and I guess there are no bindings to WebKit in Pike for that matter
One thing I noticed is that the Gtk.Label widget sucks at displaying longer texts that line wraps. Since the label widget handles some HTML formatting I thought that it would be suitable for displaying the status messages, but the text looked like shit, line wrapping where ever it felt like. And the Gtk.TextView widget doesn’t handle formatting per default so I Googled some and found that you can format text in Gtk.TextViews by inserting Gtk.TextTags at desired positions. And since Pike has the most awesome HTML parser It was just a matter of sending the text through the parser and create some Gtk.TextTags and inserting them at the same position in the text buffer. (Well, actually it wasn’t that easy but with some help from a Python class I found on the web it was doable).
So now I have a start at something that is a Gtk.HtmlTextView – actually it inherits Gtk.TextView but has an additional method insert_html_text(string text) – and albeit quite simple at the moment it’s worth continuing on. The code for the HtmlTextView is available at my Github repository.
In general I find the GTK implementation in Pike to be pretty OK, but there exist some verbose, and tedious, stuff like getting the text from a Gtk.TextView:
- Gtk.TextBuffer b = my_textview->get_buffer();
- string text = b->get_text(b->get_start_iter(), b->get_end_iter(), 0);
which in Vala and C# would be done like:
- // Vala
- string text = my_textview.get_buffer().text;
- // C#
- string text = myTextView.Buffer.Text;
Anyway! Tweepi isn’t done yet but I think I have solved the most tedious stuff and it’s starting to become useful. It’ll probably be done in a couple of weeks and I will of course release the sources then.
Gravatar module for Roxen
Although I’m working on some social web related Pike modules where a Gravatar module is included I needed a Gravatar module right now at work so I hacked up a standalone Gravatar Roxen module.
This is how it works
- <ul>
- <emit source="sql" host="mydb"
- query="SELECT name, email, `date`, body FROM my_comments"
- >
- <li>
- <gravatar-img email="&_.email;" rating="pg" size="32"
- default-image="/path/to/icon.png"
- /> &_.name; wrote at <date iso-time="&_.date;" />
- <wash-html paragraphify="">&_.body;</wash-html>
- </li>
- </emit>
- </ul>
Download the Gravatar Roxen module 14:20, Wed 09 December 2009 :: 7 kB
Merging associative arrays in PHP
It’s nice when serendipity is your friend! I was porting my Bitly class from Pike to PHP – I know there’s probably a hundred PHP classes already out there, but mine is better coded
– and noted by accident that I had used some Pike syntax in my PHP class but it was working anyway. So what was I doing? In Pike there’s separate data type for associative arrays called mapping. In Pike, in general, when merging two objects you just join them with a + sign. Thus merging two mappings you do like
- mapping m1 = ([ "key1" : "Value 1", "key2" : "Value 2" ]);
- mapping m2 = ([ "key3" : "Value 3" ]);
- write("My mapping: %O\n", m1 + m2);
- //> My mapping: ([ /* 3 elements */
- //> "key1": "Value 1",
- //> "key2": "Value 2",
- //> "key3": "Value 3"
- //> ])
And I noted that I had done the same thing in PHP and the result was perfectly valid:
- $a1 = array("key1" => "Value 1", "key2" => "Value 2");
- $a2 = array("key3" => "Value 3");
- echo "My mapping: ";
- print_r($a1 + $a2);
- //> My mapping: Array
- //> (
- //> [key1] => Value 1
- //> [key2] => Value 2
- //> [key3] => Value 3
- //> )
This method doesn’t work on flat array though so there you’ll still have to use array_merge(), but pretty nice anyway.
And oh, the PHP Bitly class will be part of the new PLib release once done!
Roxen User Conference (cont’d)
So the Roxen User Conference has come to an end. It’s always nice to meet with people who speak the same “language” (the language of the geeks perhaps), to share experiences and solutions. And of course it was nice to see the Roxen Editorial Portal in action. That’s a pretty cool piece of web based software. It was also nice to get a preview of Roxen CMS 5.0. It will have a few new features that will be nice and perhaps the greatest thing is that it will incorporate Pike 7.8 (which in it self hasn’t been released yet).
Anyway! For me it was a great experience talking to other Roxen customers and share some ideas and views. Oh, and one more nice thing: during the conference Roxen released a community site – planet.roxen.com. I hope it will be a great resource for us Roxen customers and users.
Updated Roxen trim tag
Jonas Walldén, CTO at Roxen, has improved my RXML tag contribution <trim></trim>. The code is now really beautiful and you can tell the difference from the code written by a lamer, as myself, and a real programmer, as Jonas. Jonas told me that the <trim></trim> tag will be part of the next Roxen release
Download
Roxen trim tag 17:31, Sat 17 October 2009 :: 4.8 kB
Pike trim module 17:31, Sat 17 October 2009 :: 4 kB
Bug fix for Syntaxer.pmod
It didn’t take too long to notice that I had f–ked up the HTMLParser class a little bit. It was how entities was handled that didn’t really worked as expected – entities in tag attributes was duplicated and inserted in the tag content – but the good side of it is that I learned about the HTMLParser method of the HTMLParser Pike class. I only want to match entities in the data section – i.e. tag content – and not in attributes and the HTMLParser method tells you, as the name implies, in what context the entity is found. So my entity callback function now looks like:
- //! Entity callback
- protected void ecb(Parser.HTML p, string _data)
- {
- if (p->context() == "data")
- line += colorize(entify(_data), "entity");
- }
which hopefully will be completely bug free now. So one down 854 to go
Codify RXML tag and Syntaxer.pmod 17:31, Sat 17 October 2009 :: 183.9 kB
A Pike syntax highlighting module
So I thought I should try to port my syntax highlighting script, Syntaxer, written in PHP to Pike. Mostly for the fun of it but also to improve my knowledge of string handling in Pike. The greatest concern here is that PHP is a dynamic language and Pike is not (in the same sense) and the PHP version of Syntaxer heavily depends on dynamic loading of PHP files. The reason for this is that I generate the “syntax maps” dynamically from syntax files of Edit+. That means that if you want support for a new language just drop a .stx file in the right location and there you go. My script will convert that into a static PHP file, so that the conversion only needs to be done once, and load that file on the fly when that particular language is requested.
I thought that this method would be hard to implement in Pike – although it might be possible – so I had to come up with a slightly different approach. Frankly; it’s not that often you alter the .stx files or implement support for new languages so my solution is to manually create definitions for what ever language. But I still use the .stx files from Edit+ although one needs to copy and paste bit.
In the Pike solution each language is its own class that inherits the master class .stx. The only thing you pretty much need to put in the derived class is some .stx, .stx and .stx that specify what is what in the language. For example, the C++ definition looks like this:
- inherit .Hilite;
- public string title = "C++";
- //| Override the keywords mapping
- private mapping(string:multiset(string)) keywords = ([
- "keywords" : (<
- "auto","bool","break","case","catch","char","cerr","cin",
- "class","const","continue","cout","default","delete","do",
- "double","else","enum","explicit","extern","float","for",
- "friend","goto","if","inline","int","long","namespace","new",
- "operator","private","protected","public","register","return",
- "short","signed","sizeof","static","struct","switch","template",
- "this","throw","try","typedef","union","unsigned","virtual",
- "void","volatile","while","__asm","__fastcall","__based",
- "__cdecl","__pascal","__inline","__multiple_inheritance",
- "__single_inheritance" >),
- "compiler" : (<
- "define","error","include","elif","if","line","else","ifdef","pragma" >)
- ]);
- //| Override the default since # is no line comment in C++
- protected array(string) linecomments = ({ "//" });
- void create()
- {
- ::create();
- colors += ([ "compiler" : "#060" ]);
- styles += ([ "compiler" : ({ "<b>", "</b>" }) ]);
- }
And you really don’t need to make it more fancy than that. For most C-based languages the definitions in the master class .stx is enough. Just add the keywords to the .stx mapping and it looks better than nothing
HTML parser
One thing that differs from the PHP version of Syntaxer is that SGML-based, or tag based, languages will be run through a HTML-parser. The downside of the PHP version is that tag content will be highlighted as well, which of course isn’t what we want, but since Pike has a decent HTML parser that behaves like a SAX parser so I wrote a class, .stx, that uses that for highlighting tag based stuff. The .stx class also inherits .stx so the methods and members are the same.
I wonder why there’s no, built-in, HTML parser for PHP?
A Roxen tag module
Of course I had to write a Roxen tag module so that we can highlight source code in Roxen web pages. This was the reason for writing the Pike module at all. The tag is named .stx which might not be the most innovative name but what the heck! The beauty of it is that I made it possible, in the module settings tab, to create a surrounding HTML template for the output. When you run some code through the parser you get the highlighted source code as well as the name of the language and how many lines of code was highlighted and it might be nice to present that as well (just like the code blocks on this site). It’s tedious writing that surrounding HTML every time so now it’s just to put that in the settings and the code blocks will always look the same.
Finally
There’s some stuff left to do but the code works well enough to be usable. And I must say that the speed of the Pike version is like a thousand times faster than the PHP version!
Oh, and I have implemented support for the following language:
- ActionScript
- C
- C++
- C#
- CSS
- Java
- JavaScript
- HTML
- Perl
- PHP
- Pike
- Python
- Ruby
- RXML
- XSL
And that’s that for now.
Codify RXML tag and Syntaxer.pmod 17:31, Sat 17 October 2009 :: 183.9 kB
A Pike module and a Roxen tag
When you’r used to one programming language and start learning a new one you sometimes miss some features from the former. That happened to me a couple of years ago when we started using Roxen at work. What I missed was the trim functions from PHP. Sure, Pike and RXML can trim strings from whitespace but the beauty of trim, trim and trim in PHP is that you can trim characters as well as whitespace. And to my knowledge there’s no equivalent to trim and trim – that is only trim the left and right side respectively of the string.
So I wrote a Pike module that did that and also created an RXML tag of it. Just yesterday I rewrote that code since I do think I’ve become a better programmer and have come to learn Pike a lot better since my first try.
And I also wrote a method to shorten a string from the center and out, i.e. trim.
So here are some examples of usage:
- import .trim;
- string path = "/this/is/a/path/";
- write("%s\\n", rtrim(path, "/"));
- // Will output: /this/is/a/path
- write("%s\\n", trim(path, "/"));
- // Will output: this/is/a/path
- string long_str = "This is some string that's too long for us";
- write("%s\\n", ctrim(long_str, 20));
- // Will output: This is...for us
And here’s the RXML implementation:
- <trim right="" char="/">/this/is/a/path/</trim>
- <!-- /this/is/a/path -->
- <trim center="" length="20">This is some string that's too long for us</trim>
- <!-- This is...for us -->
And that’s that.
Trim Pike module 17:31, Sat 17 October 2009 :: 4 kB
Trim Roxen tag module 17:31, Sat 17 October 2009 :: 4.8 kB
Pike multiset
It’s fascinating: I’ve been using Pike for little over two years now and I have never really understood the Pike data type “multiset”. A multiset is the keys in an associative array – or mapping as they are called in Pike, or hash in Perl, or HashTable in C# – with the values left out. So if you have a Pike mapping that looks like ([ "key1" : 1, "key2" : 2, "key3" : 3 ]) a multiset of that would look like ([ "key1" : 1, "key2" : 2, "key3" : 3 ]) and an array would be ([ "key1" : 1, "key2" : 2, "key3" : 3 ]). Mappings and arrays I have used a lot, of course, but it was quite recently it came to me what the multiset is good for!
Lets say you have a function that takes a string as argument and that argument can have like 12 different values but you only want some action to take place if the value is one of three out of the twelve possibilities. In many languages that could be written like this Pike example:
- string my_function(string arg)
- {
- if (arg != "a_value" && arg != "b_value" && arg != "g_value")
- return "no";
- return "yes";
- }
I don’t know how many times I’ve written code like that. But here the Pike multiset really shines. This is how you could use the multiset:
- string my_function(string arg)
- {
- if (!(< "a_value", "b_value", "g_value" >)[arg])
- return "no";
- return "yes";
- }
I think that’s pretty nice. And that’s probably not the only thing the multiset is useful for.
While I'm at it, what about these nice syntactic sugar flakes of Pike:
- string str = "one two three four five six";
- array a_str = str/" ";
- str = a_str*", ";
The same in PHP
- $str = "one two three four five six";
- $a_str = explode(" ", $str);
- $str = implode(", ", $a_str);
Even though I've used PHP for 7-8 years I still have trouble remembering in what order the arguments is supposed to come in the function call.
Beautiful Roxen
I’ve been really busy lately at work with various things – developing a blogging system for starters. Most of the stuff you need for a blogging system is already available in Roxen CMS that we use at work. But one thing I needed, that isn’t available, was some commenting functionality. This is something that you could quite easily implement in the templates – Roxen uses XSLT for the templating system, or their own extension of XSLT so that you can write RXML code in the XSL templates.
RXML handles database driven things quite alright but if you develop things in this layer, the presentation layer, it gets harder to maintain or implement on a different server. What you can do then is writing a Roxen Module in Pike. You can create different types of modules – provider modules, RXML tag modules and so on – and you can also combine two or more modules into one. All RXML tags in Roxen is just wrappers for underlying Pike code, so you hide the logic in Pike and provide simple interfaces in RXML. First, let me give an example of how you loop over a database record set in RXML:
- <emit source="sql" host="myhost" query="SELECT name, email FROM employees">
- <a href="mailto:&_.email;">&_.name;</a>
- </emit><else>
- No records found
- </else>
It doesn’t get more simple than that! Another thing that’s great about the modules is that you can run arbitrary functions when you load the module which means that you can create databases and database tables when you first load the module. Roxen runs on MySQL internally and Roxen provide API:s to the internal MySQL database. What this means is that if you create database driven modules it’s just to install the module and the database and its tables will be created. No fuss!
Roxen, without the CMS, is a standalone open source web server and support the same kind of modules as the CMS does, but there’s more to the CMS!
The CMS modules
I’ve been poking around in the Roxen CMS source code for a while now and I have written some pure RXML tag modules – which is quite simple – but now I saw the opportunity to extend my knowledge and make a real CMS module. Since the CMS provide access control you don’t want emit tags to list stuff that the user don’t have access to. For instance: There’s a emit tag that you can use to list the most recent pages for a given path or pats. For example:
- <h2>Latest news</h2>
- <ul class='newslist'>
- <emit source="site-news" unique-paths="" maxrows="20"
- path="/comp-a/news/*/*.xml,/comp-b/news/*/*.xml,/secret/*/*.xml"
- >
- <li><a href='&_.path;'>
- <date type='iso' date='' iso-time='&_.published;' /> |
- <span>&_.title;</span>
- </a></li>
- </emit>
- </ul>
Now, you don’t want unauthorized users to see the items from the emit path do you. This tag in particular won’t show them either and I wanted the same kind of functionality in my set of emit tags. So I poked some more!
Another thing: Each file in Roxen CMS is version controlled through CVS and I needed to get some information about the first published version so I needed to find out how to access the CVS logs. The CVS thing also means that the files in Roxen CMS is saved to a virtual file system with an actual path, i.e emit, and what if there are comments to a page and that page gets moved? Thankfully Roxen CMS provides an API to run your own code when some kind of action takes place on a particular file – if it get moved, edited, deleted, purged and so forth. And I came to understand that I needed to poke around even more
Anyway; the more you dig around at the dark side of Roxen the more impressed you get by how clean the code is, how nice the API:s are and so on. I’m no Roxen beginner by now but up until now I haven’t really used the API:s to the internal workings of Roxen and I must say that after all, it was a bliss.
The comments module
So what will all this babbling lead up to? Well, what my module now does is:
- Upon load it creates an internal database with the table in which to store the comments. Here you can also make a dump or load a dump of the comments DB. In the settings you can set the default value for how long commenting should be enabled – lets say that after 30 days no further commenting should be allowed. You can also set a default author name if you allow anonymous commenting.
- It listens to the
emitwhich means that when actions takes place on web pages in the CMS the module will be notified and take actions if necessary. If the pageemithas comments to it and the page get moved the paths in the comments table will be updated to the new path so that comments always stick to its page even if the page is moved. Also, if a page gets deleted so will the comments. - It provides a set of RXML tags, one for listing comments – either to the page to which they belong or through globs so that you can make lists of “latest comments”, one for listing a particular comment for lets say editing, one tag for adding, one for updating, one for deleting a comment, one
emittag for checking if a user have admin permission to a given comment and oneemittag to check if the commenting form has expired or not and last one tag for counting the comments for a given page. - Not the least: I followed through and really documented, through Roxens module documentation functionality, the usage of the RXML tags
So I think that it covers what you’d expect a “commenting system” should be capable of doing. There’s may be some small things to solve as always when you develop stuff but it seems to work quite satisfying.
For anyone curious, here’s the source code:
Comments – Roxen CMS Module 17:31, Sat 17 October 2009 :: 36.3 kB
Here’s some screen dumps
Generating PDFs on the fly
One time or another you come to the point, at least when you work as a web developer, when you need to generate PDFs on the fly. In principle this wouldn’t be too hard: pass the document you want to convert through a PDF printer. Well, it doesn’t sound that hard but talk is one thing and implementation another! I came to the point recently where I, or we, really needed to generate PDFs on the fly. The question of just converting one document to a PDF was not the only problem ahead: We also needed to alter the content, which is some tremendously complex content, of the PDF on the fly.
The workflow is as follows: A person submits a web based application through a web form. The commision is received by a handling officer who continues the application. The commision is sent back to the applier who in turn continues the application. The commision is once again sent to the handling officer who finish the application.
The application form, originally a Word document with loads of checkboxes, input fields and what not it’s the document at the top), at hand here is really, really complex and more or less industry standard. The pure complexity of the form is the reason why we wanted to digitalize it and make it into a more workflow like thing. Since the application form is more or less a standard we wanted the ability to see what the web based application would look like in reality if it was handled the old way through the Word document and of course give us the ability to archive the application in a constant format. And this is the type of document that people like to put in a binder so it needs to be printable and look like it always has looked like.
The first problem
So how do you go about and fill the Word document with values from a database, or how do you dynamically create a PDF that looks exactly like that complex Word document? Creating simple PDFs from a PDF API is not that hard but this really isn’t a simple structured document we’re talkning about so that didn’t sound likely. So I started looking at Adobes LiveCycle products but that would be really expensive (I mean really, really, really expensive) so we had to throw that idea away.
Then it hit me: We’re running Windows servers at work so couldn’t I build a COM based solution and use the COM interface for Word and in that way use the original Word document as a template and dynmialcally fill it with content from the database? I had never touched COM before but I thoght nothing is impossible!
The first solution
So I fired up Visual C# Express and began writing a console application that could be called from the web server. The first thing to solve was how to get all the data from the web server to the console application. Of course the console application could call the database directly but that would make the application hard to maintain, it would make it less dynamic and in general no good (and there are more documents to create and alter than the one I’ve mentioned). XML is no news to me so I though that passing an XML tree as an argument with what fields to fill and with what values would be a good idea. And since during the commision there are several types of documents to generate another argument would be what Word template to use.
So the question of how to get what information to fill the Word document with to the console application was easily solved (I love XPath).
The next question was how to use the Word COM interface, and frankly that was quite easy (thanks to Google). If you use bookmarks in the Word document you can loop over them with ease and just as easily fill them with content. So the principle I used was the following: The XML tree passed to the console application looks like this:
- <!-- The name of the root node doesn't matter -->
- <n>
- <field name="Some_Bookmark1" type="text">The value</field>
- <field name="Some_Bookmark2" type="text">Another value</field>
- <field name="Some_Bookmark3" type="checkbox">true</field>
- <!--
- ... and just as many nodes neccessary ...
- -->
- </n>
so the name attribute is correponding to the name of the bookmark/data field to alter and the node value is quite obvious the value to assign to the bookmark/data field. Text fields and checkboxes is delt with in different ways in the COM API so that’s why the name attribute.
When the bookmarks/data fields has been altered the document is saved in a temporary directory with a uniq name and the path to that document is returned by the console application.
Up to this point…
This is how things work so far:
- The console application is called with two aruments:
- What template to use
- An XML tree with what bookmarks/data fields to fill with what values
- The console application opens the template and fill it with data according to the XML tree passed as the second argument.
- The console application saves the document with a uniq name in a temporary directory and the path to that document is returned by the console application.
Quite clear I’d say
The second problem
Okey, so now this application needed to be callable from a web page. And frankly that seemed like a minor problem, and so it was. The only minor concern was that the overall web based application workflow was (is) developed by Roxen as a consultant job so the implementaion of this little Word to PDF thing needed to be as simple as possible. So it was time to fire up JEdit and do some Pike hacking.
The second solution
Thanks to the fact that there’s a module in Roxen that can execute external applications and thanks to the fact that the source code of Roxen is available I borrowed some of the code written by Marcus Wellhardt at Roxen
. I’m no wicked Pike expert like the dudes at Roxen so I borrowed the code from name that creates a background process and altered it slightly to fit my needs. On top of that I wrote a RXML tag that would be the wrapper to call to create the background process. The tag, a container tag, takes one required argument, the Word template to use, and one optional argument, the path to the directory where the template is stored (this argument is optional because it can be set globally in the module settings), and the XML tree with the bookmarks to fill as content. So the tag would be used like this (still, not all functionallity is there yet):
- <word2pdf template='the-template.doc'>
- <d>
- <field name="Some_Bookmark1" type="text">The value</field>
- <field name="Some_Bookmark2" type="text">Another value</field>
- <field name="Some_Bookmark3" type="checkbox">true</field>
- </d>
- </word2pdf>
So I tried the tag and indeed a Word document with my given data was created in the temp directory on the server!
The third problem
Now it was time to create a PDF from the temporary Word document. I found an open source PDF printer software called PDFCreator and it looked promising so I went for it. PDFCreator can be installed in “server mode” which was what I wanted and thanks to this guide it was easy to set it up as a service as well.
First I wrote a standalone Pike script for debugging and testing that would kind of emulate a web page request (it’s some what tiresome developing new thing directly through Roxen since the module needs to be reloaded/re-compiled for every change you make to the code). Anyhow, things started to work pretty well: The script created a Word document by calling my console application, the script passed the path to that document to PDFCreator and MS Word was launched and a PDF was printed to the given temp directory. Yes! PDFCreator relies on the software the orginal document is associated with.
Okey, so the code worked fine so I altered my Roxen tag module so that my tag name would behave in the same manner as the standalone Pike script. But when I ran the tag through a web page request PDFCreator hung, or rather the MS Word process created by PDFCreator hung!
The third solution
It really puzzeled me: Everything went ok if I ran the process as my user through my standalone Pike script, but when the process was created by the web server (local system) MS Word got stuck. So I changed the server process to run as an ordinary user account, my user (local administrator) and now it worked perfectly. Then it hit me: maybe the MS Office applications relies on the directory name in name and the user name doesn’t have that (it’s no ordinary user). So it seems that to get MS office apps to run from another process, that process needs to have been created by a normal user account. I dunno, maybe there’s a way around this, like installing MS Office in some kind of server mode or something like that!
Anyhow, my little RXML tag name now did what I wanted and the result of the tag is the raw data of the created PDF, the temporary Word document and the PDF is wiped clean from the server, so we can just store the raw data in a database and deliver it easily to a user when the PDF is requested.
Word2pdf wrapped up
I’m quite satisfied with the solution I came up with: The console application I wrote (I call it WordWriter) seems to work like a charm and the fact that what data to fill the template with is passed as an XML tree makes it really easy to use for more than the specific purpose it was developed for. Plus, if the over all web application Roxen developed (is developing) is changed I don’t need to change the WordWriter application
Finally this is how this little name can be used in real life:
- <?comment
- Here data is pulled from the database according to the
- application being handled
- ....
- ?>
- <define variable="var.pdfdata" trimwhites="">
- <word2pdf temlplate="my-template.doc">
- <n>
- <field name="My_Bookmark1" type="text">&sql.data1;</field>
- <field name="My_Bookmark2" type="text">&sql.data2;</field>
- <field name="My_Bookmark3" type="text">&sql.data3;</field>
- <!-- ... -->
- <field name="My_Bookmark10" type="checkbox">
- <if variable="&sql.data10; = 1">true</if>
- <else>false</else>
- </field>
- </n>
- </word2pdf>
- </define>
- <sqlquery host="dbhost"
- query="UPDATE table SET pdf1 = :pdf WHERE id = :id"
- bindings="pdf=var.pdfdata, id=sql.id"
- />
And that should do the trick!
The synergy
At my job we’re like 1200 people and sometimes people want to create PDFs either to put on our web site or e-mail to someone and of course not all computers have Adobe Acrobat installed so wouldn’t it be nice to have a form on the intranet where people could upload a file and get it back as a PDF? Since most of the PDF generating functionality was already at hand I just had to write another RXML tag that just creates a PDF from a document. Said and done so now we have PDF generating form on the intranet.
Finally
This has been a really fun thing to do from which I have learned alot of new stuff, and that is probably why I love my work so much: There’s always new things to dive into.







