Creating a DataMatrix GS1 barcode and saving to postscript, PDF, or image for free in C#.

• December 5, 2015 • Comments Off on Creating a DataMatrix GS1 barcode and saving to postscript, PDF, or image for free in C#.

I’ve been working on an interesting project where I had to learn Pitney Bowes Streamweaver in order to sort/merge and barcode postscript with very little knowledge of postscript and no training or knowledge of Streamweaver. I rolled my own in C# in order to understand how the product worked for parsing but didn’t know much about creating the data matrix barcode and placing it into the postscript, which left me relying on Streamweaver no matter what. My employer is continuing to use Streamweaver until we rewrite this functionality into Adobe ES (hopefully), but if you have small amounts of postscripts to barcode for printing or whatever maybe this will be helpful. Adobe has a free book to get you up to speed on the Postscript language and this post was helpful as well.

I wrote a small console app that will produce a barcode written out in Postscript, JPG, PDF, Hex and ASCII85 encoded. This program has few features and less options as I was just playing with different approaches, these turned out to be the best, but if you need more just ask and I can help as much as possible.


Download DataMatrix Barcode Generator

Before I go further I’d like to acknowledge and link the folks who did the real work!

Ascii85 encoding code

Here’s a sample of the code.

using System.Drawing;
using System.Drawing.Imaging;

using Ghostscript.NET.Processor;

// Examples
namespace datamatrix
    class Program

        public static void convertPDFToPs(string inputFile, string outputFile)
            List<string> cmds = new List<string>();
            string postscriptOut = string.Format("-sOutputFile={0}", outputFile);

            using (GhostscriptProcessor processor = new GhostscriptProcessor())

                processor.StartProcessing(cmds.ToArray(), null);
	 public static string generateBarcode(string outputImageFile)
	    string imageHexString = "";  // OUTPUT: Hexdecimal string.

            DmtxImageEncoder encoder = new DmtxImageEncoder();
            DmtxImageEncoderOptions options = new DmtxImageEncoderOptions();
            Bitmap encodedBitmap = new Bitmap(38, 38, PixelFormat.Format8bppIndexed);

            options.ModuleSize = 2; 
            options.MarginSize = 1;
            options.BackColor = Color.Transparent;
            options.ForeColor = Color.Black;
            options.Scheme = DmtxScheme.DmtxSchemeAsciiGS1;
            encodedBitmap = encoder.EncodeImage(gs1Code, options);
            encodedBitmap.SetResolution(96.0F, 96.0F);

            using (var stream = new MemoryStream())
                encodedBitmap.Save(stream, ImageFormat.Jpeg);
                stream.Seek(0, SeekOrigin.Begin);
                buffer = stream.ToArray();

                // Get hexdecimal
                imageHexString = BitConverter.ToString(buffer).Replace("-", "");

                // Save the image to disk, save the barcode as Jpg,Png, whatever image.
                encodedBitmap.Save(outputImageFile, ImageFormat.Jpeg); // Save the barcode as Jpg,Png, whatever image.

	 return imageHexString

Some conversions in Python.

from PIL import Image # Pillow :
import binascii
# Convert hex to jpg 
out_path  = r'c:\barcode\from_hex.jpg'
jpg_hex = u"the hex string" # Hex output from datamatrix in text file.

image_data = binascii.a2b_hex(jpg_hex)
with open(out_path, 'wb') as output:

# Convert jpg to eps 
jpg_file = r'c:\barcode\'
eps_out = jpg_file.replace('jpg','eps')

Adding jpeg hex to an Adobe postscript. You should be able to paste this into an existing postscript, just be careful where you place it; directly after %%Page might be a good start.

%%PageBoundingBox: 0 0 38 38
0 0 translate
20 20 scale
38 38   %% Width Height
8       %% Bit

If you need to convert XML to PostScript check out this excellent tool from Apache:

Leucine calculator Windows, Mac, and Linux

• November 28, 2015 • Comments Off on Leucine calculator Windows, Mac, and Linux

I created a calculator to approximately calculate mg leucine and exchange based on serving size by grams of protein. You can save the calculation as a food and further calculate meal totals. it could be helpful for body builders or those with MSUD.

I provide this software free of charge and without any warranty expressed or implied. This software was tested but could contain errors or incorrect information. This software does not contain any security features and should not be used on public or insecure computers. Please e-mail me with “leucine calc” in the subject line to report any bugs or erroneous values, or to request features. 

Consult a physician before using this software and have your doctor or nutritionist evaluate whether this software will meet your individual needs.

Download for

Windows [12.7 mb] SHA1 : 44724d50afebeeb67d384c453ee3a028cd02b8c2

Mac [2.4 mb] SHA1: 93a9371b368cc3f3b887a1937deaefb4c3a591e3

Linux 32bit [9.1] SHA1: 3a45980bc0e9aba222aba82af74195147155dcea

If you have trouble running on 64bit Linux you will need to install 32bit libs. These three terminal commands should be what you need in modern Ubuntu. Worked for me on Ubuntu Gnome 15.10.

sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386

Sort list by column preserving index. 

• September 11, 2015 • Comments Off on Sort list by column preserving index. 

This is yet another reason I love Python! 

This is good for something like generating HTML tables with rowspans that you want sorted. Each tuple is a row, each item in the tuple is a cell. If you sort this data it will change the index so if you set a rowspan on the first row and sort, it will likely span on the wrong row. This resolves that problem.

# Sort by column, in this case the last column, and keep original list index.
rows = [('Fred', 'Flintstone', 46, 0),('Wilma', 'Flintstone', 45, 33),('Pebbles', 'Flintstone', 10, 55)]
for index,row in sorted(enumerate(rows), key=lambda item: item[-1], reverse=True):
    print (index, row)

Batch base64 encode PNGs in Python 3 for use in CSS.

• September 5, 2015 • Comments Off on Batch base64 encode PNGs in Python 3 for use in CSS.

I wrote a simple Python 3 script to base64 encode a series of PNG images for use in CSS, or whatever. If you’re learning Python add file output or even go a step further and generate the CSS lines. If you’re here I will assume you are wanting these for CSS but if not, here is an example of using base64 encoded images in CSS if you’re curious.

This script can be ran at the console, as a Python import, or simply as a script.

import os
import sys
import base64

def get_image_base64(base_image_path, image_types=['png']):
    get_image_base64(base_image_path, image_types=['png']) -> dict
    Converts a folder list of images to base64.

        base_image_path = String path to files. Default 'png'
        image_types     = List of extension type to process.

    return -> Dict
    encoded_strings = {}

    if os.path.exists(base_image_path):
            for img in os.listdir(base_image_path):
                # Only get images we care about.
                if os.path.splitext(img)[-1].replace('.','').lower() not in image_types:
                # Set up the dict.                
                if img not in encoded_strings:
                # Get the image's full path.
                image_path = os.path.join(base_image_path,img)
                # Read and encode.
                with open(image_path, "rb") as stream:
                    raw =
                    inc = base64.b64encode(raw)
        except Exception as e:
        return encoded_strings
        print ('%s not found.' %base_image_path)

