![]() | Add Barcodes to Existing PDF |
This sample encodes a text message as PDF417 barcode and adds it to every page of an existing PDF file. The results are saved as a new PDF file.
using Opait.Barcoder.Api; // Creates a PDF417 barcode and adds it to all pages of a PDF file. static void AddBarcodeToPdf(string message, string sourceFile, string destFile) { // Initialize the barcoder library with default options. var barcoder = new Barcoder(); // Create a barcode encoder of the specified type and content. var encoder = barcoder.CreateEncoder(BarcodeType.PDF417, message); // Create a PDF renderer for saving generated barcodes. var renderer = barcoder.CreatePdfRenderer(); // Open the source PDF file and create a new destination PDF using (var srcPdf = barcoder.OpenPdfDocument(sourceFile)) using (var dstPdf = barcoder.CreatePdfDocument()) { // Save pages as we modify them to reduce memory requirements. dstPdf.BeginSave(destFile); // Go through each page of source PDF for (var i = 0; i < srcPdf.PageCount; i++) { // Get the source page var srcPage = srcPdf.GetPage(i); // Add a copy of the source page to the destination PDF var dstPage = dstPdf.AddPage(srcPage); // Get the bounding rectangle of the page. var bounds = dstPage.CropBox; // Append the barcode to the existing content of the page. // Remember that PDF boxes are not inverted. (X,Y) is bottom left corner. renderer.RenderBarcode(dstPage, encoder, bounds.X + 5, bounds.Y + 5, 120, 40); // Save the page. dstPdf.SavePage(dstPage); } // Complete saving of the entire document. dstPdf.EndSave(); } }