Skip to content

Instantly share code, notes, and snippets.

@randyburden
Created November 2, 2014 21:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randyburden/dd20077d49de65f97018 to your computer and use it in GitHub Desktop.
Save randyburden/dd20077d49de65f97018 to your computer and use it in GitHub Desktop.
PdfSharp extensions for adding a 2D DataMatrix barcode to a PdfPage using the IEC16022Sharp library to generate the 2D barcode image.
namespace PDFMerger.Utilities
{
/// <summary>
/// Provides extension methods for PdfSharp objects.
/// </summary>
public static class PdfSharpExtensions
{
/// <summary>
/// Adds a 2D DataMatrix barcode to the PdfPage.
/// </summary>
/// <summary>
/// This method uses the IEC16022Sharp library, an open source C# implementation of the
/// ISO/IEC 16022:2006—Data Matrix bar code symbology specification: http://iec16022sharp.sourceforge.net/
/// </summary>
/// <param name="pdfPage">PdfPage to add the barcode to.</param>
/// <param name="barcodeData">Barcode data string.</param>
/// <param name="barcodeWidth">Barcode width.</param>
/// <param name="barcodeHeight">Barcode height.</param>
/// <param name="xCoordinate">X coordinate to place the barcode at.</param>
/// <param name="yCoordinate">Y coordinate to place the bardcode at.</param>
public static void Add2DDataMatrixBarcode( this PdfSharp.Pdf.PdfPage pdfPage, string barcodeData, int barcodeWidth, int barcodeHeight, int xCoordinate, int yCoordinate )
{
// Create the 2D DataMatrix barcode
var dataMatrix2DBarcode = new IEC16022Sharp.DataMatrix( barcodeData, barcodeWidth, barcodeHeight );
// Convert the 2D barcode Bitmap to an XImage
var image = PdfSharp.Drawing.XImage.FromGdiPlusImage( dataMatrix2DBarcode.Image );
// Convert the Pdf page to a canvas that can be written to
var pdfPageGraphics = PdfSharp.Drawing.XGraphics.FromPdfPage( pdfPage );
// Draw the barcode onto the canvas
pdfPageGraphics.DrawImage( image, xCoordinate, yCoordinate, image.PointWidth, image.PointHeight );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment