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.Barcode; using Opait.Barcode.Pdf; // Creates a PDF417 barcode and adds it to all pages of a PDF file. static void AddBarcodeToPdf(string message, string sourceFile, string destFile) { // Create a barcode of the specified type and content. var barcode = Barcode.Create(BarcodeType.PDF417, message); // Create a PDF renderer with default parameters. var renderer = new BarcodePdfRenderer(); // Open the source PDF file and create a new destination PDF using (var srcPdf = new PdfDocument(sourceFile)) using (var dstPdf = new PdfDocument()) { // 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. renderer.RenderBarcode(dstPage, barcode, bounds.Left, bounds.Bottom, 120, 40); // Save the page. dstPdf.SavePage(dstPage); } // Complete saving of the entire document. dstPdf.EndSave(); } }