Rendering QR Codes on fillable PDFs

I was recently working on a project where a fillable PDF form was populated with data and a QR code needed to be placed on the form. Here an easy way to accomplish that:
First, load the form – in this example I just read it from a file. I am using this two page vaccination card:

I have the PDF in my bin directory, so I’ll just read it into memory like this:

using System.IO;
var fileBytes = File.ReadAllBytes("VaccineCard.pdf");

To fill data fields and add images to the PDF, we will use the iTextSharp Nuget package:
https://www.nuget.org/packages/iTextSharp/5.5.4 
Once that package reference is added, I can set up a PdfReader and a Stamper from the iTextSharp namespace:

using System.IO;
using iTextSharp.text.pdf;
namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            var fileBytes = File.ReadAllBytes("VaccineCard.pdf");
            using (var ms = new MemoryStream())
            {
                using (var reader = new PdfReader(fileBytes))
                {
                    using (var stamper = new PdfStamper(reader, ms))
                    {
                        ms.Write(fileBytes, 0, fileBytes.Length);
                    }
                }
            }
        }
    }

With the stamper, we can populate fillable fields using the AcroFields property. Here are the fields in the form I have loaded:

I will set a few values, and write the output to another file so we can see it:

stamper.AcroFields.SetField("First Name", "John");
stamper.AcroFields.SetField("Last Name", "Waters");
stamper.AcroFields.SetField("DOB", "1/1/2001");
stamper.AcroFields.SetField("Middle Init", "K");
// …
var output = ms.ToArray();
File.WriteAllBytes("VaccineCardFilled.pdf", output);

Here is the result:

That worked, great! Now let’s add a QR code.
For the QR codes, get the QRCoder Nuget, see https://github.com/codebude/QRCoder/

using QRCoder;

We will create a QR code for the value “123456789”. You can make QR codes out of any string – the more data the string contains, the larger and more complex the code becomes.

var qrGenerator = new QRCodeGenerator();
var qrCodeData = qrGenerator.CreateQrCode("123456789", QRCodeGenerator.ECCLevel.Q);
var qrCode = new Base64QRCode(qrCodeData);
var qrCodeImageAsBase64 = qrCode.GetGraphic(8);
var imageBytes = Convert.FromBase64String(qrCodeImageAsBase64);

If you look at the QRCoder documentation (link above), there are all kinds of ways to generate them. We will just do this simple image byte form. It uses a module size of 8 (8 dark pixels per square in the pattern). 

Next, I will place these generated QR code image bytes in an iTextSharp Image object, and set the width, height, X and Y coordinates of the image on the PDF. X starts from the left of the page, Y from the bottom of the page:

var img = Image.GetInstance(imageBytes);
img.ScaleAbsoluteWidth(40);
img.ScaleAbsoluteHeight(40);
img.SetAbsolutePosition(210, 165);

Finally, I will use the Stamper to place the image on an overlay of the form, on page 1:

stamper.GetOverContent(1).AddImage(img);

There it is!

To verify this, I will scan the QR code with RedLaser on my iPhone:

 
 
 
 
 
 
 
 
 
 
 
 
 
And there it is!
Here is the full code:

using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using QRCoder;
namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            var fileBytes = File.ReadAllBytes("VaccineCard.pdf");
            using (var ms = new MemoryStream())
            {
                using (var reader = new PdfReader(fileBytes))
                {
                    using (var stamper = new PdfStamper(reader, ms))
                    {
                        ms.Write(fileBytes, 0, fileBytes.Length);
                        stamper.AcroFields.SetField("First Name", "John");
                        stamper.AcroFields.SetField("Last Name", "Waters");
                        stamper.AcroFields.SetField("DOB", "1/1/2001");
                        stamper.AcroFields.SetField("Middle Init", "K");
                        var qrGenerator = new QRCodeGenerator();
                        var qrCodeData = qrGenerator.CreateQrCode("123456789", QRCodeGenerator.ECCLevel.Q);
                        var qrCode = new Base64QRCode(qrCodeData);
                        var qrCodeImageAsBase64 = qrCode.GetGraphic(8);
                        var imageBytes = Convert.FromBase64String(qrCodeImageAsBase64);
                        var img = Image.GetInstance(imageBytes);
                        img.ScaleAbsoluteWidth(40);
                        img.ScaleAbsoluteHeight(40);
                        img.SetAbsolutePosition(210, 165);
                        stamper.GetOverContent(1).AddImage(img);
                    }
                }
                var output = ms.ToArray();
                File.WriteAllBytes("VaccineCardFilled.pdf", output);
            }
        }
    }
}

Hopefully this will come in handy next time you need to add a QR code to a form!

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.