geeky notes on web (drupal) and .net (c#) programming, whichever prevails at the moment

 

All commits tagged ".net"

 

How to insert Javascript into PDF using PdfSharp library (adding javascript for automatic PDF self-printing functionality)

A couple of days ago we needed a tool that can: 1) merge PDFs, 2) insert Javascript to be able to automatically send itself to printer after opening and 3) have suitable license for including it to commercial closed-source app.

iTextSharp can do first two, but the commercial license costs way too much for us.

PdfSharp is another awesome library which was a breeze to do the merging of several PDFs into one and is free even for commercial use.

The only thing that was lacking is built-in ability to inject some javascript.

So when I found the problem is not yet solved by anyone across the internet, I downloaded the PdfSharp source code and went through it with a debugger.

Here is a piece of code that I came up with after a day or two that does just that. Maybe it will save you some time too

PdfDocument merged = new PdfDocument();

// ... [add pages to the PDF] ...

// Insert self-printing javascript
PdfDictionary dictJS = new PdfDictionary();
dictJS.Elements["/S"] = new PdfName("/JavaScript");
dictJS.Elements["/JS"] = new PdfStringObject(merged, "print(true);");

merged.Internals.AddObject(dictJS);

PdfDictionary dict = new PdfDictionary();
PdfArray array = new PdfArray();
dict.Elements["/Names"] = array;
array.Elements.Add(new PdfString("EmbeddedJS"));
array.Elements.Add(PdfInternals.GetReference(dictJS));
merged.Internals.AddObject(dict);

PdfDictionary group = new PdfDictionary();
group.Elements["/JavaScript"] = PdfInternals.GetReference(dict);

merged.Internals.Catalog.Elements["/Names"] = group;

string localFile = ""; // path of PDF file to be created
merged.Save(localFile);

As you can see, the code isn't hacky at all, which is good (special thanks to the authors of PdfSharp for making the library really extensible). Basically what it does is implement the method described here: http://www.fpdf.de/downloads/addons/36/ with means of PdfSharp.

}