# ==========================================================
Use as Pyhton 3+ import.
Run as script.
Run from terminal: C:\> python img2base64 c:/images png,jpg
C. Nichols
# ==========================================================
if __name__ in '__main__':
        Create a function to write results to disk.
        Add getopt and add an output file param.

    image_filter = [] # Add a filter if you need to or alter the defaults in the function directly.

    script_base_path = '' # Set the path to images here to override interactive console run.
    #script_base_path = r'C:\pyprod\prod_web\static\images'
    img_path = None
    arg_path = None
    arg_filter = None

    # Determine if this script is executed from the console.
    # ======================================================
    # Run as script.
    # ======================================================
    if script_base_path:
        if len(image_filter) > 0:
            encoded = get_image_base64(script_base_path,image_types=image_filter)
            encoded = get_image_base64(script_base_path)

    # ======================================================
    # Run as interactive console app.
    # ======================================================

        usage = '\n\nUsage:\n\n img2base64 path_to_images png,gif\n\n Path is required.\n Comma delimited list, no spaces, of extensions is optional. Default is png.'
        argc = len(sys.argv)

        if argc == 1: print ('Too few arguments! This program requires at least a path and optional extensions to process.%s'%usage)
        if argc > 3: print ('Too many arguments! This program requires path and optional extensions to process.%s'%usage)

        if argc == 2:
            prog,arg_path = sys.argv
            print ('running interactively at %s'  %arg_path)
            encoded = get_image_base64(arg_path)
        if argc == 3:
            prog,arg_path,arg_filter = sys.argv
            arg_filter = [i.strip().lower() for i in arg_filter.split(',')]

            print ('running interactively at %s with filter %s'  %(arg_path,arg_filter))
            encoded = get_image_base64(arg_path, image_types=arg_filter)

    # Do something with the output, write to file, whatever...
    for img_name,enc_string in encoded.items():
        if enc_string:
            print ('\n', img_name, '->', enc_string)
            print ('\n', img_name, '-> Failed')

Ajax driven HTML 5 radial gauge.

• March 25, 2015 • Comments Off on Ajax driven HTML 5 radial gauge.

I’ve updated the JavaScript gauge example I created years ago. It takes a value between 0 and 100 and will automatically update using Ajax to pull the values in from a json file so no need to refresh the page or submit form data, just have a script or web programming language update the json data file to update the gauge live.

If you want to create a radial gauge, like a speedometer, but are not sure where to begin this will get you started. It uses the canvas tag and works well in the latest IE. I have not tested it in other browsers but any browser that supports the canvas tag will work, including Safari on iPhone/iPad. My old code works so I have no reason to believe this wouldn’t. I’ve made this as basic as possible so it’s not bogged down in over complication or clutter. I was going to write up a walk through, but there isn’t much to it that can’t be found elsewhere, like information on JQuery Ajax, json, canvas, or HTML 5.

Download the the files, place in your web server directory, change the paths to the json and the JQuery code in the index.html file and point your browser to it. I’ve included a Python script for testing, which will update the values so you can be mesmerized as the needle spins every 30 seconds on a randomly picked value, or not.

If you want it to just update on outside a server, on refresh, page load, or form submit just remove the Ajax call in the document.ready and provide the values yourself. My old code shows how to do this with a form submit and that can be found in the Flash gauges page.

If you need a web server, get this awesome prepackaged and configured Apache server here. If you need Python, get it here. Both are free.

Statusbar example with Swift in XCode 6.2

• February 17, 2015 • Comments Off on Statusbar example with Swift in XCode 6.2

I’ve created a simple Statusbar application that dynamically creates a menu of Applications in the Utilities folder and opens the Application when the corresponding menu item is clicked. I use simple NSThread for the collection and use image assets for the icon. Not a lot of error handling and could be tweaked for speed, and maybe the thread was over kill, but it should be enough to get most people started. Hope some one finds it useful.

Here’s a link to the full project.


Minecraft Utilities

• February 8, 2015 • Comments Off on Minecraft Utilities

My son has been playing a lot of Minecraft and runs a server so I made him a series of utilities to make life easier. The first few I wrote were in Python and Tk, quick and dirty, but I wanted to learn the Swift programming language so I rewrote one utility in XCode 6 with Swift. What it does is moves worlds from the Minecraft saves folder to the server and updates the file. It’s just a simple little tool, but it saves him time as he switches between new worlds a lot. If this is something that interests you, you’re welcome to download it and use it. I consider this a public domain application so do with it as you wish. It’s tested on Yosemite.

Download MCServerUtil (MCWorld2Server)

Streamweaver and postscript, oh my…

• February 6, 2015 • Comments Off on Streamweaver and postscript, oh my…

I was tasked to write some Pitney Bowes Streamweaver code for Adobe ES produced postscript. It has been an interesting adventure as I am new to postscript and Streamweaver. I must side step the politics and get to the meat of it. So, I need to take 30k – give or take – letters with form attachments, etc. and save money. To do this the first step is too duplex. Sure, easy enough. The other savings is to group letters by address by envelope, an envelope holds seven pages. Sounds easy.

Well, the problem I have with proprietary products are the lack of examples, vague documentation, and nothing to reference on the internet. This is great for training and consulting dollars for them, but it is a waste of fucking time and money for everyone else, as you likely already know. This led me to write this in C# out of frustration in order to figure out how their product worked and to understand postscript structure.

So, I got Streamweaver working with very little code, but I also have all this C# code that adds blank pages to odd page counts for duplex reflections, sorts and merges the correspondence by address to fit into a standard envelope, and code that interrogates if the postscript is even correct in the first place! I was getting a lot of bad postscript that wasn’t very visible in Streamweaver.

I decided these might be useful command line tools. I’ll be getting these written, packaged up, and released soon. They will be free, open, and likely under the Apache 2 license. I will write them for Linux (C++ or Perl), Mac (Swift or Objective-C), and Windows (Mono C#). These will work on Adobe standard postscript.

Moon Diary – The Witch’s journal

• June 16, 2014 • Comments Off on Moon Diary – The Witch’s journal

Update – There is a major bug in the database code that causes loss of entries. Since I never got any feedback I am not patching or rewriting this software. Use at your own risk.

I created a simple journal application (book of shadows) geared towards Wiccan, it can double as a mood journal, and it’s free to use, forever – just made it for the hell of it in Xojo Basic since I got a cheap copy. If you want a secure and simple journal give it a try. All database entries are encrypted.

You can export all posts, create PDF or RTF of entries. It displays the current moon phase, weather, and astrological sign. It will notify you of Sabbats and Esbats as well. It’s only a Mac application though, sorry. Maybe if people like it I’ll make it better, add more features, and make it for Windows and Linux as well. Comment!

Update 2015-02-06, bugs: First launch shows black screen on entry listing. Not sure if this is just isolated to Yosemite or not, but restarting the app fixes this issue. I may rewrite this in Swift when I get time, which should be a bit more stable.

Update 2015-11-28: I’m planning a total rewrite in Swift and C#. I’m planning versions for Windows and Linux. The Windows and Linux versions will likely be released first and will ride on Mono,  for at least the Linux version.

Download for Mac 10.7+ MoonDiary

Quick and dirty way to get Location data on Mac in Xojo

• May 24, 2014 • Comments Off on Quick and dirty way to get Location data on Mac in Xojo

You could make a Xojo plugin in XCode to access the location data, buy a plugin, or maybe use AppleScript but I think this is simple and will work right in the console using Curl as well as within any language that can issue shell commands. Since it’s Curl it should work for Linux as well.

Create a button and add an Event Handler “Action” and paste in the following code. That’s it

  Dim s As New Shell
  Dim cmd As String
  Dim ip As Variant
  Dim city As Variant
  Dim state As Variant
  Dim country As Variant
  Dim zip As Variant
  Dim coordsArray(1) As String
  Dim coords As Variant
  Dim latitude As String
  Dim longitude As String
  cmd = "curl -s"
  If s.ErrorCode=0 Then
    Dim loc as new JSONItem(s.Result)
    ip = loc.Lookup("ip", "none")
    city = loc.Lookup("city", "none")
    state = loc.Lookup("region", "none")
    country = loc.Lookup("country", "none")
    zip = loc.Lookup("postal", "none")
    coords = loc.Lookup("loc", "")
    If len(coords) > 0 Then
      latitude = coordsArray(0)
      longitude = coordsArray(1)
    End If
    MsgBox("Error " + Str(s.ErrorCode))
  End If