diff --git a/barcode/arabic/net/compact-pdf417-encoding/_index.md b/barcode/arabic/net/compact-pdf417-encoding/_index.md index 6b447ecb2..ffe52ba1b 100644 --- a/barcode/arabic/net/compact-pdf417-encoding/_index.md +++ b/barcode/arabic/net/compact-pdf417-encoding/_index.md @@ -84,6 +84,12 @@ PDF417 المدمج هو رمز ثنائي الأبعاد عالي السعة ي ## دروس ترميز PDF417 المدمج ### [إنشاء باركودات PDF417 المدمجة](./compact-pdf417-basic-configuration/) تعلم كيفية إنشاء باركودات PDF417 المدمجة باستخدام Aspose.BarCode for .NET. دليل شامل مع تعليمات خطوة بخطوة وأمثلة شفرة. +### [مثال Aspose للباركود: إنشاء Macro PDF417 بلغة C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +تعلم كيفية إنشاء رمز Macro PDF417 باستخدام Aspose.BarCode في C# خطوة بخطوة. +### [إنشاء باركود PDF417 بلغة C# – دليل خطوة بخطوة](./generate-pdf417-barcode-in-c-step-by-step-guide/) +تعلم كيفية إنشاء باركود PDF417 باستخدام C# خطوة بخطوة مع Aspose.BarCode. +### [إنشاء باركود من النص في C# – دليل خطوة بخطوة كامل](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +### [كيفية قراءة PDF417 في C# – دليل كامل لقارئ الباركود](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) ## الأسئلة المتكررة @@ -113,4 +119,4 @@ PDF417 المدمج هو رمز ثنائي الأبعاد عالي السعة ي {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/arabic/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/arabic/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..28eb96eb9 --- /dev/null +++ b/barcode/arabic/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-08-09 +description: مثال Aspose للباركود يوضح كيفية استخدام مولد الباركود C# لإنشاء Macro + PDF417 مع دعم كامل للبيانات الوصفية. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: ar +lastmod: 2026-08-09 +og_description: يوضح مثال Aspose للباركود استخدام مولد الباركود C# لإنشاء باركود Macro + PDF417 يتضمن معرف الملف، بيانات الجزء، الطابع الزمني وبيانات تعريفية أخرى. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: مثال Aspose للباركود – إنشاء Macro PDF417 باستخدام C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'مثال Aspose للباركود: إنشاء Macro PDF417 في C#' +url: /ar/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# مثال Aspose barcode: إنشاء Macro PDF417 في C# + +إذا كنت بحاجة إلى **aspose barcode example** الذي ينشئ شيفرة باركود Macro PDF417، يوضح لك هذا الدليل كيفية القيام بذلك باستخدام **barcode generator C#**. سترى جميع الإعدادات المطلوبة، من الأبعاد الأساسية إلى مجموعة الحقول الوصفية الكاملة لـ Macro PDF417، وستحصل في النهاية على صورة PNG جاهزة للمعالجة اللاحقة. + +يغطي الدليل سير العمل الكامل، يشرح لماذا كل معلمة مهمة، ويقدم مثال كود جاهز للتنفيذ. لا تحتاج إلى مراجع خارجية؛ يمكنك نسخ الكود، تعديل القيم، وتشغيله فورًا. + +## المتطلبات المسبقة + +قبل أن تبدأ، تأكد من أن لديك: + +- .NET 6.0 (أو أحدث) مثبتًا +- Visual Studio 2022 أو أي بيئة تطوير متوافقة مع C# +- ترخيص صالح لـ **Aspose.BarCode for .NET** (الإصدار التجريبي المجاني يعمل مع هذا المثال) + +أضف حزمة Aspose.BarCode NuGet إلى مشروعك: + +```bash +dotnet add package Aspose.BarCode +``` + +## الخطوة 1: إنشاء كائن barcode generator C# + +الخطوة الأولى هي إنشاء مثيل `BarcodeGenerator` باستخدام قيمة التعداد `EncodeTypes.MacroPdf417` والنص الذي تريد ترميزه. يمكن أن يحتوي النص على أحرف Unicode، والتي يتعامل معها المكتبة تلقائيًا. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*لماذا هذا مهم*: `EncodeTypes.MacroPdf417` يخبر المحرك بإنتاج رمز Macro PDF417، الذي يدعم البيانات المقسمة وبيانات وصفية على مستوى الملف. يضمن بيان `using` تحرير الموارد غير المُدارة بعد حفظ الصورة. + +## الخطوة 2: تعريف مظهر الباركود الأساسي + +يتكون باركود Macro PDF417 من وحدات مربعة. التحكم في حجم الوحدة وعدد الأعمدة يؤثر على كل من قابلية القراءة وحجم الملف. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*لماذا هذا مهم*: `XDimension.Pixels` يحدد الكثافة البصرية؛ قيمة 2 بكسل تعمل جيدًا للعرض على الشاشة مع الحفاظ على صغر حجم الصورة. عدّل عدد الأعمدة ليتناسب مع قيود التخطيط لديك—المزيد من الأعمدة ينتج باركود أوسع وأقصر. + +## الخطوة 3: تعيين البيانات الوصفية الخاصة بـ Macro PDF417 + +يوسّع Macro PDF417 تنسيق PDF417 القياسي بإضافة حقول تمكّن من إعادة بناء ملفات كبيرة من عدة قطاعات باركود. كل حقل اختياري، لكن تعيينها يُظهر كامل إمكانيات الـ API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*لماذا هذا مهم*: +- `MacroPdf417FileID` يربط جميع القطاعات التي تنتمي إلى نفس الملف المنطقي. +- `MacroPdf417SegmentID` و `MacroPdf417SegmentsCount` يتيحان للمُحلّل إعادة ترتيب القطع بشكل صحيح. +- `MacroPdf417Checksum` يوفر فحصًا سريعًا للسلامة دون الحاجة إلى فك ترميز كامل للحمولة. +- `MacroPdf417FileSize` و `MacroPdf417TimeStamp` يسمحان للأنظمة اللاحقة بالتحقق من أن الملف المعاد بناؤه يطابق الأصلي. +- `MacroPdf417Addressee` / `MacroPdf417Sender` مفيدان في سيناريوهات اللوجستيات أو تبادل المستندات. +- تعيين `MacroPdf417Terminator` إلى `Set` يُشير إلى أن هذا الباركود هو القطاع النهائي، مما يبسط خوارزمية إعادة البناء. + +## الخطوة 4: حفظ صورة الباركود المُولدة + +أخيرًا، احفظ الباركود كملف PNG. يمكنك اختيار أي تنسيق مدعوم (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*لماذا هذا مهم*: PNG يحافظ على بيانات البكسل بدون فقدان، مما يضمن أن القارئات تقرأ النمط الدقيق للوحدات التي قمت بتكوينها. قد يؤثر تغيير التنسيق على الجودة البصرية وحجم الملف. + +### النتيجة المتوقعة + +تشغيل البرنامج الكامل ينشئ ملفًا باسم **ExtPDF417Meta.png**. عند فتح الصورة، ستظهر شيفرة باركود Macro PDF417 مستطيلة مع النص “Åspóse.Barcóde©” مُرمّزًا، وتطابق الكثافة البصرية البُعد X البالغ 2 بكسل الذي حددته. قراءة الصورة باستخدام قارئ يدعم PDF417 تُعيد جميع الحقول الوصفية التي عُرّفت في الخطوة 3. + +## مثال عملي كامل + +انسخ الشيفرة أدناه إلى مشروع وحدة تحكم جديد (`dotnet new console`) واستبدل `YOUR_DIRECTORY` بمسار مطلق أو نسبي موجود على جهازك. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +شغّل البرنامج (`dotnet run`). بعد التنفيذ، تحقق من ظهور ملف PNG في الموقع الذي حددته. استخدم أي تطبيق قراءة باركود يدعم Macro PDF417 لتأكيد أن البيانات الوصفية مدمجة بشكل صحيح. + +## الاختلافات الشائعة والحالات الطرفية + +- **تنسيقات صور مختلفة**: استبدل `BarCodeImageFormat.Png` بـ `Jpeg` أو `Bmp` أو `Tiff` إذا كان نظامك اللاحق يفضّل تنسيقًا آخر. +- **تغيير حجم الوحدة**: القيم الأكبر لـ `XDimension.Pixels` تحسّن موثوقية القراءة على الماسحات منخفضة الدقة لكنها تزيد من حجم الصورة. +- **عدة قطاعات**: لإنشاء ملف متعدد القطاعات، أنشئ سلسلة من الباركودات، وزد `MacroPdf417SegmentID` لكل واحدة، واحتفظ بـ `MacroPdf417FileID` ثابتًا. يجب أن يحتوي القطاع الأخير فقط على `MacroPdf417Terminator` مُعيّن. +- **دعم Unicode**: المُولّد يرمّز أحرف Unicode تلقائيًا؛ تأكد من أن السلسلة المصدرية تستخدم ترميز UTF-8 إذا قرأتها من ملف خارجي. +- **معالجة الأخطاء**: غلف كتلة `using` بكتلة `try‑catch` لالتقاط `BarCodeException` في حال وجود معلمات غير صالحة (مثل عدد الأعمدة خارج النطاق). + +## نصائح احترافية + +- **الأداء**: أعد استخدام كائن `BarcodeGenerator` واحد عند إنشاء العديد من الباركودات بنفس الإعدادات؛ غير خاصية `CodeText` فقط بين عمليات الحفظ. +- **تقدير حجم الملف**: يجب أن يتطابق حقل `MacroPdf417FileSize` مع عدد البايتات للحمولة الأصلية؛ الاختلافات قد تتسبب في فشل التحقق في الأنظمة اللاحقة. +- **الاختبار**: تحقق من صحة الباركودات المُولدة باستخدام كل من المُحلّل المدمج في Aspose (`BarCodeReader`) ومُسحّب طرف ثالث لضمان التوافقية. + +## الخاتمة + +هذا **aspose barcode example + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تُبنى على التقنيات الموضحة في هذا الدليل. كل مصدر يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف نهج تنفيذ بديلة في مشاريعك الخاصة. + +- [كيفية إنشاء باركود – Compact PDF417 باستخدام Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [كيفية إنشاء منطقة هادئة للباركود Code 16K باستخدام Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [كيفية إنشاء منطقة هادئة للباركود ITF-14 باستخدام Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/arabic/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/arabic/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..7ab07c81d --- /dev/null +++ b/barcode/arabic/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-08-09 +description: إنشاء باركود من النص في C# باستخدام Aspose.BarCode. تعلم كيفية إنشاء + الباركود، ومعالجة الأحرف الخاصة، وإنشاء باركود PDF417 في C# بسرعة. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: ar +lastmod: 2026-08-09 +og_description: إنشاء باركود من النص في C# باستخدام Aspose.BarCode. يوضح هذا الدرس + كيفية إنشاء باركود، ودعم الأحرف الخاصة، وإنشاء باركود PDF417 في C# مع الكود الكامل. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: إنشاء باركود من النص في C# – دليل خطوة بخطوة سريع +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: إنشاء باركود من النص في C# – دليل خطوة بخطوة كامل +url: /ar/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء باركود من نص في C# – دليل خطوة بخطوة كامل + +إذا كنت بحاجة إلى **generate barcode from text** في تطبيق .NET، فإن هذا الدليل يشرح لك العملية بالكامل. سترى كيفية إنشاء الباركود، إدارة الأحرف الخاصة، وإنشاء تنفيذ PDF417 barcode C# يعمل مباشرةً. + +إنشاء باركود من نص هو طلب شائع لأنظمة الجرد، منصات التذاكر، وتدفقات عمل المستندات. بنهاية هذا الشرح ستحصل على تطبيق كونسول C# قابل للتنفيذ ينتج صورة PNG من نوع MicroPdf417 باستخدام Aspose.BarCode. لا تحتاج إلى خدمات خارجية، والكود يدعم أحرف Unicode مثل “Å”، “©”، و “é”. + +## المتطلبات المسبقة + +- .NET 6.0 SDK أو أحدث (الكود يعمل أيضاً مع .NET Core 3.1 و .NET Framework 4.7+) +- Visual Studio 2022 (أو أي بيئة تطوير تدعم C#) +- **Aspose.BarCode for .NET** حزمة NuGet + ```bash + dotnet add package Aspose.BarCode + ``` +- معرفة أساسية بصياغة C# + +## إنشاء باركود من نص – إعداد المولد + +الخطوة الأولى هي إنشاء كائن `BarcodeGenerator` يعرف أي **barcode encode type** تريد. في هذا الشرح نستخدم `EncodeTypes.MicroPdf417`، وهو نسخة مضغوطة من PDF417 مناسبة لسلاسل البيانات القصيرة. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Why this works:** +- `EncodeTypes.MicroPdf417` يخبر المكتبة باستخدام عائلة PDF417، مما يلبي متطلب **create pdf417 barcode c#**. +- المُنشئ يستقبل النص الأصلي، وهو جوهر **generate barcode from text**. +- دعم Unicode مدمج، لذا الأحرف مثل “Å” و “©” تُشفّر بشكل صحيح، مما يعالج **barcode with special characters**. + +## كيفية إنشاء باركود بأحرف خاصة + +عندما يحتوي بياناتك على رموز غير ASCII، يجب التأكد من أن المولد يستخدم ترميز UTF‑8. Aspose.BarCode يكتشف Unicode تلقائيًا، لكن يمكنك تعيين ترميز النص صراحة إذا واجهت مشاكل: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +إضافة هذا السطر قبل `ConfigureGenerator` يضمن أن **barcode with special characters** يُظهر بشكل صحيح على أي منصة. + +### نصيحة عملية +إذا كان الإخراج مشوشًا، تحقق من أن الخط المستخدم من قبل مُولّد الباركود يدعم الرموز المطلوبة. يمكنك تضمين خط TrueType مخصص عبر: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## أنواع ترميز الباركود التي يمكنك اختيارها + +Aspose.BarCode يدعم العشرات من **barcode encode types**، كل منها مناسب لحالات استخدام مختلفة: + +| نوع الترميز | حالة الاستخدام النموذجية | +|----------------------------|----------------------------------------------| +| `EncodeTypes.Code128` | ملصقات الشحن، الجرد | +| `EncodeTypes.QR` | المدفوعات المحمولة، الروابط | +| `EncodeTypes.Pdf417` | رخص القيادة، بطاقات الصعود | +| `EncodeTypes.MicroPdf417` | حجم بيانات صغير، مساحة محدودة | +| `EncodeTypes.DataMatrix` | عناصر صغيرة، كثافة بيانات عالية | + +تغيير نوع الترميز بسيط مثل استبدال قيمة الـ enum في المُنشئ: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +هذه المرونة تسمح لك بالإجابة على أسئلة **barcode encode types** دون مغادرة بيئة التطوير. + +## إنشاء باركود PDF417 C# – الخطوات النهائية والتحقق + +بعد ضبط المولد، الجزء الأخير من **create pdf417 barcode c#** هو حفظ الصورة وتأكيد النتيجة. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +شغّل البرنامج (`dotnet run`) وسترى رسالة كونسول مشابهة لـ: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +افتح ملف PNG؛ سترى باركود MicroPdf417 واضح يُشفّر السلسلة “Åspóse.Barcóde©”. مسحه باستخدام ماسح باركود محمول (مثل ZXing) يُعيد النص الأصلي، مما يثبت أن **generate barcode from text** يعمل حتى مع الأحرف الخاصة. + +### حالة حافة: نص طويل جدًا + +MicroPdf417 لديه سعة بيانات قصوى تبلغ 1 KB. إذا تجاوز مدخلك هذا الحد، تُطلق المكتبة استثناء `ArgumentException`. للتعامل مع ذلك بأناقة: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +للحمولات الأكبر، انتقل إلى `EncodeTypes.Pdf417` الكامل أو `EncodeTypes.DataMatrix`. + +## المشكلات الشائعة وكيفية تجنّبها + +| المشكلة | السبب | الحل | +|--------------------------------|------------------------------------------|------| +| الباركود يظهر غير واضح | XDimension منخفض جدًا (مثلاً 1 px) | زيادة `XDimension.Pixels` إلى 2‑3 px | +| الأحرف Unicode تصبح `?` | ترميز النص الافتراضي هو ASCII | تعيين `TextEncoding = Encoding.UTF8` | +| ملف الصورة لم يُنشأ | دليل الإخراج غير موجود | استخدام `Directory.CreateDirectory` قبل `Save` | +| المسح الضوئي لا يستطيع قراءة الباركود | عدد الأعمدة كبير جدًا للبيانات القصيرة | تقليل `Pdf417.Columns` (مثلاً 3‑4) | + +## الكود الكامل (جاهز للنسخ) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Expected output:** ملف باسم `MicroPdf417.png` موجود في مجلد `output`، يحتوي على باركود MicroPdf417 واضح يُشفّر السلسلة الأصلية مع الأحرف الخاصة. + +## الخلاصة + +أنت الآن تعرف كيف **generate barcode from text** في C# باستخدام Aspose.BarCode، وكيفية التعامل مع **barcode with special characters**، وكيفية **create pdf417 barcode c#** مع تحكم كامل في خيارات الترميز. من خلال تعديل **barcode encode types** يمكنك إنتاج QR codes، Code128، DataMatrix، أو أي تنسيق آخر مدعوم. + +بعد ذلك، استكشف المواضيع التالية لتعميق خبرتك في الباركود: + +- [كيفية إنشاء باركود – PDF417 مضغوط باستخدام Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [كيفية إنشاء باركود – تكوين Code 39 باستخدام Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [كيفية إنشاء باركود - أنواع الباركود أحادية البعد](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/arabic/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/arabic/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..acdb1a046 --- /dev/null +++ b/barcode/arabic/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-08-09 +description: إنشاء رمز شريطي PDF417 في C# بسرعة. تعلّم كيفية إنشاء PDF417 باستخدام + الوضع المدمج، التحكم في الأعمدة، وإخراج PNG باستخدام واجهة برمجة التطبيقات BarcodeGenerator. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: ar +lastmod: 2026-08-09 +og_description: إنشاء رمز شريطي PDF417 في C# مع مثال مختصر. يوضح لك هذا الدليل كيفية + تكوين وضع الضغط، ضبط الأعمدة، وحفظ النتيجة كصورة PNG. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: إنشاء رمز شريطي PDF417 في C# – دليل كامل +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: إنشاء باركود PDF417 في C# – دليل خطوة بخطوة +url: /ar/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء باركود PDF417 في C# – دليل خطوة بخطوة + +إذا كنت بحاجة إلى **إنشاء باركود PDF417** في تطبيق .NET، فإن هذا الدليل يوضح لك بالضبط كيفية القيام بذلك. سترى برنامجًا كاملاً قابلاً للتنفيذ يُنشئ باركود PDF417 مضغوط، يخصص حجمه، ويحفظ الصورة كملف PNG. + +إنشاء باركود PDF417 هو طلب شائع لتذاكر الهواتف المحمولة، تتبع المخزون، وأمان المستندات. يغطي هذا الدليل خيارات التكوين الأساسية، يشرح لماذا كل إعداد مهم، ويقدم نصائح عملية للاستخدام في العالم الحقيقي. + +## المتطلبات المسبقة + +قبل أن تبدأ، تأكد من وجود ما يلي: + +* .NET 6.0 SDK أو أحدث مثبت +* بيئة تطوير C# مثل Visual Studio 2022 أو Visual Studio Code +* حزمة NuGet **Aspose.BarCode for .NET** (الإصدار 23.10 أو أحدث) + +يمكنك تثبيت الحزمة باستخدام أمر سطر الأوامر التالي: + +```bash +dotnet add package Aspose.BarCode +``` + +يفترض الكود أدناه أن الحزمة مُشار إليها وأن لديك صلاحية كتابة إلى دليل الإخراج. + +## الخطوة 1: إعداد المشروع واستيراد المساحات الاسمية + +أنشئ مشروع وحدة تحكم جديد وأضف توجيهات `using` المطلوبة. تُظهر هذه المساحات الاسمية فئة `BarcodeGenerator` وتعداد صيغ الصورة. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**لماذا هذا مهم:** استيراد المساحات الاسمية الصحيحة يضمن أن المترجم يستطيع العثور على النوع `BarcodeGenerator` وتعداد `BarCodeImageFormat`. عدم وجود مساحة اسمية يؤدي إلى خطأ تجميع، مما يوقف عملية إنشاء الباركود. + +## الخطوة 2: تهيئة `BarcodeGenerator` بترميز PDF417 + +يتلقى مُنشئ `BarcodeGenerator` معاملين: نوع الباركود (`EncodeTypes.Pdf417`) والنص الذي تريد ترميزه. يدعم PDF417 مجموعة واسعة من الأحرف، بما في ذلك رموز Unicode. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**شرح:** +* `EncodeTypes.Pdf417` يخبر المكتبة باستخدام معيار PDF417. +* نص العينة يحتوي على أحرف مُعَلمة ورمز حقوق النشر لتوضيح معالجة Unicode. + +إذا كنت بحاجة إلى ترميز بيانات رقمية فقط، يمكنك تمرير سلسلة بسيطة مثل `"1234567890"`. + +## الخطوة 3: ضبط البُعد X للحصول على دقة أعلى + +يتحكم البُعد X في عرض وحدة الباركود الفردية (أصغر عنصر أسود أو أبيض). ضبط قيمة بكسل أصغر ينتج صورة ذات دقة أعلى. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**لماذا يتم ضبطه؟** قد ينتج بُعد X الافتراضي 3–4 بكسل باركودًا يبدو خشنًا على الشاشات ذات الكثافة العالية DPI. تقليلها إلى **2 بكسل** يوازن بين قابلية القراءة وحجم الملف، خاصةً عندما تقوم بتمكين وضع الضغط لاحقًا. + +## الخطوة 4: تكوين عدد الأعمدة + +يسمح PDF417 لك بتحديد عدد الأعمدة التي يجب أن يحتويها الباركود. عدد أقل من الأعمدة يجعل الباركود أضيق لكن أطول، بينما عدد أكبر ينتج باركودًا أعرض وأقصر. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**نصيحة عملية:** لتذاكر الهواتف المحمولة التي تحتاج إلى أن تتناسب مع ملصق ضيق، يعمل عدد الأعمدة **3–5** بشكل جيد. زد العدد إذا كان لديك الكثير من البيانات وتريد باركودًا أقصر. + +## الخطوة 5: تمكين وضع الضغط لقص الصفوف الفارغة + +يزيل وضع الضغط الصفوف غير الضرورية من مصفوفة الباركود، مما يقلل من حجم الصورة الإجمالي دون فقدان البيانات المشفرة. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**متى تستخدمه:** إذا كنت تنشئ باركودات للتخزين أو النقل عبر الشبكة، يمكن لوضع الضغط تقليل ملف PNG بنسبة تصل إلى 30 %. ومع ذلك، قد لا تدعم بعض القارئات القديمة PDF417 المقصوص؛ اختبر ذلك مع الأجهزة المستهدفة. + +## الخطوة 6: حفظ الباركود كصورة PNG + +اختر مسار الإخراج واستدعِ `Save`. ينتج تعداد `BarCodeImageFormat.Png` صورة غير مضغوطة مناسبة لمعظم التطبيقات. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**التحقق من النتيجة:** افتح ملف PNG في أي عارض صور. يجب أن ترى باركودًا كثيفًا وعالي التباين يطابق نص العينة. مسح الصورة باستخدام قارئ PDF417 (مثل ZXing أو تطبيق هاتف ذكي) يعيد السلسلة الأصلية `"Åspóse.Barcóde©"`. + +![صورة باركود PDF417 تم إنشاؤها وحفظها كملف PNG](compact-pdf417.png "باركود PDF417 تم إنشاؤه في C#") + +*الصورة أعلاه توضح النتيجة النهائية لكود الدليل.* + +## مثال كامل قابل للتنفيذ + +بجمع كل الأجزاء معًا، إليك برنامج وحدة تحكم كامل يمكنك نسخه، لصقه، وتشغيله. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### النتيجة المتوقعة + +تشغيل البرنامج يطبع: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +الملف `CompactPdf417.png` يحتوي على باركود PDF417 مضغوط يرمز إلى سلسلة Unicode المقدمة. مسح الصورة باستخدام قارئ PDF417 قياسي يعيد النص الدقيق. + +## تنوعات شائعة وحالات حافة + +| الحالة | التعديل | السبب | +|-----------|------------|--------| +| **حجم بيانات أطول** (مثال، > 150 حرف) | زيادة `generator.Parameters.Barcode.Pdf417.Columns` إلى 6‑8 | المزيد من الأعمدة يمنع الباركود من أن يصبح طويلًا جدًا. | +| **الحاجة إلى خلفية شفافة** | استخدام `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | PNG الشفاف يندمج بشكل أفضل مع طبقات واجهة المستخدم. | +| **إنشاء JPEG للويب** | تغيير الصيغة إلى `BarCodeImageFormat.Jpeg` واختيارياً ضبط `ImageQuality` | JPEG يقلل حجم الملف على حساب فقدان الدقة غير الضائعة. | +| **معالجة إدخال فارغ أو null** | حماية الإدخال قبل إنشاء المولد: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | يمنع استثناءات وقت التشغيل ويضمن باركودات ذات معنى. | + +## نصائح للاستخدام في بيئة الإنتاج + +* **معالجة الاستثناءات:** غلف منطق الإنشاء داخل كتلة `try/catch` لتسجيل الأخطاء مثل نقص مساحة القرص أو المعاملات غير الصالحة. +* **الأداء:** أعد استخدام كائن `BarcodeGenerator` واحد عند إنشاء العديد من الباركودات بنفس الإعدادات؛ فقط قم بتحديث خاصية `CodeText` بين عمليات الحفظ. +* **الأمان:** عندما يحتوي النص المشفر على معلومات حساسة، فكر في تشفيره قبل تمريره إلى المولد وفك تشفيره بعد المسح. + +## الخلاصة + +أنت الآن تعرف كيف **تنشئ باركود PDF417** في C# باستخدام مكتبة Aspose.BarCode، وتضبط وضع الضغط، وتتحكم في عدد الأعمدة، وتصدّر النتيجة كصورة PNG. غطى هذا الدليل كل خطوة من إعداد المشروع إلى التعامل مع الحالات الخاصة، مقدمًا لك حلًا جاهزًا للاستخدام في تطبيقات تعتمد على الباركود. + +بعد ذلك، استكشف المواضيع ذات الصلة مثل **إنشاء رموز QR في C#**، **إنشاء باركودات دفعةً**, و**دمج مسح الباركود مع التطبيقات المحمولة**. كل منها يبني على أساسيات `BarcodeGenerator` التي تعلمتها الآن. + +برمجة سعيدة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية إنشاء باركود PDF417 – ترميز PDF417 مضغوط](/barcode/english/net/compact-pdf417-encoding/) +- [كيفية إنشاء باركود – PDF417 مضغوط باستخدام Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [كيفية إنشاء باركود Aztec بنسبة أبعاد مخصصة باستخدام Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/arabic/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/arabic/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..3cf7cca62 --- /dev/null +++ b/barcode/arabic/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-09 +description: كيفية قراءة PDF417 في C# باستخدام BarCodeReader. تعلم قراءة ملفات PNG + للباركود، ومعالجة عدة باركودات، واستخراج البيانات الوصفية الموسعة. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: ar +lastmod: 2026-08-09 +og_description: كيفية قراءة PDF417 في C# باستخدام Aspose.BarCode. يوضح هذا البرنامج + التعليمي كيفية قراءة ملفات PNG للباركود، ومعالجة عدة باركودات في صورة واحدة، واسترجاع + بيانات التعريف الموسعة لـ PDF417. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: كيفية قراءة PDF417 في C# – دليل قارئ الباركود +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: كيفية قراءة PDF417 في C# – دليل شامل لقارئ الباركود +url: /ar/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية قراءة PDF417 في C# – دليل قارئ الباركود الكامل + +إذا كنت بحاجة إلى **كيفية قراءة PDF417** في تطبيق .NET، فإن هذا الدليل يزودك بحل جاهز للتنفيذ. ستتعرف على كيفية قراءة صورة PNG لباركود، ومعالجة عدة باركودات في نفس الصورة، واستخراج الحقول الموسعة لـ PDF417 التي يخفيها العديد من الماسحات. + +قراءة باركودات PDF417 شائعة في اللوجستيات، وإصدار التذاكر، وإدارة المستندات. بحلول نهاية هذا الدرس يمكنك فك تشفير صورة Macro PDF417، وعرض كل نتيجة، واستخدام المعلومات الإضافية (معرف الملف، عدد القطاعات، الطوابع الزمنية، إلخ) في منطق عملك الخاص. + +## المتطلبات المسبقة + +- .NET 6.0 أو أحدث (الكود يعمل أيضًا مع .NET Framework 4.7+) +- Visual Studio 2022 أو أي بيئة تطوير C# +- **Aspose.BarCode for .NET** (نسخة تجريبية مجانية أو حزمة NuGet مرخصة) +- صورة PNG تحتوي على باركود Macro PDF417 (ملف العينة اسمه `ExtPDF417Meta.png`) + +> **نصيحة احترافية:** قم بتثبيت المكتبة باستخدام وحدة تحكم NuGet: +> `dotnet add package Aspose.BarCode` + +## كيفية قراءة PDF417 باستخدام BarCodeReader في C# + +جوهر الحل هو الفئة `BarCodeReader`. تقبل مسار الصورة وعداد `DecodeType` الذي يخبر المحرك بالرمز الذي يجب البحث عنه. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### لماذا يعمل هذا + +- **`DecodeType.MacroPdf417`** يخبر القارئ بالبحث عن نسخة Macro PDF417، التي تخزن الحقول الإضافية التي تراها في الخطوة 4. +- كتلة `using` تقوم بتحرير القارئ تلقائيًا، وتحرير مقابض الملفات. +- `ReadBarCodes()` تُرجع **كل** الباركودات التي تطابق النوع المطلوب، مما يلبي متطلب *قراءة عدة باركودات* حتى إذا كانت الصورة تحتوي على واحد فقط. + +تشغيل البرنامج يطبع مخرجات مشابهة لـ: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## استخدام قارئ الباركود C# لقراءة عدة باركودات + +إذا كانت الصورة تحتوي على عدة رموز Macro PDF417 (مثلاً، صفحة ممسوحة ضوئيًا تحتوي على دفعة من التذاكر)، فإن حلقة `foreach` نفسها تعالج كل واحدة. لا يلزم أي كود إضافي؛ القارئ يجمع النتائج داخليًا. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### الأخطاء الشائعة + +- **تنسيق الصورة:** القارئ يدعم PNG، JPEG، BMP، وTIFF. إذا جربت تنسيقًا لا يستطيع فك تشفيره، ستحصل على مجموعة فارغة. لهذا يسلط الدرس الضوء على *قراءة باركود PNG*. +- **الدقة:** الصور منخفضة الدقة (< 300 dpi) قد تتسبب في فقدان القطاعات. قم بزيادة الدقة أو اطلب مسحًا بجودة أعلى عندما يكون ذلك ممكنًا. +- **علامة Macro:** نسيان `DecodeType.MacroPdf417` يقتصر المحرك على PDF417 العادي ويتجاهل البيانات الموسعة. دائمًا حدد نوع الماكرو عندما تحتاج إلى حقول *قراءة باركود موسعة*. + +## قراءة ملفات PNG للباركود – أفضل الممارسات + +التعامل مع ملفات PNG سهل لأن التنسيق يحافظ على بيانات البكسل بدون فقدان. إليك قائمة سريعة: + +1. تحقق من وجود الملف قبل إنشاء القارئ. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. استخدم `Image.FromFile` فقط عندما تحتاج إلى معالجة مسبقة (دوران، قص). يمكن لـ `BarCodeReader` فتح الملف مباشرة، مما يجنب تخصيص ذاكرة إضافية. +3. إذا كان PNG يحتوي على شفافية، يظل القارئ يعمل لأن الباركود يُرسم على بكسلات غير شفافة. + +## الوصول إلى بيانات PDF417 الموسعة + +الكائن `Extended.Pdf417` يكشف كل حقل اختياري معرف في مواصفة PDF417. يمكنك ربط هذه الحقول بنموذج نطاق، تخزينها في قاعدة بيانات، أو استخدامها للتحقق. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +املأ النموذج: + + + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات المعروضة في هذا الدليل. كل مصدر يتضمن أمثلة شفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية قراءة باركود DataMatrix باستخدام Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [كيفية إنشاء باركود – PDF417 مضغوط باستخدام Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [قراءة باركود DataMatrix C# – توليد وضع DataMatrix (تلقائي)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/chinese/net/compact-pdf417-encoding/_index.md b/barcode/chinese/net/compact-pdf417-encoding/_index.md index 165dd64a9..c4c0a4023 100644 --- a/barcode/chinese/net/compact-pdf417-encoding/_index.md +++ b/barcode/chinese/net/compact-pdf417-encoding/_index.md @@ -85,7 +85,23 @@ Aspose.BarCode 允许您设置 `Pdf417ErrorCorrectionLevel` 属性(0‑8)。 ### [创建紧凑 PDF417 条形码](./compact-pdf417-basic-configuration/) -了解如何使用 Aspose.BarCode for .NET 生成紧凑 PDF417 条形码。提供完整的分步指南和代码示例。 +了解如何使用 Aspose.BarCode for .NET 生成紧凑 PDF417 条码。提供完整的分步指南和代码示例。 + +### [Aspose 条码示例:在 C# 中生成宏 PDF417](./aspose-barcode-example-generate-macro-pdf417-in-c/) + +了解如何使用 Aspose.BarCode for .NET 在 C# 中生成宏 PDF417 条码。提供完整的示例代码和步骤说明。 + +### [在 C# 中生成 PDF417 条形码 – 步骤指南](./generate-pdf417-barcode-in-c-step-by-step-guide/) + +了解如何使用 Aspose.BarCode for .NET 在 C# 中逐步生成 PDF417 条码,包含完整代码示例。 + +### [在 C# 中从文本生成条形码 – 完整分步指南](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) + +了解如何使用 Aspose.BarCode for .NET 在 C# 中从文本生成条形码,提供完整的分步指南和代码示例。 + +### [如何在 C# 中读取 PDF417 – 完整条码读取指南](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) + +了解如何使用 Aspose.BarCode for .NET 在 C# 中读取 PDF417 条码,提供完整的步骤和示例代码。 ## 常见问题 @@ -115,4 +131,4 @@ Aspose.BarCode 允许您设置 `Pdf417ErrorCorrectionLevel` 属性(0‑8)。 {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/chinese/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/chinese/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..c0327e969 --- /dev/null +++ b/barcode/chinese/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-09 +description: Aspose 条码示例展示如何使用 C# 条码生成器创建具有完整元数据支持的宏 PDF417。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: zh +lastmod: 2026-08-09 +og_description: Aspose 条形码示例演示如何使用 C# 条形码生成器生成包含文件 ID、段数据、时间戳及其他元数据的 Macro PDF417 + 条码。 +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Aspose 条码示例 – 使用 C# 创建宏 PDF417 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: Aspose 条形码示例:在 C# 中生成宏 PDF417 +url: /zh/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose 条形码示例:在 C# 中生成 Macro PDF417 + +如果您需要一个 **aspose barcode example** 来创建 Macro PDF417 条形码,本指南将展示如何使用 **barcode generator C#** 实现。您将看到所有必需的设置,从基本尺寸到完整的 Macro PDF417 元数据字段,最终得到一张可供后续处理的 PNG 图像。 + +本教程涵盖完整工作流,解释每个参数的重要性,并提供可直接运行的代码示例。无需外部引用;复制代码、调整数值后即可立即运行。 + +## 前置条件 + +在开始之前,请确保您已具备: + +- 已安装 .NET 6.0(或更高版本) +- Visual Studio 2022 或任意支持 C# 的 IDE +- 有效的 **Aspose.BarCode for .NET** 许可证(免费试用版即可运行本示例) + +将 Aspose.BarCode NuGet 包添加到项目中: + +```bash +dotnet add package Aspose.BarCode +``` + +## 第一步:创建 barcode generator C# 实例 + +第一步是使用 `EncodeTypes.MacroPdf417` 枚举值和要编码的文本实例化 `BarcodeGenerator`。文本可以包含 Unicode 字符,库会自动处理。 + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*为什么重要*:`EncodeTypes.MacroPdf417` 告诉引擎生成 Macro PDF417 符号,该符号支持分段数据和额外的文件级元数据。`using` 语句确保在保存图像后释放非托管资源。 + +## 第二步:定义条形码的基本外观 + +Macro PDF417 条形码由方形模块组成。控制模块大小和列数会影响可读性和文件大小。 + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*为什么重要*:`XDimension.Pixels` 决定视觉密度;2 像素的值在屏幕显示时效果良好且保持图像体积小。根据布局约束调整列数——列数越多,条形码越宽、越短。 + +## 第三步:设置 Macro PDF417 特定元数据 + +Macro PDF417 在标准 PDF417 格式基础上扩展了字段,以便从多个条形码段重建大文件。每个字段都是可选的,但设置它们可以展示 API 的全部功能。 + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*为什么重要*: +- `MacroPdf417FileID` 将属于同一逻辑文件的所有段关联起来。 +- `MacroPdf417SegmentID` 与 `MacroPdf417SegmentsCount` 使解码器能够正确重新排序片段。 +- `MacroPdf417Checksum` 提供快速完整性校验,无需解码整个负载。 +- `MacroPdf417FileSize` 与 `MacroPdf417TimeStamp` 让下游系统验证重建文件是否与原始文件匹配。 +- `MacroPdf417Addressee` / `MacroPdf417Sender` 在物流或文档交换场景中非常有用。 +- 将 `MacroPdf417Terminator` 设置为 `Set` 标记此条形码为最后一个段,简化重建算法。 + +## 第四步:保存生成的条形码图像 + +最后,将条形码写入 PNG 文件。您可以选择任何受支持的格式(`Png`、`Jpeg`、`Bmp`、`Gif`、`Tiff`)。 + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*为什么重要*:PNG 保留无损像素数据,确保扫描仪读取您配置的精确模块图案。更改格式可能会影响视觉质量和文件大小。 + +### 预期输出 + +运行完整程序后会生成名为 **ExtPDF417Meta.png** 的文件。打开图像可看到一个矩形的 Macro PDF417 条形码,已编码文本为 “Åspóse.Barcóde©”,视觉密度与您设置的 2 像素 X 维度相匹配。使用兼容 PDF417 的阅读器扫描该图像,可返回第 3 步中定义的所有元数据字段。 + +## 完整可运行示例 + +将以下代码复制到新建的控制台项目(`dotnet new console`)中,并将 `YOUR_DIRECTORY` 替换为您机器上存在的绝对或相对路径。 + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +运行程序(`dotnet run`)。执行完毕后,确认 PNG 文件出现在您指定的位置。使用任何支持 Macro PDF417 的条形码读取应用,验证元数据已正确嵌入。 + +## 常见变体和边缘情况 + +- **不同的图像格式**:如果下游系统偏好其他格式,可将 `BarCodeImageFormat.Png` 替换为 `Jpeg`、`Bmp` 或 `Tiff`。 +- **更改模块大小**:较大的 `XDimension.Pixels` 值可提升低分辨率扫描仪的扫描可靠性,但会增大图像尺寸。 +- **多个段**:若要生成多段文件,生成一系列条形码,为每个条形码递增 `MacroPdf417SegmentID`,并保持 `MacroPdf417FileID` 不变。仅最后一个段应将 `MacroPdf417Terminator` 设置为 `Set`。 +- **Unicode 支持**:生成器会自动编码 Unicode 字符;如果从外部文件读取源字符串,请确保使用 UTF-8 编码。 +- **错误处理**:将 `using` 块包装在 try‑catch 中,以捕获 `BarCodeException`,处理参数无效(例如列数超出范围)等错误。 + +## 专业技巧 + +- **性能**:在创建大量具有相同设置的条形码时,复用单个 `BarcodeGenerator` 实例;仅在保存之间更改 `CodeText` 属性。 +- **文件大小估算**:`MacroPdf417FileSize` 字段应与原始负载的字节数相匹配;不匹配可能导致下游验证失败。 +- **测试**:使用 Aspose 内置解码器 (`BarCodeReader`) 与第三方扫描器同时验证生成的条形码,以确保互操作性。 + +## 结论 + +此 **aspose barcode example + +## 接下来您应该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助您在项目中进一步掌握 API 功能并探索替代实现方式。每个资源都提供完整的可运行代码示例和逐步解释。 + +- [如何使用 Aspose.BarCode 创建紧凑型 PDF417 条形码](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [如何使用 Aspose.BarCode for .NET 为 Code 16K 条形码创建静默区](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [如何使用 Aspose.BarCode for .NET 为 ITF-14 条形码创建静默区](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/chinese/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/chinese/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..14ccfcfa1 --- /dev/null +++ b/barcode/chinese/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-08-09 +description: 使用 Aspose.BarCode 在 C# 中从文本生成条形码。了解如何生成条形码、处理特殊字符,并快速创建 PDF417 条形码(C#)。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: zh +lastmod: 2026-08-09 +og_description: 使用 Aspose.BarCode 在 C# 中从文本生成条形码。本教程展示了如何生成条形码、支持特殊字符,并使用完整代码创建 PDF417 + 条形码(C#)。 +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: 在 C# 中从文本生成条形码 – 快速一步步指南 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: 在 C# 中从文本生成条形码 – 完整的逐步指南 +url: /zh/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中从文本生成条形码 – 完整分步指南 + +如果您需要在 .NET 应用程序中 **从文本生成条形码**,本指南将带您完整完成整个过程。您将了解如何生成条形码、处理特殊字符,并创建一个开箱即用的 PDF417 条形码 C# 实现。 + +从文本生成条形码是库存系统、票务平台和文档工作流中的常见需求。完成本教程后,您将拥有一个可运行的 C# 控制台应用程序,使用 Aspose.BarCode 生成 MicroPdf417 PNG 图像。无需外部服务,代码还能处理诸如 “Å”、 “©” 和 “é” 等 Unicode 字符。 + +## 前提条件 + +- .NET 6.0 SDK 或更高版本(代码同样适用于 .NET Core 3.1 和 .NET Framework 4.7+) +- Visual Studio 2022(或任何支持 C# 的 IDE) +- **Aspose.BarCode for .NET** NuGet 包 + ```bash + dotnet add package Aspose.BarCode + ``` +- 基本的 C# 语法知识 + +## 从文本生成条形码 – 设置生成器 + +第一步是创建一个 `BarcodeGenerator` 实例,并指定您想要的 **barcode encode type**。本教程使用 `EncodeTypes.MicroPdf417`,它是适用于短数据字符串的紧凑型 PDF417 变体。 + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**工作原理说明:** +- `EncodeTypes.MicroPdf417` 告诉库使用 PDF417 系列,满足 **create pdf417 barcode c#** 的需求。 +- 构造函数接收原始文本,这正是 **generate barcode from text** 的核心。 +- 内置 Unicode 支持,能够正确编码 “Å” 与 “©” 等字符,解决 **barcode with special characters** 的问题。 + +## 如何生成带有特殊字符的条形码 + +当数据包含非 ASCII 符号时,需要确保生成器使用 UTF‑8 编码。Aspose.BarCode 会自动检测 Unicode,但如果遇到问题,可以显式设置文本编码: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +在 `ConfigureGenerator` 之前添加此行,可保证 **barcode with special characters** 在任何平台上都能正确渲染。 + +### 实用技巧 +如果输出出现乱码,请确认条形码渲染器使用的字体支持所需字形。您可以通过以下方式嵌入自定义 TrueType 字体: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## 可供选择的条形码编码类型 + +Aspose.BarCode 支持数十种 **barcode encode types**,每种都适用于不同的使用场景: + +| 编码类型 | 常见使用场景 | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | 运输标签、库存管理 | +| `EncodeTypes.QR` | 移动支付、URL | +| `EncodeTypes.Pdf417` | 驾驶执照、登机牌 | +| `EncodeTypes.MicroPdf417` | 小数据负载、空间受限 | +| `EncodeTypes.DataMatrix` | 微小物品、高数据密度 | + +只需在构造函数中替换枚举值即可更改编码类型: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +这种灵活性让您在 IDE 中即可回答 **barcode encode types** 的相关问题。 + +## 创建 PDF417 条形码 C# – 最后步骤与验证 + +配置好生成器后,**create pdf417 barcode c#** 的最后一步是保存图像并确认结果。 + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +运行程序(`dotnet run`),您应在控制台看到类似以下的消息: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +打开 PNG 文件,您会看到一张清晰的 MicroPdf417 条形码,编码的字符串为 “Åspóse.Barcóde©”。使用移动条形码扫描器(例如 ZXing)扫描后返回原始文本,证明 **generate barcode from text** 在特殊字符下也能正常工作。 + +### 边缘情况:超长文本 + +MicroPdf417 的最大数据容量为 1 KB。如果输入超过此限制,库会抛出 `ArgumentException`。可通过以下方式优雅处理: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +对于更大的负载,请切换到完整的 `EncodeTypes.Pdf417` 或 `EncodeTypes.DataMatrix`。 + +## 常见陷阱及规避方法 + +| 问题 | 原因 | 解决方案 | +|-----------------------------------|----------------------------------------|----------| +| 条形码显示模糊 | XDimension 过低(如 1 px) | 将 `XDimension.Pixels` 提升至 2‑3 px | +| Unicode 字符显示为 `?` | 默认文本编码为 ASCII | 设置 `TextEncoding = Encoding.UTF8` | +| 未生成图像文件 | 输出目录不存在 | 在 `Save` 前使用 `Directory.CreateDirectory` | +| 扫描器无法读取条形码 | 短数据使用的列数过多 | 减少 `Pdf417.Columns`(如 3‑4 列) | + +## 完整源码(可直接复制) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**预期输出:** 在 `output` 文件夹下生成名为 `MicroPdf417.png` 的文件,内含清晰的 MicroPdf417 条形码,能够编码带有特殊字符的原始字符串。 + +## 结论 + +现在,您已经掌握了如何在 C# 中使用 Aspose.BarCode **generate barcode from text**,以及如何处理 **barcode with special characters**,并能够 **create pdf417 barcode c#** 并完全控制编码选项。通过调整 **barcode encode types**,您可以生成 QR 码、Code128、DataMatrix 或其他受支持的格式。 + +接下来,探索以下主题以深化您的条形码专业知识: + +- **How to generate barcode** 批量生成(对数千条记录使用 `Parallel.ForEach` 提升速度) +- 自定义颜色并在条形码中添加徽标 +- 将条形码生成集成到 ASP.NET Core API 中,实现即时图像返回 +- 使用 ZXing.Net、IronBarcode 等开源库作为替代方案 + +尽情尝试不同的尺寸、列设置和编码类型吧。祝编码愉快,愿您的应用扫描无误! + +## 接下来该学习什么? + +以下教程涵盖与本指南技术密切相关的主题,提供完整的可运行代码示例和逐步解释,帮助您掌握更多 API 功能并在项目中探索替代实现方式。 + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/chinese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/chinese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..a24ef5454 --- /dev/null +++ b/barcode/chinese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-09 +description: 快速在 C# 中生成 PDF417 条码。了解如何使用 BarcodeGenerator API 通过紧凑模式、列控制和 PNG 输出生成 + PDF417。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: zh +lastmod: 2026-08-09 +og_description: 在 C# 中生成 PDF417 条码的简明示例。本指南展示如何配置紧凑模式、设置列数,并将结果保存为 PNG 图像。 +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: 在 C# 中生成 PDF417 条形码 – 完整教程 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: 在 C# 中生成 PDF417 条码 – 步骤指南 +url: /zh/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中生成 PDF417 条形码 – 步骤指南 + +如果您需要在 .NET 应用程序中**生成 PDF417 条形码**,本教程将向您展示具体的实现方法。您将看到一个完整、可运行的程序,它可以创建紧凑的 PDF417 条形码、定制其尺寸,并将图像保存为 PNG 文件。 + +生成 PDF417 条形码是移动票务、库存跟踪和文档安全等场景的常见需求。本指南涵盖关键的配置选项,解释每个设置的意义,并提供实用的真实场景使用技巧。 + +## 前置条件 + +在开始之前,请确保您具备以下条件: + +* .NET 6.0 SDK 或更高版本已安装 +* C# IDE,例如 Visual Studio 2022 或 Visual Studio Code +* **Aspose.BarCode for .NET** NuGet 包(版本 23.10 或更高) + +您可以使用以下 CLI 命令安装该包: + +```bash +dotnet add package Aspose.BarCode +``` + +下面的代码假设已引用该包,并且您对输出目录拥有写入权限。 + +## 步骤 1:设置项目并导入命名空间 + +创建一个新的控制台项目并添加所需的 `using` 指令。这些命名空间公开 `BarcodeGenerator` 类和图像格式枚举。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**为什么这很重要:** 导入正确的命名空间可确保编译器能够定位 `BarcodeGenerator` 类型和 `BarCodeImageFormat` 枚举。缺少命名空间会导致编译错误,从而中断条形码生成过程。 + +## 步骤 2:使用 PDF417 编码初始化 `BarcodeGenerator` + +`BarcodeGenerator` 构造函数接受两个参数:条形码符号系统 (`EncodeTypes.Pdf417`) 和要编码的文本。PDF417 支持广泛的字符集,包括 Unicode 符号。 + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**说明:** +* `EncodeTypes.Pdf417` 告诉库使用 PDF417 标准。 +* 示例文本包含重音字符和版权符号,以演示 Unicode 处理。 + +如果只需要编码数字数据,可以传入类似 `"1234567890"` 的普通字符串。 + +## 步骤 3:调整 X 维度以获得更高分辨率 + +X 维度控制单个条形码模块(最小的黑白单元)的宽度。设置更小的像素值可获得更高分辨率的图像。 + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**为什么要调整?** 默认的 3–4 像素 X 维度在高 DPI 屏幕上可能导致条形码显得粗糙。将其降低到 **2 像素** 可在保持可读性的同时平衡文件大小,尤其是在随后启用紧凑模式时。 + +## 步骤 4:配置列数 + +PDF417 允许您指定条形码应包含的列数。列数少会使条形码更窄但更高,列数多则生成更宽、较短的条形码。 + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**实用提示:** 对于需要放在窄标签内的移动票务,**3–5** 列的设置效果良好。如果数据量大且希望条形码更短,可增加列数。 + +## 步骤 5:启用紧凑模式以截断空行 + +紧凑模式会移除条形码矩阵中不必要的行,从而在不丢失编码数据的前提下降低整体图像尺寸。 + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**何时使用:** 如果您生成的条形码用于存储或网络传输,紧凑模式可将 PNG 文件大小缩小最多 30 %。但某些旧版扫描仪可能不支持截断的 PDF417;请在目标硬件上进行测试。 + +## 步骤 6:将条形码保存为 PNG 图像 + +选择输出路径并调用 `Save`。`BarCodeImageFormat.Png` 枚举会生成适用于大多数场景的无损图像。 + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**结果验证:** 在任意图像查看器中打开 PNG 文件。您应该看到一条密集、高对比度的条形码,且内容与示例文本一致。使用 PDF417 读取器(例如 ZXing 或手机应用)扫描该图像,可返回原始字符串 `"Åspóse.Barcóde©"`。 + +![已保存为 PNG 的生成的 PDF417 条形码图像](compact-pdf417.png "C# 中生成的 PDF417 条形码") + +*上图展示了本教程代码的最终输出效果。* + +## 完整、可运行的示例 + +将所有步骤组合在一起,以下是一个完整的控制台程序,您可以复制、粘贴并直接运行。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### 预期输出 + +运行程序后会打印: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +文件 `CompactPdf417.png` 包含一个紧凑的 PDF417 条形码,编码了提供的 Unicode 字符串。使用标准 PDF417 读取器扫描该图像可得到完全相同的文本。 + +## 常见变体和边缘情况 + +| 情形 | 调整 | 原因 | +|-----------|------------|--------| +| **数据负载较长**(例如 > 150 字符) | 将 `generator.Parameters.Barcode.Pdf417.Columns` 增加至 6‑8 | 更多列可防止条形码变得过高。 | +| **需要透明背景** | 使用 `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | 透明 PNG 更易在 UI 覆盖层中使用。 | +| **为 Web 生成 JPEG** | 将格式改为 `BarCodeImageFormat.Jpeg` 并可选设置 `ImageQuality` | JPEG 可在牺牲无损性的前提下降低文件大小。 | +| **处理 null 或空输入** | 在创建生成器前进行检查:`if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | 防止运行时异常并确保生成有意义的条形码。 | + +## 生产环境使用技巧 + +* **异常处理:** 将生成逻辑包装在 `try/catch` 块中,以记录磁盘空间不足或参数无效等错误。 +* **性能:** 在大量生成条形码且设置相同的情况下,复用同一个 `BarcodeGenerator` 实例;只在保存之间更新 `CodeText` 属性。 +* **安全性:** 当编码的文本包含敏感信息时,考虑在传递给生成器之前进行加密,扫描后再解密。 + +## 结论 + +您现在已经掌握了使用 Aspose.BarCode 库在 C# 中**生成 PDF417 条形码**的完整流程,能够配置紧凑模式、控制列数,并将结果导出为 PNG 图像。本教程覆盖了从项目搭建到边缘案例处理的每一步,为条形码驱动的应用提供了即插即用的解决方案。 + +接下来,您可以进一步探索 **在 C# 中创建 QR 码**、**批量条形码生成**以及**将条形码扫描集成到移动应用**等相关主题。所有这些都基于您刚刚掌握的 `BarcodeGenerator` 基础。 + +祝编码愉快! + +## 接下来应该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助您进一步掌握 API 功能并在项目中尝试不同的实现方式。每篇资源都提供完整的可运行代码示例和逐步解释。 + +- [如何生成 PDF417 条形码 – 紧凑 PDF417 编码](/barcode/english/net/compact-pdf417-encoding/) +- [如何创建条形码 – 使用 Aspose.BarCode 的紧凑 PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [如何使用 Aspose.BarCode for .NET 生成具有自定义宽高比的 Aztec 条形码](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/chinese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/chinese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..7ccf26584 --- /dev/null +++ b/barcode/chinese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-08-09 +description: 如何在 C# 中使用 BarCodeReader 读取 PDF417。学习读取条形码 PNG 文件、处理多个条形码并提取扩展元数据。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: zh +lastmod: 2026-08-09 +og_description: 如何在 C# 中使用 Aspose.BarCode 读取 PDF417。本教程展示了如何读取条形码 PNG 文件、在同一图像中处理多个条形码以及检索扩展的 + PDF417 元数据。 +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: 如何在 C# 中读取 PDF417 – 条形码阅读器教程 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: 如何在 C# 中读取 PDF417 – 完整条码阅读器指南 +url: /zh/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 C# 中读取 PDF417 – 完整条码读取指南 + +如果您需要在 .NET 应用程序中**读取 PDF417**,本指南为您提供一个即开即用的解决方案。您将看到如何读取条码 PNG、在同一图像中处理多个条码,以及提取许多扫描仪隐藏的扩展 PDF417 字段。 + +在物流、票务和文档管理中,读取 PDF417 条码非常常见。通过本教程,您可以解码 Macro PDF417 图像,显示所有结果,并在自己的业务逻辑中使用额外信息(文件 ID、段计数、时间戳等)。 + +## Prerequisites + +- .NET 6.0 或更高版本(代码同样适用于 .NET Framework 4.7+) +- Visual Studio 2022 或任何 C# IDE +- **Aspose.BarCode for .NET**(免费试用或授权的 NuGet 包) +- 包含 Macro PDF417 条码的 PNG 图像(示例文件名为 `ExtPDF417Meta.png`) + +> **技巧提示:** 使用 NuGet 控制台安装库: +> `dotnet add package Aspose.BarCode` + +## 使用 BarCodeReader 在 C# 中读取 PDF417 + +该解决方案的核心是 `BarCodeReader` 类。它接受图像路径和一个 `DecodeType` 枚举,用于指示引擎要查找的符号类型。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### 为什么这样有效 + +- **`DecodeType.MacroPdf417`** 告诉读取器查找 Macro PDF417 变体,该变体存储您在第 4 步中看到的额外字段。 +- `using` 块会自动释放读取器,释放文件句柄。 +- `ReadBarCodes()` 返回**所有**匹配请求类型的条码,即使图像中只有一个,也满足*读取多个条码*的需求。 + +运行程序后会打印类似以下的输出: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## 使用 C# 条码读取器读取多个条码 + +如果图像包含多个 Macro PDF417 符号(例如,包含一批票据的扫描页),相同的 `foreach` 循环会处理每一个。无需额外代码;读取器会在内部聚合结果。 + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### 常见陷阱 + +- **图像格式:** 读取器支持 PNG、JPEG、BMP 和 TIFF。如果使用它无法解码的格式,将得到空集合。这也是教程强调*读取条码 PNG*的原因。 +- **分辨率:** 低分辨率图像(< 300 dpi)可能导致段缺失。尽可能进行放大或请求更高质量的扫描。 +- **宏标志:** 忘记使用 `DecodeType.MacroPdf417` 会将引擎限制为普通 PDF417 并丢弃扩展数据。当需要*读取条码扩展*字段时,请始终指定宏类型。 + +## 读取条码 PNG 文件 – 最佳实践 + +使用 PNG 文件相对简单,因为该格式保留无损像素数据。以下是快速检查清单: + +1. 在创建读取器之前验证文件是否存在。 + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. 仅在需要预处理(旋转、裁剪)时使用 `Image.FromFile`。`BarCodeReader` 可以直接打开文件,从而避免额外的内存分配。 +3. 如果 PNG 包含透明度,读取器仍然可以工作,因为条码渲染在不透明像素上。 + +## 访问扩展 PDF417 元数据 + +`Extended.Pdf417` 对象公开了 PDF417 规范定义的所有可选字段。您可以将这些字段映射到领域模型、存储到数据库或用于验证。 + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +填充模型: + + + +## 接下来您应该学习什么? + +以下教程涵盖与本指南演示的技术密切相关的主题。每个资源都包含完整的可运行代码示例和逐步说明,帮助您掌握更多 API 功能,并在自己的项目中探索替代实现方案。 + +- [如何使用 Aspose.BarCode for .NET 读取 DataMatrix 条码](/barcode/english/net/datamatrix-barcode-reading/) +- [如何使用 Aspose.BarCode 创建条码 – 紧凑型 PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [读取 DataMatrix 条码 C# – 生成 DataMatrix 模式(自动)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/czech/net/compact-pdf417-encoding/_index.md b/barcode/czech/net/compact-pdf417-encoding/_index.md index 29de108a1..25967fbaf 100644 --- a/barcode/czech/net/compact-pdf417-encoding/_index.md +++ b/barcode/czech/net/compact-pdf417-encoding/_index.md @@ -86,6 +86,18 @@ Mimo základy, zde jsou některé praktické tipy pro zefektivnění vašeho pra ### [Vytváření Compact PDF417 čárových kódů](./compact-pdf417-basic-configuration/) Naučte se generovat Compact PDF417 čárové kódy pomocí Aspose.BarCode pro .NET. Kompletní průvodce s krok‑za‑krokem instrukcemi a ukázkami kódu. +### [Příklad Aspose Barcode: generování Macro PDF417 v C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Ukázka, jak pomocí Aspose.BarCode pro .NET vygenerovat Macro PDF417 čárový kód v jazyce C#. + +### [Generování PDF417 čárového kódu v C# – krok za krokem](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Podrobný návod, jak v C# pomocí Aspose.BarCode vytvořit PDF417 čárový kód s ukázkovým kódem. + +### [Generování čárového kódu z textu v C# – kompletní krok‑za‑krokem průvodce](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Kompletní návod, jak v C# pomocí Aspose.BarCode vygenerovat čárový kód z libovolného textu. + +### [Jak číst PDF417 v C# – kompletní průvodce čtečkou čárových kódů](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +Kompletní návod, jak v C# pomocí Aspose.BarCode načíst a dekódovat PDF417 čárové kódy. + ## Často kladené otázky **Q:** Jaké je maximální množství dat, která mohu uložit do Compact PDF417 čárového kódu? @@ -114,4 +126,4 @@ Naučte se generovat Compact PDF417 čárové kódy pomocí Aspose.BarCode pro . {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/czech/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/czech/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..4e8749315 --- /dev/null +++ b/barcode/czech/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-09 +description: Příklad Aspose Barcode ukazující, jak v C# použít generátor čárových + kódů k vytvoření Macro PDF417 s plnou podporou metadat. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: cs +lastmod: 2026-08-09 +og_description: Příklad čárového kódu Aspose ukazuje použití generátoru čárových kódů + v C# k vytvoření makro PDF417 čárového kódu, který obsahuje ID souboru, data segmentu, + časové razítko a další metadata. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Příklad čárového kódu Aspose – vytvořit Macro PDF417 v C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Příklad čárového kódu Aspose: generování Macro PDF417 v C#' +url: /cs/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Příklad Aspose barcode: generování Macro PDF417 v C# + +Pokud potřebujete **aspose barcode example**, který vytvoří čárový kód Macro PDF417, tento průvodce vám ukáže, jak to provést pomocí **barcode generator C#**. Uvidíte všechna potřebná nastavení, od základních rozměrů po kompletní sadu polí metadat Macro PDF417, a získáte PNG obrázek připravený pro další zpracování. + +Tutoriál pokrývá celý pracovní postup, vysvětluje, proč je každý parametr důležitý, a poskytuje připravený kód, který lze okamžitě spustit. Žádné externí odkazy nejsou potřeba; můžete kód zkopírovat, upravit hodnoty a spustit ho ihned. + +## Požadavky + +Než začnete, ujistěte se, že máte: + +- .NET 6.0 (nebo novější) nainstalováno +- Visual Studio 2022 nebo jakékoli IDE kompatibilní s C# +- Platnou licenci pro **Aspose.BarCode for .NET** (pro tento příklad funguje bezplatná zkušební verze) + +Přidejte do svého projektu NuGet balíček Aspose.BarCode: + +```bash +dotnet add package Aspose.BarCode +``` + +## Krok 1: Vytvoření instance barcode generator C# + +Prvním krokem je vytvořit instanci `BarcodeGenerator` s hodnotou výčtu `EncodeTypes.MacroPdf417` a textem, který chcete zakódovat. Text může obsahovat Unicode znaky, které knihovna zpracuje automaticky. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Proč je to důležité*: `EncodeTypes.MacroPdf417` říká enginu, aby vytvořil symbol Macro PDF417, který podporuje segmentovaná data a další metadata na úrovni souboru. `using` blok zajišťuje uvolnění neřízených prostředků po uložení obrázku. + +## Krok 2: Definování základního vzhledu čárového kódu + +Macro PDF417 čárový kód se skládá ze čtvercových modulů. Ovládání velikosti modulu a počtu sloupců ovlivňuje čitelnost i velikost souboru. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Proč je to důležité*: `XDimension.Pixels` určuje vizuální hustotu; hodnota 2 pixelů dobře funguje pro zobrazení na obrazovce a zároveň udržuje obrázek malý. Upravením počtu sloupců přizpůsobíte kód vašim rozměrům – více sloupců vytvoří širší a kratší čárový kód. + +## Krok 3: Nastavení specifických metadat Macro PDF417 + +Macro PDF417 rozšiřuje standardní formát PDF417 o pole, která umožňují rekonstrukci velkých souborů z více segmentů čárových kódů. Každé pole je volitelné, ale jejich nastavení ukazuje plné možnosti API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Proč je to důležité*: +- `MacroPdf417FileID` propojuje všechny segmenty patřící ke stejnému logickému souboru. +- `MacroPdf417SegmentID` a `MacroPdf417SegmentsCount` umožňují dekodéru správně seřadit fragmenty. +- `MacroPdf417Checksum` poskytuje rychlou kontrolu integrity bez nutnosti dekódovat celý payload. +- `MacroPdf417FileSize` a `MacroPdf417TimeStamp` umožňují následným systémům ověřit, že rekonstruovaný soubor odpovídá originálu. +- `MacroPdf417Addressee` / `MacroPdf417Sender` jsou užitečné v logistických nebo dokumentových scénářích. +- Nastavením `MacroPdf417Terminator` na `Set` označíte tento čárový kód jako poslední segment, což zjednodušuje algoritmus rekonstrukce. + +## Krok 4: Uložení vygenerovaného obrázku čárového kódu + +Nakonec zapíšete čárový kód do PNG souboru. Můžete zvolit libovolný podporovaný formát (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Proč je to důležité*: PNG zachovává bezztrátová data pixelů, což zajišťuje, že skenery přečtou přesně ten modulový vzor, který jste nastavili. Změna formátu může ovlivnit vizuální kvalitu a velikost souboru. + +### Očekávaný výstup + +Po spuštění kompletního programu se vytvoří soubor **ExtPDF417Meta.png**. Otevřením obrázku uvidíte obdélníkový Macro PDF417 čárový kód s textem „Åspóse.Barcóde©“ zakódovaným, a vizuální hustota odpovídá nastavené 2‑pixelové X‑dimenzi. Naskenováním obrázku čtečkou kompatibilní s PDF417 získáte všechna metadata definovaná v kroku 3. + +## Kompletní funkční příklad + +Zkopírujte níže uvedený kód do nového konzolového projektu (`dotnet new console`) a nahraďte `YOUR_DIRECTORY` absolutní nebo relativní cestou, která existuje na vašem počítači. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Spusťte program (`dotnet run`). Po dokončení ověřte, že se PNG soubor objevil na zadaném umístění. Použijte libovolnou aplikaci pro čtení čárových kódů, která podporuje Macro PDF417, a potvrďte, že metadata jsou správně vložena. + +## Běžné varianty a okrajové případy + +- **Různé formáty obrázků**: Nahraďte `BarCodeImageFormat.Png` hodnotou `Jpeg`, `Bmp` nebo `Tiff`, pokud váš následný systém upřednostňuje jiný formát. +- **Změna velikosti modulu**: Větší hodnoty `XDimension.Pixels` zlepšují spolehlivost skenování na nízkém rozlišení, ale zvětšují velikost obrázku. +- **Více segmentů**: Pro vytvoření souboru s více segmenty vygenerujte sérii čárových kódů, inkrementujte `MacroPdf417SegmentID` u každého a ponechte `MacroPdf417FileID` konstantní. Pouze poslední segment by měl mít nastavený `MacroPdf417Terminator`. +- **Podpora Unicode**: Generátor automaticky kóduje Unicode znaky; ujistěte se, že váš vstupní řetězec používá kódování UTF‑8, pokud jej čtete z externího souboru. +- **Zpracování chyb**: Zabalte `using` blok do try‑catch a zachyťte `BarCodeException` pro neplatné parametry (např. počet sloupců mimo rozsah). + +## Praktické tipy + +- **Výkon**: Znovu použijte jedinou instanci `BarcodeGenerator` při vytváření mnoha čárových kódů se stejným nastavením; mezi ukládáními měňte pouze vlastnost `CodeText`. +- **Odhad velikosti souboru**: Pole `MacroPdf417FileSize` by mělo odpovídat počtu bajtů původního payloadu; nesoulad může způsobit selhání validace v následných systémech. +- **Testování**: Ověřte vygenerované čárové kódy jak pomocí vestavěného dekodéru Aspose (`BarCodeReader`), tak pomocí třetí strany, abyste zajistili interoperabilitu. + +## Závěr + +Tento **aspose barcode example + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční příklady kódu s podrobnými vysvětleními, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní přístupy ve vašich vlastních projektech. + +- [Jak vytvořit čárový kód – Compact PDF417 s Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Jak vytvořit tichou zónu čárového kódu pro Code 16K pomocí Aspose.BarCode pro .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [Jak vytvořit tichou zónu čárového kódu pro ITF-14 pomocí Aspose.BarCode pro .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/czech/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/czech/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..2ec41d41b --- /dev/null +++ b/barcode/czech/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-08-09 +description: Generujte čárový kód z textu v C# pomocí Aspose.BarCode. Naučte se, jak + generovat čárový kód, zacházet se speciálními znaky a rychle vytvořit PDF417 čárový + kód v C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: cs +lastmod: 2026-08-09 +og_description: Generujte čárový kód z textu v C# pomocí Aspose.BarCode. Tento tutoriál + ukazuje, jak generovat čárový kód, podporovat speciální znaky a vytvořit PDF417 + čárový kód v C# s kompletním kódem. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Vytvořte čárový kód z textu v C# – rychlý krok‑za‑krokem průvodce +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Generování čárového kódu z textu v C# – kompletní krok‑za‑krokem průvodce +url: /cs/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generovat čárový kód z textu v C# – kompletní průvodce krok za krokem + +Pokud potřebujete **generovat čárový kód z textu** v .NET aplikaci, tento průvodce vás provede celým procesem. Uvidíte, jak generovat čárový kód, spravovat speciální znaky a vytvořit implementaci PDF417 čárového kódu v C#, která funguje ihned. + +Generování čárového kódu z textu je běžnou požadavkem pro inventární systémy, platformy pro prodej vstupenek a pracovní postupy s dokumenty. Na konci tohoto tutoriálu budete mít spustitelnou C# konzolovou aplikaci, která pomocí Aspose.BarCode vytvoří PNG obrázek MicroPdf417. Žádné externí služby nejsou potřeba a kód zvládá Unicode znaky jako “Å”, “©” a “é”. + +## Požadavky + +- .NET 6.0 SDK nebo novější (kód také funguje s .NET Core 3.1 a .NET Framework 4.7+) +- Visual Studio 2022 (nebo jakékoli IDE podporující C#) +- **Aspose.BarCode for .NET** NuGet balíček + ```bash + dotnet add package Aspose.BarCode + ``` +- Základní znalost syntaxe C# + +## Generovat čárový kód z textu – nastavení generátoru + +Prvním krokem je vytvořit instanci `BarcodeGenerator`, která ví, jaký **typ kódování čárového kódu** chcete. V tomto tutoriálu používáme `EncodeTypes.MicroPdf417`, což je kompaktní varianta PDF417 vhodná pro krátké datové řetězce. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Proč to funguje:** +- `EncodeTypes.MicroPdf417` říká knihovně, aby použila rodinu PDF417, čímž splňuje požadavek **create pdf417 barcode c#**. +- Konstruktor přijímá surový text, což je podstata **generate barcode from text**. +- Podpora Unicode je vestavěná, takže znaky jako “Å” a “©” jsou kódovány správně, což řeší **barcode with special characters**. + +## Jak generovat čárový kód se speciálními znaky + +Když vaše data obsahují ne‑ASCII symboly, musíte zajistit, aby generátor používal kódování UTF‑8. Aspose.BarCode automaticky detekuje Unicode, ale můžete explicitně nastavit kódování textu, pokud narazíte na problémy: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Přidání tohoto řádku před `ConfigureGenerator` zaručuje, že **barcode with special characters** se vykreslí správně na jakékoli platformě. + +### Praktický tip +Pokud výstup vypadá poškozeně, ověřte, že písmo použité renderérem čárových kódů podporuje požadované glyfy. Vlastní TrueType písmo můžete vložit pomocí: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Typy kódování čárových kódů, které můžete zvolit + +Aspose.BarCode podporuje desítky **barcode encode types**, z nichž každý je vhodný pro různé případy použití: + +| Encode type | Typické použití | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | Štítky pro dopravu, inventář | +| `EncodeTypes.QR` | Mobilní platby, URL | +| `EncodeTypes.Pdf417` | Řidičské průkazy, palubní vstupenky | +| `EncodeTypes.MicroPdf417` | Malé datové náklady, omezený prostor | +| `EncodeTypes.DataMatrix` | Malé položky, vysoká datová hustota | + +Změna typu kódování je tak jednoduchá, jako vyměnit hodnotu enumu v konstruktoru: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Tato flexibilita vám umožní odpovědět na otázky ohledně **barcode encode types** bez opuštění IDE. + +## Vytvořit PDF417 čárový kód v C# – poslední kroky a ověření + +Po nastavení generátoru je poslední částí **create pdf417 barcode c#** uložení obrázku a potvrzení výsledku. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Spusťte program (`dotnet run`) a měli byste vidět zprávu v konzoli podobnou této: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Otevřete PNG soubor; uvidíte ostrý MicroPdf417 čárový kód, který kóduje řetězec “Åspóse.Barcóde©”. Skenování pomocí mobilního skeneru čárových kódů (např. ZXing) vrátí původní text, což dokazuje, že **generate barcode from text** funguje i se speciálními znaky. + +### Okrajový případ: velmi dlouhý text + +MicroPdf417 má maximální kapacitu dat 1 KB. Pokud váš vstup překročí tento limit, knihovna vyhodí `ArgumentException`. Pro elegantní ošetření: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Pro větší náklady přepněte na plnou `EncodeTypes.Pdf417` nebo `EncodeTypes.DataMatrix`. + +## Časté úskalí a jak se jim vyhnout + +| Problém | Příčina | Řešení | +|---------------------------------------|-------------------------------------------|--------| +| Čárový kód je rozmazaný | XDimension příliš nízký (např. 1 px) | Zvyšte `XDimension.Pixels` na 2‑3 px | +| Unicode znaky se mění na `?` | Výchozí kódování textu je ASCII | Nastavte `TextEncoding = Encoding.UTF8` | +| Soubor obrázku nebyl vytvořen | Výstupní adresář neexistuje | Použijte `Directory.CreateDirectory` před `Save` | +| Skener nedokáže čárový kód přečíst | Příliš mnoho sloupců pro krátká data | Snižte `Pdf417.Columns` (např. 3‑4) | + +## Kompletní zdrojový kód (připravený ke kopírování) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Očekávaný výstup:** soubor pojmenovaný `MicroPdf417.png` umístěný ve složce `output`, obsahující čistý MicroPdf417 čárový kód, který kóduje původní řetězec se speciálními znaky. + +## Závěr + +Nyní víte, jak **generovat čárový kód z textu** v C# pomocí Aspose.BarCode, jak zacházet s **barcode with special characters**, a jak **create pdf417 barcode c#** s plnou kontrolou nad možnostmi kódování. Úpravou **barcode encode types** můžete vytvářet QR kódy, Code128, DataMatrix nebo jakýkoli jiný podporovaný formát. + +Dále prozkoumejte následující témata, abyste prohloubili své znalosti o čárových kódech: + +- **How to generate barcode** ve šarži pro tisíce záznamů (použijte `Parallel.ForEach` pro rychlost) +- Přizpůsobení barev a přidání loga uvnitř čárového kódu +- Integrace generování čárových kódů do ASP.NET Core API pro okamžité doručování obrázků +- Použití dalších knihoven jako ZXing.Net nebo IronBarcode jako open‑source alternativy + +Neváhejte experimentovat s různými rozměry, nastavením sloupců a typy kódování. Šťastné programování a ať vaše aplikace skenují bezchybně! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Jak vytvořit čárový kód – Kompaktní PDF417 s Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Jak generovat čárový kód – Konfigurace Code 39 s Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Jak generovat čárový kód – Jednorozměrné typy čárových kódů](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/czech/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/czech/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..105c60381 --- /dev/null +++ b/barcode/czech/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-08-09 +description: Rychle generujte čárový kód PDF417 v C#. Naučte se, jak generovat PDF417 + s kompaktním režimem, řízením sloupců a výstupem PNG pomocí API BarcodeGenerator. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: cs +lastmod: 2026-08-09 +og_description: Vygenerujte čárový kód PDF417 v C# pomocí stručného příkladu. Tento + průvodce vám ukáže, jak nastavit kompaktní režim, nastavit sloupce a uložit výsledek + jako PNG obrázek. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Vytvořte čárový kód PDF417 v C# – kompletní návod +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: Generování čárového kódu PDF417 v C# – krok za krokem +url: /cs/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generování PDF417 čárového kódu v C# – krok za krokem + +Pokud potřebujete **vygenerovat PDF417 čárový kód** v .NET aplikaci, tento tutoriál vám přesně ukáže, jak na to. Uvidíte kompletní, spustitelný program, který vytvoří kompaktní PDF417 čárový kód, přizpůsobí jeho velikost a uloží obrázek jako PNG soubor. + +Generování PDF417 čárového kódu je běžná potřeba pro mobilní vstupenky, sledování zásob a zabezpečení dokumentů. Tento průvodce pokrývá základní konfigurační možnosti, vysvětluje, proč je každé nastavení důležité, a poskytuje praktické tipy pro reálné nasazení. + +## Předpoklady + +Než začnete, ujistěte se, že máte: + +* .NET 6.0 SDK nebo novější nainstalovaný +* C# IDE, např. Visual Studio 2022 nebo Visual Studio Code +* NuGet balíček **Aspose.BarCode for .NET** (verze 23.10 nebo novější) + +Balíček můžete nainstalovat pomocí následujícího CLI příkazu: + +```bash +dotnet add package Aspose.BarCode +``` + +Níže uvedený kód předpokládá, že je balíček referencován a že máte oprávnění zapisovat do výstupního adresáře. + +## Krok 1: Nastavení projektu a import jmenných prostorů + +Vytvořte nový konzolový projekt a přidejte požadované `using` direktivy. Tyto jmenné prostory zpřístupňují třídu `BarcodeGenerator` a výčtový typ pro formát obrázku. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Proč je to důležité:** Import správných jmenných prostorů zajišťuje, že kompilátor najde typ `BarcodeGenerator` a výčet `BarCodeImageFormat`. Chybějící jmenný prostor vede k chybě kompilace, která zastaví proces generování čárového kódu. + +## Krok 2: Inicializace `BarcodeGenerator` s kódováním PDF417 + +Konstruktor `BarcodeGenerator` přijímá dva argumenty: symbologii čárového kódu (`EncodeTypes.Pdf417`) a text, který chcete zakódovat. PDF417 podporuje širokou škálu znaků, včetně Unicode symbolů. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Vysvětlení:** +* `EncodeTypes.Pdf417` říká knihovně, aby použila standard PDF417. +* Ukázkový text obsahuje diakritické znaky a symbol copyrightu pro demonstraci práce s Unicode. + +Pokud potřebujete zakódovat jen číselná data, můžete předat prostý řetězec jako `"1234567890"`. + +## Krok 3: Úprava X‑dimenze pro vyšší rozlišení + +X‑dimenze řídí šířku jednoho modulu čárového kódu (nejmenšího černého nebo bílého prvku). Nastavení menší hodnoty v pixelech vede k obrázku s vyšším rozlišením. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Proč to upravit?** Výchozí X‑dimenze 3–4 pixelů může vytvořit čárový kód, který vypadá hrubě na obrazovkách s vysokým DPI. Snížení na **2 pixely** vyvažuje čitelnost a velikost souboru, zejména když později zapnete kompaktní režim. + +## Krok 4: Nastavení počtu sloupců + +PDF417 umožňuje určit, kolik sloupců má čárový kód obsahovat. Méně sloupců dělá čárový kód užší, ale vyšší, zatímco více sloupců vytvoří širší, kratší kód. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Praktický tip:** Pro mobilní vstupenky, které musí zapadnout do úzké etikety, funguje počet sloupců **3–5** dobře. Počet sloupců zvyšte, pokud máte hodně dat a chcete kratší čárový kód. + +## Krok 5: Povolení kompaktního režimu pro oříznutí prázdných řádků + +Kompaktní režim odstraňuje z matice čárového kódu zbytečné řádky, čímž snižuje celkovou velikost obrázku, aniž by ztratil zakódovaná data. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Kdy jej použít:** Pokud generujete čárové kódy pro ukládání nebo přenos přes síť, kompaktní režim může zmenšit PNG soubor až o 30 %. Některé starší skenery však nemusí podporovat oříznutý PDF417; otestujte s vaším cílovým hardwarem. + +## Krok 6: Uložení čárového kódu jako PNG obrázku + +Zvolte výstupní cestu a zavolejte `Save`. Výčet `BarCodeImageFormat.Png` vytvoří bezztrátový obrázek vhodný pro většinu aplikací. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Ověření výsledku:** Otevřete PNG soubor v libovolném prohlížeči obrázků. Měli byste vidět hustý, vysokokontrastní čárový kód, který odpovídá ukázkovému textu. Naskenováním obrázku čtečkou PDF417 (např. ZXing nebo mobilní aplikací) získáte původní řetězec `"Åspóse.Barcóde©"`. + +![Generated PDF417 barcode image saved as PNG](compact-pdf417.png "Generated PDF417 barcode in C#") + +*Obrázek výše demonstruje finální výstup kódu z tutoriálu.* + +## Kompletní, spustitelný příklad + +Když spojíme všechny části, získáme kompletní konzolový program, který můžete zkopírovat, vložit a spustit. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Očekávaný výstup + +Po spuštění programu se vypíše: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +Soubor `CompactPdf417.png` obsahuje kompaktní PDF417 čárový kód, který zakóduje poskytnutý Unicode řetězec. Naskenováním obrázku standardní čtečkou PDF417 získáte přesně stejný text. + +## Běžné varianty a okrajové případy + +| Situace | Úprava | Důvod | +|-----------|------------|--------| +| **Delší datový payload** (např. > 150 znaků) | Zvyšte `generator.Parameters.Barcode.Pdf417.Columns` na 6‑8 | Více sloupců zabrání tomu, aby čárový kód byl příliš vysoký. | +| **Potřeba průhledného pozadí** | Použijte `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | Průhledný PNG se lépe integruje do UI překryvů. | +| **Generování JPEG pro web** | Změňte formát na `BarCodeImageFormat.Jpeg` a volitelně nastavte `ImageQuality` | JPEG snižuje velikost souboru na úkor bezztrátové věrnosti. | +| **Zpracování null nebo prázdného vstupu** | Ověřte vstup před vytvořením generátoru: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Zabrání výjimkám za běhu a zajistí smysluplné čárové kódy. | + +## Tipy pro produkční nasazení + +* **Zpracování výjimek:** Zabalte logiku generování do `try/catch` bloku a logujte chyby, jako je nedostatek místa na disku nebo neplatné parametry. +* **Výkon:** Při generování mnoha čárových kódů se stejným nastavením znovu použijte jedinou instanci `BarcodeGenerator`; mezi ukládáními pouze aktualizujte vlastnost `CodeText`. +* **Bezpečnost:** Pokud zakódovaný text obsahuje citlivé informace, zvažte jeho šifrování před předáním generátoru a dešifrování po načtení. + +## Závěr + +Nyní víte, jak **vygenerovat PDF417 čárový kód** v C# pomocí knihovny Aspose.BarCode, nakonfigurovat kompaktní režim, řídit počet sloupců a exportovat výsledek jako PNG obrázek. Tento tutoriál pokryl každý krok od nastavení projektu po řešení okrajových případů a poskytl vám připravené řešení pro aplikace založené na čárových kódech. + +Dále prozkoumejte související témata, jako je **vytváření QR kódů v C#**, **hromadné generování čárových kódů** a **integrace skenování čárových kódů do mobilních aplikací**. Všechna tato témata staví na stejných základech `BarcodeGenerator`, které jste právě zvládli. + +Šťastné kódování! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s krok‑za‑krokem vysvětlením, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní přístupy ve vašich projektech. + +- [How to Generate PDF417 Barcodes – Compact PDF417 Encoding](/barcode/english/net/compact-pdf417-encoding/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/czech/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/czech/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..2e35b83a7 --- /dev/null +++ b/barcode/czech/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-09 +description: Jak číst PDF417 v C# pomocí BarCodeReaderu. Naučte se číst soubory PNG + s čárovými kódy, zpracovávat více čárových kódů a extrahovat rozšířené metadata. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: cs +lastmod: 2026-08-09 +og_description: Jak číst PDF417 v C# s Aspose.BarCode. Tento tutoriál vám ukáže, jak + číst soubory PNG s čárovým kódem, zpracovávat více čárových kódů v jednom obrázku + a získat rozšířená metadata PDF417. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Jak číst PDF417 v C# – návod na čtečku čárových kódů +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Jak číst PDF417 v C# – kompletní průvodce čtečkou čárových kódů +url: /cs/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak číst PDF417 v C# – kompletní průvodce čtečkou čárových kódů + +Pokud potřebujete **jak číst PDF417** v .NET aplikaci, tento průvodce vám poskytne připravené řešení. Uvidíte, jak načíst PNG s čárovým kódem, zpracovat několik čárových kódů ve stejném obrázku a získat rozšířená pole PDF417, která mnoho skenerů skrývá. + +Čtení čárových kódů PDF417 je běžné v logistice, prodeji vstupenek a správě dokumentů. Na konci tohoto tutoriálu budete umět dekódovat obrázek Macro PDF417, zobrazit každý výsledek a použít doplňující informace (ID souboru, počet segmentů, časová razítka atd.) ve své vlastní obchodní logice. + +## Prerequisites + +- .NET 6.0 nebo novější (kód také funguje s .NET Framework 4.7+) +- Visual Studio 2022 nebo jakékoli C# IDE +- **Aspose.BarCode for .NET** (bezplatná zkušební verze nebo licencovaný NuGet balíček) +- PNG obrázek, který obsahuje čárový kód Macro PDF417 (vzorek souboru se jmenuje `ExtPDF417Meta.png`) + +> **Tip:** Nainstalujte knihovnu pomocí NuGet konzole: +> `dotnet add package Aspose.BarCode` + +## How to read PDF417 with BarCodeReader in C# + +Jádrem řešení je třída `BarCodeReader`. Přijímá cestu k obrázku a výčtový typ `DecodeType`, který říká enginu, jakou symbologii hledat. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Why this works + +- `DecodeType.MacroPdf417` říká čtečce, aby hledala variantu Macro PDF417, která ukládá dodatečná pole, která vidíte v kroku 4. +- `using` blok automaticky uvolní čtečku, čímž uvolní souborové handle. +- `ReadBarCodes()` vrací **všechny** čárové kódy, které odpovídají požadovanému typu, což splňuje požadavek *číst více čárových kódů* i když obrázek obsahuje jen jeden. + +Spuštěním programu se vytiskne výstup podobný: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## Using C# barcode reader to read multiple barcodes + +Pokud obrázek obsahuje několik symbolů Macro PDF417 (například naskenovanou stránku s dávkou vstupenek), stejný `foreach` cyklus zpracuje každý z nich. Není potřeba žádný další kód; čtečka interně agreguje výsledky. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Common pitfalls + +- **Formát obrázku:** Čtečka podporuje PNG, JPEG, BMP a TIFF. Pokud zkusíte formát, který nedokáže dekódovat, získáte prázdnou kolekci. Proto tutoriál zdůrazňuje *číst čárový kód PNG*. +- **Rozlišení:** Nízké rozlišení obrázků (< 300 dpi) může způsobit chybějící segmenty. Pokud je to možné, zvyšte rozlišení nebo požádejte o sken v lepší kvalitě. +- **Makro příznak:** Zapomenutí `DecodeType.MacroPdf417` omezuje engine na obyčejný PDF417 a zahazuje rozšířená data. Vždy specifikujte makro typ, když potřebujete pole *číst rozšířené čárové kódy*. + +## Reading barcode PNG files – best practices + +Práce s PNG soubory je jednoduchá, protože formát zachovává bezztrátová pixelová data. Zde je rychlý kontrolní seznam: + +1. Ověřte, že soubor existuje, než vytvoříte čtečku. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Používejte `Image.FromFile` pouze pokud potřebujete předzpracovat (otočit, oříznout). `BarCodeReader` může soubor otevřít přímo, což zabraňuje dalšímu alokování paměti. +3. Pokud PNG obsahuje průhlednost, čtečka stále funguje, protože čárový kód je vykreslen na neprůhledných pixelech. + +## Accessing extended PDF417 metadata + +Objekt `Extended.Pdf417` zpřístupňuje každé volitelné pole definované specifikací PDF417. Můžete tato pole mapovat na doménový model, uložit je do databáze nebo použít pro validaci. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Naplnění modelu: + + + +## What Should You Learn Next? + +Následující tutoriály pokrývají úzce související témata, která navazují na techniky předvedené v tomto průvodci. Každý zdroj obsahuje kompletní funkční příklady kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [How to Read DataMatrix Barcodes with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Read DataMatrix barcode C# – Generate DataMatrix Mode (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/dutch/net/compact-pdf417-encoding/_index.md b/barcode/dutch/net/compact-pdf417-encoding/_index.md index 64f0fba6f..50e11869d 100644 --- a/barcode/dutch/net/compact-pdf417-encoding/_index.md +++ b/barcode/dutch/net/compact-pdf417-encoding/_index.md @@ -84,6 +84,22 @@ Voorbij de basis, hier zijn enkele praktische tips om je workflow te stroomlijne Leer hoe je Compact PDF417 barcodes genereert met Aspose.BarCode voor .NET. Uitgebreide gids met stap‑voor‑stap instructies en code‑voorbeelden. +### [Aspose barcode voorbeeld: Macro PDF417 genereren in C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) + +Voorbeeldcode om een Macro PDF417 barcode te genereren met Aspose.BarCode in C#. + +### [PDF417-barcode genereren in C# – stapsgewijze handleiding](./generate-pdf417-barcode-in-c-step-by-step-guide/) + +Leer hoe je stap voor stap een PDF417-barcode maakt in C# met Aspose.BarCode voor .NET. + +### [Barcode genereren vanuit tekst in C# – volledige stap‑voor‑stap handleiding](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) + +Leer hoe je in C# een barcode genereert vanuit tekst met een volledige stap‑voor‑stap handleiding. + +### [Hoe PDF417 in C# te lezen – complete barcode‑leesgids](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) + +Leer stap‑voor‑stap hoe je PDF417‑barcodes kunt lezen in C# met Aspose.BarCode, inclusief voorbeeldcode en configuratie‑tips. + ## Veelgestelde Vragen **V: Wat is de maximale hoeveelheid data die ik kan opslaan in een Compact PDF417 barcode?** @@ -112,4 +128,4 @@ A: Geen externe lettertypen zijn nodig; de bibliotheek verwerkt alle rendering i {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/dutch/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/dutch/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..0acfabf49 --- /dev/null +++ b/barcode/dutch/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-09 +description: Aspose barcode-voorbeeld dat laat zien hoe je een barcodegenerator in + C# gebruikt om een Macro PDF417 met volledige metadata-ondersteuning te maken. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: nl +lastmod: 2026-08-09 +og_description: Het Aspose barcode-voorbeeld toont het gebruik van een barcodegenerator + in C# om een Macro PDF417-barcode te maken die bestand‑ID, segmentgegevens, tijdstempel + en andere metadata bevat. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Aspose barcode voorbeeld – maak Macro PDF417 met C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Aspose barcode-voorbeeld: genereer Macro PDF417 in C#' +url: /nl/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose barcode voorbeeld: genereer Macro PDF417 in C# + +Als je een **aspose barcode voorbeeld** nodig hebt dat een Macro PDF417 barcode maakt, laat deze gids je zien hoe je dit doet met een **barcode generator C#**. Je ziet elke vereiste instelling, van basisafmetingen tot de volledige set van Macro PDF417 metadata‑velden, en je eindigt met een PNG‑afbeelding die klaar is voor downstream verwerking. + +De tutorial behandelt de volledige workflow, legt uit waarom elke parameter belangrijk is, en biedt een kant‑klaar code‑voorbeeld. Er zijn geen externe referenties nodig; je kunt de code kopiëren, de waarden aanpassen en direct uitvoeren. + +## Vereisten + +- .NET 6.0 (of later) geïnstalleerd +- Visual Studio 2022 of een C#‑compatibele IDE +- Een geldige licentie voor **Aspose.BarCode for .NET** (de gratis proefversie werkt voor dit voorbeeld) + +Voeg het Aspose.BarCode NuGet‑pakket toe aan je project: + +```bash +dotnet add package Aspose.BarCode +``` + +## Stap 1: Maak de barcode generator C#‑instantie + +De eerste stap is om `BarcodeGenerator` te instantieren met de `EncodeTypes.MacroPdf417` enum‑waarde en de tekst die je wilt coderen. De tekst kan Unicode‑tekens bevatten, die de bibliotheek automatisch verwerkt. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Waarom dit belangrijk is*: `EncodeTypes.MacroPdf417` vertelt de engine om een Macro PDF417‑symbool te produceren, dat gesegmenteerde data en extra bestands‑niveau metadata ondersteunt. De `using`‑statement garandeert dat niet‑beheerde resources worden vrijgegeven nadat de afbeelding is opgeslagen. + +## Stap 2: Definieer basis barcode‑uiterlijk + +Een Macro PDF417‑barcode bestaat uit vierkante modules. Het regelen van de module‑grootte en het aantal kolommen beïnvloedt zowel de leesbaarheid als de bestandsgrootte. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Waarom dit belangrijk is*: `XDimension.Pixels` bepaalt de visuele dichtheid; een waarde van 2 pixels werkt goed voor weergave op schermen terwijl de afbeelding klein blijft. Pas het aantal kolommen aan om aan je lay‑outbeperkingen te voldoen — meer kolommen creëren een bredere, kortere barcode. + +## Stap 3: Stel Macro PDF417‑specifieke metadata in + +Macro PDF417 breidt het standaard PDF417‑formaat uit met velden die reconstructie van grote bestanden uit meerdere barcode‑segmenten mogelijk maken. Elk veld is optioneel, maar het instellen ervan toont de volledige mogelijkheden van de API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Waarom dit belangrijk is*: +- `MacroPdf417FileID` koppelt alle segmenten die tot hetzelfde logische bestand behoren. +- `MacroPdf417SegmentID` en `MacroPdf417SegmentsCount` stellen de decoder in staat fragmenten correct te herschikken. +- `MacroPdf417Checksum` biedt een snelle integriteitscontrole zonder de volledige payload te decoderen. +- `MacroPdf417FileSize` en `MacroPdf417TimeStamp` stellen downstream‑systemen in staat te verifiëren dat het gereconstrueerde bestand overeenkomt met het origineel. +- `MacroPdf417Addressee` / `MacroPdf417Sender` zijn nuttig in logistieke of document‑uitwisselingsscenario's. +- Het instellen van `MacroPdf417Terminator` op `Set` markeert deze barcode als het laatste segment, wat het reconstructie‑algoritme vereenvoudigt. + +## Stap 4: Sla de gegenereerde barcode‑afbeelding op + +Tot slot schrijf je de barcode naar een PNG‑bestand. Je kunt elk ondersteund formaat kiezen (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Waarom dit belangrijk is*: PNG behoudt verliesvrije pixeldata, waardoor scanners het exacte module‑patroon dat je hebt geconfigureerd kunnen lezen. Het wijzigen van het formaat kan de visuele kwaliteit en bestandsgrootte beïnvloeden. + +### Verwachte output + +Het uitvoeren van het volledige programma maakt een bestand genaamd **ExtPDF417Meta.png** aan. Het openen van de afbeelding toont een rechthoekige Macro PDF417‑barcode met de tekst “Åspóse.Barcóde©” gecodeerd, en de visuele dichtheid komt overeen met de 2‑pixel X‑dimensie die je hebt ingesteld. Het scannen van de afbeelding met een PDF417‑compatibele lezer retourneert alle metadata‑velden die in Stap 3 zijn gedefinieerd. + +## Volledig werkend voorbeeld + +Kopieer de onderstaande code in een nieuw console‑project (`dotnet new console`) en vervang `YOUR_DIRECTORY` door een absoluut of relatief pad dat bestaat op jouw machine. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Voer het programma uit (`dotnet run`). Na uitvoering, controleer of het PNG‑bestand verschijnt op de opgegeven locatie. Gebruik een barcode‑lezer‑app die Macro PDF417 ondersteunt om te bevestigen dat de metadata correct is ingebed. + +## Veelvoorkomende variaties en randgevallen + +- **Verschillende afbeeldingsformaten**: Vervang `BarCodeImageFormat.Png` door `Jpeg`, `Bmp` of `Tiff` als je downstream‑systeem een ander formaat prefereert. +- **Aanpassen module‑grootte**: Grotere `XDimension.Pixels`‑waarden verbeteren de scan‑betrouwbaarheid op low‑resolution scanners maar vergroten de afbeelding. +- **Meerdere segmenten**: Om een multi‑segment bestand te produceren, genereer een reeks barcodes, verhoog `MacroPdf417SegmentID` voor elk, en houd `MacroPdf417FileID` constant. Alleen het laatste segment moet `MacroPdf417Terminator` ingesteld hebben. +- **Unicode‑ondersteuning**: De generator codeert Unicode‑tekens automatisch; zorg ervoor dat je bron‑string UTF‑8‑codering gebruikt als je deze uit een extern bestand leest. +- **Foutafhandeling**: Plaats de `using`‑block in een try‑catch om `BarCodeException` te vangen voor ongeldige parameters (bijv. kolom‑aantal buiten bereik). + +## Pro‑tips + +- **Prestaties**: Hergebruik een enkele `BarcodeGenerator`‑instantie bij het maken van veel barcodes met dezelfde instellingen; wijzig alleen de `CodeText`‑eigenschap tussen opslagen. +- **Bestandsgrootte‑schatting**: Het `MacroPdf417FileSize`‑veld moet overeenkomen met het byte‑aantal van de originele payload; mismatches kunnen downstream‑validatiefouten veroorzaken. +- **Testen**: Valideer gegenereerde barcodes met zowel Aspose’s ingebouwde decoder (`BarCodeReader`) als een scanner van derden om interoperabiliteit te waarborgen. + +## Conclusie + +Dit **aspose barcode voorbeeld + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe een barcode te maken – Compact PDF417 met Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Hoe een barcode‑rustzone te maken voor Code 16K met Aspose.BarCode voor .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [Hoe een barcode‑rustzone te maken voor ITF-14 met Aspose.BarCode voor .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/dutch/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/dutch/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..c4f348f97 --- /dev/null +++ b/barcode/dutch/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-08-09 +description: Genereer een barcode vanuit tekst in C# met Aspose.BarCode. Leer hoe + je een barcode genereert, speciale tekens verwerkt en snel een PDF417-barcode in + C# maakt. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: nl +lastmod: 2026-08-09 +og_description: Genereer een barcode vanuit tekst in C# met Aspose.BarCode. Deze tutorial + laat zien hoe je een barcode genereert, speciale tekens ondersteunt en een PDF417-barcode + in C# maakt met volledige code. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Barcode genereren uit tekst in C# – snelle stap‑voor‑stap gids +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Barcode genereren vanuit tekst in C# – volledige stapsgewijze handleiding +url: /nl/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Genereer barcode vanuit tekst in C# – volledige stap‑voor‑stap gids + +Als je **barcode vanuit tekst wilt genereren** in een .NET‑applicatie, leidt deze gids je door het volledige proces. Je ziet hoe je een barcode genereert, speciale tekens beheert en een PDF417‑barcode‑C#‑implementatie maakt die direct werkt. + +Het genereren van een barcode vanuit tekst is een veelvoorkomende eis voor voorraadsystemen, ticketplatforms en documentworkflows. Aan het einde van deze tutorial heb je een uitvoerbare C#‑console‑app die een MicroPdf417‑PNG‑afbeelding produceert met Aspose.BarCode. Er zijn geen externe services nodig, en de code verwerkt Unicode‑tekens zoals “Å”, “©” en “é”. + +## Vereisten + +- .NET 6.0 SDK of later (de code werkt ook met .NET Core 3.1 en .NET Framework 4.7+) +- Visual Studio 2022 (of een IDE die C# ondersteunt) +- **Aspose.BarCode for .NET** NuGet‑pakket + ```bash + dotnet add package Aspose.BarCode + ``` +- Basiskennis van C#‑syntaxis + +## Barcode genereren vanuit tekst – de generator instellen + +De eerste stap is het aanmaken van een `BarcodeGenerator`‑instance die weet welk **barcode‑encode‑type** je wilt. In deze tutorial gebruiken we `EncodeTypes.MicroPdf417`, een compacte variant van PDF417 die geschikt is voor korte gegevensreeksen. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Waarom dit werkt:** +- `EncodeTypes.MicroPdf417` vertelt de bibliotheek om de PDF417‑familie te gebruiken, waardoor aan de **create pdf417 barcode c#**‑vereiste wordt voldaan. +- De constructor ontvangt de ruwe tekst, wat de essentie is van **generate barcode from text**. +- Unicode‑ondersteuning is ingebouwd, zodat tekens zoals “Å” en “©” correct worden gecodeerd, wat **barcode with special characters** adresseert. + +## Hoe barcode met speciale tekens te genereren + +Wanneer je gegevens niet‑ASCII‑symbolen bevatten, moet je ervoor zorgen dat de generator UTF‑8‑codering gebruikt. Aspose.BarCode detecteert automatisch Unicode, maar je kunt de tekencodering expliciet instellen als je problemen ondervindt: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Het toevoegen van deze regel vóór `ConfigureGenerator` garandeert dat **barcode with special characters** correct wordt weergegeven op elk platform. + +### Praktische tip +Als de output er onduidelijk uitziet, controleer dan of het lettertype dat de barcode‑renderer gebruikt de benodigde glyphs ondersteunt. Je kunt een aangepast TrueType‑lettertype insluiten via: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Barcode‑encode‑types die je kunt kiezen + +Aspose.BarCode ondersteunt tientallen **barcode encode types**, elk geschikt voor verschillende use‑cases: + +| Encode type | Typisch gebruik | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | Verzendlabels, voorraad | +| `EncodeTypes.QR` | Mobiele betalingen, URL's | +| `EncodeTypes.Pdf417` | Rijbewijzen, instapkaarten | +| `EncodeTypes.MicroPdf417` | Kleine gegevenspayloads, beperkte ruimte | +| `EncodeTypes.DataMatrix` | Kleine items, hoge gegevensdichtheid | + +Het wijzigen van het encode‑type is net zo eenvoudig als het verwisselen van de enum‑waarde in de constructor: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Deze flexibiliteit stelt je in staat om **barcode encode types**‑vragen te beantwoorden zonder de IDE te verlaten. + +## PDF417‑barcode maken in C# – laatste stappen en verificatie + +Na het configureren van de generator is het laatste deel van **create pdf417 barcode c#** het opslaan van de afbeelding en het bevestigen van het resultaat. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Voer het programma uit (`dotnet run`) en je zou een console‑bericht moeten zien dat lijkt op: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Open het PNG‑bestand; je ziet een scherpe MicroPdf417‑barcode die de tekenreeks “Åspóse.Barcóde©” codeert. Het scannen ervan met een mobiele barcode‑scanner (bijv. ZXing) geeft de oorspronkelijke tekst terug, wat bewijst dat **generate barcode from text** zelfs met speciale tekens werkt. + +### Randgeval: zeer lange tekst +MicroPdf417 heeft een maximale gegevenscapaciteit van 1 KB. Als je invoer deze limiet overschrijdt, gooit de bibliotheek een `ArgumentException`. Om dit netjes af te handelen: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Voor grotere payloads, schakel over naar de volledige `EncodeTypes.Pdf417` of `EncodeTypes.DataMatrix`. + +## Veelvoorkomende valkuilen en hoe ze te vermijden + +| Probleem | Oorzaak | Oplossing | +|----------------------------------------|-------------------------------------------|-----------| +| Barcode ziet er wazig uit | XDimension te laag (bijv. 1 px) | Verhoog `XDimension.Pixels` naar 2‑3 px | +| Unicode‑tekens worden `?` | Standaard tekencodering is ASCII | Stel `TextEncoding = Encoding.UTF8` in | +| Afbeeldingsbestand niet aangemaakt | Uitvoermap bestaat niet | Gebruik `Directory.CreateDirectory` vóór `Save` | +| Scanner kan de barcode niet lezen | Te veel kolommen voor korte data | Verlaag `Pdf417.Columns` (bijv. 3‑4) | + +## Volledige broncode (klaar om te kopiëren) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Verwachte output:** een bestand genaamd `MicroPdf417.png` in de `output`‑map, met een duidelijke MicroPdf417‑barcode die de oorspronkelijke tekenreeks met speciale tekens codeert. + +## Conclusie + +Je weet nu hoe je **barcode vanuit tekst kunt genereren** in C# met Aspose.BarCode, hoe je **barcode met speciale tekens** kunt verwerken, en hoe je **create pdf417 barcode c#** kunt uitvoeren met volledige controle over de coderingsopties. Door de **barcode encode types** aan te passen kun je QR‑codes, Code128, DataMatrix of elk ander ondersteund formaat produceren. + +Verken vervolgens de volgende onderwerpen om je barcode‑expertise te verdiepen: + +- **Hoe barcode te genereren** in batch voor duizenden records (gebruik `Parallel.ForEach` voor snelheid) +- Kleuren aanpassen en logo's toevoegen binnen de barcode +- Barcode‑generatie integreren in ASP.NET Core‑API's voor realtime afbeeldingslevering +- Andere bibliotheken gebruiken zoals ZXing.Net of IronBarcode voor open‑source alternatieven + +Voel je vrij om te experimenteren met verschillende afmetingen, kolominstellingen en encode‑types. Veel plezier met coderen, en moge je applicaties feilloos scannen! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe barcode te maken – Compact PDF417 met Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Hoe barcode te genereren – Code 39‑configuratie met Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Hoe barcode te genereren – Eén-dimensionale barcode‑types](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/dutch/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/dutch/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..800bda715 --- /dev/null +++ b/barcode/dutch/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-08-09 +description: Genereer PDF417‑barcode in C# snel. Leer hoe je PDF417 kunt genereren + met compacte modus, kolomcontrole en PNG‑output met de BarcodeGenerator‑API. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: nl +lastmod: 2026-08-09 +og_description: Genereer PDF417-barcode in C# met een beknopt voorbeeld. Deze gids + laat zien hoe je compacte modus configureert, kolommen instelt en het resultaat + opslaat als een PNG-afbeelding. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Genereer PDF417‑barcode in C# – volledige tutorial +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: PDF417‑barcode genereren in C# – stapsgewijze handleiding +url: /nl/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF417‑barcode genereren in C# – stapsgewijze handleiding + +Als je een **PDF417‑barcode** moet genereren in een .NET‑applicatie, laat deze tutorial precies zien hoe je dat doet. Je ziet een compleet, uitvoerbaar programma dat een compacte PDF417‑barcode maakt, de grootte aanpast en de afbeelding opslaat als een PNG‑bestand. + +Het genereren van een PDF417‑barcode is een veelvoorkomende eis voor mobiel ticketing, voorraadtracking en documentbeveiliging. Deze gids behandelt de essentiële configuratie‑opties, legt uit waarom elke instelling belangrijk is, en geeft praktische tips voor gebruik in de praktijk. + +## Vereisten + +Voordat je begint, zorg dat je het volgende hebt: + +* .NET 6.0 SDK of later geïnstalleerd +* Een C#‑IDE zoals Visual Studio 2022 of Visual Studio Code +* Het **Aspose.BarCode for .NET** NuGet‑pakket (versie 23.10 of nieuwer) + +Je kunt het pakket installeren met de volgende CLI‑opdracht: + +```bash +dotnet add package Aspose.BarCode +``` + +De code hieronder gaat ervan uit dat het pakket is gerefereerd en dat je schrijfrechten hebt op de output‑map. + +## Stap 1: Het project opzetten en namespaces importeren + +Maak een nieuw console‑project aan en voeg de benodigde `using`‑directieven toe. Deze namespaces maken de `BarcodeGenerator`‑klasse en de enumeratie voor afbeeldingsformaten beschikbaar. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Waarom dit belangrijk is:** Het importeren van de juiste namespaces zorgt ervoor dat de compiler de `BarcodeGenerator`‑type en de `BarCodeImageFormat`‑enum kan vinden. Het ontbreken van een namespace leidt tot een compilatiefout, waardoor het barcode‑generatieproces wordt onderbroken. + +## Stap 2: De `BarcodeGenerator` initialiseren met PDF417‑codering + +De constructor van `BarcodeGenerator` ontvangt twee argumenten: de barcode‑symbologie (`EncodeTypes.Pdf417`) en de tekst die je wilt coderen. PDF417 ondersteunt een breed scala aan tekens, inclusief Unicode‑symbolen. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Uitleg:** +* `EncodeTypes.Pdf417` vertelt de bibliotheek om de PDF417‑standaard te gebruiken. +* De voorbeeldtekst bevat accenten en een copyright‑symbool om Unicode‑verwerking te demonstreren. + +Als je alleen numerieke gegevens moet coderen, kun je een eenvoudige string zoals `"1234567890"` doorgeven. + +## Stap 3: De X‑dimensie aanpassen voor fijnere resolutie + +De X‑dimensie bepaalt de breedte van één barcode‑module (het kleinste zwarte of witte element). Een kleinere pixelwaarde levert een afbeelding met hogere resolutie op. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Waarom aanpassen?** Een standaard X‑dimensie van 3–4 pixels kan een barcode opleveren die er grof uitziet op schermen met hoge DPI. Het verlagen naar **2 pixels** biedt een goede balans tussen leesbaarheid en bestandsgrootte, vooral wanneer je later compacte modus inschakelt. + +## Stap 4: Het aantal kolommen configureren + +PDF417 laat je bepalen hoeveel kolommen de barcode moet bevatten. Minder kolommen maken de barcode smaller maar hoger, terwijl meer kolommen een bredere, kortere barcode opleveren. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Praktische tip:** Voor mobiele tickets die binnen een smalle etiket moeten passen, werkt een kolomtelling van **3–5** goed. Verhoog het aantal als je veel data hebt en een kortere barcode wilt. + +## Stap 5: Compacte modus inschakelen om lege rijen te verkorten + +Compacte modus verwijdert onnodige rijen uit de barcode‑matrix, waardoor de totale afbeeldingsgrootte wordt verkleind zonder verlies van gecodeerde data. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Wanneer te gebruiken:** Als je barcodes genereert voor opslag of netwerkoverdracht, kan compacte modus het PNG‑bestand tot wel 30 % verkleinen. Sommige oudere scanners ondersteunen echter geen verkorte PDF417; test dit met je doelhardware. + +## Stap 6: De barcode opslaan als PNG‑afbeelding + +Kies een output‑pad en roep `Save` aan. De enumeratie `BarCodeImageFormat.Png` produceert een verliesvrije afbeelding die voor de meeste toepassingen geschikt is. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Resultaatverificatie:** Open het PNG‑bestand in een willekeurige afbeeldingsviewer. Je zou een dichte, hoog‑contrasterende barcode moeten zien die overeenkomt met de voorbeeldtekst. Het scannen van de afbeelding met een PDF417‑lezer (bijv. ZXing of een smartphone‑app) geeft de oorspronkelijke string `"Åspóse.Barcóde©"` terug. + +![Generated PDF417 barcode image saved as PNG](compact-pdf417.png "Generated PDF417 barcode in C#") + +*De bovenstaande afbeelding toont de uiteindelijke output van de code uit de tutorial.* + +## Volledig, uitvoerbaar voorbeeld + +Alle onderdelen samengevoegd, hier is een compleet console‑programma dat je kunt kopiëren, plakken en uitvoeren. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Verwachte output + +Het uitvoeren van het programma geeft: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +Het bestand `CompactPdf417.png` bevat een compacte PDF417‑barcode die de opgegeven Unicode‑string codeert. Het scannen van de afbeelding met een standaard PDF417‑lezer levert exact dezelfde tekst op. + +## Veelvoorkomende variaties en randgevallen + +| Situatie | Aanpassing | Reden | +|-----------|------------|--------| +| **Langere gegevenspayload** (bijv. > 150 tekens) | Verhoog `generator.Parameters.Barcode.Pdf417.Columns` naar 6‑8 | Meer kolommen voorkomen dat de barcode te hoog wordt. | +| **Transparante achtergrond nodig** | Gebruik `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | Een transparante PNG integreert beter in UI‑overlays. | +| **JPEG genereren voor web** | Verander het formaat naar `BarCodeImageFormat.Jpeg` en stel eventueel `ImageQuality` in | JPEG verkleint de bestandsgrootte ten koste van verliesvrije kwaliteit. | +| **Null‑ of lege invoer verwerken** | Controleer de invoer vóór het aanmaken van de generator: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Voorkomt runtime‑exceptions en zorgt voor betekenisvolle barcodes. | + +## Tips voor productiegebruik + +* **Exception handling:** Plaats de generatie‑logica in een `try/catch`‑blok om fouten zoals onvoldoende schijfruimte of ongeldige parameters te loggen. +* **Performance:** Hergebruik een enkele `BarcodeGenerator`‑instantie bij het genereren van veel barcodes met dezelfde instellingen; werk alleen de `CodeText`‑eigenschap bij tussen opslagen. +* **Beveiliging:** Wanneer de gecodeerde tekst gevoelige informatie bevat, overweeg dan om deze te versleutelen vóór het doorgeven aan de generator en te ontsleutelen na het scannen. + +## Conclusie + +Je weet nu hoe je een **PDF417‑barcode** kunt genereren in C# met de Aspose.BarCode‑bibliotheek, compacte modus kunt configureren, het aantal kolommen kunt regelen en het resultaat als PNG‑afbeelding kunt exporteren. Deze tutorial heeft elke stap behandeld, van projectopzet tot het omgaan met randgevallen, en biedt een kant‑en‑klaar oplossing voor barcode‑gedreven toepassingen. + +Verken vervolgens gerelateerde onderwerpen zoals **QR‑codes maken in C#**, **batch‑barcode‑generatie**, en **barcode‑scannen integreren in mobiele apps**. Elk van deze bouwt voort op dezelfde `BarcodeGenerator`‑fundamenten die je nu beheerst. + +Happy coding! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap‑uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [How to Generate PDF417 Barcodes – Compact PDF417 Encoding](/barcode/english/net/compact-pdf417-encoding/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/dutch/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/dutch/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..a9d18c4bc --- /dev/null +++ b/barcode/dutch/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-09 +description: Hoe PDF417 te lezen in C# met de BarCodeReader. Leer barcode‑PNG‑bestanden + te lezen, meerdere barcodes te verwerken en uitgebreide metadata te extraheren. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: nl +lastmod: 2026-08-09 +og_description: Hoe PDF417 te lezen in C# met Aspose.BarCode. Deze tutorial laat zien + hoe je barcode‑PNG‑bestanden kunt lezen, meerdere barcodes in één afbeelding kunt + verwerken en uitgebreide PDF417‑metadata kunt ophalen. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Hoe PDF417 te lezen in C# – barcodelezer tutorial +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Hoe PDF417 lezen in C# – volledige gids voor barcodelezers +url: /nl/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe PDF417 lezen in C# – complete barcode lezer gids + +Als je **PDF417 wilt lezen** in een .NET‑applicatie, biedt deze gids een kant‑klaar‑te‑gebruiken oplossing. Je ziet hoe je een barcode‑PNG kunt lezen, meerdere barcodes in dezelfde afbeelding kunt verwerken, en de uitgebreide PDF417‑velden kunt ophalen die veel scanners verbergen. + +Het lezen van PDF417‑barcodes is gebruikelijk in logistiek, ticketverkoop en documentbeheer. Aan het einde van deze tutorial kun je een Macro PDF417‑afbeelding decoderen, elk resultaat weergeven, en de extra informatie (file ID, segment count, timestamps, enz.) gebruiken in je eigen bedrijfslogica. + +## Prerequisites + +- .NET 6.0 of later (de code werkt ook met .NET Framework 4.7+) +- Visual Studio 2022 of een andere C#‑IDE +- **Aspose.BarCode for .NET** (gratis proefversie of gelicentieerd NuGet‑pakket) +- Een PNG‑afbeelding die een Macro PDF417‑barcode bevat (het voorbeeldbestand heet `ExtPDF417Meta.png`) + +> **Pro tip:** Installeer de bibliotheek via de NuGet‑console: +> `dotnet add package Aspose.BarCode` + +## Hoe PDF417 lezen met BarCodeReader in C# + +De kern van de oplossing is de `BarCodeReader`‑klasse. Deze accepteert een pad naar een afbeelding en een `DecodeType`‑enum die de engine vertelt welke symbologie gezocht moet worden. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Waarom dit werkt + +- **`DecodeType.MacroPdf417`** vertelt de lezer om te zoeken naar de Macro PDF417‑variant, die de extra velden opslaat die je ziet in stap 4. +- Het `using`‑blok ruimt de lezer automatisch op en sluit bestands­handles. +- `ReadBarCodes()` retourneert **alle** barcodes die overeenkomen met het gevraagde type, waardoor de *read multiple barcodes*‑vereiste wordt vervuld, zelfs als de afbeelding slechts één barcode bevat. + +Het uitvoeren van het programma geeft een output weer die er ongeveer zo uitziet: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## C# barcode lezer gebruiken om meerdere barcodes te lezen + +Bevat een afbeelding meerdere Macro PDF417‑symbolen (bijvoorbeeld een gescande pagina met een batch tickets), dan verwerkt dezelfde `foreach`‑lus elk exemplaar. Er is geen extra code nodig; de lezer verzamelt de resultaten intern. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Veelvoorkomende valkuilen + +- **Image format:** De lezer ondersteunt PNG, JPEG, BMP en TIFF. Als je een formaat probeert dat niet kan worden gedecodeerd, krijg je een lege collectie. Daarom benadrukt de tutorial *read barcode PNG*. +- **Resolution:** Low‑resolution afbeeldingen (< 300 dpi) kunnen gemiste segmenten veroorzaken. Upscale of vraag een scan van hogere kwaliteit aan wanneer mogelijk. +- **Macro flag:** Het vergeten van `DecodeType.MacroPdf417` beperkt de engine tot gewone PDF417 en negeert de uitgebreide data. Specificeer altijd het macro‑type wanneer je *read barcode extended*‑velden nodig hebt. + +## Barcode PNG‑bestanden lezen – best practices + +Werken met PNG‑bestanden is eenvoudig omdat het formaat verliesvrije pixeldata behoudt. Hier is een snelle checklist: + +1. Controleer of het bestand bestaat voordat je de lezer maakt. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Gebruik `Image.FromFile` alleen wanneer je vooraf moet bewerken (roteren, bijsnijden). De `BarCodeReader` kan het bestand direct openen, waardoor extra geheugenallocatie wordt vermeden. +3. Als de PNG transparantie bevat, werkt de lezer nog steeds omdat de barcode op ondoorzichtige pixels wordt gerenderd. + +## Toegang tot uitgebreide PDF417‑metadata + +Het `Extended.Pdf417`‑object maakt elk optioneel veld uit de PDF417‑specificatie beschikbaar. Je kunt deze velden naar een domeinmodel mappen, opslaan in een database, of gebruiken voor validatie. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Vul het model: + + + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe DataMatrix‑barcodes lezen met Aspose.BarCode voor .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Hoe een barcode maken – Compact PDF417 met Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [DataMatrix‑barcode lezen C# – DataMatrix‑modus genereren (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/english/net/compact-pdf417-encoding/_index.md b/barcode/english/net/compact-pdf417-encoding/_index.md index 1762ea2a8..11183662b 100644 --- a/barcode/english/net/compact-pdf417-encoding/_index.md +++ b/barcode/english/net/compact-pdf417-encoding/_index.md @@ -83,6 +83,14 @@ Beyond the basics, here are some practical tips to streamline your workflow: ## Compact PDF417 Encoding Tutorials ### [Creating Compact PDF417 Barcodes](./compact-pdf417-basic-configuration/) Learn how to generate Compact PDF417 barcodes using Aspose.BarCode for .NET. Comprehensive guide with step-by-step instructions and code examples. +### [Aspose barcode example: generate Macro PDF417 in C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Learn how to generate Macro PDF417 barcodes in C# using Aspose.BarCode for .NET with a step‑by‑step example. +### [Generate PDF417 barcode in C# – step‑by‑step guide](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Step‑by‑step guide to generate PDF417 barcodes in C# using Aspose.BarCode for .NET. +### [Generate barcode from text in C# – complete step‑by‑step guide](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Full step‑by‑step tutorial on generating barcodes from text in C# using Aspose.BarCode for .NET. +### [How to read PDF417 in C# – complete barcode reader guide](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +Learn how to read PDF417 barcodes in C# using Aspose.BarCode for .NET with a full step‑by‑step guide. ## Frequently Asked Questions @@ -112,4 +120,4 @@ A: No external fonts are required; the library handles all rendering internally. {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/english/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/english/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..8c0403915 --- /dev/null +++ b/barcode/english/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-08-09 +description: Aspose barcode example showing how to use a barcode generator C# to create + a Macro PDF417 with full metadata support. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: en +lastmod: 2026-08-09 +og_description: Aspose barcode example demonstrates using a barcode generator C# to + produce a Macro PDF417 barcode that includes file ID, segment data, timestamp and + other metadata. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Aspose barcode example – create Macro PDF417 with C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Aspose barcode example: generate Macro PDF417 in C#' +url: /net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose barcode example: generate Macro PDF417 in C# + +If you need an **aspose barcode example** that creates a Macro PDF417 barcode, this guide shows you how to do it with a **barcode generator C#**. You will see every required setting, from basic dimensions to the full set of Macro PDF417 metadata fields, and you will end up with a PNG image ready for downstream processing. + +The tutorial covers the complete workflow, explains why each parameter matters, and provides a ready‑to‑run code sample. No external references are required; you can copy the code, adjust the values, and run it immediately. + +## Prerequisites + +Before you start, make sure you have: + +- .NET 6.0 (or later) installed +- Visual Studio 2022 or any C#‑compatible IDE +- A valid license for **Aspose.BarCode for .NET** (the free trial works for this example) + +Add the Aspose.BarCode NuGet package to your project: + +```bash +dotnet add package Aspose.BarCode +``` + +## Step 1: Create the barcode generator C# instance + +The first step is to instantiate `BarcodeGenerator` with the `EncodeTypes.MacroPdf417` enum value and the text you want to encode. The text can contain Unicode characters, which the library handles automatically. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Why this matters*: `EncodeTypes.MacroPdf417` tells the engine to produce a Macro PDF417 symbol, which supports segmented data and additional file‑level metadata. The `using` statement guarantees that unmanaged resources are released after the image is saved. + +## Step 2: Define basic barcode appearance + +A Macro PDF417 barcode consists of square modules. Controlling the module size and column count influences both readability and file size. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Why this matters*: `XDimension.Pixels` determines the visual density; a value of 2 pixels works well for screen display while keeping the image small. Adjust the column count to fit your layout constraints—more columns create a wider, shorter barcode. + +## Step 3: Set Macro PDF417 specific metadata + +Macro PDF417 extends the standard PDF417 format with fields that enable reconstruction of large files from multiple barcode segments. Each field is optional, but setting them demonstrates the full capabilities of the API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Why this matters*: +- `MacroPdf417FileID` links all segments belonging to the same logical file. +- `MacroPdf417SegmentID` and `MacroPdf417SegmentsCount` enable the decoder to reorder fragments correctly. +- `MacroPdf417Checksum` provides a quick integrity check without decoding the entire payload. +- `MacroPdf417FileSize` and `MacroPdf417TimeStamp` allow downstream systems to verify that the reconstructed file matches the original. +- `MacroPdf417Addressee` / `MacroPdf417Sender` are useful in logistics or document‑exchange scenarios. +- Setting `MacroPdf417Terminator` to `Set` marks this barcode as the final segment, which simplifies the reconstruction algorithm. + +## Step 4: Save the generated barcode image + +Finally, write the barcode to a PNG file. You can choose any supported format (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Why this matters*: PNG preserves lossless pixel data, ensuring that scanners read the exact module pattern you configured. Changing the format may affect the visual quality and file size. + +### Expected output + +Running the complete program creates a file named **ExtPDF417Meta.png**. Opening the image shows a rectangular Macro PDF417 barcode with the text “Åspóse.Barcóde©” encoded, and the visual density matches the 2‑pixel X dimension you set. Scanning the image with a PDF417‑compatible reader returns all metadata fields defined in Step 3. + +## Full working example + +Copy the code below into a new console project (`dotnet new console`) and replace `YOUR_DIRECTORY` with an absolute or relative path that exists on your machine. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Run the program (`dotnet run`). After execution, verify that the PNG file appears at the location you specified. Use any barcode‑reading app that supports Macro PDF417 to confirm that the metadata is correctly embedded. + +## Common variations and edge cases + +- **Different image formats**: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Tiff` if your downstream system prefers another format. +- **Changing module size**: Larger `XDimension.Pixels` values improve scan reliability on low‑resolution scanners but increase image size. +- **Multiple segments**: To produce a multi‑segment file, generate a series of barcodes, increment `MacroPdf417SegmentID` for each, and keep `MacroPdf417FileID` constant. Only the last segment should have `MacroPdf417Terminator` set. +- **Unicode support**: The generator automatically encodes Unicode characters; ensure your source string uses UTF‑8 encoding if you read it from an external file. +- **Error handling**: Wrap the `using` block in a try‑catch to capture `BarCodeException` for invalid parameters (e.g., column count out of range). + +## Pro tips + +- **Performance**: Reuse a single `BarcodeGenerator` instance when creating many barcodes with the same settings; only change the `CodeText` property between saves. +- **File size estimation**: The `MacroPdf417FileSize` field should match the byte count of the original payload; mismatches may cause downstream validation failures. +- **Testing**: Validate generated barcodes with both Aspose’s built‑in decoder (`BarCodeReader`) and a third‑party scanner to ensure interoperability. + +## Conclusion + +This **aspose barcode example + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to create barcode quiet zone for Code 16K using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/english/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/og-image.png b/barcode/english/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/og-image.png new file mode 100644 index 000000000..8def41d2a Binary files /dev/null and b/barcode/english/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/og-image.png differ diff --git a/barcode/english/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/english/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3a66c6f01 --- /dev/null +++ b/barcode/english/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-08-09 +description: Generate barcode from text in C# with Aspose.BarCode. Learn how to generate + barcode, handle special characters, and create PDF417 barcode C# quickly. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: en +lastmod: 2026-08-09 +og_description: Generate barcode from text in C# using Aspose.BarCode. This tutorial + shows how to generate barcode, support special characters, and create PDF417 barcode + C# with full code. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Generate barcode from text in C# – quick step‑by‑step guide +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Generate barcode from text in C# – complete step‑by‑step guide +url: /net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generate barcode from text in C# – complete step‑by‑step guide + +If you need to **generate barcode from text** in a .NET application, this guide walks you through the entire process. You’ll see how to generate barcode, manage special characters, and create a PDF417 barcode C# implementation that works out‑of‑the‑box. + +Generating a barcode from text is a common requirement for inventory systems, ticketing platforms, and document workflows. By the end of this tutorial you will have a runnable C# console app that produces a MicroPdf417 PNG image using Aspose.BarCode. No external services are required, and the code handles Unicode characters such as “Å”, “©”, and “é”. + +## Prerequisites + +- .NET 6.0 SDK or later (the code also works with .NET Core 3.1 and .NET Framework 4.7+) +- Visual Studio 2022 (or any IDE that supports C#) +- **Aspose.BarCode for .NET** NuGet package + ```bash + dotnet add package Aspose.BarCode + ``` +- Basic knowledge of C# syntax + +## Generate barcode from text – setting up the generator + +The first step is to create a `BarcodeGenerator` instance that knows which **barcode encode type** you want. In this tutorial we use `EncodeTypes.MicroPdf417`, which is a compact variant of PDF417 suitable for short data strings. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Why this works:** +- `EncodeTypes.MicroPdf417` tells the library to use the PDF417 family, satisfying the **create pdf417 barcode c#** requirement. +- The constructor receives the raw text, which is the essence of **generate barcode from text**. +- Unicode support is built‑in, so characters like “Å” and “©” are encoded correctly, addressing **barcode with special characters**. + +## How to generate barcode with special characters + +When your data contains non‑ASCII symbols, you must ensure the generator uses UTF‑8 encoding. Aspose.BarCode automatically detects Unicode, but you can explicitly set the text encoding if you run into issues: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Adding this line before `ConfigureGenerator` guarantees that **barcode with special characters** renders correctly on any platform. + +### Practical tip +If the output looks garbled, verify the font used by the barcode renderer supports the required glyphs. You can embed a custom TrueType font via: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Barcode encode types you can choose + +Aspose.BarCode supports dozens of **barcode encode types**, each suited for different use cases: + +| Encode type | Typical use case | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | Shipping labels, inventory | +| `EncodeTypes.QR` | Mobile payments, URLs | +| `EncodeTypes.Pdf417` | Driver’s licenses, boarding passes | +| `EncodeTypes.MicroPdf417` | Small data payloads, limited space | +| `EncodeTypes.DataMatrix` | Tiny items, high data density | + +Changing the encode type is as simple as swapping the enum value in the constructor: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +This flexibility lets you answer **barcode encode types** questions without leaving the IDE. + +## Create PDF417 barcode C# – final steps and verification + +After configuring the generator, the last part of **create pdf417 barcode c#** is saving the image and confirming the result. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Run the program (`dotnet run`) and you should see a console message similar to: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Open the PNG file; you’ll see a crisp MicroPdf417 barcode that encodes the string “Åspóse.Barcóde©”. Scanning it with a mobile barcode scanner (e.g., ZXing) returns the original text, proving that **generate barcode from text** works even with special characters. + +### Edge case: very long text + +MicroPdf417 has a maximum data capacity of 1 KB. If your input exceeds this limit, the library throws an `ArgumentException`. To handle this gracefully: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +For larger payloads, switch to the full `EncodeTypes.Pdf417` or `EncodeTypes.DataMatrix`. + +## Common pitfalls and how to avoid them + +| Issue | Cause | Fix | +|-------------------------------------|-----------------------------------------|-----| +| Barcode appears blurry | XDimension too low (e.g., 1 px) | Increase `XDimension.Pixels` to 2‑3 px | +| Unicode characters become `?` | Default text encoding is ASCII | Set `TextEncoding = Encoding.UTF8` | +| Image file not created | Output directory does not exist | Use `Directory.CreateDirectory` before `Save` | +| Scanner cannot read the barcode | Too many columns for short data | Reduce `Pdf417.Columns` (e.g., 3‑4) | + +## Full source code (ready to copy) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Expected output:** a file named `MicroPdf417.png` located in the `output` folder, containing a clear MicroPdf417 barcode that encodes the original string with special characters. + +## Conclusion + +You now know how to **generate barcode from text** in C# using Aspose.BarCode, how to handle **barcode with special characters**, and how to **create pdf417 barcode c#** with full control over encoding options. By adjusting the **barcode encode types** you can produce QR codes, Code128, DataMatrix, or any other supported format. + +Next, explore the following topics to deepen your barcode expertise: + +- **How to generate barcode** in batch for thousands of records (use `Parallel.ForEach` for speed) +- Customizing colors and adding logos inside the barcode +- Integrating barcode generation into ASP.NET Core APIs for on‑the‑fly image delivery +- Using other libraries such as ZXing.Net or IronBarcode for open‑source alternatives + +Feel free to experiment with different dimensions, column settings, and encode types. Happy coding, and may your applications scan flawlessly! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/english/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/og-image.png b/barcode/english/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/og-image.png new file mode 100644 index 000000000..cb5eacbad Binary files /dev/null and b/barcode/english/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/og-image.png differ diff --git a/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..8964880c4 --- /dev/null +++ b/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-08-09 +description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 with + compact mode, column control, and PNG output using the BarcodeGenerator API. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: en +lastmod: 2026-08-09 +og_description: Generate PDF417 barcode in C# with a concise example. This guide shows + you how to configure compact mode, set columns, and save the result as a PNG image. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Generate PDF417 barcode in C# – complete tutorial +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: Generate PDF417 barcode in C# – step‑by‑step guide +url: /net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generate PDF417 barcode in C# – step‑by‑step guide + +If you need to **generate PDF417 barcode** in a .NET application, this tutorial shows you exactly how to do it. You’ll see a complete, runnable program that creates a compact PDF417 barcode, customizes its size, and saves the image as a PNG file. + +Generating a PDF417 barcode is a common requirement for mobile ticketing, inventory tracking, and document security. This guide covers the essential configuration options, explains why each setting matters, and provides practical tips for real‑world use. + +## Prerequisites + +Before you start, make sure you have: + +* .NET 6.0 SDK or later installed +* A C# IDE such as Visual Studio 2022 or Visual Studio Code +* The **Aspose.BarCode for .NET** NuGet package (version 23.10 or newer) + +You can install the package with the following CLI command: + +```bash +dotnet add package Aspose.BarCode +``` + +The code below assumes the package is referenced and that you have write permission to the output directory. + +## Step 1: Set up the project and import namespaces + +Create a new console project and add the required `using` directives. These namespaces expose the `BarcodeGenerator` class and the image format enumeration. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Why this matters:** Importing the correct namespaces ensures the compiler can locate the `BarcodeGenerator` type and the `BarCodeImageFormat` enum. Missing a namespace results in a compilation error, which halts the barcode generation process. + +## Step 2: Initialize the `BarcodeGenerator` with PDF417 encoding + +The `BarcodeGenerator` constructor receives two arguments: the barcode symbology (`EncodeTypes.Pdf417`) and the text you want to encode. PDF417 supports a wide range of characters, including Unicode symbols. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Explanation:** +* `EncodeTypes.Pdf417` tells the library to use the PDF417 standard. +* The sample text contains accented characters and a copyright symbol to demonstrate Unicode handling. + +If you need to encode only numeric data, you can pass a plain string like `"1234567890"`. + +## Step 3: Adjust the X‑dimension for finer resolution + +The X‑dimension controls the width of a single barcode module (the smallest black or white element). Setting a smaller pixel value yields a higher‑resolution image. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Why adjust it?** A default X‑dimension of 3–4 pixels may produce a barcode that looks coarse on high‑DPI screens. Reducing it to **2 pixels** balances readability with file size, especially when you later enable compact mode. + +## Step 4: Configure the number of columns + +PDF417 allows you to specify how many columns the barcode should contain. Fewer columns make the barcode narrower but taller, while more columns create a wider, shorter barcode. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Practical tip:** For mobile tickets that need to fit within a narrow label, a column count of **3–5** works well. Increase the count if you have a lot of data and want a shorter barcode. + +## Step 5: Enable compact mode to truncate empty rows + +Compact mode removes unnecessary rows from the barcode matrix, reducing the overall image size without losing encoded data. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**When to use it:** If you are generating barcodes for storage or network transmission, compact mode can shrink the PNG file by up to 30 %. However, some legacy scanners may not support truncated PDF417; test with your target hardware. + +## Step 6: Save the barcode as a PNG image + +Choose an output path and invoke `Save`. The `BarCodeImageFormat.Png` enumeration produces a lossless image suitable for most applications. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Result verification:** Open the PNG file in any image viewer. You should see a dense, high‑contrast barcode that matches the sample text. Scanning the image with a PDF417 reader (e.g., ZXing or a smartphone app) returns the original string `"Åspóse.Barcóde©"`. + +![Generated PDF417 barcode image saved as PNG](compact-pdf417.png "Generated PDF417 barcode in C#") + +*The image above demonstrates the final output of the tutorial’s code.* + +## Full, runnable example + +Putting all the pieces together, here is a complete console program you can copy, paste, and run. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Expected output + +Running the program prints: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +The file `CompactPdf417.png` contains a compact PDF417 barcode that encodes the Unicode string provided. Scanning the image with a standard PDF417 reader returns the exact text. + +## Common variations and edge cases + +| Situation | Adjustment | Reason | +|-----------|------------|--------| +| **Longer data payload** (e.g., > 150 characters) | Increase `generator.Parameters.Barcode.Pdf417.Columns` to 6‑8 | More columns prevent the barcode from becoming excessively tall. | +| **Need for a transparent background** | Use `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | Transparent PNG integrates better into UI overlays. | +| **Generating JPEG for web** | Change the format to `BarCodeImageFormat.Jpeg` and optionally set `ImageQuality` | JPEG reduces file size at the cost of lossless fidelity. | +| **Handling null or empty input** | Guard the input before creating the generator: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Prevents runtime exceptions and ensures meaningful barcodes. | + +## Tips for production use + +* **Exception handling:** Wrap the generation logic in a `try/catch` block to log errors such as insufficient disk space or invalid parameters. +* **Performance:** Reuse a single `BarcodeGenerator` instance when generating many barcodes with the same settings; only update the `CodeText` property between saves. +* **Security:** When the encoded text contains sensitive information, consider encrypting it before passing it to the generator and decrypting after scanning. + +## Conclusion + +You now know how to **generate PDF417 barcode** in C# using the Aspose.BarCode library, configure compact mode, control column count, and export the result as a PNG image. This tutorial covered every step from project setup to edge‑case handling, giving you a ready‑to‑use solution for barcode‑driven applications. + +Next, explore related topics such as **creating QR codes in C#**, **batch barcode generation**, and **integrating barcode scanning with mobile apps**. Each of these builds on the same `BarcodeGenerator` fundamentals you’ve just mastered. + +Happy coding! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to Generate PDF417 Barcodes – Compact PDF417 Encoding](/barcode/english/net/compact-pdf417-encoding/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/og-image.png b/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/og-image.png new file mode 100644 index 000000000..4e62b2312 Binary files /dev/null and b/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/og-image.png differ diff --git a/barcode/english/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/english/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..1853d8eb4 --- /dev/null +++ b/barcode/english/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-08-09 +description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: en +lastmod: 2026-08-09 +og_description: How to read PDF417 in C# with Aspose.BarCode. This tutorial shows + you how to read barcode PNG files, process multiple barcodes in one image, and retrieve + extended PDF417 metadata. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: How to read PDF417 in C# – barcode reader tutorial +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: How to read PDF417 in C# – complete barcode reader guide +url: /net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to read PDF417 in C# – complete barcode reader guide + +If you need to **how to read PDF417** in a .NET application, this guide gives you a ready‑to‑run solution. You’ll see how to read a barcode PNG, process several barcodes in the same image, and pull the extended PDF417 fields that many scanners hide. + +Reading PDF417 barcodes is common in logistics, ticketing, and document management. By the end of this tutorial you can decode a Macro PDF417 image, display every result, and use the extra information (file ID, segment count, timestamps, etc.) in your own business logic. + +## Prerequisites + +- .NET 6.0 or later (the code also works with .NET Framework 4.7+) +- Visual Studio 2022 or any C# IDE +- **Aspose.BarCode for .NET** (free trial or licensed NuGet package) +- A PNG image that contains a Macro PDF417 barcode (the sample file is named `ExtPDF417Meta.png`) + +> **Pro tip:** Install the library with the NuGet console: +> `dotnet add package Aspose.BarCode` + +## How to read PDF417 with BarCodeReader in C# + +The core of the solution is the `BarCodeReader` class. It accepts an image path and a `DecodeType` enum that tells the engine which symbology to look for. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Why this works + +- **`DecodeType.MacroPdf417`** tells the reader to look for the Macro PDF417 variant, which stores the extra fields you see in step 4. +- The `using` block disposes the reader automatically, releasing file handles. +- `ReadBarCodes()` returns **all** barcodes that match the requested type, which satisfies the *read multiple barcodes* requirement even if the image contains just one. + +Running the program prints output similar to: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## Using C# barcode reader to read multiple barcodes + +If an image contains several Macro PDF417 symbols (for example, a scanned page with a batch of tickets), the same `foreach` loop processes each one. No extra code is required; the reader aggregates results internally. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Common pitfalls + +- **Image format:** The reader supports PNG, JPEG, BMP, and TIFF. If you try a format it cannot decode, you’ll get an empty collection. That’s why the tutorial highlights *read barcode PNG*. +- **Resolution:** Low‑resolution images (< 300 dpi) may cause missed segments. Upscale or request a higher‑quality scan when possible. +- **Macro flag:** Forgetting `DecodeType.MacroPdf417` limits the engine to plain PDF417 and discards the extended data. Always specify the macro type when you need *read barcode extended* fields. + +## Reading barcode PNG files – best practices + +Working with PNG files is straightforward because the format preserves lossless pixel data. Here’s a quick checklist: + +1. Verify the file exists before creating the reader. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The `BarCodeReader` can open the file directly, which avoids extra memory allocation. +3. If the PNG contains transparency, the reader still works because the barcode is rendered on opaque pixels. + +## Accessing extended PDF417 metadata + +The `Extended.Pdf417` object exposes every optional field defined by the PDF417 specification. You can map these fields to a domain model, store them in a database, or use them for validation. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Populate the model: + +```csharp +Pdf417Metadata meta = new Pdf417Metadata +{ + FileID = result.Extended.Pdf417.MacroPdf417FileID, + SegmentID = result.Extended.Pdf417.MacroPdf417SegmentID + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to Read DataMatrix Barcodes with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Read DataMatrix barcode C# – Generate DataMatrix Mode (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/english/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/og-image.png b/barcode/english/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/og-image.png new file mode 100644 index 000000000..783f2e4af Binary files /dev/null and b/barcode/english/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/og-image.png differ diff --git a/barcode/french/net/compact-pdf417-encoding/_index.md b/barcode/french/net/compact-pdf417-encoding/_index.md index 13df3a6a5..8f9782cc5 100644 --- a/barcode/french/net/compact-pdf417-encoding/_index.md +++ b/barcode/french/net/compact-pdf417-encoding/_index.md @@ -87,6 +87,18 @@ Au‑delà des bases, voici quelques astuces pratiques pour optimiser votre flux ### [Créer des codes-barres Compact PDF417](./compact-pdf417-basic-configuration/) Apprenez à générer des codes-barres Compact PDF417 en utilisant Aspose.BarCode pour .NET. Guide complet avec des instructions étape par étape et des exemples de code. +### [Exemple Aspose Barcode : générer Macro PDF417 en C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Exemple de génération d'un code-barres Macro PDF417 en C# avec Aspose.BarCode. + +### [Générer un code-barres PDF417 en C# – guide étape par étape](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Guide complet pour créer un code-barres PDF417 en C# avec Aspose.BarCode, incluant le code source et les meilleures pratiques. + +### [Générer un code-barres à partir de texte en C# – guide complet étape par étape](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Apprenez à créer un code-barres à partir de texte en C# avec Aspose.BarCode, incluant un guide détaillé et du code d'exemple. + +### [Comment lire le PDF417 en C# – guide complet du lecteur de code-barres](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +Apprenez à décoder les codes-barres PDF417 en C# avec Aspose.BarCode, incluant un guide détaillé et des exemples de code. + ## Questions fréquentes **Q : Quelle est la quantité maximale de données que je peux stocker dans un code‑barcode Compact PDF417 ?** @@ -115,4 +127,4 @@ R : Aucune police externe n'est requise ; la bibliothèque gère tout le ren {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/french/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/french/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..1b2291e08 --- /dev/null +++ b/barcode/french/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-09 +description: Exemple Aspose Barcode montrant comment utiliser le générateur de code-barres + C# pour créer un Macro PDF417 avec prise en charge complète des métadonnées. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: fr +lastmod: 2026-08-09 +og_description: L'exemple de code‑barres Aspose montre l'utilisation d'un générateur + de code‑barres C# pour produire un code‑barres Macro PDF417 incluant l'ID du fichier, + les données de segment, l'horodatage et d'autres métadonnées. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Exemple de code-barres Aspose – créer un Macro PDF417 avec C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Exemple de code-barres Aspose : générer Macro PDF417 en C#' +url: /fr/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Exemple Aspose Barcode : générer Macro PDF417 en C# + +Si vous avez besoin d'un **exemple Aspose barcode** qui crée un code-barres Macro PDF417, ce guide vous montre comment le faire avec un **générateur de code-barres C#**. Vous verrez chaque paramètre requis, des dimensions de base à l'ensemble complet des champs de métadonnées Macro PDF417, et vous obtiendrez une image PNG prête pour le traitement en aval. + +Le tutoriel couvre le flux de travail complet, explique pourquoi chaque paramètre est important et fournit un exemple de code prêt à l'exécution. Aucune référence externe n'est requise ; vous pouvez copier le code, ajuster les valeurs et l'exécuter immédiatement. + +## Prérequis + +- .NET 6.0 (ou version ultérieure) installé +- Visual Studio 2022 ou tout IDE compatible C# +- Une licence valide pour **Aspose.BarCode for .NET** (l'essai gratuit fonctionne pour cet exemple) + +Ajoutez le package NuGet Aspose.BarCode à votre projet : + +```bash +dotnet add package Aspose.BarCode +``` + +## Étape 1 : Créer l'instance du générateur de code-barres C# + +La première étape consiste à instancier `BarcodeGenerator` avec la valeur d'énumération `EncodeTypes.MacroPdf417` et le texte que vous souhaitez encoder. Le texte peut contenir des caractères Unicode, que la bibliothèque gère automatiquement. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Pourquoi c'est important* : `EncodeTypes.MacroPdf417` indique au moteur de produire un symbole Macro PDF417, qui prend en charge les données segmentées et des métadonnées supplémentaires au niveau du fichier. L'instruction `using` garantit que les ressources non gérées sont libérées après l'enregistrement de l'image. + +## Étape 2 : Définir l'apparence de base du code-barres + +Un code-barres Macro PDF417 est composé de modules carrés. Le contrôle de la taille du module et du nombre de colonnes influence à la fois la lisibilité et la taille du fichier. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Pourquoi c'est important* : `XDimension.Pixels` détermine la densité visuelle ; une valeur de 2 pixels fonctionne bien pour l'affichage à l'écran tout en gardant l'image petite. Ajustez le nombre de colonnes pour répondre à vos contraintes de mise en page — plus de colonnes créent un code-barres plus large et plus court. + +## Étape 3 : Définir les métadonnées spécifiques à Macro PDF417 + +Macro PDF417 étend le format PDF417 standard avec des champs qui permettent la reconstruction de gros fichiers à partir de plusieurs segments de code-barres. Chaque champ est optionnel, mais les définir montre toutes les capacités de l'API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Pourquoi c'est important* : +- `MacroPdf417FileID` lie tous les segments appartenant au même fichier logique. +- `MacroPdf417SegmentID` et `MacroPdf417SegmentsCount` permettent au décodeur de réordonner correctement les fragments. +- `MacroPdf417Checksum` fournit une vérification d'intégrité rapide sans décoder l'intégralité de la charge utile. +- `MacroPdf417FileSize` et `MacroPdf417TimeStamp` permettent aux systèmes en aval de vérifier que le fichier reconstruit correspond à l'original. +- `MacroPdf417Addressee` / `MacroPdf417Sender` sont utiles dans les scénarios logistiques ou d'échange de documents. +- Définir `MacroPdf417Terminator` à `Set` marque ce code-barres comme le segment final, ce qui simplifie l'algorithme de reconstruction. + +## Étape 4 : Enregistrer l'image du code-barres généré + +Enfin, écrivez le code-barres dans un fichier PNG. Vous pouvez choisir n'importe quel format pris en charge (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Pourquoi c'est important* : PNG conserve les données pixel sans perte, garantissant que les scanners lisent exactement le motif de modules que vous avez configuré. Modifier le format peut affecter la qualité visuelle et la taille du fichier. + +### Résultat attendu + +L'exécution du programme complet crée un fichier nommé **ExtPDF417Meta.png**. L'ouverture de l'image montre un code-barres Macro PDF417 rectangulaire avec le texte « Åspóse.Barcóde© » encodé, et la densité visuelle correspond à la dimension X de 2 pixels que vous avez définie. Scanner l'image avec un lecteur compatible PDF417 renvoie tous les champs de métadonnées définis à l'Étape 3. + +## Exemple complet fonctionnel + +Copiez le code ci-dessous dans un nouveau projet console (`dotnet new console`) et remplacez `YOUR_DIRECTORY` par un chemin absolu ou relatif qui existe sur votre machine. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Exécutez le programme (`dotnet run`). Après l'exécution, vérifiez que le fichier PNG apparaît à l'emplacement que vous avez spécifié. Utilisez n'importe quelle application de lecture de code-barres qui prend en charge Macro PDF417 pour confirmer que les métadonnées sont correctement intégrées. + +## Variantes courantes et cas limites + +- **Différents formats d'image** : Remplacez `BarCodeImageFormat.Png` par `Jpeg`, `Bmp` ou `Tiff` si votre système en aval préfère un autre format. +- **Modification de la taille du module** : Des valeurs plus grandes de `XDimension.Pixels` améliorent la fiabilité du scan sur des scanners basse résolution mais augmentent la taille de l'image. +- **Segments multiples** : Pour produire un fichier multi‑segment, générez une série de code‑barres, incrémentez `MacroPdf417SegmentID` pour chaque, et conservez `MacroPdf417FileID` constant. Seul le dernier segment doit avoir `MacroPdf417Terminator` défini. +- **Prise en charge Unicode** : Le générateur encode automatiquement les caractères Unicode ; assurez‑vous que votre chaîne source utilise l'encodage UTF‑8 si vous la lisez depuis un fichier externe. +- **Gestion des erreurs** : Enveloppez le bloc `using` dans un try‑catch pour capturer `BarCodeException` en cas de paramètres invalides (par ex., nombre de colonnes hors plage). + +## Conseils pro + +- **Performance** : Réutilisez une seule instance de `BarcodeGenerator` lors de la création de nombreux code‑barres avec les mêmes paramètres ; ne changez que la propriété `CodeText` entre les enregistrements. +- **Estimation de la taille du fichier** : Le champ `MacroPdf417FileSize` doit correspondre au nombre d'octets de la charge utile originale ; des divergences peuvent entraîner des échecs de validation en aval. +- **Tests** : Validez les code‑barres générés avec le décodeur intégré d'Aspose (`BarCodeReader`) ainsi qu'avec un scanner tiers pour garantir l'interopérabilité. + +## Conclusion + +Cet **exemple Aspose barcode** + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s'appuient sur les techniques démontrées dans ce guide. Chaque ressource inclut des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités supplémentaires de l'API et explorer des approches d'implémentation alternatives dans vos propres projets. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to create barcode quiet zone for Code 16K using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/french/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/french/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..7298afd93 --- /dev/null +++ b/barcode/french/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-08-09 +description: Générez un code‑barres à partir du texte en C# avec Aspose.BarCode. Apprenez + comment générer un code‑barres, gérer les caractères spéciaux et créer rapidement + un code‑barres PDF417 en C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: fr +lastmod: 2026-08-09 +og_description: Générez un code‑barres à partir du texte en C# avec Aspose.BarCode. + Ce tutoriel montre comment générer un code‑barres, prendre en charge les caractères + spéciaux et créer un code‑barres PDF417 en C# avec le code complet. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Générer un code‑barres à partir de texte en C# – guide rapide étape par + étape +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Générer un code‑barres à partir du texte en C# – guide complet étape par étape +url: /fr/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Générer un code‑barres à partir de texte en C# – guide complet étape par étape + +Si vous devez **générer un code‑barres à partir de texte** dans une application .NET, ce guide vous accompagne tout au long du processus. Vous verrez comment générer un code‑barres, gérer les caractères spéciaux et créer une implémentation C# du code‑barres PDF417 qui fonctionne immédiatement. + +Générer un code‑barres à partir de texte est une exigence courante pour les systèmes d’inventaire, les plateformes de billetterie et les flux de travail documentaires. À la fin de ce tutoriel, vous disposerez d’une application console C# exécutable qui produit une image PNG MicroPdf417 à l’aide d’Aspose.BarCode. Aucun service externe n’est requis, et le code gère les caractères Unicode tels que « Å », « © » et « é ». + +## Prérequis + +- SDK .NET 6.0 ou ultérieur (le code fonctionne également avec .NET Core 3.1 et .NET Framework 4.7+) +- Visual Studio 2022 (ou tout IDE supportant C#) +- **Aspose.BarCode for .NET** package NuGet + ```bash + dotnet add package Aspose.BarCode + ``` +- Connaissances de base en syntaxe C# + +## Générer un code‑barres à partir de texte – configuration du générateur + +La première étape consiste à créer une instance `BarcodeGenerator` qui sait quel **type d’encodage de code‑barres** vous souhaitez. Dans ce tutoriel, nous utilisons `EncodeTypes.MicroPdf417`, une variante compacte de PDF417 adaptée aux chaînes de données courtes. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Pourquoi cela fonctionne :** +- `EncodeTypes.MicroPdf417` indique à la bibliothèque d’utiliser la famille PDF417, répondant ainsi à l’exigence **create pdf417 barcode c#**. +- Le constructeur reçoit le texte brut, qui est l’essence de **generate barcode from text**. +- La prise en charge Unicode est intégrée, de sorte que des caractères comme « Å » et « © » sont encodés correctement, répondant à **barcode with special characters**. + +## Comment générer un code‑barres avec des caractères spéciaux + +Lorsque vos données contiennent des symboles non ASCII, vous devez vous assurer que le générateur utilise l’encodage UTF‑8. Aspose.BarCode détecte automatiquement Unicode, mais vous pouvez définir explicitement l’encodage du texte si vous rencontrez des problèmes : + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Ajouter cette ligne avant `ConfigureGenerator` garantit que **barcode with special characters** s’affiche correctement sur n’importe quelle plateforme. + +### Astuce pratique +Si la sortie apparaît corrompue, vérifiez que la police utilisée par le rendu du code‑barres prend en charge les glyphes requis. Vous pouvez intégrer une police TrueType personnalisée via : + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Types d’encodage de code‑barres disponibles + +Aspose.BarCode prend en charge des dizaines de **types d’encodage de code‑barres**, chacun adapté à différents cas d’utilisation : + +| Type d'encodage | Cas d'utilisation typique | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | Étiquettes d’expédition, inventaire | +| `EncodeTypes.QR` | Paiements mobiles, URL | +| `EncodeTypes.Pdf417` | Permis de conduire, cartes d’embarquement | +| `EncodeTypes.MicroPdf417` | Petites charges de données, espace limité | +| `EncodeTypes.DataMatrix` | Articles minuscules, densité de données élevée | + +Modifier le type d’encodage est aussi simple que d’échanger la valeur de l’énumération dans le constructeur : + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Cette flexibilité vous permet de répondre aux questions sur les **barcode encode types** sans quitter l’IDE. + +## Créer un code‑barres PDF417 C# – étapes finales et vérification + +Après avoir configuré le générateur, la dernière partie de **create pdf417 barcode c#** consiste à enregistrer l’image et à confirmer le résultat. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Exécutez le programme (`dotnet run`) et vous devriez voir un message console similaire à : + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Ouvrez le fichier PNG ; vous verrez un code‑barres MicroPdf417 net qui encode la chaîne « Åspóse.Barcóde© ». Le scanner mobile (par ex., ZXing) renvoie le texte original, prouvant que **generate barcode from text** fonctionne même avec des caractères spéciaux. + +### Cas limite : texte très long + +MicroPdf417 a une capacité maximale de 1 KB. Si votre entrée dépasse cette limite, la bibliothèque lève une `ArgumentException`. Pour gérer cela proprement : + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Pour des charges plus importantes, passez à `EncodeTypes.Pdf417` complet ou à `EncodeTypes.DataMatrix`. + +## Pièges courants et comment les éviter + +| Problème | Cause | Solution | +|---------------------------------------|---------------------------------------|----------| +| Le code‑barres apparaît flou | XDimension trop faible (ex. 1 px) | Augmenter `XDimension.Pixels` à 2‑3 px | +| Les caractères Unicode deviennent `?`| L’encodage texte par défaut est ASCII | Définir `TextEncoding = Encoding.UTF8` | +| Le fichier image n’est pas créé | Le répertoire de sortie n’existe pas | Utiliser `Directory.CreateDirectory` avant `Save` | +| Le scanner ne lit pas le code‑barres | Trop de colonnes pour peu de données | Réduire `Pdf417.Columns` (ex. 3‑4) | + +## Code source complet (prêt à copier) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Sortie attendue :** un fichier nommé `MicroPdf417.png` situé dans le dossier `output`, contenant un code‑barres MicroPdf417 clair qui encode la chaîne originale avec les caractères spéciaux. + +## Conclusion + +Vous savez maintenant comment **générer un code‑barres à partir de texte** en C# avec Aspose.BarCode, comment gérer **barcode with special characters**, et comment **create pdf417 barcode c#** avec un contrôle complet des options d’encodage. En ajustant les **barcode encode types**, vous pouvez produire des QR codes, Code128, DataMatrix ou tout autre format supporté. + +Ensuite, explorez les sujets suivants pour approfondir votre expertise en codes‑barres : + +- **How to generate barcode** en lot pour des milliers d’enregistrements (utilisez `Parallel.ForEach` pour la rapidité) +- Personnalisation des couleurs et ajout de logos à l’intérieur du code‑barres +- Intégration de la génération de code‑barres dans les API ASP.NET Core pour une livraison d’image à la volée +- Utilisation d’autres bibliothèques telles que ZXing.Net ou IronBarcode pour des alternatives open‑source + +N’hésitez pas à expérimenter avec différentes dimensions, réglages de colonnes et types d’encodage. Bon codage, et que vos applications scannent sans accroc ! + +## What Should You Learn Next? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités API supplémentaires et à explorer des approches d’implémentation alternatives dans vos propres projets. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/french/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/french/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..c3a7daf3f --- /dev/null +++ b/barcode/french/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-08-09 +description: Générez un code‑barres PDF417 en C# rapidement. Apprenez à générer du + PDF417 en mode compact, avec contrôle des colonnes et sortie PNG en utilisant l’API + BarcodeGenerator. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: fr +lastmod: 2026-08-09 +og_description: Générez un code‑barres PDF417 en C# avec un exemple concis. Ce guide + vous montre comment configurer le mode compact, définir les colonnes et enregistrer + le résultat en tant qu’image PNG. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Générer un code‑barres PDF417 en C# – tutoriel complet +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: Générer un code‑barres PDF417 en C# – guide pas à pas +url: /fr/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Générer un code‑barres PDF417 en C# – guide étape par étape + +Si vous devez **générer un code‑barres PDF417** dans une application .NET, ce tutoriel vous montre exactement comment le faire. Vous verrez un programme complet et exécutable qui crée un code‑barres PDF417 compact, personnalise sa taille et enregistre l'image au format PNG. + +La génération d'un code‑barres PDF417 est une exigence courante pour la billetterie mobile, le suivi d'inventaire et la sécurité des documents. Ce guide couvre les options de configuration essentielles, explique pourquoi chaque paramètre est important et fournit des conseils pratiques pour une utilisation en conditions réelles. + +## Prérequis + +* SDK .NET 6.0 ou version ultérieure installé +* Un IDE C# tel que Visual Studio 2022 ou Visual Studio Code +* Le package NuGet **Aspose.BarCode for .NET** (version 23.10 ou plus récente) + +Vous pouvez installer le package avec la commande CLI suivante : + +```bash +dotnet add package Aspose.BarCode +``` + +Le code ci‑dessous suppose que le package est référencé et que vous disposez des droits d’écriture sur le répertoire de sortie. + +## Étape 1 : Configurer le projet et importer les espaces de noms + +Créez un nouveau projet console et ajoutez les directives `using` requises. Ces espaces de noms exposent la classe `BarcodeGenerator` et l’énumération des formats d’image. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Pourquoi c’est important :** Importer les bons espaces de noms garantit que le compilateur peut localiser le type `BarcodeGenerator` et l’énumération `BarCodeImageFormat`. L’absence d’un espace de noms entraîne une erreur de compilation, ce qui interrompt le processus de génération du code‑barres. + +## Étape 2 : Initialiser le `BarcodeGenerator` avec l’encodage PDF417 + +Le constructeur `BarcodeGenerator` reçoit deux arguments : la symbologie du code‑barres (`EncodeTypes.Pdf417`) et le texte que vous souhaitez encoder. PDF417 prend en charge un large éventail de caractères, y compris les symboles Unicode. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Explication :** +* `EncodeTypes.Pdf417` indique à la bibliothèque d’utiliser la norme PDF417. +* Le texte d’exemple contient des caractères accentués et un symbole de copyright pour démontrer la prise en charge d’Unicode. + +Si vous devez encoder uniquement des données numériques, vous pouvez passer une chaîne simple comme `"1234567890"`. + +## Étape 3 : Ajuster la X‑dimension pour une résolution plus fine + +La X‑dimension contrôle la largeur d’un seul module du code‑barres (l’élément noir ou blanc le plus petit). Définir une valeur en pixels plus petite produit une image à plus haute résolution. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Pourquoi l’ajuster ?** Une X‑dimension par défaut de 3–4 pixels peut produire un code‑barres qui paraît grossier sur des écrans haute‑DPI. La réduire à **2 pixels** équilibre lisibilité et taille du fichier, surtout lorsque vous activez ensuite le mode compact. + +## Étape 4 : Configurer le nombre de colonnes + +PDF417 vous permet de spécifier le nombre de colonnes que le code‑barres doit contenir. Moins de colonnes rendent le code‑barres plus étroit mais plus haut, tandis que davantage de colonnes produisent un code‑barres plus large et plus court. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Conseil pratique :** Pour les billets mobiles qui doivent tenir sur une étiquette étroite, un nombre de colonnes de **3–5** fonctionne bien. Augmentez le nombre si vous avez beaucoup de données et souhaitez un code‑barres plus court. + +## Étape 5 : Activer le mode compact pour tronquer les rangées vides + +Le mode compact supprime les rangées inutiles de la matrice du code‑barres, réduisant la taille globale de l’image sans perdre les données encodées. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Quand l’utiliser :** Si vous générez des codes‑barres pour le stockage ou la transmission réseau, le mode compact peut réduire le fichier PNG jusqu’à 30 %. Cependant, certains lecteurs anciens peuvent ne pas prendre en charge le PDF417 tronqué ; testez avec votre matériel cible. + +## Étape 6 : Enregistrer le code‑barres en image PNG + +Choisissez un chemin de sortie et appelez `Save`. L’énumération `BarCodeImageFormat.Png` produit une image sans perte adaptée à la plupart des applications. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Vérification du résultat :** Ouvrez le fichier PNG dans n’importe quel visualiseur d’image. Vous devriez voir un code‑barres dense et à fort contraste qui correspond au texte d’exemple. Scanner l’image avec un lecteur PDF417 (par ex., ZXing ou une application smartphone) renvoie la chaîne originale `"Åspóse.Barcóde©"`. + +![Image du code‑barres PDF417 généré enregistrée au format PNG](compact-pdf417.png "Code‑barres PDF417 généré en C#") + +*L’image ci‑dessus montre le résultat final du code du tutoriel.* + +## Exemple complet, exécutable + +En assemblant tous les éléments, voici un programme console complet que vous pouvez copier, coller et exécuter. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Sortie attendue + +L’exécution du programme affiche : + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +Le fichier `CompactPdf417.png` contient un code‑barres PDF417 compact qui encode la chaîne Unicode fournie. Scanner l’image avec un lecteur PDF417 standard renvoie le texte exact. + +## Variantes courantes et cas limites + +| Situation | Ajustement | Raison | +|-----------|------------|--------| +| **Charge de données plus longue** (p. ex., > 150 caractères) | Augmenter `generator.Parameters.Barcode.Pdf417.Columns` à 6‑8 | Plus de colonnes évitent que le code‑barres ne devienne excessivement haut. | +| **Besoin d’un arrière‑plan transparent** | Utiliser `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | Un PNG transparent s’intègre mieux aux superpositions d’interface. | +| **Générer du JPEG pour le web** | Modifier le format en `BarCodeImageFormat.Jpeg` et éventuellement définir `ImageQuality` | Le JPEG réduit la taille du fichier au prix d’une perte de fidélité sans perte. | +| **Gestion d’une entrée nulle ou vide** | Protéger l’entrée avant de créer le générateur : `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Empêche les exceptions d’exécution et garantit des codes‑barres significatifs. | + +## Conseils pour la mise en production + +* **Gestion des exceptions :** Encapsulez la logique de génération dans un bloc `try/catch` pour consigner les erreurs telles que l’espace disque insuffisant ou des paramètres invalides. +* **Performance :** Réutilisez une seule instance de `BarcodeGenerator` lors de la génération de nombreux codes‑barres avec les mêmes paramètres ; mettez simplement à jour la propriété `CodeText` entre les sauvegardes. +* **Sécurité :** Lorsque le texte encodé contient des informations sensibles, envisagez de le chiffrer avant de le transmettre au générateur et de le déchiffrer après le scan. + +## Conclusion + +Vous savez maintenant comment **générer un code‑barres PDF417** en C# en utilisant la bibliothèque Aspose.BarCode, configurer le mode compact, contrôler le nombre de colonnes et exporter le résultat sous forme d’image PNG. Ce tutoriel a couvert chaque étape, de la configuration du projet à la gestion des cas limites, vous offrant une solution prête à l’emploi pour les applications basées sur les codes‑barres. + +Ensuite, explorez des sujets connexes tels que **la création de QR codes en C#**, **la génération de lots de codes‑barres**, et **l’intégration du scan de codes‑barres avec des applications mobiles**. Chacun de ces sujets repose sur les mêmes fondamentaux du `BarcodeGenerator` que vous venez de maîtriser. + +Bon codage ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Comment générer des codes‑barres PDF417 – Encodage PDF417 compact](/barcode/english/net/compact-pdf417-encoding/) +- [Comment créer un code‑barres – PDF417 compact avec Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Comment générer un code‑barres Aztec avec un rapport d’aspect personnalisé en utilisant Aspose.BarCode pour .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/french/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/french/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..348ee13cb --- /dev/null +++ b/barcode/french/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-09 +description: Comment lire le PDF417 en C# avec le BarCodeReader. Apprenez à lire les + fichiers PNG de codes-barres, à gérer plusieurs codes-barres et à extraire les métadonnées + étendues. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: fr +lastmod: 2026-08-09 +og_description: Comment lire le PDF417 en C# avec Aspose.BarCode. Ce tutoriel vous + montre comment lire des fichiers PNG de codes-barres, traiter plusieurs codes-barres + dans une même image et récupérer les métadonnées étendues du PDF417. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Comment lire le PDF417 en C# – tutoriel de lecteur de code-barres +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Comment lire le PDF417 en C# – guide complet du lecteur de codes-barres +url: /fr/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment lire PDF417 en C# – guide complet du lecteur de codes-barres + +Si vous avez besoin de **comment lire PDF417** dans une application .NET, ce guide vous fournit une solution prête à l’emploi. Vous verrez comment lire un PNG de code-barres, traiter plusieurs codes-barres dans la même image, et extraire les champs PDF417 étendus que de nombreux scanners masquent. + +La lecture des codes-barres PDF417 est courante dans la logistique, la billetterie et la gestion de documents. À la fin de ce tutoriel, vous pourrez décoder une image Macro PDF417, afficher chaque résultat, et utiliser les informations supplémentaires (ID de fichier, nombre de segments, horodatages, etc.) dans votre propre logique métier. + +## Prérequis + +- .NET 6.0 ou version ultérieure (le code fonctionne également avec .NET Framework 4.7+) +- Visual Studio 2022 ou tout IDE C# +- **Aspose.BarCode for .NET** (version d’essai gratuite ou package NuGet sous licence) +- Une image PNG contenant un code-barres Macro PDF417 (le fichier d’exemple s’appelle `ExtPDF417Meta.png`) + +> **Astuce pro** : Installez la bibliothèque avec la console NuGet : +> `dotnet add package Aspose.BarCode` + +## Comment lire PDF417 avec BarCodeReader en C# + +Le cœur de la solution est la classe `BarCodeReader`. Elle accepte un chemin d’image et une énumération `DecodeType` qui indique au moteur quelle symbologie rechercher. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Pourquoi cela fonctionne + +- **`DecodeType.MacroPdf417`** indique au lecteur de rechercher la variante Macro PDF417, qui stocke les champs supplémentaires que vous voyez à l’étape 4. +- Le bloc `using` libère automatiquement le lecteur, en fermant les descripteurs de fichiers. +- `ReadBarCodes()` renvoie **tous** les codes-barres correspondant au type demandé, ce qui satisfait le besoin de *lire plusieurs codes-barres* même si l’image ne contient qu’un seul. + +L’exécution du programme affiche une sortie similaire à : + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## Utiliser le lecteur de codes-barres C# pour lire plusieurs codes-barres + +Si une image contient plusieurs symboles Macro PDF417 (par exemple, une page numérisée avec un lot de billets), la même boucle `foreach` traite chacun d’eux. Aucun code supplémentaire n’est nécessaire ; le lecteur agrège les résultats en interne. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Pièges courants + +- **Format d’image :** Le lecteur prend en charge PNG, JPEG, BMP et TIFF. Si vous essayez un format qu’il ne peut pas décoder, vous obtiendrez une collection vide. C’est pourquoi le tutoriel met en avant *lire le code-barres PNG*. +- **Résolution :** Les images à basse résolution (< 300 dpi) peuvent entraîner des segments manquants. Agrandissez ou demandez un scan de meilleure qualité lorsque c’est possible. +- **Drapeau Macro :** Oublier `DecodeType.MacroPdf417` limite le moteur au PDF417 simple et supprime les données étendues. Spécifiez toujours le type macro lorsque vous avez besoin des champs *lire le code-barres étendu*. + +## Lecture de fichiers PNG de codes-barres – bonnes pratiques + +Travailler avec des fichiers PNG est simple car le format préserve les données de pixels sans perte. Voici une checklist rapide : + +1. Vérifiez que le fichier existe avant de créer le lecteur. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Utilisez `Image.FromFile` uniquement si vous devez pré‑traiter (rotation, recadrage). Le `BarCodeReader` peut ouvrir le fichier directement, ce qui évite une allocation mémoire supplémentaire. +3. Si le PNG contient de la transparence, le lecteur fonctionne toujours car le code-barres est rendu sur des pixels opaques. + +## Accéder aux métadonnées PDF417 étendues + +L’objet `Extended.Pdf417` expose chaque champ optionnel défini par la spécification PDF417. Vous pouvez mapper ces champs à un modèle métier, les stocker dans une base de données, ou les utiliser pour la validation. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Remplir le modèle : + + + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Comment lire les codes-barres DataMatrix avec Aspose.BarCode pour .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Comment créer un code-barres – PDF417 compact avec Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Lire le code-barres DataMatrix C# – Générer le mode DataMatrix (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/german/net/compact-pdf417-encoding/_index.md b/barcode/german/net/compact-pdf417-encoding/_index.md index 201fcffef..7d89a2165 100644 --- a/barcode/german/net/compact-pdf417-encoding/_index.md +++ b/barcode/german/net/compact-pdf417-encoding/_index.md @@ -57,7 +57,7 @@ Jetzt, wo die Theorie klar ist, erzeugen wir einen Barcode. Die folgenden Schrit 4. **Aussehen anpassen** – Farben, Ränder ändern oder bei Bedarf eine Beschriftung hinzufügen. 5. **Bild speichern** – Export nach PNG, JPEG oder einem anderen unterstützten Format. -> **Pro‑Tipp:** Verwenden Sie dieselbe `BarcodeGenerator`‑Instanz, wenn Sie in einer Schleife mehrere Barcodes erzeugen, um die Leistung zu steigern. +> **Pro‑Tip:** Verwenden Sie dieselbe `BarcodeGenerator`‑Instanz, wenn Sie in einer Schleife mehrere Barcodes erzeugen, um die Leistung zu steigern. ## PDF417 Barcode‑Beispiel @@ -85,6 +85,18 @@ Nachfolgend eine knappe Beschreibung eines typischen Barcode‑Erstellungsszenar ### [Creating Compact PDF417 Barcodes](./compact-pdf417-basic-configuration/) Erfahren Sie, wie Sie Compact PDF417 Barcodes mit Aspose.BarCode für .NET erzeugen. Umfassender Leitfaden mit Schritt‑für‑Schritt‑Anweisungen und Code‑Beispielen. +### [Aspose Barcode‑Beispiel: Macro PDF417 in C# erzeugen](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Erfahren Sie, wie Sie mit Aspose.BarCode für .NET einen Macro PDF417 Barcode in C# erzeugen. + +### [PDF417-Barcode in C# generieren – Schritt‑für‑Schritt‑Anleitung](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Erfahren Sie, wie Sie mit Aspose.BarCode für .NET einen PDF417‑Barcode in C# Schritt für Schritt erstellen. + +### [Barcode aus Text in C# generieren – vollständige Schritt‑für‑Schritt‑Anleitung](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Erfahren Sie, wie Sie mit Aspose.BarCode für .NET aus einem Text in C# einen Barcode erstellen. + +### [Wie man PDF417 in C# liest – vollständiger Barcode‑Reader‑Leitfaden](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +Erfahren Sie, wie Sie mit Aspose.BarCode für .NET PDF417‑Barcodes in C# auslesen – Schritt‑für‑Schritt‑Anleitung. + ## Häufig gestellte Fragen **F: Wie viel Daten kann ich maximal in einem Compact PDF417 Barcode speichern?** @@ -113,4 +125,4 @@ A: Nein, es werden keine externen Schriftarten benötigt; die Bibliothek überni {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/german/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/german/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..7cf2621ba --- /dev/null +++ b/barcode/german/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-08-09 +description: Aspose-Barcode-Beispiel, das zeigt, wie man den Barcode-Generator in + C# verwendet, um ein Macro PDF417 mit voller Metadatenunterstützung zu erzeugen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: de +lastmod: 2026-08-09 +og_description: Das Aspose‑Barcode‑Beispiel demonstriert die Verwendung eines Barcode‑Generators + in C#, um einen Macro‑PDF417‑Barcode zu erzeugen, der Datei‑ID, Segmentdaten, Zeitstempel + und weitere Metadaten enthält. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Aspose Barcode-Beispiel – Macro PDF417 mit C# erstellen +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Aspose Barcode‑Beispiel: Macro‑PDF417 in C# generieren' +url: /de/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose‑Barcode‑Beispiel: Macro PDF417 in C# erzeugen + +Wenn Sie ein **aspose barcode example** benötigen, das einen Macro PDF417‑Barcode erstellt, zeigt Ihnen diese Anleitung, wie Sie dies mit einem **barcode generator C#** umsetzen. Sie sehen jede erforderliche Einstellung, von den Grundmaßen bis zum vollständigen Satz der Macro PDF417‑Metadatenfelder, und erhalten am Ende ein PNG‑Bild, das für die Weiterverarbeitung bereitsteht. + +Das Tutorial deckt den gesamten Workflow ab, erklärt, warum jeder Parameter wichtig ist, und liefert ein sofort ausführbares Code‑Beispiel. Es werden keine externen Verweise benötigt; Sie können den Code kopieren, die Werte anpassen und sofort ausführen. + +## Voraussetzungen + +Bevor Sie beginnen, stellen Sie sicher, dass Sie Folgendes haben: + +- .NET 6.0 (oder höher) installiert +- Visual Studio 2022 oder eine beliebige C#‑kompatible IDE +- Eine gültige Lizenz für **Aspose.BarCode for .NET** (die kostenlose Testversion funktioniert für dieses Beispiel) + +Fügen Sie das Aspose.BarCode‑NuGet‑Paket zu Ihrem Projekt hinzu: + +```bash +dotnet add package Aspose.BarCode +``` + +## Schritt 1: Instanziieren des Barcode‑Generators C# + +Der erste Schritt besteht darin, `BarcodeGenerator` mit dem Enum‑Wert `EncodeTypes.MacroPdf417` und dem Text, den Sie codieren möchten, zu instanziieren. Der Text kann Unicode‑Zeichen enthalten, die die Bibliothek automatisch verarbeitet. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Warum das wichtig ist*: `EncodeTypes.MacroPdf417` weist die Engine an, ein Macro PDF417‑Symbol zu erzeugen, das segmentierte Daten und zusätzliche datei‑bezogene Metadaten unterstützt. Die `using`‑Anweisung stellt sicher, dass nicht verwaltete Ressourcen nach dem Speichern des Bildes freigegeben werden. + +## Schritt 2: Grundlegendes Aussehen des Barcodes festlegen + +Ein Macro PDF417‑Barcode besteht aus quadratischen Modulen. Die Kontrolle der Modulgröße und der Spaltenanzahl beeinflusst sowohl die Lesbarkeit als auch die Dateigröße. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Warum das wichtig ist*: `XDimension.Pixels` bestimmt die visuelle Dichte; ein Wert von 2 Pixel funktioniert gut für die Anzeige auf Bildschirmen und hält das Bild klein. Passen Sie die Spaltenanzahl an Ihre Layout‑Beschränkungen an – mehr Spalten erzeugen einen breiteren, kürzeren Barcode. + +## Schritt 3: Macro PDF417‑spezifische Metadaten setzen + +Macro PDF417 erweitert das Standard‑PDF417‑Format um Felder, die die Rekonstruktion großer Dateien aus mehreren Barcode‑Segmenten ermöglichen. Jedes Feld ist optional, aber das Setzen demonstriert die vollen Möglichkeiten der API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Warum das wichtig ist*: +- `MacroPdf417FileID` verknüpft alle Segmente, die zu derselben logischen Datei gehören. +- `MacroPdf417SegmentID` und `MacroPdf417SegmentsCount` ermöglichen es dem Decoder, Fragmente korrekt zu reorderieren. +- `MacroPdf417Checksum` liefert eine schnelle Integritätsprüfung, ohne die gesamte Nutzlast zu decodieren. +- `MacroPdf417FileSize` und `MacroPdf417TimeStamp` erlauben nachgelagerten Systemen zu prüfen, ob die rekonstruierte Datei mit dem Original übereinstimmt. +- `MacroPdf417Addressee` / `MacroPdf417Sender` sind in Logistik‑ oder Dokumentenaustausch‑Szenarien nützlich. +- Das Setzen von `MacroPdf417Terminator` auf `Set` markiert diesen Barcode als letztes Segment, was den Rekonstruktions‑Algorithmus vereinfacht. + +## Schritt 4: Das erzeugte Barcode‑Bild speichern + +Zum Schluss schreiben Sie den Barcode in eine PNG‑Datei. Sie können jedes unterstützte Format wählen (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Warum das wichtig ist*: PNG bewahrt verlustfreie Pixeldaten und stellt sicher, dass Scanner das exakt konfigurierte Modul‑Muster lesen. Das Ändern des Formats kann die visuelle Qualität und Dateigröße beeinflussen. + +### Erwartete Ausgabe + +Das Ausführen des vollständigen Programms erzeugt eine Datei namens **ExtPDF417Meta.png**. Beim Öffnen des Bildes sehen Sie einen rechteckigen Macro PDF417‑Barcode mit dem codierten Text „Åspóse.Barcóde©“, und die visuelle Dichte entspricht der von Ihnen festgelegten 2‑Pixel‑X‑Dimension. Das Scannen des Bildes mit einem PDF417‑kompatiblen Leser liefert alle in Schritt 3 definierten Metadatenfelder zurück. + +## Vollständiges funktionierendes Beispiel + +Kopieren Sie den untenstehenden Code in ein neues Konsolen‑Projekt (`dotnet new console`) und ersetzen Sie `YOUR_DIRECTORY` durch einen absoluten oder relativen Pfad, der auf Ihrem Rechner existiert. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Führen Sie das Programm aus (`dotnet run`). Nach der Ausführung prüfen Sie, ob die PNG‑Datei an dem von Ihnen angegebenen Ort erscheint. Verwenden Sie eine Barcode‑Lese‑App, die Macro PDF417 unterstützt, um zu bestätigen, dass die Metadaten korrekt eingebettet sind. + +## Häufige Varianten und Sonderfälle + +- **Verschiedene Bildformate**: Ersetzen Sie `BarCodeImageFormat.Png` durch `Jpeg`, `Bmp` oder `Tiff`, wenn Ihr nachgelagertes System ein anderes Format bevorzugt. +- **Änderung der Modulgröße**: Größere Werte für `XDimension.Pixels` verbessern die Scan‑Zuverlässigkeit bei Low‑Resolution‑Scannern, erhöhen jedoch die Bildgröße. +- **Mehrere Segmente**: Um eine mehrsegmentige Datei zu erzeugen, generieren Sie eine Reihe von Barcodes, erhöhen Sie `MacroPdf417SegmentID` für jedes und halten Sie `MacroPdf417FileID` konstant. Nur das letzte Segment sollte `MacroPdf417Terminator` gesetzt haben. +- **Unicode‑Unterstützung**: Der Generator codiert Unicode‑Zeichen automatisch; stellen Sie sicher, dass Ihre Quellzeichenkette UTF‑8 verwendet, wenn Sie sie aus einer externen Datei einlesen. +- **Fehlerbehandlung**: Umfassen Sie den `using`‑Block mit einem `try‑catch`, um `BarCodeException` für ungültige Parameter (z. B. Spaltenzahl außerhalb des zulässigen Bereichs) abzufangen. + +## Profi‑Tipps + +- **Performance**: Wiederverwenden Sie eine einzelne `BarcodeGenerator`‑Instanz, wenn Sie viele Barcodes mit denselben Einstellungen erzeugen; ändern Sie nur die Eigenschaft `CodeText` zwischen den Saves. +- **Dateigrößenschätzung**: Das Feld `MacroPdf417FileSize` sollte der Byte‑Anzahl der ursprünglichen Nutzlast entsprechen; Abweichungen können zu Validierungsfehlern im nachgelagerten System führen. +- **Testing**: Validieren Sie erzeugte Barcodes sowohl mit Asposes eingebautem Decoder (`BarCodeReader`) als auch mit einem Drittanbieter‑Scanner, um Interoperabilität sicherzustellen. + +## Fazit + +Dieses **aspose barcode example** + + +## Was sollten Sie als Nächstes lernen? + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to create barcode quiet zone for Code 16K using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/german/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/german/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..4ccf51227 --- /dev/null +++ b/barcode/german/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-08-09 +description: Barcode aus Text in C# mit Aspose.BarCode generieren. Erfahren Sie, wie + Sie Barcodes erzeugen, Sonderzeichen verarbeiten und schnell einen PDF417‑Barcode + in C# erstellen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: de +lastmod: 2026-08-09 +og_description: Erstellen Sie einen Barcode aus Text in C# mit Aspose.BarCode. Dieses + Tutorial zeigt, wie man einen Barcode generiert, Sonderzeichen unterstützt und einen + PDF417‑Barcode in C# mit vollständigem Code erstellt. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Barcode aus Text in C# generieren – schnelle Schritt‑für‑Schritt‑Anleitung +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Barcode aus Text in C# generieren – vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode aus Text in C# generieren – vollständige Schritt‑für‑Schritt‑Anleitung + +Wenn Sie **Barcode aus Text generieren** in einer .NET‑Anwendung benötigen, führt Sie diese Anleitung durch den gesamten Prozess. Sie sehen, wie man Barcodes generiert, Sonderzeichen verwaltet und eine PDF417‑Barcode‑C#‑Implementierung erstellt, die sofort einsatzbereit ist. + +Das Generieren eines Barcodes aus Text ist eine gängige Anforderung für Inventursysteme, Ticketplattformen und Dokumenten‑Workflows. Am Ende dieses Tutorials haben Sie eine ausführbare C#‑Konsolenanwendung, die ein MicroPdf417‑PNG‑Bild mit Aspose.BarCode erzeugt. Es werden keine externen Dienste benötigt, und der Code verarbeitet Unicode‑Zeichen wie „Å“, „©“ und „é“. + +## Voraussetzungen + +- .NET 6.0 SDK oder neuer (der Code funktioniert auch mit .NET Core 3.1 und .NET Framework 4.7+) +- Visual Studio 2022 (oder jede IDE, die C# unterstützt) +- **Aspose.BarCode for .NET** NuGet‑Paket + ```bash + dotnet add package Aspose.BarCode + ``` +- Grundlegende Kenntnisse der C#‑Syntax + +## Barcode aus Text generieren – Einrichtung des Generators + +Der erste Schritt besteht darin, eine `BarcodeGenerator`‑Instanz zu erstellen, die den gewünschten **barcode encode type** kennt. In diesem Tutorial verwenden wir `EncodeTypes.MicroPdf417`, eine kompakte Variante von PDF417, die für kurze Datenzeichenketten geeignet ist. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Warum das funktioniert:** +- `EncodeTypes.MicroPdf417` weist die Bibliothek an, die PDF417‑Familie zu verwenden, und erfüllt die **create pdf417 barcode c#** Anforderung. +- Der Konstruktor erhält den Rohtext, der das Wesentliche von **Barcode aus Text generieren** darstellt. +- Unicode‑Unterstützung ist integriert, sodass Zeichen wie „Å“ und „©“ korrekt codiert werden, was **barcode with special characters** adressiert. + +## Wie man Barcodes mit Sonderzeichen generiert + +Wenn Ihre Daten nicht‑ASCII‑Symbole enthalten, müssen Sie sicherstellen, dass der Generator UTF‑8‑Kodierung verwendet. Aspose.BarCode erkennt Unicode automatisch, Sie können jedoch die Textkodierung explizit setzen, falls Probleme auftreten: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Das Hinzufügen dieser Zeile vor `ConfigureGenerator` stellt sicher, dass **barcode with special characters** auf jeder Plattform korrekt dargestellt wird. + +### Praktischer Hinweis +Wenn die Ausgabe verzerrt aussieht, prüfen Sie, ob die vom Barcode‑Renderer verwendete Schriftart die erforderlichen Glyphen unterstützt. Sie können eine benutzerdefinierte TrueType‑Schriftart einbetten über: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Barcode‑Kodierungstypen, die Sie wählen können + +Aspose.BarCode unterstützt Dutzende von **barcode encode types**, die jeweils für unterschiedliche Anwendungsfälle geeignet sind: + +| Encode type | Typischer Anwendungsfall | +|----------------------------|----------------------------------------------| +| `EncodeTypes.Code128` | Versandetiketten, Inventur | +| `EncodeTypes.QR` | Mobile Zahlungen, URLs | +| `EncodeTypes.Pdf417` | Führerscheine, Bordkarten | +| `EncodeTypes.MicroPdf417` | Kleine Datenmengen, begrenzter Platz | +| `EncodeTypes.DataMatrix` | Winzige Objekte, hohe Datendichte | + +Den Kodierungstyp zu ändern ist so einfach wie das Austauschen des Enum‑Werts im Konstruktor: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Diese Flexibilität ermöglicht es Ihnen, Fragen zu **barcode encode types** zu beantworten, ohne die IDE zu verlassen. + +## PDF417‑Barcode in C# erstellen – letzte Schritte und Verifizierung + +Nach der Konfiguration des Generators ist der letzte Teil von **create pdf417 barcode c#** das Speichern des Bildes und die Bestätigung des Ergebnisses. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Führen Sie das Programm (`dotnet run`) aus und Sie sollten eine Konsolennachricht ähnlich der folgenden sehen: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Öffnen Sie die PNG‑Datei; Sie sehen einen scharfen MicroPdf417‑Barcode, der die Zeichenkette „Åspóse.Barcóde©“ codiert. Das Scannen mit einem mobilen Barcode‑Scanner (z. B. ZXing) liefert den Originaltext zurück und beweist, dass **Barcode aus Text generieren** auch mit Sonderzeichen funktioniert. + +### Sonderfall: sehr langer Text + +MicroPdf417 hat eine maximale Datenkapazität von 1 KB. Wenn Ihre Eingabe dieses Limit überschreitet, wirft die Bibliothek eine `ArgumentException`. Um dies elegant zu handhaben: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Für größere Datenmengen wechseln Sie zu `EncodeTypes.Pdf417` oder `EncodeTypes.DataMatrix`. + +## Häufige Fallstricke und wie man sie vermeidet + +| Problem | Ursache | Lösung | +|-------------------------------------|-----------------------------------------|--------| +| Barcode erscheint unscharf | XDimension zu niedrig (z. B. 1 px) | `XDimension.Pixels` auf 2‑3 px erhöhen | +| Unicode‑Zeichen werden zu `?` | Standard‑Textkodierung ist ASCII | `TextEncoding = Encoding.UTF8` setzen | +| Bilddatei wurde nicht erstellt | Ausgabeverzeichnis existiert nicht | `Directory.CreateDirectory` vor `Save` verwenden | +| Scanner kann den Barcode nicht lesen| Zu viele Spalten für kurze Daten | `Pdf417.Columns` reduzieren (z. B. 3‑4) | + +## Vollständiger Quellcode (bereit zum Kopieren) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Erwartete Ausgabe:** eine Datei namens `MicroPdf417.png` im Ordner `output`, die einen klaren MicroPdf417‑Barcode enthält, der die ursprüngliche Zeichenkette mit Sonderzeichen codiert. + +## Fazit + +Sie wissen jetzt, wie man **Barcode aus Text generieren** in C# mit Aspose.BarCode, wie man **barcode with special characters** handhabt und wie man **create pdf417 barcode c#** mit voller Kontrolle über die Kodierungsoptionen erstellt. Durch Anpassen der **barcode encode types** können Sie QR‑Codes, Code128, DataMatrix oder jedes andere unterstützte Format erzeugen. + +Als Nächstes erkunden Sie die folgenden Themen, um Ihr Barcode‑Wissen zu vertiefen: + +- **Wie man Barcodes** stapelweise für tausende Datensätze generiert (verwenden Sie `Parallel.ForEach` für Geschwindigkeit) +- Anpassen von Farben und Hinzufügen von Logos im Barcode +- Integration der Barcode‑Erstellung in ASP.NET Core APIs für die sofortige Bildauslieferung +- Verwendung anderer Bibliotheken wie ZXing.Net oder IronBarcode für Open‑Source‑Alternativen + +Fühlen Sie sich frei, mit verschiedenen Dimensionen, Spalteneinstellungen und Kodierungstypen zu experimentieren. Viel Spaß beim Programmieren und möge Ihre Anwendung fehlerfrei scannen! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Wie man Barcode erstellt – Kompakter PDF417 mit Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Wie man Barcode generiert – Code‑39‑Konfiguration mit Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Wie man Barcode generiert – Ein‑dimensionaler Barcode‑Typen](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/german/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/german/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..1e1ee90fa --- /dev/null +++ b/barcode/german/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,229 @@ +--- +category: general +date: 2026-08-09 +description: Erzeugen Sie schnell einen PDF417-Barcode in C#. Erfahren Sie, wie Sie + PDF417 mit kompaktem Modus, Spaltensteuerung und PNG-Ausgabe mithilfe der BarcodeGenerator-API + generieren. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: de +lastmod: 2026-08-09 +og_description: Erzeugen Sie einen PDF417-Barcode in C# mit einem kurzen Beispiel. + Dieser Leitfaden zeigt Ihnen, wie Sie den kompakten Modus konfigurieren, Spalten + festlegen und das Ergebnis als PNG‑Bild speichern. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: PDF417-Barcode in C# generieren – vollständiges Tutorial +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: PDF417-Barcode in C# generieren – Schritt‑für‑Schritt‑Anleitung +url: /de/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF417‑Barcode in C# generieren – Schritt‑für‑Schritt‑Anleitung + +Wenn Sie **PDF417‑Barcode** in einer .NET‑Anwendung **generieren** müssen, zeigt Ihnen dieses Tutorial genau, wie es geht. Sie sehen ein vollständiges, ausführbares Programm, das einen kompakten PDF417‑Barcode erstellt, seine Größe anpasst und das Bild als PNG‑Datei speichert. + +Das Generieren eines PDF417‑Barcodes ist eine häufige Anforderung für mobiles Ticketing, Bestandsverfolgung und Dokumentensicherheit. Dieser Leitfaden behandelt die wesentlichen Konfigurationsoptionen, erklärt, warum jede Einstellung wichtig ist, und gibt praktische Tipps für den Einsatz in der Praxis. + +## Voraussetzungen + +Bevor Sie beginnen, stellen Sie sicher, dass Sie Folgendes haben: + +* .NET 6.0 SDK oder neuer installiert +* Eine C#‑IDE wie Visual Studio 2022 oder Visual Studio Code +* Das **Aspose.BarCode for .NET** NuGet‑Paket (Version 23.10 oder neuer) + +Sie können das Paket mit dem folgenden CLI‑Befehl installieren: + +```bash +dotnet add package Aspose.BarCode +``` + +Der nachfolgende Code geht davon aus, dass das Paket referenziert ist und Sie Schreibrechte für das Ausgabeverzeichnis besitzen. + +## Schritt 1: Projekt einrichten und Namespaces importieren + +Erstellen Sie ein neues Konsolenprojekt und fügen Sie die erforderlichen `using`‑Direktiven hinzu. Diese Namespaces stellen die Klasse `BarcodeGenerator` und die Aufzählung für das Bildformat bereit. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Warum das wichtig ist:** Das Importieren der richtigen Namespaces stellt sicher, dass der Compiler den Typ `BarcodeGenerator` und die Aufzählung `BarCodeImageFormat` finden kann. Fehlt ein Namespace, entsteht ein Kompilierungsfehler, der den Barcode‑Generierungsprozess stoppt. + +## Schritt 2: `BarcodeGenerator` mit PDF417‑Kodierung initialisieren + +Der Konstruktor von `BarcodeGenerator` erhält zwei Argumente: die Barcode‑Symbologie (`EncodeTypes.Pdf417`) und den zu kodierenden Text. PDF417 unterstützt ein breites Spektrum an Zeichen, einschließlich Unicode‑Symbole. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Erläuterung:** +* `EncodeTypes.Pdf417` weist die Bibliothek an, den PDF417‑Standard zu verwenden. +* Der Beispieltext enthält Akzentzeichen und ein Copyright‑Symbol, um die Unicode‑Verarbeitung zu demonstrieren. + +Wenn Sie nur numerische Daten kodieren möchten, können Sie einen einfachen String wie `"1234567890"` übergeben. + +## Schritt 3: X‑Dimension für höhere Auflösung anpassen + +Die X‑Dimension steuert die Breite eines einzelnen Barcode‑Moduls (das kleinste schwarze oder weiße Element). Ein kleinerer Pixelwert liefert ein Bild mit höherer Auflösung. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Warum anpassen?** Eine Standard‑X‑Dimension von 3–4 Pixeln kann auf hochauflösenden Bildschirmen grob wirken. Durch Reduzierung auf **2 Pixel** wird die Lesbarkeit bei gleichzeitig kleinerer Dateigröße verbessert, besonders wenn Sie anschließend den kompakten Modus aktivieren. + +## Schritt 4: Anzahl der Spalten konfigurieren + +PDF417 erlaubt die Angabe, wie viele Spalten der Barcode enthalten soll. Weniger Spalten machen den Barcode schmaler, aber höher, während mehr Spalten zu einem breiteren, kürzeren Barcode führen. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Praktischer Tipp:** Für mobile Tickets, die in ein schmales Etikett passen müssen, funktioniert eine Spaltenzahl von **3–5** gut. Erhöhen Sie die Zahl, wenn Sie viele Daten haben und einen kürzeren Barcode wünschen. + +## Schritt 5: Kompaktmodus aktivieren, um leere Zeilen zu entfernen + +Der Kompaktmodus entfernt unnötige Zeilen aus der Barcode‑Matrix und reduziert so die Gesamtabmessungen, ohne kodierte Daten zu verlieren. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Wann verwenden?** Wenn Sie Barcodes zur Speicherung oder Netzwerkübertragung erzeugen, kann der Kompaktmodus die PNG‑Datei um bis zu 30 % verkleinern. Einige ältere Scanner unterstützen jedoch gekürzte PDF417‑Barcodes nicht; testen Sie daher mit Ihrer Zielhardware. + +## Schritt 6: Barcode als PNG‑Bild speichern + +Wählen Sie einen Ausgabepfad und rufen Sie `Save` auf. Die Aufzählung `BarCodeImageFormat.Png` erzeugt ein verlustfreies Bild, das für die meisten Anwendungen geeignet ist. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Ergebnis‑Verifizierung:** Öffnen Sie die PNG‑Datei in einem Bildbetrachter. Sie sollten einen dichten, hochkontrastierten Barcode sehen, der dem Beispieltext entspricht. Das Scannen des Bildes mit einem PDF417‑Reader (z. B. ZXing oder einer Smartphone‑App) liefert den ursprünglichen String `"Åspóse.Barcóde©"`. + +![Generiertes PDF417-Barcode-Bild, gespeichert als PNG](compact-pdf417.png "Generierter PDF417-Barcode in C#") + +*Das obige Bild zeigt das Endergebnis des Tutorial‑Codes.* + +## Vollständiges, ausführbares Beispiel + +Alle Teile zusammengefügt ergibt das folgende Konsolenprogramm, das Sie kopieren, einfügen und ausführen können. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Erwartete Ausgabe + +Beim Ausführen des Programms wird Folgendes ausgegeben: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +Die Datei `CompactPdf417.png` enthält einen kompakten PDF417‑Barcode, der den bereitgestellten Unicode‑String kodiert. Das Scannen des Bildes mit einem Standard‑PDF417‑Reader liefert exakt den Text. + +## Häufige Varianten und Sonderfälle + +| Situation | Anpassung | Grund | +|-----------|------------|--------| +| **Längere Datenmenge** (z. B. > 150 Zeichen) | `generator.Parameters.Barcode.Pdf417.Columns` auf 6‑8 erhöhen | Mehr Spalten verhindern, dass der Barcode zu hoch wird. | +| **Transparenter Hintergrund erforderlich** | `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` verwenden | Transparente PNGs lassen sich besser in UI‑Overlays einbinden. | +| **JPEG für das Web erzeugen** | Format zu `BarCodeImageFormat.Jpeg` ändern und optional `ImageQuality` setzen | JPEG reduziert die Dateigröße, kostet jedoch verlustfreie Genauigkeit. | +| **Null‑ oder leere Eingabe** | Eingabe vor Generator‑Erstellung prüfen: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Verhindert Laufzeit‑Exceptions und sorgt für sinnvolle Barcodes. | + +## Tipps für den Produktionseinsatz + +* **Fehlerbehandlung:** Umschließen Sie die Generierungslogik mit einem `try/catch`‑Block, um Fehler wie zu wenig Speicherplatz oder ungültige Parameter zu protokollieren. +* **Performance:** Verwenden Sie eine einzige `BarcodeGenerator`‑Instanz, wenn Sie viele Barcodes mit denselben Einstellungen erzeugen; aktualisieren Sie nur die Eigenschaft `CodeText` zwischen den Saves. +* **Sicherheit:** Enthält der zu kodierende Text sensible Informationen, sollten Sie ihn vor dem Übergeben an den Generator verschlüsseln und nach dem Scannen wieder entschlüsseln. + +## Fazit + +Sie wissen jetzt, wie Sie **PDF417‑Barcode** in C# mit der Aspose.BarCode‑Bibliothek generieren, den Kompaktmodus konfigurieren, die Spaltenanzahl steuern und das Ergebnis als PNG‑Bild exportieren. Dieses Tutorial hat jeden Schritt von der Projekt‑Einrichtung bis zur Behandlung von Sonderfällen abgedeckt und liefert Ihnen eine sofort einsetzbare Lösung für barcode‑basierte Anwendungen. + +Als Nächstes können Sie verwandte Themen erkunden, etwa **QR‑Codes in C# erstellen**, **Batch‑Barcode‑Generierung** und **Barcode‑Scanning in mobilen Apps integrieren**. All diese bauen auf denselben `BarcodeGenerator`‑Grundlagen auf, die Sie gerade gemeistert haben. + +Viel Spaß beim Coden! + + +## Was sollten Sie als Nächstes lernen? + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, damit Sie weitere API‑Funktionen beherrschen und alternative Implementierungsansätze in Ihren Projekten erkunden können. + +- [How to Generate PDF417 Barcodes – Compact PDF417 Encoding](/barcode/english/net/compact-pdf417-encoding/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/german/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/german/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..49828fbf2 --- /dev/null +++ b/barcode/german/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-09 +description: Wie man PDF417 in C# mit dem BarCodeReader liest. Lernen Sie, Barcode‑PNG‑Dateien + zu lesen, mehrere Barcodes zu verarbeiten und erweiterte Metadaten zu extrahieren. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: de +lastmod: 2026-08-09 +og_description: Wie man PDF417 in C# mit Aspose.BarCode liest. Dieses Tutorial zeigt, + wie man Barcode‑PNG‑Dateien liest, mehrere Barcodes in einem Bild verarbeitet und + erweiterte PDF417‑Metadaten abruft. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Wie man PDF417 in C# liest – Barcode‑Reader‑Tutorial +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Wie man PDF417 in C# liest – vollständiger Barcode‑Reader‑Leitfaden +url: /de/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man PDF417 in C# liest – vollständiger Barcode‑Reader‑Leitfaden + +Wenn Sie **PDF417 lesen** in einer .NET‑Anwendung benötigen, bietet Ihnen dieser Leitfaden eine sofort einsatzbereite Lösung. Sie sehen, wie man ein Barcode‑PNG liest, mehrere Barcodes im selben Bild verarbeitet und die erweiterten PDF417‑Felder extrahiert, die viele Scanner verbergen. + +Das Lesen von PDF417‑Barcodes ist in Logistik, Ticketing und Dokumentenmanagement üblich. Am Ende dieses Tutorials können Sie ein Macro PDF417‑Bild dekodieren, jedes Ergebnis anzeigen und die zusätzlichen Informationen (Datei‑ID, Segment‑Anzahl, Zeitstempel usw.) in Ihrer eigenen Geschäftslogik verwenden. + +## Voraussetzungen + +- .NET 6.0 oder höher (der Code funktioniert auch mit .NET Framework 4.7+) +- Visual Studio 2022 oder jede C#‑IDE +- **Aspose.BarCode for .NET** (Kostenlose Testversion oder lizenziertes NuGet‑Paket) +- Eine PNG‑Datei, die einen Macro PDF417‑Barcode enthält (die Beispieldatei heißt `ExtPDF417Meta.png`) + +> **Pro‑Tipp:** Installieren Sie die Bibliothek über die NuGet‑Konsole: +> `dotnet add package Aspose.BarCode` + +## PDF417 mit BarCodeReader in C# lesen + +Der Kern der Lösung ist die Klasse `BarCodeReader`. Sie akzeptiert einen Bildpfad und ein `DecodeType`‑Enum, das der Engine mitteilt, nach welcher Symbolik gesucht werden soll. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Warum das funktioniert + +- **`DecodeType.MacroPdf417`** weist den Reader an, nach der Macro PDF417‑Variante zu suchen, die die zusätzlichen Felder aus Schritt 4 speichert. +- Der `using`‑Block gibt den Reader automatisch frei und schließt Dateihandles. +- `ReadBarCodes()` liefert **alle** Barcodes, die dem angeforderten Typ entsprechen, was die Anforderung *mehrere Barcodes lesen* erfüllt, selbst wenn das Bild nur einen enthält. + +Das Ausführen des Programms gibt eine Ausgabe ähnlich der folgenden aus: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## C# Barcode‑Reader zum Lesen mehrerer Barcodes verwenden + +Enthält ein Bild mehrere Macro PDF417‑Symbole (z. B. eine gescannte Seite mit einer Charge von Tickets), verarbeitet die gleiche `foreach`‑Schleife jedes einzelne. Kein zusätzlicher Code ist nötig; der Reader aggregiert die Ergebnisse intern. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Häufige Fallstricke + +- **Bildformat:** Der Reader unterstützt PNG, JPEG, BMP und TIFF. Wenn Sie ein Format verwenden, das er nicht dekodieren kann, erhalten Sie eine leere Sammlung. Deshalb betont das Tutorial *Barcode‑PNG lesen*. +- **Auflösung:** Bilder mit niedriger Auflösung (< 300 dpi) können fehlende Segmente verursachen. Skalieren Sie hoch oder fordern Sie einen Scan höherer Qualität an, wenn möglich. +- **Macro‑Flag:** Das Vergessen von `DecodeType.MacroPdf417` beschränkt die Engine auf einfachen PDF417 und verwirft die erweiterten Daten. Geben Sie immer den Macro‑Typ an, wenn Sie *erweiterte Barcode‑Felder lesen* benötigen. + +## Lesen von Barcode‑PNG‑Dateien – bewährte Verfahren + +Die Arbeit mit PNG‑Dateien ist unkompliziert, weil das Format verlustfreie Pixeldaten bewahrt. Hier ist eine kurze Checkliste: + +1. Verifizieren Sie, dass die Datei existiert, bevor Sie den Reader erstellen. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Verwenden Sie `Image.FromFile` nur, wenn Sie Vorverarbeitung benötigen (drehen, zuschneiden). Der `BarCodeReader` kann die Datei direkt öffnen, was zusätzlichen Speicherverbrauch vermeidet. +3. Enthält das PNG Transparenz, funktioniert der Reader weiterhin, da der Barcode auf undurchsichtigen Pixeln gerendert wird. + +## Zugriff auf erweiterte PDF417‑Metadaten + +Das Objekt `Extended.Pdf417` stellt jedes optionale Feld bereit, das in der PDF417‑Spezifikation definiert ist. Sie können diese Felder einem Domänenmodell zuordnen, in einer Datenbank speichern oder für Validierungen nutzen. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Füllen Sie das Modell aus: + + + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Wie man DataMatrix‑Barcodes mit Aspose.BarCode for .NET liest](/barcode/english/net/datamatrix-barcode-reading/) +- [Wie man Barcode – Compact PDF417 mit Aspose.BarCode erstellt](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [DataMatrix‑Barcode C# lesen – DataMatrix‑Modus (Auto) generieren](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/greek/net/compact-pdf417-encoding/_index.md b/barcode/greek/net/compact-pdf417-encoding/_index.md index 06b8d9294..714920e16 100644 --- a/barcode/greek/net/compact-pdf417-encoding/_index.md +++ b/barcode/greek/net/compact-pdf417-encoding/_index.md @@ -46,7 +46,7 @@ weight: 29 - **Λειτουργία Συμπαγούς:** Αφαιρεί περιττές προσθήκες, δημιουργώντας έναν μικρότερο κώδικα χωρίς να θυσιάζει την αναγνωσιμότητα. ### Επιλογές Διόρθωσης Σφαλμάτων PDF417 -Το Aspose.BarCode σας επιτρέπει να ορίσετε την ιδιότητα `Pdf417ErrorCorrectionLevel` (0‑8). Τα υψηλότερα επίπεδα αυξάνουν τον πλεονασμό, κάτι χρήσιμο σε σκληρά περιβάλλοντα όπως η βιομηχανική σάρωση. Επιλέξτε επίπεδο βάσει της ανοχή σας στον κίνδυνο και των περιορισμών χώρου. +Το Aspose.BarCode σας επιτρέπει να ορίσετε την ιδιότητα `Pdf417ErrorCorrectionLevel` (0‑8). Τα υψηλότερα επίπεδα αυξάνουν τον πλεονασμό, κάτι χρήσιμο σε σκληρά περιβάλλοντα όπως η βιομηχανική σάρωση. Επιλέξτε επίπεδο βάσει της ανοχής σας στον κίνδυνο και των περιορισμών χώρου. ## Δημιουργία Συμπαγών PDF417 Κωδικών με το Aspose.BarCode for .NET @@ -76,7 +76,7 @@ weight: 29 - **Οπτική Επωνυμία:** Εφαρμόστε προσαρμοσμένα χρώματα ή ενσωματώστε λογότυπο μέσω του API `Image` για να ταιριάζει με την εταιρική ταυτότητα. - **Δοκιμές:** Επικυρώστε τους δημιουργημένους κώδικες με φυσικό σαρωτή ή εφαρμογή κινητού πριν την υλοποίηση. -## Καλές Πρακτικές για τη Δημιουργία PDF417 Κωδικών +## Καλές Πρακτικές για τη Δημιουργία PDF417 Κωδίκων - **Επικύρωση Μήκους Εισόδου:** Βεβαιωθείτε ότι τα δεδομένα δεν υπερβαίνουν τη μέγιστη χωρητικότητα για το επιλεγμένο επίπεδο διόρθωσης. - **Διαχείριση Εξαιρέσεων:** Περιβάλλετε τον κώδικα δημιουργίας σε μπλοκ try‑catch για να συλλάβετε σφάλματα άδειας ή μορφοποίησης. @@ -86,6 +86,18 @@ weight: 29 ### [Δημιουργία Συμπαγών PDF417 Κωδικών](./compact-pdf417-basic-configuration/) Μάθετε πώς να δημιουργείτε Συμπαγείς PDF417 κωδικούς χρησιμοποιώντας το Aspose.BarCode for .NET. Αναλυτικός οδηγός με βήμα‑βήμα οδηγίες και παραδείγματα κώδικα. +### [Παράδειγμα Aspose barcode: δημιουργία Macro PDF417 σε C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Παράδειγμα κώδικα C# για δημιουργία Macro PDF417 χρησιμοποιώντας το Aspose.BarCode. + +### [Δημιουργία κώδικα PDF417 σε C# – βήμα‑βήμα οδηγός](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Οδηγός βήμα‑βήμα για τη δημιουργία κώδικα PDF417 σε C# με Aspose.BarCode. + +### [Δημιουργία barcode από κείμενο σε C# – πλήρης βήμα‑βήμα οδηγός](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Οδηγός βήμα‑βήμα για τη δημιουργία barcode από κείμενο σε C# χρησιμοποιώντας Aspose.BarCode. + +### [Πώς να διαβάσετε PDF417 σε C# – πλήρης οδηγός ανάγνωσης barcode](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +Οδηγός βήμα‑βήμα για την ανάγνωση κωδίκων PDF417 σε C# με το Aspose.BarCode. + ## Συχνές Ερωτήσεις **Ε: Ποιο είναι το μέγιστο ποσό δεδομένων που μπορώ να αποθηκεύσω σε έναν Συμπαγή PDF417 κώδικα;** @@ -98,7 +110,7 @@ weight: 29 Α: Ναι. Το Aspose.BarCode for .NET υποστηρίζει πλήρως το .NET Core 3.1 και μεταγενέστερες εκδόσεις. **Ε: Είναι δυνατόν να προσαρμόσω τα χρώματα προσκηνίου και φόντου του κώδικα;** -Α: Απολύτως. Χρησιμοποιήστε τις ιδιότητες `ForeColor` και `BackColor` του γεννήτρια για να ταιριάξετε το θέμα της διεπαφής σας. +Α: Απόλυτα. Χρησιμοποιήστε τις ιδιότητες `ForeColor` και `BackColor` του γεννήτρια για να ταιριάξετε το θέμα της διεπαφής σας. **Ε: Πρέπει να εγκαταστήσω επιπλέον γραμματοσειρές ή πόρους;** Α: Δεν απαιτούνται εξωτερικές γραμματοσειρές· η βιβλιοθήκη διαχειρίζεται όλη την απόδοση εσωτερικά. @@ -114,4 +126,4 @@ weight: 29 {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/greek/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/greek/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..635bf7b2b --- /dev/null +++ b/barcode/greek/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-08-09 +description: Παράδειγμα barcode της Aspose που δείχνει πώς να χρησιμοποιήσετε έναν + δημιουργό barcode σε C# για τη δημιουργία ενός Macro PDF417 με πλήρη υποστήριξη + μεταδεδομένων. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: el +lastmod: 2026-08-09 +og_description: Το παράδειγμα barcode της Aspose δείχνει τη χρήση ενός γεννήτριας + barcode C# για την παραγωγή ενός Macro PDF417 barcode που περιλαμβάνει το αναγνωριστικό + αρχείου, τα δεδομένα τμήματος, την χρονική σήμανση και άλλα μεταδεδομένα. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Παράδειγμα barcode Aspose – δημιουργία Macro PDF417 με C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Παράδειγμα barcode Aspose: δημιουργία Macro PDF417 σε C#' +url: /el/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Παράδειγμα Aspose barcode: δημιουργία Macro PDF417 σε C# + +Αν χρειάζεστε ένα **aspose barcode example** που δημιουργεί έναν κωδικό Macro PDF417, αυτός ο οδηγός σας δείχνει πώς να το κάνετε με έναν **barcode generator C#**. Θα δείτε όλες τις απαιτούμενες ρυθμίσεις, από τις βασικές διαστάσεις μέχρι το πλήρες σύνολο των πεδίων μεταδεδομένων Macro PDF417, και θα καταλήξετε με μια εικόνα PNG έτοιμη για επεξεργασία downstream. + +Το tutorial καλύπτει τη πλήρη ροή εργασίας, εξηγεί γιατί κάθε παράμετρος είναι σημαντική και παρέχει ένα έτοιμο‑για‑εκτέλεση δείγμα κώδικα. Δεν απαιτούνται εξωτερικές αναφορές· μπορείτε να αντιγράψετε τον κώδικα, να προσαρμόσετε τις τιμές και να τον εκτελέσετε αμέσως. + +## Προαπαιτούμενα + +Πριν ξεκινήσετε, βεβαιωθείτε ότι έχετε: + +- .NET 6.0 (ή νεότερο) εγκατεστημένο +- Visual Studio 2022 ή οποιοδήποτε IDE συμβατό με C# +- Ένα έγκυρο license για **Aspose.BarCode for .NET** (η δωρεάν δοκιμή λειτουργεί για αυτό το παράδειγμα) + +Προσθέστε το πακέτο NuGet Aspose.BarCode στο project σας: + +```bash +dotnet add package Aspose.BarCode +``` + +## Βήμα 1: Δημιουργία του αντικειμένου barcode generator C# + +Το πρώτο βήμα είναι η δημιουργία ενός αντικειμένου `BarcodeGenerator` με την τιμή του enum `EncodeTypes.MacroPdf417` και το κείμενο που θέλετε να κωδικοποιήσετε. Το κείμενο μπορεί να περιέχει χαρακτήρες Unicode, τους οποίους η βιβλιοθήκη διαχειρίζεται αυτόματα. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Γιατί είναι σημαντικό*: Το `EncodeTypes.MacroPdf417` λέει στη μηχανή να παραγάγει ένα σύμβολο Macro PDF417, το οποίο υποστηρίζει τμηματικά δεδομένα και πρόσθετα μεταδεδομένα επιπέδου αρχείου. Η δήλωση `using` εγγυάται ότι οι μη διαχειριζόμενοι πόροι απελευθερώνονται μετά την αποθήκευση της εικόνας. + +## Βήμα 2: Ορισμός βασικής εμφάνισης του barcode + +Ένας κωδικός Macro PDF417 αποτελείται από τετράγωνα modules. Ο έλεγχος του μεγέθους του module και του αριθμού των στηλών επηρεάζει τόσο την αναγνωσιμότητα όσο και το μέγεθος του αρχείου. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Γιατί είναι σημαντικό*: Το `XDimension.Pixels` καθορίζει την οπτική πυκνότητα· μια τιμή 2 pixels λειτουργεί καλά για προβολή στην οθόνη ενώ διατηρεί την εικόνα μικρή. Προσαρμόστε τον αριθμό στηλών ώστε να ταιριάζει με τους περιορισμούς του layout σας—περισσότερες στήλες δημιουργούν έναν πιο πλατύ, πιο σύντομο barcode. + +## Βήμα 3: Ορισμός μεταδεδομένων ειδικών για Macro PDF417 + +Το Macro PDF417 επεκτείνει το τυπικό φορμά PDF417 με πεδία που επιτρέπουν την ανασύνθεση μεγάλων αρχείων από πολλαπλά τμήματα barcode. Κάθε πεδίο είναι προαιρετικό, αλλά η ρύθμιση τους δείχνει τις πλήρεις δυνατότητες του API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Γιατί είναι σημαντικό*: +- `MacroPdf417FileID` συνδέει όλα τα τμήματα που ανήκουν στο ίδιο λογικό αρχείο. +- `MacroPdf417SegmentID` και `MacroPdf417SegmentsCount` επιτρέπουν στον αποκωδικοποιητή να επανατάξει σωστά τα τμήματα. +- `MacroPdf417Checksum` παρέχει έναν γρήγορο έλεγχο ακεραιότητας χωρίς την ανάγκη αποκωδικοποίησης ολόκληρου του payload. +- `MacroPdf417FileSize` και `MacroPdf417TimeStamp` επιτρέπουν στα downstream συστήματα να επαληθεύσουν ότι το ανασυγκροτημένο αρχείο ταιριάζει με το αρχικό. +- `MacroPdf417Addressee` / `MacroPdf417Sender` είναι χρήσιμα σε σενάρια λογιστικής ή ανταλλαγής εγγράφων. +- Ορίζοντας το `MacroPdf417Terminator` σε `Set` σηματοδοτεί αυτό το barcode ως το τελικό τμήμα, κάτι που απλοποιεί τον αλγόριθμο ανασύνθεσης. + +## Βήμα 4: Αποθήκευση της παραγόμενης εικόνας barcode + +Τέλος, γράψτε τον barcode σε αρχείο PNG. Μπορείτε να επιλέξετε οποιαδήποτε υποστηριζόμενη μορφή (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Γιατί είναι σημαντικό*: Το PNG διατηρεί τα pixel δεδομένα χωρίς απώλειες, εξασφαλίζοντας ότι οι σαρωτές διαβάζουν ακριβώς το μοτίβο modules που διαμορφώσατε. Η αλλαγή μορφής μπορεί να επηρεάσει την οπτική ποιότητα και το μέγεθος του αρχείου. + +### Αναμενόμενο αποτέλεσμα + +Η εκτέλεση του πλήρους προγράμματος δημιουργεί ένα αρχείο με όνομα **ExtPDF417Meta.png**. Το άνοιγμα της εικόνας εμφανίζει έναν ορθογώνιο Macro PDF417 barcode με το κείμενο “Åspóse.Barcóde©” κωδικοποιημένο, και η οπτική πυκνότητα ταιριάζει με τη διάσταση X 2 pixel που ορίσατε. Η σάρωση της εικόνας με έναν PDF417‑συμβατό αναγνώστη επιστρέφει όλα τα πεδία μεταδεδομένων που ορίστηκαν στο Βήμα 3. + +## Πλήρες λειτουργικό παράδειγμα + +Αντιγράψτε τον κώδικα παρακάτω σε ένα νέο console project (`dotnet new console`) και αντικαταστήστε το `YOUR_DIRECTORY` με μια απόλυτη ή σχετική διαδρομή που υπάρχει στο σύστημά σας. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Εκτελέστε το πρόγραμμα (`dotnet run`). Μετά την εκτέλεση, ελέγξτε ότι το αρχείο PNG εμφανίζεται στην τοποθεσία που καθορίσατε. Χρησιμοποιήστε οποιαδήποτε εφαρμογή ανάγνωσης barcode που υποστηρίζει Macro PDF417 για να επιβεβαιώσετε ότι τα μεταδεδομένα έχουν ενσωματωθεί σωστά. + +## Συνηθισμένες παραλλαγές και περιπτώσεις άκρων + +- **Διαφορετικές μορφές εικόνας**: Αντικαταστήστε το `BarCodeImageFormat.Png` με `Jpeg`, `Bmp` ή `Tiff` εάν το downstream σύστημά σας προτιμά άλλη μορφή. +- **Αλλαγή μεγέθους module**: Μεγαλύτερες τιμές `XDimension.Pixels` βελτιώνουν την αξιοπιστία σάρωσης σε σαρωτές χαμηλής ανάλυσης, αλλά αυξάνουν το μέγεθος της εικόνας. +- **Πολλαπλά τμήματα**: Για παραγωγή αρχείου πολλαπλών τμημάτων, δημιουργήστε μια σειρά barcode, αυξήστε το `MacroPdf417SegmentID` για κάθε ένα και κρατήστε σταθερό το `MacroPdf417FileID`. Μόνο το τελευταίο τμήμα πρέπει να έχει το `MacroPdf417Terminator` ορισμένο. +- **Υποστήριξη Unicode**: Ο γεννήτορας κωδικοποιεί αυτόματα χαρακτήρες Unicode· βεβαιωθείτε ότι η πηγή string χρησιμοποιεί κωδικοποίηση UTF‑8 εάν το διαβάζετε από εξωτερικό αρχείο. +- **Διαχείριση σφαλμάτων**: Τυλίξτε το block `using` σε try‑catch για να συλλάβετε `BarCodeException` σε περίπτωση μη έγκυρων παραμέτρων (π.χ., αριθμός στηλών εκτός εύρους). + +## Pro tips + +- **Performance**: Επαναχρησιμοποιήστε ένα μόνο αντικείμενο `BarcodeGenerator` όταν δημιουργείτε πολλούς barcode με τις ίδιες ρυθμίσεις· αλλάξτε μόνο την ιδιότητα `CodeText` μεταξύ των αποθηκεύσεων. +- **Εκτίμηση μεγέθους αρχείου**: Το πεδίο `MacroPdf417FileSize` πρέπει να ταιριάζει με τον αριθμό byte του αρχικού payload· ασυμφωνίες μπορεί να προκαλέσουν αποτυχίες επικύρωσης downstream. +- **Testing**: Επικυρώστε τους παραγόμενους barcode τόσο με τον ενσωματωμένο αποκωδικοποιητή της Aspose (`BarCodeReader`) όσο και με τρίτο scanner για να διασφαλίσετε διαλειτουργικότητα. + +## Συμπέρασμα + +Αυτό το **aspose barcode example + + +## Τι πρέπει να μάθετε στη συνέχεια; + + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κυριαρχήσετε πρόσθετες δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to create barcode quiet zone for Code 16K using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/greek/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/greek/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..7ab8ed812 --- /dev/null +++ b/barcode/greek/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-08-09 +description: Δημιουργήστε barcode από κείμενο σε C# με το Aspose.BarCode. Μάθετε πώς + να δημιουργείτε barcode, να διαχειρίζεστε ειδικούς χαρακτήρες και να δημιουργείτε + γρήγορα barcode PDF417 σε C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: el +lastmod: 2026-08-09 +og_description: Δημιουργήστε κωδικό γραμμής από κείμενο σε C# χρησιμοποιώντας το Aspose.BarCode. + Αυτό το σεμινάριο δείχνει πώς να δημιουργήσετε κωδικό γραμμής, να υποστηρίξετε ειδικούς + χαρακτήρες και να δημιουργήσετε κωδικό PDF417 σε C# με πλήρη κώδικα. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Δημιουργία barcode από κείμενο σε C# – γρήγορος οδηγός βήμα‑βήμα +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Δημιουργία γραμμωτού κώδικα από κείμενο σε C# – πλήρης οδηγός βήμα‑βήμα +url: /el/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία barcode από κείμενο σε C# – πλήρης οδηγός βήμα‑βήμα + +Αν χρειάζεστε **generate barcode from text** σε μια εφαρμογή .NET, αυτός ο οδηγός σας καθοδηγεί μέσα από όλη τη διαδικασία. Θα δείτε πώς να δημιουργήσετε barcode, να διαχειριστείτε ειδικούς χαρακτήρες και να δημιουργήσετε μια υλοποίηση PDF417 barcode σε C# που λειτουργεί αμέσως. + +Η δημιουργία barcode από κείμενο είναι μια συνηθισμένη απαίτηση για συστήματα αποθεμάτων, πλατφόρμες έκδοσης εισιτηρίων και ροές εργασίας εγγράφων. Στο τέλος αυτού του tutorial θα έχετε μια εκτελέσιμη εφαρμογή κονσόλας C# που παράγει μια εικόνα PNG MicroPdf417 χρησιμοποιώντας το Aspose.BarCode. Δεν απαιτούνται εξωτερικές υπηρεσίες και ο κώδικας διαχειρίζεται χαρακτήρες Unicode όπως “Å”, “©”, και “é”. + +## Prerequisites + +- .NET 6.0 SDK ή νεότερο (ο κώδικας λειτουργεί επίσης με .NET Core 3.1 και .NET Framework 4.7+) +- Visual Studio 2022 (ή οποιοδήποτε IDE που υποστηρίζει C#) +- **Aspose.BarCode for .NET** πακέτο NuGet + ```bash + dotnet add package Aspose.BarCode + ``` +- Βασικές γνώσεις σύνταξης C# + +## Δημιουργία barcode από κείμενο – ρύθμιση του γεννήτριας + +Το πρώτο βήμα είναι να δημιουργήσετε μια παρουσία `BarcodeGenerator` που γνωρίζει ποιο **barcode encode type** θέλετε. Σε αυτό το tutorial χρησιμοποιούμε το `EncodeTypes.MicroPdf417`, που είναι μια συμπαγής παραλλαγή του PDF417 κατάλληλη για σύντομες αλφαριθμητικές συμβολοσειρές. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Γιατί αυτό λειτουργεί:** +- `EncodeTypes.MicroPdf417` λέει στη βιβλιοθήκη να χρησιμοποιήσει την οικογένεια PDF417, ικανοποιώντας την απαίτηση **create pdf417 barcode c#**. +- Ο κατασκευαστής λαμβάνει το ακατέργαστο κείμενο, που αποτελεί την ουσία του **generate barcode from text**. +- Η υποστήριξη Unicode είναι ενσωματωμένη, έτσι χαρακτήρες όπως “Å” και “©” κωδικοποιούνται σωστά, αντιμετωπίζοντας το **barcode with special characters**. + +## Πώς να δημιουργήσετε barcode με ειδικούς χαρακτήρες + +Όταν τα δεδομένα σας περιέχουν σύμβολα μη‑ASCII, πρέπει να διασφαλίσετε ότι η γεννήτρια χρησιμοποιεί κωδικοποίηση UTF‑8. Το Aspose.BarCode ανιχνεύει αυτόματα Unicode, αλλά μπορείτε ρητά να ορίσετε την κωδικοποίηση κειμένου αν αντιμετωπίσετε προβλήματα: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Η προσθήκη αυτής της γραμμής πριν από το `ConfigureGenerator` εγγυάται ότι το **barcode with special characters** αποδίδεται σωστά σε οποιαδήποτε πλατφόρμα. + +### Πρακτική συμβουλή +Αν το αποτέλεσμα φαίνεται χαραγμένο, ελέγξτε ότι η γραμματοσειρά που χρησιμοποιεί ο renderer του barcode υποστηρίζει τα απαιτούμενα γλυφά. Μπορείτε να ενσωματώσετε μια προσαρμοσμένη γραμματοσειρά TrueType μέσω: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Τύποι κωδικοποίησης barcode που μπορείτε να επιλέξετε + +Το Aspose.BarCode υποστηρίζει δεκάδες **barcode encode types**, καθένας κατάλληλος για διαφορετικές περιπτώσεις χρήσης: + +| Τύπος κωδικοποίησης | Τυπική περίπτωση χρήσης | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | Ετικέτες αποστολής, αποθέματα | +| `EncodeTypes.QR` | Κινητές πληρωμές, URLs | +| `EncodeTypes.Pdf417` | Άδειες οδήγησης, κάρτες επιβίβασης | +| `EncodeTypes.MicroPdf417` | Μικρά δεδομένα, περιορισμένος χώρος | +| `EncodeTypes.DataMatrix` | Μικροσκοπικά αντικείμενα, υψηλή πυκνότητα δεδομένων | + +Η αλλαγή του τύπου κωδικοποίησης είναι τόσο απλή όσο η αντικατάσταση της τιμής enum στον κατασκευαστή: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Αυτή η ευελιξία σας επιτρέπει να απαντήσετε σε ερωτήσεις σχετικά με **barcode encode types** χωρίς να φύγετε από το IDE. + +## Δημιουργία PDF417 barcode C# – τελικά βήματα και επαλήθευση + +Αφού διαμορφώσετε τη γεννήτρια, το τελευταίο μέρος του **create pdf417 barcode c#** είναι η αποθήκευση της εικόνας και η επιβεβαίωση του αποτελέσματος. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Εκτελέστε το πρόγραμμα (`dotnet run`) και θα πρέπει να δείτε ένα μήνυμα κονσόλας παρόμοιο με: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Ανοίξτε το αρχείο PNG· θα δείτε ένα καθαρό MicroPdf417 barcode που κωδικοποιεί τη συμβολοσειρά “Åspóse.Barcóde©”. Η σάρωση του με έναν κινητό scanner barcode (π.χ., ZXing) επιστρέφει το αρχικό κείμενο, αποδεικνύοντας ότι το **generate barcode from text** λειτουργεί ακόμη και με ειδικούς χαρακτήρες. + +### Ακραία περίπτωση: πολύ μακρύ κείμενο + +Το MicroPdf417 έχει μέγιστη χωρητικότητα δεδομένων 1 KB. Εάν η είσοδός σας υπερβαίνει αυτό το όριο, η βιβλιοθήκη ρίχνει `ArgumentException`. Για να το διαχειριστείτε ομαλά: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Για μεγαλύτερα payloads, μεταβείτε στο πλήρες `EncodeTypes.Pdf417` ή `EncodeTypes.DataMatrix`. + +## Συνηθισμένα προβλήματα και πώς να τα αποφύγετε + +| Πρόβλημα | Αιτία | Διόρθωση | +|----------------------------------|---------------------------------------|----------| +| Το barcode εμφανίζεται θολό | Το XDimension είναι πολύ χαμηλό (π.χ., 1 px) | Αυξήστε το `XDimension.Pixels` σε 2‑3 px | +| Οι χαρακτήρες Unicode γίνονται `?` | Η προεπιλεγμένη κωδικοποίηση κειμένου είναι ASCII | Ορίστε `TextEncoding = Encoding.UTF8` | +| Το αρχείο εικόνας δεν δημιουργείται | Ο φάκελος εξόδου δεν υπάρχει | Χρησιμοποιήστε `Directory.CreateDirectory` πριν από το `Save` | +| Ο scanner δεν μπορεί να διαβάσει το barcode | Πάρα πολλές στήλες για μικρά δεδομένα | Μειώστε το `Pdf417.Columns` (π.χ., 3‑4) | + +## Πλήρης κώδικας πηγής (έτοιμος για αντιγραφή) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Αναμενόμενο αποτέλεσμα:** ένα αρχείο με όνομα `MicroPdf417.png` στο φάκελο `output`, που περιέχει ένα καθαρό MicroPdf417 barcode που κωδικοποιεί την αρχική συμβολοσειρά με ειδικούς χαρακτήρες. + +## Συμπέρασμα + +Τώρα ξέρετε πώς να **generate barcode from text** σε C# χρησιμοποιώντας το Aspose.BarCode, πώς να διαχειριστείτε **barcode with special characters**, και πώς να **create pdf417 barcode c#** με πλήρη έλεγχο των επιλογών κωδικοποίησης. Με την προσαρμογή των **barcode encode types** μπορείτε να παράγετε QR codes, Code128, DataMatrix ή οποιαδήποτε άλλη υποστηριζόμενη μορφή. + +Στη συνέχεια, εξερευνήστε τα παρακάτω θέματα για να εμβαθύνετε τις γνώσεις σας στα barcode: + +- **How to generate barcode** σε παρτίδες για χιλιάδες εγγραφές (χρησιμοποιήστε `Parallel.ForEach` για ταχύτητα) +- Προσαρμογή χρωμάτων και προσθήκη λογοτύπων μέσα στο barcode +- Ενσωμάτωση της δημιουργίας barcode σε ASP.NET Core APIs για άμεση παράδοση εικόνας +- Χρήση άλλων βιβλιοθηκών όπως ZXing.Net ή IronBarcode για ανοιχτού κώδικα εναλλακτικές + +Νιώστε ελεύθεροι να πειραματιστείτε με διαφορετικές διαστάσεις, ρυθμίσεις στηλών και τύπους κωδικοποίησης. Καλή προγραμματιστική δουλειά, και εύχομαι οι εφαρμογές σας να σκανάρουν άψογα! + +## Τι Θα Πρέπει Να Μάθετε Στη Σύντομη Μελλοντική + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που βασίζονται στις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να δημιουργήσετε Barcode – Compact PDF417 με Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Πώς να δημιουργήσετε Barcode – Ρύθμιση Code 39 με Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Πώς να δημιουργήσετε Barcode - Τύποι μονοδιάστατων Barcode](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/greek/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/greek/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..120ae15b4 --- /dev/null +++ b/barcode/greek/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-08-09 +description: Δημιουργήστε γρήγορα κωδικό PDF417 σε C#. Μάθετε πώς να δημιουργείτε + PDF417 με συμπαγή λειτουργία, έλεγχο στηλών και έξοδο PNG χρησιμοποιώντας το API + BarcodeGenerator. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: el +lastmod: 2026-08-09 +og_description: Δημιουργήστε γραμμωτό κώδικα PDF417 σε C# με ένα σύντομο παράδειγμα. + Αυτός ο οδηγός σας δείχνει πώς να ρυθμίσετε τη συμπαγή λειτουργία, να ορίσετε στήλες + και να αποθηκεύσετε το αποτέλεσμα ως εικόνα PNG. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Δημιουργία γραμμωτού κώδικα PDF417 σε C# – πλήρης οδηγός +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: Δημιουργία barcode PDF417 σε C# – οδηγός βήμα‑βήμα +url: /el/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία PDF417 barcode σε C# – οδηγός βήμα‑βήμα + +Αν χρειάζεστε **δημιουργήσετε PDF417 barcode** σε μια εφαρμογή .NET, αυτό το tutorial σας δείχνει ακριβώς πώς να το κάνετε. Θα δείτε ένα πλήρες, εκτελέσιμο πρόγραμμα που δημιουργεί ένα compact PDF417 barcode, προσαρμόζει το μέγεθός του και αποθηκεύει την εικόνα ως αρχείο PNG. + +Η δημιουργία ενός PDF417 barcode είναι συχνή απαίτηση για κινητά εισιτήρια, παρακολούθηση αποθεμάτων και ασφάλεια εγγράφων. Αυτός ο οδηγός καλύπτει τις βασικές επιλογές διαμόρφωσης, εξηγεί γιατί κάθε ρύθμιση είναι σημαντική και παρέχει πρακτικές συμβουλές για πραγματική χρήση. + +## Προαπαιτούμενα + +* .NET 6.0 SDK ή νεότερο εγκατεστημένο +* Ένα IDE C# όπως το Visual Studio 2022 ή το Visual Studio Code +* Το πακέτο **Aspose.BarCode for .NET** NuGet (έκδοση 23.10 ή νεότερη) + +Μπορείτε να εγκαταστήσετε το πακέτο με την ακόλουθη εντολή CLI: + +```bash +dotnet add package Aspose.BarCode +``` + +Ο κώδικας παρακάτω υποθέτει ότι το πακέτο έχει αναφερθεί και ότι έχετε δικαίωμα εγγραφής στον φάκελο εξόδου. + +## Βήμα 1: Ρύθμιση του έργου και εισαγωγή namespaces + +Δημιουργήστε ένα νέο console project και προσθέστε τις απαιτούμενες οδηγίες `using`. Αυτά τα namespaces εκθέτουν την κλάση `BarcodeGenerator` και την απαρίθμηση μορφής εικόνας. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Γιατί είναι σημαντικό:** Η εισαγωγή των σωστών namespaces εξασφαλίζει ότι ο μεταγλωττιστής μπορεί να εντοπίσει τον τύπο `BarcodeGenerator` και το enum `BarCodeImageFormat`. Η έλλειψη ενός namespace προκαλεί σφάλμα μεταγλώττισης, το οποίο σταματά τη διαδικασία δημιουργίας barcode. + +## Βήμα 2: Αρχικοποίηση του `BarcodeGenerator` με κωδικοποίηση PDF417 + +Ο κατασκευαστής `BarcodeGenerator` δέχεται δύο ορίσματα: τη συμβολική μορφή barcode (`EncodeTypes.Pdf417`) και το κείμενο που θέλετε να κωδικοποιήσετε. Το PDF417 υποστηρίζει ευρύ φάσμα χαρακτήρων, συμπεριλαμβανομένων των συμβόλων Unicode. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Εξήγηση:** +* `EncodeTypes.Pdf417` λέει στη βιβλιοθήκη να χρησιμοποιήσει το πρότυπο PDF417. +* Το δείγμα κειμένου περιέχει τόνους και ένα σύμβολο πνευματικών δικαιωμάτων για να δείξει τη διαχείριση Unicode. + +Αν χρειάζεστε κωδικοποίηση μόνο αριθμητικών δεδομένων, μπορείτε να περάσετε μια απλή συμβολοσειρά όπως `"1234567890"`. + +## Βήμα 3: Ρύθμιση της διάστασης X για πιο λεπτή ανάλυση + +Η διάσταση X ελέγχει το πλάτος ενός μονής μονάδας barcode (το μικρότερο μαύρο ή λευκό στοιχείο). Ορίζοντας μικρότερη τιμή pixel λαμβάνετε εικόνα υψηλότερης ανάλυσης. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Γιατί να το ρυθμίσετε;** Μια προεπιλεγμένη διάσταση X 3–4 pixel μπορεί να παράγει barcode που φαίνεται χονδροειδές σε οθόνες υψηλής DPI. Η μείωση σε **2 pixel** ισορροπεί την αναγνωσιμότητα με το μέγεθος του αρχείου, ειδικά όταν ενεργοποιήσετε το compact mode. + +## Βήμα 4: Διαμόρφωση του αριθμού στηλών + +Το PDF417 σας επιτρέπει να καθορίσετε πόσες στήλες θα περιέχει το barcode. Λιγότερες στήλες κάνουν το barcode πιο στενό αλλά ψηλότερο, ενώ περισσότερες στήλες δημιουργούν ένα πιο πλατύ, κοντύτερο barcode. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Πρακτική συμβουλή:** Για κινητά εισιτήρια που πρέπει να χωρέσουν σε στενή ετικέτα, ένας αριθμός στηλών **3–5** λειτουργεί καλά. Αυξήστε τον αριθμό αν έχετε πολλά δεδομένα και θέλετε ένα πιο κοντό barcode. + +## Βήμα 5: Ενεργοποίηση compact mode για περικοπή κενών σειρών + +Το compact mode αφαιρεί περιττές σειρές από το matrix του barcode, μειώνοντας το συνολικό μέγεθος της εικόνας χωρίς να χάνεται η κωδικοποιημένη πληροφορία. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Πότε να το χρησιμοποιήσετε:** Αν δημιουργείτε barcodes για αποθήκευση ή μετάδοση μέσω δικτύου, το compact mode μπορεί να μειώσει το αρχείο PNG έως και 30 %. Ωστόσο, ορισμένα παλιά scanners μπορεί να μην υποστηρίζουν το truncated PDF417· δοκιμάστε το με το υλικό σας. + +## Βήμα 6: Αποθήκευση του barcode ως εικόνα PNG + +Επιλέξτε διαδρομή εξόδου και καλέστε `Save`. Η απαρίθμηση `BarCodeImageFormat.Png` παράγει μια lossless εικόνα κατάλληλη για τις περισσότερες εφαρμογές. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Επαλήθευση αποτελέσματος:** Ανοίξτε το αρχείο PNG σε οποιονδήποτε προβολέα εικόνων. Θα πρέπει να δείτε ένα πυκνό, υψηλής αντίθεσης barcode που ταιριάζει με το δείγμα κειμένου. Η σάρωση της εικόνας με έναν PDF417 reader (π.χ., ZXing ή εφαρμογή smartphone) επιστρέφει την αρχική συμβολοσειρά `"Åspóse.Barcóde©"`. + +![Δημιουργημένη εικόνα barcode PDF417 αποθηκευμένη ως PNG](compact-pdf417.png "Δημιουργημένο PDF417 barcode σε C#") + +*Η παραπάνω εικόνα δείχνει το τελικό αποτέλεσμα του κώδικα του tutorial.* + +## Πλήρες, εκτελέσιμο παράδειγμα + +Συνδυάζοντας όλα τα κομμάτια, εδώ είναι ένα πλήρες console πρόγραμμα που μπορείτε να αντιγράψετε, επικολλήσετε και να τρέξετε. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Αναμενόμενη έξοδος + +Η εκτέλεση του προγράμματος εκτυπώνει: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +Το αρχείο `CompactPdf417.png` περιέχει ένα compact PDF417 barcode που κωδικοποιεί τη Unicode συμβολοσειρά που δόθηκε. Η σάρωση της εικόνας με έναν τυπικό PDF417 reader επιστρέφει το ακριβές κείμενο. + +## Συνηθισμένες παραλλαγές και ακραίες περιπτώσεις + +| Κατάσταση | Ρύθμιση | Αιτία | +|-----------|------------|--------| +| **Μεγαλύτερο φορτίο δεδομένων** (π.χ., > 150 χαρακτήρες) | Αυξήστε το `generator.Parameters.Barcode.Pdf417.Columns` σε 6‑8 | Περισσότερες στήλες αποτρέπουν το barcode να γίνει υπερβολικά ψηλό. | +| **Ανάγκη για διαφανές φόντο** | Χρησιμοποιήστε `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | Το διαφανές PNG ενσωματώνεται καλύτερα σε επικάλυψη UI. | +| **Δημιουργία JPEG για web** | Αλλάξτε τη μορφή σε `BarCodeImageFormat.Jpeg` και προαιρετικά ορίστε `ImageQuality` | Το JPEG μειώνει το μέγεθος του αρχείου με κόστος την απώλεια ακριβούς πιστότητας. | +| **Διαχείριση null ή κενής εισόδου** | Προστατέψτε την είσοδο πριν δημιουργήσετε το generator: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Αποτρέπει εξαιρέσεις χρόνου εκτέλεσης και εξασφαλίζει ουσιαστικά barcodes. | + +## Συμβουλές για παραγωγική χρήση + +* **Exception handling:** Τυλίξτε τη λογική δημιουργίας σε ένα μπλοκ `try/catch` για να καταγράψετε σφάλματα όπως ανεπαρκής χώρος δίσκου ή μη έγκυρες παραμέτρους. +* **Performance:** Επαναχρησιμοποιήστε ένα μόνο αντικείμενο `BarcodeGenerator` όταν δημιουργείτε πολλά barcodes με τις ίδιες ρυθμίσεις· απλώς ενημερώστε την ιδιότητα `CodeText` μεταξύ των αποθηκεύσεων. +* **Security:** Όταν το κωδικοποιημένο κείμενο περιέχει ευαίσθητες πληροφορίες, σκεφτείτε την κρυπτογράφηση πριν το περάσετε στο generator και την αποκρυπτογράφηση μετά τη σάρωση. + +## Συμπέρασμα + +Τώρα ξέρετε πώς να **δημιουργήσετε PDF417 barcode** σε C# χρησιμοποιώντας τη βιβλιοθήκη Aspose.BarCode, να ρυθμίσετε το compact mode, να ελέγξετε τον αριθμό στηλών και να εξάγετε το αποτέλεσμα ως εικόνα PNG. Αυτό το tutorial κάλυψε κάθε βήμα από τη ρύθμιση του έργου μέχρι τη διαχείριση ακραίων περιπτώσεων, παρέχοντάς σας μια έτοιμη λύση για εφαρμογές που βασίζονται σε barcode. + +Στη συνέχεια, εξερευνήστε συναφή θέματα όπως **δημιουργία QR codes σε C#**, **batch barcode generation**, και **ενσωμάτωση σάρωσης barcode σε κινητές εφαρμογές**. Κάθε ένα από αυτά βασίζεται στα ίδια θεμέλια του `BarcodeGenerator` που μόλις μάθατε. + +Καλή προγραμματιστική! + +## Τι Θα Μάθετε Στη Σειρά; + +Οι παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικά παραδείγματα κώδικα με βήμα‑βήμα επεξηγήσεις για να σας βοηθήσουν να κυριαρχήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να Δημιουργήσετε PDF417 Barcodes – Compact PDF417 Encoding](/barcode/english/net/compact-pdf417-encoding/) +- [Πώς να Δημιουργήσετε Barcode – Compact PDF417 με Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Πώς να δημιουργήσετε Aztec barcode με προσαρμοσμένη αναλογία διαστάσεων χρησιμοποιώντας Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/greek/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/greek/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..2e8bf6cb1 --- /dev/null +++ b/barcode/greek/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-09 +description: Πώς να διαβάσετε PDF417 σε C# χρησιμοποιώντας το BarCodeReader. Μάθετε + να διαβάζετε αρχεία PNG με barcode, να διαχειρίζεστε πολλαπλά barcode και να εξάγετε + εκτεταμένα μεταδεδομένα. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: el +lastmod: 2026-08-09 +og_description: Πώς να διαβάσετε PDF417 σε C# με το Aspose.BarCode. Αυτό το σεμινάριο + σας δείχνει πώς να διαβάζετε αρχεία PNG με barcode, να επεξεργάζεστε πολλαπλά barcode + σε μία εικόνα και να ανακτάτε εκτεταμένα μεταδεδομένα PDF417. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Πώς να διαβάσετε PDF417 σε C# – οδηγός ανάγνωσης γραμμωτού κώδικα +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Πώς να διαβάσετε PDF417 σε C# – πλήρης οδηγός ανάγνωσης γραμμωτού κώδικα +url: /el/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να διαβάσετε PDF417 σε C# – πλήρης οδηγός ανάγνωσης barcode + +Αν χρειάζεστε **πώς να διαβάσετε PDF417** σε μια εφαρμογή .NET, αυτός ο οδηγός σας παρέχει μια έτοιμη προς εκτέλεση λύση. Θα δείτε πώς να διαβάσετε ένα barcode PNG, να επεξεργαστείτε πολλά barcodes στην ίδια εικόνα και να εξάγετε τα επεκταμένα πεδία PDF417 που κρύβουν πολλά scanners. + +Η ανάγνωση barcode PDF417 είναι κοινή στη λογιστική, τα εισιτήρια και τη διαχείριση εγγράφων. Στο τέλος αυτού του tutorial μπορείτε να αποκωδικοποιήσετε μια εικόνα Macro PDF417, να εμφανίσετε κάθε αποτέλεσμα και να χρησιμοποιήσετε τις επιπλέον πληροφορίες (file ID, segment count, timestamps κ.λπ.) στη δική σας επιχειρηματική λογική. + +## Προαπαιτούμενα + +- .NET 6.0 ή νεότερο (ο κώδικας λειτουργεί επίσης με .NET Framework 4.7+) +- Visual Studio 2022 ή οποιοδήποτε IDE C# +- **Aspose.BarCode for .NET** (δωρεάν δοκιμή ή αδειοδοτημένο πακέτο NuGet) +- Μια εικόνα PNG που περιέχει ένα barcode Macro PDF417 (το δείγμα αρχείου ονομάζεται `ExtPDF417Meta.png`) + +> **Pro tip:** Εγκαταστήστε τη βιβλιοθήκη με την κονσόλα NuGet: +> `dotnet add package Aspose.BarCode` + +## Πώς να διαβάσετε PDF417 με BarCodeReader σε C# + +Ο πυρήνας της λύσης είναι η κλάση `BarCodeReader`. Δέχεται μια διαδρομή εικόνας και ένα enum `DecodeType` που λέει στη μηχανή ποια συμβολική γραφή να αναζητήσει. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Γιατί λειτουργεί αυτό + +- **`DecodeType.MacroPdf417`** λέει στον αναγνώστη να ψάξει για την παραλλαγή Macro PDF417, η οποία αποθηκεύει τα επιπλέον πεδία που βλέπετε στο βήμα 4. +- Το μπλοκ `using` απελευθερώνει αυτόματα τον αναγνώστη, απελευθερώνοντας τους χειριστές αρχείων. +- Η μέθοδος `ReadBarCodes()` επιστρέφει **όλα** τα barcodes που ταιριάζουν με τον ζητούμενο τύπο, ικανοποιώντας την απαίτηση *read multiple barcodes* ακόμη και αν η εικόνα περιέχει μόνο ένα. + +Η εκτέλεση του προγράμματος εκτυπώνει έξοδο παρόμοια με: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## Χρήση του αναγνώστη barcode C# για ανάγνωση πολλαπλών barcode + +Αν μια εικόνα περιέχει αρκετά σύμβολα Macro PDF417 (π.χ., μια σκαναρισμένη σελίδα με μια παρτίδα εισιτηρίων), ο ίδιος βρόχος `foreach` επεξεργάζεται το καθένα. Δεν απαιτείται επιπλέον κώδικας· ο αναγνώστης συγκεντρώνει τα αποτελέσματα εσωτερικά. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Συνηθισμένα προβλήματα + +- **Image format:** Ο αναγνώστης υποστηρίζει PNG, JPEG, BMP και TIFF. Αν δοκιμάσετε μια μορφή που δεν μπορεί να αποκωδικοποιήσει, θα λάβετε μια κενή συλλογή. Γι' αυτό το tutorial τονίζει το *read barcode PNG*. +- **Resolution:** Οι εικόνες χαμηλής ανάλυσης (< 300 dpi) μπορεί να προκαλέσουν χαμένα τμήματα. Ανεβάστε την ανάλυση ή ζητήστε σάρωση υψηλότερης ποιότητας όταν είναι δυνατόν. +- **Macro flag:** Η παράλειψη του `DecodeType.MacroPdf417` περιορίζει τη μηχανή σε απλό PDF417 και απορρίπτει τα επεκταμένα δεδομένα. Πάντα να καθορίζετε τον τύπο macro όταν χρειάζεστε τα πεδία *read barcode extended*. + +## Ανάγνωση αρχείων barcode PNG – βέλτιστες πρακτικές + +Η εργασία με αρχεία PNG είναι απλή επειδή η μορφή διατηρεί τα pixel δεδομένα χωρίς απώλειες. Ακολουθεί μια σύντομη λίστα ελέγχου: + +1. Επαληθεύστε ότι το αρχείο υπάρχει πριν δημιουργήσετε τον αναγνώστη. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Χρησιμοποιήστε `Image.FromFile` μόνο όταν χρειάζεται προεπεξεργασία (περιστροφή, περικοπή). Η `BarCodeReader` μπορεί να ανοίξει το αρχείο απευθείας, αποφεύγοντας επιπλέον κατανομή μνήμης. +3. Αν το PNG περιέχει διαφάνεια, ο αναγνώστης λειτουργεί ακόμη επειδή το barcode αποδίδεται σε αδιαφανή pixel. + +## Πρόσβαση στα επεκταμένα μεταδεδομένα PDF417 + +Το αντικείμενο `Extended.Pdf417` εκθέτει κάθε προαιρετικό πεδίο που ορίζεται από την προδιαγραφή PDF417. Μπορείτε να αντιστοιχίσετε αυτά τα πεδία σε ένα domain model, να τα αποθηκεύσετε σε μια βάση δεδομένων ή να τα χρησιμοποιήσετε για επικύρωση. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Συμπληρώστε το μοντέλο: + + + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που βασίζονται στις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να διαβάσετε DataMatrix Barcodes με Aspose.BarCode για .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Πώς να δημιουργήσετε Barcode – Compact PDF417 με Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Διαβάστε DataMatrix barcode C# – Δημιουργία DataMatrix Mode (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hindi/net/compact-pdf417-encoding/_index.md b/barcode/hindi/net/compact-pdf417-encoding/_index.md index 7df391155..4029c8fc0 100644 --- a/barcode/hindi/net/compact-pdf417-encoding/_index.md +++ b/barcode/hindi/net/compact-pdf417-encoding/_index.md @@ -86,6 +86,22 @@ Aspose.BarCode आपको `Pdf417ErrorCorrectionLevel` प्रॉपर् Aspose.BarCode for .NET का उपयोग करके Compact PDF417 बारकोड कैसे जनरेट करें सीखें। चरण‑दर‑चरण निर्देशों और कोड उदाहरणों के साथ व्यापक गाइड। +### [Aspose बारकोड उदाहरण: C# में मैक्रो PDF417 जनरेट करें](./aspose-barcode-example-generate-macro-pdf417-in-c/) + +C# में Aspose.BarCode का उपयोग करके मैक्रो PDF417 बारकोड बनाने का उदाहरण देखें। + +### [PDF417 बारकोड जनरेट करें C# में – चरण‑दर‑चरण गाइड](./generate-pdf417-barcode-in-c-step-by-step-guide/) + +C# में Aspose.BarCode का उपयोग करके PDF417 बारकोड बनाने के चरण‑दर‑चरण मार्गदर्शन। + +### [C# में टेक्स्ट से बारकोड जनरेट करें – पूर्ण चरण‑दर‑चरण गाइड](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) + +C# में टेक्स्ट से बारकोड बनाने की पूरी प्रक्रिया देखें। + +### [C# में PDF417 पढ़ें – पूर्ण बारकोड रीडर गाइड](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) + +C# में Aspose.BarCode का उपयोग करके PDF417 बारकोड को पढ़ने के लिए विस्तृत चरण‑दर‑चरण मार्गदर्शन। + ## अक्सर पूछे जाने वाले प्रश्न **Q: Compact PDF417 बारकोड में मैं अधिकतम कितना डेटा स्टोर कर सकता हूँ?** @@ -114,4 +130,4 @@ A: कोई बाहरी फ़ॉन्ट आवश्यक नहीं {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hindi/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/hindi/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..9ae4d8165 --- /dev/null +++ b/barcode/hindi/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-09 +description: Aspose बारकोड उदाहरण जो दिखाता है कि C# में बारकोड जेनरेटर का उपयोग करके + पूर्ण मेटाडेटा समर्थन के साथ मैक्रो PDF417 कैसे बनाएं। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: hi +lastmod: 2026-08-09 +og_description: Aspose बारकोड उदाहरण दिखाता है कि कैसे C# में बारकोड जेनरेटर का उपयोग + करके एक मैक्रो PDF417 बारकोड बनाया जाए जिसमें फ़ाइल आईडी, सेगमेंट डेटा, टाइमस्टैम्प + और अन्य मेटाडेटा शामिल हों। +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Aspose बारकोड उदाहरण – C# के साथ मैक्रो PDF417 बनाएं +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Aspose बारकोड उदाहरण: C# में मैक्रो PDF417 जनरेट करें' +url: /hi/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose बारकोड उदाहरण: C# में Macro PDF417 उत्पन्न करें + +यदि आपको एक **aspose barcode example** चाहिए जो Macro PDF417 बारकोड बनाता है, तो यह गाइड आपको **barcode generator C#** के साथ यह करने का तरीका दिखाता है। आप सभी आवश्यक सेटिंग्स देखेंगे, बुनियादी आयामों से लेकर Macro PDF417 मेटाडाटा फ़ील्ड्स के पूर्ण सेट तक, और अंत में आपके पास एक PNG इमेज होगी जो डाउनस्ट्रीम प्रोसेसिंग के लिए तैयार होगी। + +यह ट्यूटोरियल पूर्ण वर्कफ़्लो को कवर करता है, प्रत्येक पैरामीटर क्यों महत्वपूर्ण है समझाता है, और एक तैयार‑से‑चलाने वाला कोड नमूना प्रदान करता है। कोई बाहरी रेफ़रेंस आवश्यक नहीं है; आप कोड को कॉपी कर सकते हैं, मानों को समायोजित कर सकते हैं, और तुरंत चला सकते हैं। + +## आवश्यकताएँ + +- .NET 6.0 (या बाद का) स्थापित हो +- Visual Studio 2022 या कोई भी C#‑compatible IDE +- **Aspose.BarCode for .NET** के लिए वैध लाइसेंस (इस उदाहरण के लिए फ्री ट्रायल काम करता है) + +अपने प्रोजेक्ट में Aspose.BarCode NuGet पैकेज जोड़ें: + +```bash +dotnet add package Aspose.BarCode +``` + +## चरण 1: बारकोड जेनरेटर C# इंस्टेंस बनाएं + +पहला कदम `BarcodeGenerator` को `EncodeTypes.MacroPdf417` एन्‍उम वैल्यू और उस टेक्स्ट के साथ इंस्टैंशिएट करना है जिसे आप एन्कोड करना चाहते हैं। टेक्स्ट में Unicode कैरेक्टर्स हो सकते हैं, जिन्हें लाइब्रेरी स्वचालित रूप से संभालती है। + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Why this matters*: `EncodeTypes.MacroPdf417` इंजन को बताता है कि वह Macro PDF417 सिम्बल उत्पन्न करे, जो सेगमेंटेड डेटा और अतिरिक्त फ़ाइल‑लेवल मेटाडाटा का समर्थन करता है। `using` स्टेटमेंट यह सुनिश्चित करता है कि इमेज सेव होने के बाद अनमैनेज्ड रिसोर्सेज रिलीज़ हो जाएँ। + +## चरण 2: बेसिक बारकोड अपीयरेंस निर्धारित करें + +Macro PDF417 बारकोड वर्गाकार मॉड्यूल्स से बना होता है। मॉड्यूल साइज और कॉलम काउंट को नियंत्रित करने से पढ़ने की आसानी और फ़ाइल साइज दोनों पर असर पड़ता है। + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Why this matters*: `XDimension.Pixels` विज़ुअल डेंसिटी तय करता है; 2 पिक्सेल का मान स्क्रीन डिस्प्ले के लिए उपयुक्त है जबकि इमेज को छोटा रखता है। कॉलम काउंट को अपने लेआउट प्रतिबंधों के अनुसार समायोजित करें—अधिक कॉलम एक चौड़ा, छोटा बारकोड बनाते हैं। + +## चरण 3: Macro PDF417 विशिष्ट मेटाडाटा सेट करें + +Macro PDF417 मानक PDF417 फ़ॉर्मेट को ऐसे फ़ील्ड्स के साथ विस्तारित करता है जो कई बारकोड सेगमेंट्स से बड़े फ़ाइलों को पुनः निर्मित करने में मदद करते हैं। प्रत्येक फ़ील्ड वैकल्पिक है, लेकिन इन्हें सेट करने से API की पूरी क्षमता दिखती है। + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Why this matters*: +- `MacroPdf417FileID` सभी सेगमेंट्स को उसी लॉजिकल फ़ाइल से जोड़ता है। +- `MacroPdf417SegmentID` और `MacroPdf417SegmentsCount` डिकोडर को फ्रैगमेंट्स को सही क्रम में रखने में सक्षम बनाते हैं। +- `MacroPdf417Checksum` पूरे पेलोड को डिकोड किए बिना त्वरित इंटेग्रिटी चेक प्रदान करता है। +- `MacroPdf417FileSize` और `MacroPdf417TimeStamp` डाउनस्ट्रीम सिस्टम को यह सत्यापित करने में मदद करते हैं कि पुनः निर्मित फ़ाइल मूल के समान है या नहीं। +- `MacroPdf417Addressee` / `MacroPdf417Sender` लॉजिस्टिक्स या डॉक्यूमेंट‑एक्सचेंज परिदृश्यों में उपयोगी होते हैं। +- `MacroPdf417Terminator` को `Set` करने से यह बारकोड अंतिम सेगमेंट के रूप में चिह्नित होता है, जिससे पुनः निर्माण एल्गोरिद्म सरल हो जाता है। + +## चरण 4: उत्पन्न बारकोड इमेज को सेव करें + +अंत में, बारकोड को PNG फ़ाइल में लिखें। आप कोई भी सपोर्टेड फ़ॉर्मेट (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`) चुन सकते हैं। + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Why this matters*: PNG लॉसलेस पिक्सेल डेटा को संरक्षित करता है, जिससे स्कैनर ठीक वही मॉड्यूल पैटर्न पढ़ता है जो आपने कॉन्फ़िगर किया है। फ़ॉर्मेट बदलने से विज़ुअल क्वालिटी और फ़ाइल साइज पर असर पड़ सकता है। + +### अपेक्षित आउटपुट + +पूरा प्रोग्राम चलाने पर **ExtPDF417Meta.png** नाम की फ़ाइल बनती है। इमेज खोलने पर एक आयताकार Macro PDF417 बारकोड दिखेगा जिसमें “Åspóse.Barcóde©” टेक्स्ट एन्कोडेड होगा, और विज़ुअल डेंसिटी आपके द्वारा सेट किए गए 2‑पिक्सेल X डाइमेंशन से मेल खाएगी। PDF417‑कम्पैटिबल रीडर से इमेज स्कैन करने पर चरण 3 में परिभाषित सभी मेटाडाटा फ़ील्ड्स प्राप्त होंगे। + +## पूर्ण कार्यशील उदाहरण + +नीचे दिया गया कोड एक नए कंसोल प्रोजेक्ट (`dotnet new console`) में कॉपी करें और `YOUR_DIRECTORY` को अपने मशीन पर मौजूद किसी एब्सोल्यूट या रिलेटिव पाथ से बदलें। + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +प्रोग्राम चलाएँ (`dotnet run`)। निष्पादन के बाद, सुनिश्चित करें कि PNG फ़ाइल उस लोकेशन पर मौजूद है जिसे आपने निर्दिष्ट किया था। किसी भी बारकोड‑रीडिंग ऐप का उपयोग करें जो Macro PDF417 को सपोर्ट करता हो, यह पुष्टि करने के लिए कि मेटाडाटा सही ढंग से एम्बेड हुआ है। + +## सामान्य विविधताएँ और एज केस + +- **विभिन्न इमेज फ़ॉर्मेट्स**: यदि आपका डाउनस्ट्रीम सिस्टम किसी अन्य फ़ॉर्मेट को पसंद करता है तो `BarCodeImageFormat.Png` को `Jpeg`, `Bmp`, या `Tiff` से बदलें। +- **मॉड्यूल साइज बदलना**: बड़े `XDimension.Pixels` मान कम‑रिज़ॉल्यूशन स्कैनर्स पर स्कैन विश्वसनीयता बढ़ाते हैं लेकिन इमेज साइज भी बढ़ाते हैं। +- **एकाधिक सेगमेंट्स**: मल्टी‑सेगमेंट फ़ाइल बनाने के लिए बारकोड की एक श्रृंखला जनरेट करें, प्रत्येक के लिए `MacroPdf417SegmentID` को इन्क्रीमेंट करें, और `MacroPdf417FileID` को स्थिर रखें। केवल अंतिम सेगमेंट में `MacroPdf417Terminator` सेट होना चाहिए। +- **Unicode सपोर्ट**: जेनरेटर स्वचालित रूप से Unicode कैरेक्टर्स को एन्कोड करता है; यदि आप स्ट्रिंग को बाहरी फ़ाइल से पढ़ते हैं तो सुनिश्चित करें कि स्रोत UTF‑8 एन्कोडिंग में हो। +- **एरर हैंडलिंग**: `using` ब्लॉक को try‑catch में रैप करें ताकि `BarCodeException` को कैप्चर किया जा सके जब पैरामीटर अमान्य हों (जैसे, कॉलम काउंट रेंज से बाहर हो)। + +## प्रो टिप्स + +- **परफ़ॉर्मेंस**: जब कई बारकोड एक ही सेटिंग्स के साथ बनाते हैं तो एक ही `BarcodeGenerator` इंस्टेंस को पुनः उपयोग करें; केवल `CodeText` प्रॉपर्टी को सेव्स के बीच बदलें। +- **फ़ाइल साइज अनुमान**: `MacroPdf417FileSize` फ़ील्ड को मूल पेलोड के बाइट काउंट से मिलाना चाहिए; असंगतियों से डाउनस्ट्रीम वैलिडेशन फेल हो सकता है। +- **टेस्टिंग**: उत्पन्न बारकोड को Aspose के बिल्ट‑इन डिकोडर (`BarCodeReader`) और किसी थर्ड‑पार्टी स्कैनर दोनों से वैलिडेट करें ताकि इंटरऑपरेबिलिटी सुनिश्चित हो सके। + +## निष्कर्ष + +यह **aspose barcode example + +## आगे क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में प्रदर्शित तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ का पता लगा सकें। + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to create barcode quiet zone for Code 16K using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hindi/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/hindi/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..410e7842a --- /dev/null +++ b/barcode/hindi/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-08-09 +description: Aspose.BarCode के साथ C# में टेक्स्ट से बारकोड जनरेट करें। जानें कैसे + बारकोड बनाएं, विशेष अक्षरों को संभालें, और जल्दी से PDF417 बारकोड C# में बनाएं। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: hi +lastmod: 2026-08-09 +og_description: Aspose.BarCode का उपयोग करके C# में टेक्स्ट से बारकोड जनरेट करें। + यह ट्यूटोरियल दिखाता है कि कैसे बारकोड जनरेट करें, विशेष अक्षरों का समर्थन करें, + और पूर्ण कोड के साथ C# में PDF417 बारकोड बनाएं। +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: C# में टेक्स्ट से बारकोड जनरेट करें – तेज़ चरण‑दर‑चरण गाइड +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: C# में टेक्स्ट से बारकोड जेनरेट करें – पूर्ण चरण‑दर‑चरण गाइड +url: /hi/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# टेक्स्ट से बारकोड जेनरेट करें C# में – पूर्ण चरण‑दर‑चरण गाइड + +यदि आपको .NET एप्लिकेशन में **टेक्स्ट से बारकोड जेनरेट** करने की आवश्यकता है, तो यह गाइड आपको पूरी प्रक्रिया से गुज़राएगा। आप देखेंगे कि बारकोड कैसे जेनरेट करें, विशेष अक्षरों को कैसे संभालें, और एक PDF417 बारकोड C# इम्प्लीमेंटेशन कैसे बनाएं जो तुरंत काम करे। + +टेक्स्ट से बारकोड जेनरेट करना इन्वेंटरी सिस्टम, टिकटिंग प्लेटफ़ॉर्म और दस्तावेज़ वर्कफ़्लो के लिए सामान्य आवश्यकता है। इस ट्यूटोरियल के अंत तक आपके पास एक चलाने योग्य C# कंसोल ऐप होगा जो Aspose.BarCode का उपयोग करके एक MicroPdf417 PNG इमेज बनाता है। कोई बाहरी सेवा आवश्यक नहीं है, और कोड Unicode अक्षरों जैसे “Å”, “©”, और “é” को संभालता है। + +## Prerequisites + +- .NET 6.0 SDK या बाद का संस्करण (कोड .NET Core 3.1 और .NET Framework 4.7+ के साथ भी काम करता है) +- Visual Studio 2022 (या कोई भी IDE जो C# को सपोर्ट करता हो) +- **Aspose.BarCode for .NET** NuGet पैकेज + ```bash + dotnet add package Aspose.BarCode + ``` +- C# सिंटैक्स का बुनियादी ज्ञान + +## Generate barcode from text – सेटअप जनरेटर + +पहला कदम `BarcodeGenerator` इंस्टेंस बनाना है जो यह जानता हो कि आपको कौन सा **बारकोड एन्कोड टाइप** चाहिए। इस ट्यूटोरियल में हम `EncodeTypes.MicroPdf417` का उपयोग करते हैं, जो PDF417 का एक कॉम्पैक्ट वैरिएंट है और छोटे डेटा स्ट्रिंग्स के लिए उपयुक्त है। + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**यह क्यों काम करता है:** +- `EncodeTypes.MicroPdf417` लाइब्रेरी को PDF417 परिवार का उपयोग करने के लिए बताता है, जिससे **create pdf417 barcode c#** की आवश्यकता पूरी होती है। +- कंस्ट्रक्टर रॉ टेक्स्ट प्राप्त करता है, जो **generate barcode from text** का मूल है। +- Unicode सपोर्ट बिल्ट‑इन है, इसलिए “Å” और “©” जैसे अक्षर सही ढंग से एन्कोड होते हैं, जिससे **barcode with special characters** का समाधान मिलता है। + +## How to generate barcode with special characters + +जब आपके डेटा में non‑ASCII प्रतीक हों, तो आपको यह सुनिश्चित करना चाहिए कि जनरेटर UTF‑8 एन्कोडिंग का उपयोग करे। Aspose.BarCode स्वचालित रूप से Unicode का पता लगाता है, लेकिन यदि समस्या आती है तो आप टेक्स्ट एन्कोडिंग स्पष्ट रूप से सेट कर सकते हैं: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +`ConfigureGenerator` से पहले यह लाइन जोड़ने से **barcode with special characters** किसी भी प्लेटफ़ॉर्म पर सही ढंग से रेंडर होता है। + +### Practical tip +यदि आउटपुट गड़बड़ दिखता है, तो जांचें कि बारकोड रेंडरर द्वारा उपयोग किया गया फ़ॉन्ट आवश्यक glyphs को सपोर्ट करता है या नहीं। आप एक कस्टम TrueType फ़ॉन्ट इस प्रकार एम्बेड कर सकते हैं: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Barcode encode types you can choose + +Aspose.BarCode कई **बारकोड एन्कोड टाइप** सपोर्ट करता है, प्रत्येक विभिन्न उपयोग मामलों के लिए उपयुक्त है: + +| Encode type | Typical use case | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | शिपिंग लेबल, इन्वेंटरी | +| `EncodeTypes.QR` | मोबाइल पेमेंट, URLs | +| `EncodeTypes.Pdf417` | ड्राइवर लाइसेंस, बोर्डिंग पासेज | +| `EncodeTypes.MicroPdf417` | छोटे डेटा पेलोड, सीमित स्पेस | +| `EncodeTypes.DataMatrix` | बहुत छोटे आइटम, उच्च डेटा घनत्व | + +कंस्ट्रक्टर में enum वैल्यू को बदलना इतना ही आसान है: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +यह लचीलापन आपको **barcode encode types** से जुड़े प्रश्नों का उत्तर IDE छोड़े बिना देने में मदद करता है। + +## Create PDF417 barcode C# – अंतिम कदम और सत्यापन + +जनरेटर को कॉन्फ़िगर करने के बाद, **create pdf417 barcode c#** का अंतिम हिस्सा इमेज को सेव करना और परिणाम की पुष्टि करना है। + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +प्रोग्राम चलाएँ (`dotnet run`) और आपको कंसोल में कुछ इस तरह का संदेश दिखना चाहिए: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +PNG फ़ाइल खोलें; आपको एक स्पष्ट MicroPdf417 बारकोड दिखाई देगा जो स्ट्रिंग “Åspóse.Barcóde©” को एन्कोड करता है। इसे मोबाइल बारकोड स्कैनर (जैसे ZXing) से स्कैन करने पर मूल टेक्स्ट वापस मिलता है, जिससे यह सिद्ध होता है कि **generate barcode from text** विशेष अक्षरों के साथ भी काम करता है। + +### Edge case: बहुत लंबा टेक्स्ट + +MicroPdf417 की अधिकतम डेटा क्षमता 1 KB है। यदि आपका इनपुट इस सीमा से अधिक है, तो लाइब्रेरी `ArgumentException` फेंकेगी। इसे सहजता से संभालने के लिए: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +बड़े पेलोड के लिए, पूर्ण `EncodeTypes.Pdf417` या `EncodeTypes.DataMatrix` पर स्विच करें। + +## Common pitfalls and how to avoid them + +| Issue | Cause | Fix | +|-------------------------------------|-----------------------------------------|-----| +| बारकोड धुंधला दिखता है | XDimension बहुत कम (जैसे, 1 px) | `XDimension.Pixels` को 2‑3 px बढ़ाएँ | +| Unicode अक्षर `?` में बदल जाते हैं | डिफ़ॉल्ट टेक्स्ट एन्कोडिंग ASCII है | `TextEncoding = Encoding.UTF8` सेट करें | +| इमेज फ़ाइल नहीं बनती | आउटपुट डायरेक्टरी मौजूद नहीं है | `Save` से पहले `Directory.CreateDirectory` उपयोग करें | +| स्कैनर बारकोड नहीं पढ़ पाता | छोटे डेटा के लिए कॉलम बहुत अधिक हैं | `Pdf417.Columns` को कम करें (जैसे, 3‑4) | + +## Full source code (ready to copy) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Expected output:** एक फ़ाइल जिसका नाम `MicroPdf417.png` है, `output` फ़ोल्डर में स्थित, जिसमें एक स्पष्ट MicroPdf417 बारकोड है जो मूल स्ट्रिंग को विशेष अक्षरों के साथ एन्कोड करता है। + +## Conclusion + +अब आप जानते हैं कि Aspose.BarCode का उपयोग करके C# में **टेक्स्ट से बारकोड जेनरेट** कैसे करें, **विशेष अक्षरों वाले बारकोड** को कैसे हैंडल करें, और **create pdf417 barcode c#** को एन्कोडिंग विकल्पों पर पूर्ण नियंत्रण के साथ कैसे बनाएं। **बारकोड एन्कोड टाइप** को समायोजित करके आप QR कोड, Code128, DataMatrix या कोई भी समर्थित फ़ॉर्मेट बना सकते हैं। + +अगले चरण में, अपनी बारकोड विशेषज्ञता को गहरा करने के लिए निम्नलिखित विषयों का अन्वेषण करें: + +- हजारों रिकॉर्ड के लिए बैच में **बारकोड जेनरेट** कैसे करें (स्पीड के लिए `Parallel.ForEach` उपयोग करें) +- बारकोड के अंदर रंग कस्टमाइज़ करना और लोगो जोड़ना +- ASP.NET Core API में बारकोड जेनरेशन को इंटीग्रेट करना ताकि ऑन‑द‑फ्लाई इमेज डिलीवरी हो सके +- ZXing.Net या IronBarcode जैसी ओपन‑सोर्स लाइब्रेरी का उपयोग करना + +विभिन्न डाइमेंशन, कॉलम सेटिंग्स और एन्कोड टाइप के साथ प्रयोग करने में संकोच न करें। कोडिंग का आनंद लें, और आपकी एप्लिकेशन हमेशा flawless स्कैन करे! + +## What Should You Learn Next? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में प्रदर्शित तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर करने में मदद करेंगे। + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hindi/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/hindi/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..010847c29 --- /dev/null +++ b/barcode/hindi/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,228 @@ +--- +category: general +date: 2026-08-09 +description: C# में तेज़ी से PDF417 बारकोड जनरेट करें। कॉम्पैक्ट मोड, कॉलम नियंत्रण + और PNG आउटपुट के साथ PDF417 कैसे जनरेट करें, यह BarcodeGenerator API का उपयोग करके + सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: hi +lastmod: 2026-08-09 +og_description: C# में संक्षिप्त उदाहरण के साथ PDF417 बारकोड जनरेट करें। यह गाइड आपको + दिखाता है कि कैसे कॉम्पैक्ट मोड कॉन्फ़िगर करें, कॉलम सेट करें, और परिणाम को PNG + इमेज के रूप में सहेजें। +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: C# में PDF417 बारकोड जेनरेट करें – पूर्ण ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: C# में PDF417 बारकोड बनाएं – चरण‑दर‑चरण मार्गदर्शिका +url: /hi/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generate PDF417 barcode in C# – step‑by‑step guide + +यदि आपको .NET एप्लिकेशन में **PDF417 बारकोड उत्पन्न** करना है, तो यह ट्यूटोरियल आपको ठीक‑ठीक दिखाएगा कि कैसे करना है। आप एक पूर्ण, चलने योग्य प्रोग्राम देखेंगे जो एक कॉम्पैक्ट PDF417 बारकोड बनाता है, उसके आकार को कस्टमाइज़ करता है, और इमेज को PNG फ़ाइल के रूप में सेव करता है। + +PDF417 बारकोड का निर्माण मोबाइल टिकटिंग, इन्वेंटरी ट्रैकिंग और दस्तावेज़ सुरक्षा जैसे कई परिदृश्यों में सामान्य आवश्यकता है। यह गाइड आवश्यक कॉन्फ़िगरेशन विकल्पों को कवर करता है, प्रत्येक सेटिंग का महत्व समझाता है, और वास्तविक उपयोग के लिए व्यावहारिक टिप्स प्रदान करता है। + +## Prerequisites + +शुरू करने से पहले सुनिश्चित करें कि आपके पास निम्नलिखित हों: + +* .NET 6.0 SDK या बाद का संस्करण स्थापित हो +* Visual Studio 2022 या Visual Studio Code जैसे C# IDE +* **Aspose.BarCode for .NET** NuGet पैकेज (संस्करण 23.10 या नया) + +आप नीचे दिए गए CLI कमांड से पैकेज इंस्टॉल कर सकते हैं: + +```bash +dotnet add package Aspose.BarCode +``` + +यह कोड मानता है कि पैकेज रेफ़रेंस किया गया है और आपके पास आउटपुट डायरेक्टरी में लिखने की अनुमति है। + +## Step 1: Set up the project and import namespaces + +एक नया कंसोल प्रोजेक्ट बनाएं और आवश्यक `using` निर्देश जोड़ें। ये नेमस्पेस `BarcodeGenerator` क्लास और इमेज फ़ॉर्मेट एनेमरेशन को एक्सपोज़ करते हैं। + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Why this matters:** सही नेमस्पेस इम्पोर्ट करने से कंपाइलर `BarcodeGenerator` टाइप और `BarCodeImageFormat` एनेम को ढूँढ पाता है। नेमस्पेस मिस होने पर कंपाइलेशन एरर आता है, जिससे बारकोड जनरेशन प्रक्रिया रुक जाती है। + +## Step 2: Initialize the `BarcodeGenerator` with PDF417 encoding + +`BarcodeGenerator` कंस्ट्रक्टर दो आर्गुमेंट लेता है: बारकोड सिम्बोलॉजी (`EncodeTypes.Pdf417`) और वह टेक्स्ट जिसे आप एन्कोड करना चाहते हैं। PDF417 विस्तृत कैरेक्टर रेंज, जिसमें यूनिकोड सिम्बॉल भी शामिल हैं, को सपोर्ट करता है। + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Explanation:** +* `EncodeTypes.Pdf417` लाइब्रेरी को PDF417 स्टैंडर्ड उपयोग करने के लिए बताता है। +* सैंपल टेक्स्ट में एक्सेंटेड कैरेक्टर और कॉपीराइट सिम्बॉल शामिल हैं ताकि यूनिकोड हैंडलिंग दिखा सकें। + +यदि आपको केवल संख्यात्मक डेटा एन्कोड करना है, तो आप `"1234567890"` जैसी साधारण स्ट्रिंग पास कर सकते हैं। + +## Step 3: Adjust the X‑dimension for finer resolution + +X‑dimension एक सिंगल बारकोड मॉड्यूल (सबसे छोटा ब्लैक या व्हाइट एलिमेंट) की चौड़ाई को नियंत्रित करता है। छोटा पिक्सेल वैल्यू सेट करने से हाई‑रेज़ोल्यूशन इमेज मिलती है। + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Why adjust it?** डिफ़ॉल्ट X‑dimension 3–4 पिक्सेल अक्सर हाई‑DPI स्क्रीन पर बारकोड को मोटा दिखा सकता है। इसे **2 पिक्सेल** तक घटाने से रीडेबिलिटी और फ़ाइल साइज के बीच संतुलन बना रहता है, विशेषकर जब आप बाद में कॉम्पैक्ट मोड एनेबल करते हैं। + +## Step 4: Configure the number of columns + +PDF417 आपको यह निर्धारित करने की अनुमति देता है कि बारकोड में कितनी कॉलम हों। कम कॉलम बारकोड को संकरी लेकिन लंबी बनाते हैं, जबकि अधिक कॉलम बारकोड को चौड़ा और छोटा बनाते हैं। + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Practical tip:** मोबाइल टिकटों के लिए जो संकीर्ण लेबल में फिट होना चाहिए, **3–5** कॉलम की संख्या उपयुक्त रहती है। यदि डेटा बहुत अधिक है और आप छोटा बारकोड चाहते हैं, तो कॉलम काउंट बढ़ा सकते हैं। + +## Step 5: Enable compact mode to truncate empty rows + +कॉम्पैक्ट मोड बारकोड मैट्रिक्स से अनावश्यक पंक्तियों को हटा देता है, जिससे कुल इमेज साइज घट जाता है बिना एन्कोडेड डेटा खोए। + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**When to use it:** यदि आप बारकोड को स्टोरेज या नेटवर्क ट्रांसमिशन के लिए जनरेट कर रहे हैं, तो कॉम्पैक्ट मोड PNG फ़ाइल को लगभग 30 % तक छोटा कर सकता है। हालांकि, कुछ लेगेसी स्कैनर ट्रंकेटेड PDF417 को सपोर्ट नहीं कर सकते; अपने टार्गेट हार्डवेयर पर टेस्ट करना न भूलें। + +## Step 6: Save the barcode as a PNG image + +आउटपुट पाथ चुनें और `Save` को कॉल करें। `BarCodeImageFormat.Png` एनेमरेशन एक लॉसलेस इमेज बनाता है जो अधिकांश एप्लिकेशन के लिए उपयुक्त है। + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Result verification:** किसी भी इमेज व्यूअर में PNG फ़ाइल खोलें। आपको एक घना, हाई‑कॉन्ट्रास्ट बारकोड दिखना चाहिए जो सैंपल टेक्स्ट से मेल खाता हो। PDF417 रीडर (जैसे ZXing या स्मार्टफ़ोन ऐप) से स्कैन करने पर मूल स्ट्रिंग `"Åspóse.Barcóde©"` प्राप्त होगी। + +![Generated PDF417 barcode image saved as PNG](compact-pdf417.png "Generated PDF417 barcode in C#") + +*ऊपर की इमेज ट्यूटोरियल के कोड का अंतिम आउटपुट दर्शाती है।* + +## Full, runnable example + +सभी हिस्सों को मिलाकर, यहाँ एक पूर्ण कंसोल प्रोग्राम है जिसे आप कॉपी‑पेस्ट करके चला सकते हैं। + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Expected output + +प्रोग्राम चलाने पर यह प्रिंट करेगा: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +फ़ाइल `CompactPdf417.png` में एक कॉम्पैक्ट PDF417 बारकोड होगा जो प्रदान किए गए यूनिकोड स्ट्रिंग को एन्कोड करता है। इसे मानक PDF417 रीडर से स्कैन करने पर वही टेक्स्ट मिलेगा। + +## Common variations and edge cases + +| Situation | Adjustment | Reason | +|-----------|------------|--------| +| **Longer data payload** (e.g., > 150 characters) | `generator.Parameters.Barcode.Pdf417.Columns` को 6‑8 तक बढ़ाएँ | अधिक कॉलम बारकोड को अत्यधिक लंबा होने से बचाते हैं। | +| **Need for a transparent background** | `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` उपयोग करें | ट्रांसपेरेंट PNG UI ओवरले में बेहतर इंटीग्रेट होता है। | +| **Generating JPEG for web** | फ़ॉर्मेट को `BarCodeImageFormat.Jpeg` बदलें और वैकल्पिक रूप से `ImageQuality` सेट करें | JPEG फ़ाइल साइज घटाता है लेकिन लॉसलेस फ़िडेलिटी नहीं रखता। | +| **Handling null or empty input** | जनरेटर बनाने से पहले इनपुट की जाँच करें: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | रन‑टाइम एक्सेप्शन से बचाता है और अर्थपूर्ण बारकोड सुनिश्चित करता है। | + +## Tips for production use + +* **Exception handling:** जनरेशन लॉजिक को `try/catch` ब्लॉक में रैप करें ताकि डिस्क स्पेस कम या गलत पैरामीटर जैसी त्रुटियों को लॉग किया जा सके। +* **Performance:** कई बारकोड जनरेट करते समय एक ही `BarcodeGenerator` इंस्टेंस को री‑यूज़ करें; केवल `CodeText` प्रॉपर्टी को अपडेट करें और फिर सेव करें। +* **Security:** यदि एन्कोडेड टेक्स्ट में संवेदनशील जानकारी है, तो जनरेटर को पास करने से पहले उसे एन्क्रिप्ट करें और स्कैन के बाद डिक्रिप्ट करें। + +## Conclusion + +आप अब Aspose.BarCode लाइब्रेरी का उपयोग करके C# में **PDF417 बारकोड उत्पन्न** करना, कॉम्पैक्ट मोड कॉन्फ़िगर करना, कॉलम काउंट कंट्रोल करना, और परिणाम को PNG इमेज के रूप में एक्सपोर्ट करना जानते हैं। इस ट्यूटोरियल ने प्रोजेक्ट सेटअप से लेकर एज‑केस हैंडलिंग तक हर कदम को कवर किया, जिससे आपके पास बारकोड‑ड्रिवेन एप्लिकेशन के लिए एक तैयार‑से‑उपयोग समाधान है। + +आगे, **C# में QR कोड बनाना**, **बैच बारकोड जनरेशन**, और **मोबाइल ऐप्स के साथ बारकोड स्कैनिंग इंटीग्रेशन** जैसे संबंधित विषयों का अन्वेषण करें। ये सभी वही `BarcodeGenerator` फंडामेंटल्स पर आधारित हैं जिन्हें आपने अभी मास्टर किया है। + +Happy coding! + + +## What Should You Learn Next? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक रिसोर्स में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स को मास्टर कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर कर सकें। + +- [How to Generate PDF417 Barcodes – Compact PDF417 Encoding](/barcode/english/net/compact-pdf417-encoding/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hindi/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/hindi/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..b8eddd3d7 --- /dev/null +++ b/barcode/hindi/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-09 +description: BarCodeReader का उपयोग करके C# में PDF417 कैसे पढ़ें। बारकोड PNG फ़ाइलें + पढ़ना सीखें, कई बारकोड को संभालें, और विस्तारित मेटाडेटा निकालें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: hi +lastmod: 2026-08-09 +og_description: C# में Aspose.BarCode के साथ PDF417 को कैसे पढ़ें। यह ट्यूटोरियल आपको + दिखाता है कि बारकोड PNG फ़ाइलें कैसे पढ़ें, एक छवि में कई बारकोड कैसे प्रोसेस करें, + और विस्तारित PDF417 मेटाडेटा कैसे प्राप्त करें। +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: C# में PDF417 कैसे पढ़ें – बारकोड रीडर ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: C# में PDF417 को कैसे पढ़ें – पूर्ण बारकोड रीडर गाइड +url: /hi/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में PDF417 कैसे पढ़ें – पूर्ण बारकोड रीडर गाइड + +यदि आपको .NET एप्लिकेशन में **PDF417 कैसे पढ़ें** की आवश्यकता है, तो यह गाइड आपको एक तैयार‑से‑चलाने वाला समाधान देता है। आप देखेंगे कि कैसे एक बारकोड PNG पढ़ें, एक ही छवि में कई बारकोड प्रोसेस करें, और उन विस्तारित PDF417 फ़ील्ड्स को निकालें जो कई स्कैनर छिपाते हैं। + +लॉजिस्टिक्स, टिकटिंग, और दस्तावेज़ प्रबंधन में PDF417 बारकोड पढ़ना आम है। इस ट्यूटोरियल के अंत तक आप एक Macro PDF417 छवि को डिकोड कर सकते हैं, प्रत्येक परिणाम प्रदर्शित कर सकते हैं, और अतिरिक्त जानकारी (फ़ाइल आईडी, सेगमेंट काउंट, टाइमस्टैम्प आदि) को अपने व्यावसायिक लॉजिक में उपयोग कर सकते हैं। + +## आवश्यकताएँ + +- .NET 6.0 या बाद का (कोड .NET Framework 4.7+ के साथ भी काम करता है) +- Visual Studio 2022 या कोई भी C# IDE +- **Aspose.BarCode for .NET** (नि:शुल्क ट्रायल या लाइसेंस्ड NuGet पैकेज) +- एक PNG छवि जिसमें Macro PDF417 बारकोड हो (नमूना फ़ाइल का नाम `ExtPDF417Meta.png` है) + +> **Pro tip:** लाइब्रेरी को NuGet कंसोल से इंस्टॉल करें: +> `dotnet add package Aspose.BarCode` + +## C# में BarCodeReader के साथ PDF417 कैसे पढ़ें + +समाधान का मुख्य भाग `BarCodeReader` क्लास है। यह एक इमेज पाथ और एक `DecodeType` एन्‍यूम लेता है जो इंजन को बताता है कि किस सिम्बोलॉजी की तलाश करनी है। + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### यह क्यों काम करता है + +- **`DecodeType.MacroPdf417`** रीडर को Macro PDF417 वैरिएंट खोजने के लिए बताता है, जो चरण 4 में दिखाए गए अतिरिक्त फ़ील्ड्स को संग्रहीत करता है। +- `using` ब्लॉक रीडर को स्वचालित रूप से डिस्पोज़ करता है, फ़ाइल हैंडल्स को रिलीज़ करता है। +- `ReadBarCodes()` **सभी** बारकोड्स लौटाता है जो अनुरोधित प्रकार से मेल खाते हैं, जिससे *read multiple barcodes* आवश्यकता पूरी होती है भले ही छवि में केवल एक ही बारकोड हो। + +प्रोग्राम चलाने पर आउटपुट इस प्रकार दिखेगा: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## C# बारकोड रीडर का उपयोग करके कई बारकोड पढ़ना + +यदि किसी छवि में कई Macro PDF417 सिम्बॉल हों (उदाहरण के लिए, टिकटों के एक बैच के साथ स्कैन की गई पेज), तो वही `foreach` लूप प्रत्येक को प्रोसेस करता है। अतिरिक्त कोड की आवश्यकता नहीं है; रीडर आंतरिक रूप से परिणामों को एकत्रित करता है। + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### सामान्य जाल + +- **Image format:** रीडर PNG, JPEG, BMP, और TIFF को सपोर्ट करता है। यदि आप ऐसा फ़ॉर्मेट उपयोग करते हैं जिसे वह डिकोड नहीं कर सकता, तो आपको एक खाली कलेक्शन मिलेगा। इसलिए ट्यूटोरियल *read barcode PNG* को हाइलाइट करता है। +- **Resolution:** कम‑रिज़ॉल्यूशन वाली छवियाँ (< 300 dpi) से सेगमेंट मिस हो सकते हैं। संभव हो तो अपस्केल करें या उच्च‑गुणवत्ता स्कैन का अनुरोध करें। +- **Macro flag:** `DecodeType.MacroPdf417` को भूल जाने से इंजन केवल साधारण PDF417 तक सीमित हो जाता है और विस्तारित डेटा को हटा देता है। जब आपको *read barcode extended* फ़ील्ड्स चाहिए हों तो हमेशा मैक्रो टाइप निर्दिष्ट करें। + +## बारकोड PNG फ़ाइलें पढ़ना – सर्वोत्तम प्रथाएँ + +PNG फ़ाइलों के साथ काम करना सरल है क्योंकि यह फ़ॉर्मेट लॉसलेस पिक्सेल डेटा को संरक्षित रखता है। यहाँ एक त्वरित चेकलिस्ट है: + +1. रीडर बनाने से पहले फ़ाइल मौजूद है या नहीं जांचें। + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. `Image.FromFile` का उपयोग केवल तब करें जब आपको प्री‑प्रोसेस (घुमाना, क्रॉप) करना हो। `BarCodeReader` फ़ाइल को सीधे खोल सकता है, जिससे अतिरिक्त मेमोरी आवंटन से बचा जा सकता है। +3. यदि PNG में ट्रांसपेरेंसी है, तो भी रीडर काम करता है क्योंकि बारकोड अपारदर्शी पिक्सेल पर रेंडर किया गया है। + +## विस्तारित PDF417 मेटाडाटा तक पहुँच + +`Extended.Pdf417` ऑब्जेक्ट PDF417 स्पेसिफिकेशन द्वारा परिभाषित सभी वैकल्पिक फ़ील्ड्स को उजागर करता है। आप इन फ़ील्ड्स को डोमेन मॉडल में मैप कर सकते हैं, डेटाबेस में स्टोर कर सकते हैं, या वैधता के लिए उपयोग कर सकते हैं। + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +मॉडल को भरें: + + + +## अब आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स निकट संबंधित विषयों को कवर करते हैं जो इस गाइड में दर्शाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक कार्यान्वयन दृष्टिकोणों की खोज करने में मदद करती हैं। + +- [Aspose.BarCode for .NET के साथ DataMatrix बारकोड कैसे पढ़ें](/barcode/english/net/datamatrix-barcode-reading/) +- [Aspose.BarCode के साथ बारकोड बनाना – कॉम्पैक्ट PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [DataMatrix बारकोड C# में पढ़ें – DataMatrix मोड (ऑटो) उत्पन्न करें](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hongkong/net/compact-pdf417-encoding/_index.md b/barcode/hongkong/net/compact-pdf417-encoding/_index.md index 9254eb3ec..cb742be4f 100644 --- a/barcode/hongkong/net/compact-pdf417-encoding/_index.md +++ b/barcode/hongkong/net/compact-pdf417-encoding/_index.md @@ -84,6 +84,18 @@ Aspose.BarCode 讓你設定 `Pdf417ErrorCorrectionLevel` 屬性 (0‑8)。較高 ### [建立緊湊式 PDF417 條碼](./compact-pdf417-basic-configuration/) 了解如何使用 Aspose.BarCode for .NET 產生緊湊式 PDF417 條碼。完整指南包含一步一步說明與程式碼範例。 +### [Aspose 條碼範例:在 C# 中產生 Macro PDF417](./aspose-barcode-example-generate-macro-pdf417-in-c/) +示範如何使用 Aspose.BarCode for .NET 在 C# 中生成 Macro PDF417 條碼。 + +### [在 C# 中產生 PDF417 條碼 – 步驟指南](./generate-pdf417-barcode-in-c-step-by-step-guide/) +逐步說明如何使用 Aspose.BarCode for .NET 在 C# 中生成 PDF417 條碼。 + +### [在 C# 中從文字產生條碼 – 完整步驟指南](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +說明如何使用 Aspose.BarCode for .NET 在 C# 中將文字轉換為條碼的完整流程。 + +### [如何在 C# 中讀取 PDF417 – 完整條碼閱讀器指南](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +說明如何使用 Aspose.BarCode for .NET 在 C# 中完整讀取 PDF417 條碼的步驟與範例。 + ## 常見問題 **Q: 緊湊式 PDF417 條碼最多能儲存多少資料?** @@ -112,4 +124,4 @@ A: 不需要外部字型;函式庫會在內部處理所有渲染。 {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hongkong/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/hongkong/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..33d332e0e --- /dev/null +++ b/barcode/hongkong/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-08-09 +description: Aspose 條碼範例示範如何使用 C# 條碼產生器建立具備完整中繼資料支援的 Macro PDF417。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: zh-hant +lastmod: 2026-08-09 +og_description: Aspose 條碼範例示範如何使用 C# 條碼產生器產生包含檔案 ID、段資料、時間戳記及其他中繼資料的 Macro PDF417 + 條碼。 +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Aspose 條碼範例 – 使用 C# 建立宏式 PDF417 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: Aspose 條碼範例:在 C# 中產生 Macro PDF417 +url: /zh-hant/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose 條碼範例:在 C# 中產生 Macro PDF417 + +如果您需要一個 **aspose barcode example** 來建立 Macro PDF417 條碼,本指南將示範如何使用 **barcode generator C#** 完成。您將看到所有必需的設定,從基本尺寸到完整的 Macro PDF417 中繼資料欄位,最終會得到一個可供後續處理的 PNG 圖片。 + +本教學涵蓋完整工作流程,說明每個參數的重要性,並提供可直接執行的程式碼範例。無需外部參考;您只要複製程式碼、調整數值,即可立即執行。 + +## 前置條件 + +- .NET 6.0(或更新版本)已安裝 +- Visual Studio 2022 或任何相容 C# 的 IDE +- 有效的 **Aspose.BarCode for .NET** 授權(此範例可使用免費試用版) + +將 Aspose.BarCode NuGet 套件加入您的專案: + +```bash +dotnet add package Aspose.BarCode +``` + +## 步驟 1:建立 barcode generator C# 實例 + +第一步是使用 `EncodeTypes.MacroPdf417` 列舉值以及您想要編碼的文字來實例化 `BarcodeGenerator`。文字可以包含 Unicode 字元,函式庫會自動處理。 + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*為什麼這很重要*:`EncodeTypes.MacroPdf417` 告訴引擎產生 Macro PDF417 符號,支援分段資料與額外的檔案層級中繼資料。`using` 陳述式確保在儲存影像後釋放非受控資源。 + +## 步驟 2:定義條碼的基本外觀 + +Macro PDF417 條碼由方形模組組成。控制模組大小與欄位數會影響可讀性與檔案大小。 + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*為什麼這很重要*:`XDimension.Pixels` 決定視覺密度;2 像素的值在螢幕顯示時效果良好且保持影像小巧。調整欄位數以符合您的版面限制——欄位越多會產生較寬、較短的條碼。 + +## 步驟 3:設定 Macro PDF417 專屬中繼資料 + +Macro PDF417 在標準 PDF417 格式上加入欄位,使得可從多個條碼片段重建大型檔案。每個欄位皆為選填,但設定它們可展示 API 的完整功能。 + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*為什麼這很重要*: +- `MacroPdf417FileID` 連結屬於同一邏輯檔案的所有片段。 +- `MacroPdf417SegmentID` 與 `MacroPdf417SegmentsCount` 讓解碼器能正確重新排序片段。 +- `MacroPdf417Checksum` 提供快速完整性檢查,無需解碼整個有效負載。 +- `MacroPdf417FileSize` 與 `MacroPdf417TimeStamp` 讓下游系統驗證重建檔案是否與原始檔案相符。 +- `MacroPdf417Addressee` / `MacroPdf417Sender` 在物流或文件交換情境中很有用。 +- 將 `MacroPdf417Terminator` 設為 `Set` 表示此條碼為最後一段,簡化重建演算法。 + +## 步驟 4:儲存產生的條碼影像 + +最後,將條碼寫入 PNG 檔案。您可以選擇任何支援的格式(`Png`、`Jpeg`、`Bmp`、`Gif`、`Tiff`)。 + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*為什麼這很重要*:PNG 保留無損像素資料,確保掃描器讀取您設定的精確模組圖樣。變更格式可能會影響視覺品質與檔案大小。 + +### 預期輸出 + +執行完整程式會產生名為 **ExtPDF417Meta.png** 的檔案。開啟影像會看到一個矩形的 Macro PDF417 條碼,編碼了文字 “Åspóse.Barcóde©”,且視覺密度符合您設定的 2 像素 X 維度。使用相容 PDF417 的讀取器掃描此影像,可返回第 3 步中定義的所有中繼資料欄位。 + +## 完整可執行範例 + +將以下程式碼複製到新的主控台專案(`dotnet new console`),並將 `YOUR_DIRECTORY` 替換為您機器上存在的絕對或相對路徑。 + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +執行程式(`dotnet run`)。執行完畢後,確認 PNG 檔案出現在您指定的位置。使用任何支援 Macro PDF417 的條碼讀取應用程式,確認中繼資料已正確嵌入。 + +## 常見變化與邊緣案例 + +- **不同的影像格式**:如果下游系統偏好其他格式,將 `BarCodeImageFormat.Png` 替換為 `Jpeg`、`Bmp` 或 `Tiff`。 +- **變更模組大小**:較大的 `XDimension.Pixels` 數值可提升低解析度掃描器的掃描可靠性,但會增加影像大小。 +- **多段式**:若要產生多段式檔案,產生一系列條碼,為每個條碼遞增 `MacroPdf417SegmentID`,且保持 `MacroPdf417FileID` 不變。只有最後一段應設定 `MacroPdf417Terminator`。 +- **Unicode 支援**:產生器會自動編碼 Unicode 字元;若從外部檔案讀取,請確保來源字串使用 UTF‑8 編碼。 +- **錯誤處理**:將 `using` 區塊包在 try‑catch 中,以捕捉 `BarCodeException`,處理無效參數(例如欄位數超出範圍)。 + +## 專業提示 + +- **效能**:在大量產生設定相同的條碼時,重複使用單一 `BarcodeGenerator` 實例;僅在儲存之間變更 `CodeText` 屬性。 +- **檔案大小估算**:`MacroPdf417FileSize` 欄位應與原始有效負載的位元組數相符;不符可能導致下游驗證失敗。 +- **測試**:使用 Aspose 內建的解碼器 (`BarCodeReader`) 以及第三方掃描器驗證產生的條碼,以確保相容性。 + +## 結論 + +這個 **aspose barcode example + +## 接下來該學什麼? + +以下教學涵蓋與本指南示範技術密切相關的主題。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助您精通其他 API 功能,並在自己的專案中探索替代實作方式。 + +- [如何使用 Aspose.BarCode 建立條碼 – Compact PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [如何使用 Aspose.BarCode for .NET 為 Code 16K 建立條碼靜區](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [如何使用 Aspose.BarCode for .NET 為 ITF-14 建立條碼靜區](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hongkong/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/hongkong/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..9813308f8 --- /dev/null +++ b/barcode/hongkong/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Generate barcode from text in C# with Aspose.BarCode. Learn how to generate + barcode, handle special characters, and create PDF417 barcode C# quickly. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: zh-hant +lastmod: 2026-08-09 +og_description: 使用 Aspose.BarCode 在 C# 中從文字產生條碼。本教學示範如何產生條碼、支援特殊字元,並以完整程式碼建立 PDF417 + 條碼(C#)。 +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: 使用 C# 從文字生成條碼 – 快速逐步指南 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: 在 C# 中從文字產生條碼 – 完整逐步指南 +url: /zh-hant/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 於 C# 產生文字條碼 – 完整步驟指南 + +如果您需要在 .NET 應用程式中 **從文字產生條碼**,本指南將帶您一步步完成整個流程。您將學會如何產生條碼、處理特殊字元,並建立一個可直接使用的 PDF417 條碼 C# 實作。 + +從文字產生條碼是庫存系統、票券平台與文件工作流程的常見需求。完成本教學後,您將擁有一個可執行的 C# 主控台應用程式,使用 Aspose.BarCode 產生 MicroPdf417 PNG 圖片。無需外部服務,且程式碼能正確處理如 “Å”、 “©”、 “é” 等 Unicode 字元。 + +## 前置條件 + +- .NET 6.0 SDK 或更新版本(程式碼同樣支援 .NET Core 3.1 與 .NET Framework 4.7+) +- Visual Studio 2022(或任何支援 C# 的 IDE) +- **Aspose.BarCode for .NET** NuGet 套件 + ```bash + dotnet add package Aspose.BarCode + ``` +- 基本的 C# 語法知識 + +## 從文字產生條碼 – 設定產生器 + +第一步是建立一個 `BarcodeGenerator` 實例,告訴它您想使用哪種 **條碼編碼類型**。本教學使用 `EncodeTypes.MicroPdf417`,這是 PDF417 的緊湊變種,適合短資料字串。 + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**為什麼這樣寫會有效:** +- `EncodeTypes.MicroPdf417` 讓函式庫使用 PDF417 系列,滿足 **create pdf417 barcode c#** 的需求。 +- 建構子直接接受原始文字,這正是 **generate barcode from text** 的核心。 +- 內建 Unicode 支援,像 “Å” 與 “©” 之類的字元會正確編碼,解決 **barcode with special characters** 的問題。 + +## 如何產生含特殊字元的條碼 + +當資料包含非 ASCII 符號時,必須確保產生器使用 UTF‑8 編碼。Aspose.BarCode 會自動偵測 Unicode,但若遇到問題,可明確設定文字編碼: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +在呼叫 `ConfigureGenerator` 之前加入此行,可保證 **barcode with special characters** 在任何平台上皆能正確呈現。 + +### 實用小技巧 +如果輸出看起來亂碼,請確認條碼渲染器使用的字型支援所需字形。您可以透過以下方式嵌入自訂 TrueType 字型: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## 可選的條碼編碼類型 + +Aspose.BarCode 支援數十種 **barcode encode types**,每種皆適用於不同情境: + +| Encode type | Typical use case | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | Shipping labels, inventory | +| `EncodeTypes.QR` | Mobile payments, URLs | +| `EncodeTypes.Pdf417` | Driver’s licenses, boarding passes | +| `EncodeTypes.MicroPdf417` | Small data payloads, limited space | +| `EncodeTypes.DataMatrix` | Tiny items, high data density | + +只要在建構子中換成其他 enum 值,即可變更編碼類型: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +此彈性讓您在 IDE 內即可回答 **barcode encode types** 的相關問題。 + +## 建立 PDF417 條碼 C# – 最後步驟與驗證 + +完成產生器設定後,**create pdf417 barcode c#** 的最後一步是儲存影像並確認結果。 + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +執行程式 (`dotnet run`) 後,您應會在主控台看到類似以下訊息: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +開啟 PNG 檔案,即可看到清晰的 MicroPdf417 條碼,編碼內容為 “Åspóse.Barcóde©”。使用手機條碼掃描器(例如 ZXing)掃描後,會回傳原始文字,證明 **generate barcode from text** 即使含特殊字元亦能正常運作。 + +### 邊緣案例:極長文字 + +MicroPdf417 的最大資料容量為 1 KB。若輸入超過此上限,函式庫會拋出 `ArgumentException`。可使用以下方式優雅處理: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +若需更大負載,請改用完整的 `EncodeTypes.Pdf417` 或 `EncodeTypes.DataMatrix`。 + +## 常見陷阱與避免方式 + +| Issue | Cause | Fix | +|-------------------------------------|-----------------------------------------|-----| +| 條碼顯示模糊 | XDimension 設定過低(例如 1 px) | 將 `XDimension.Pixels` 提升至 2‑3 px | +| Unicode 字元顯示為 `?` | 預設文字編碼為 ASCII | 設定 `TextEncoding = Encoding.UTF8` | +| 圖片檔案未建立 | 輸出目錄不存在 | 在 `Save` 前使用 `Directory.CreateDirectory` | +| 掃描器無法讀取條碼 | 短資料使用過多欄位 | 減少 `Pdf417.Columns`(例如 3‑4) | + +## 完整原始碼(可直接複製) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**預期輸出:** 在 `output` 資料夾內產生名為 `MicroPdf417.png` 的檔案,內含清晰的 MicroPdf417 條碼,編碼原始含特殊字元的字串。 + +## 結論 + +您現在已掌握如何在 C# 使用 Aspose.BarCode **generate barcode from text**、如何處理 **barcode with special characters**,以及如何 **create pdf417 barcode c#**,並能自行調整 **barcode encode types** 以產生 QR Code、Code128、DataMatrix 或其他支援的格式。 + +接下來,您可以探索以下主題,以深化條碼專業知識: + +- **批次產生條碼**(針對數千筆資料,使用 `Parallel.ForEach` 提升速度) +- 自訂顏色與在條碼內加入商標 +- 將條碼產生整合至 ASP.NET Core API,實現即時影像傳遞 +- 使用其他函式庫(如 ZXing.Net 或 IronBarcode)作為開源替代方案 + +歡迎嘗試不同的尺寸、欄位設定與編碼類型。祝開發順利,條碼掃描無礙! + +## 接下來您可以學習什麼? + +以下教學與本指南緊密相關,提供完整可執行的程式碼範例與逐步說明,協助您掌握更多 API 功能並探索其他實作方式: + +- [如何使用 Aspose.BarCode 建立條碼 – 緊湊 PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [如何使用 Aspose.BarCode 產生條碼 – Code 39 設定](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [如何產生條碼 – 一維條碼類型總覽](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hongkong/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/hongkong/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..bad65d352 --- /dev/null +++ b/barcode/hongkong/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-09 +description: 快速於 C# 產生 PDF417 條碼。學習如何使用 BarcodeGenerator API 以緊湊模式、欄位控制及 PNG 輸出產生 + PDF417。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: zh-hant +lastmod: 2026-08-09 +og_description: 使用 C# 產生 PDF417 條碼,提供簡潔範例。本指南說明如何設定緊湊模式、設定欄位,並將結果儲存為 PNG 圖像。 +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: 在 C# 中產生 PDF417 條碼 – 完整教學 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: 在 C# 中產生 PDF417 條碼 – 步驟說明指南 +url: /zh-hant/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中產生 PDF417 條碼 – 步驟指南 + +如果你需要在 .NET 應用程式中 **產生 PDF417 條碼**,本教學會完整示範如何操作。你將看到一個完整、可執行的程式,能建立緊湊的 PDF417 條碼、調整其尺寸,並將影像儲存為 PNG 檔案。 + +產生 PDF417 條碼是行動票證、庫存追蹤與文件安全等情境的常見需求。本指南涵蓋必要的設定選項、說明每個設定的意義,並提供實務使用的小技巧。 + +## 前置條件 + +在開始之前,請確保你已具備: + +* 已安裝 .NET 6.0 SDK 或更新版本 +* 具備 Visual Studio 2022 或 Visual Studio Code 等 C# IDE +* **Aspose.BarCode for .NET** NuGet 套件(版本 23.10 或更新) + +你可以使用以下 CLI 指令安裝套件: + +```bash +dotnet add package Aspose.BarCode +``` + +以下程式碼假設已正確引用套件,且你對輸出目錄具有寫入權限。 + +## Step 1: 設定專案並匯入命名空間 + +建立新的 Console 專案,並加入必要的 `using` 指令。這些命名空間會公開 `BarcodeGenerator` 類別與影像格式列舉。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**為什麼這很重要:** 匯入正確的命名空間可讓編譯器找到 `BarcodeGenerator` 類型與 `BarCodeImageFormat` 列舉。若缺少命名空間,會導致編譯錯誤,進而中斷條碼產生流程。 + +## Step 2: 使用 PDF417 編碼初始化 `BarcodeGenerator` + +`BarcodeGenerator` 建構子接受兩個參數:條碼符號系統 (`EncodeTypes.Pdf417`) 與要編碼的文字。PDF417 支援廣泛的字元,包括 Unicode 符號。 + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**說明:** +* `EncodeTypes.Pdf417` 告訴函式庫使用 PDF417 標準。 +* 範例文字包含重音字元與版權符號,以示範 Unicode 處理。 + +如果只需要編碼數字資料,可傳入純字串,例如 `"1234567890"`。 + +## Step 3: 調整 X‑dimension 以獲得更細緻的解析度 + +X‑dimension 控制單一條碼模組(最小的黑或白元素)的寬度。設定較小的像素值即可得到更高解析度的影像。 + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**為什麼要調整?** 預設的 3–4 像素 X‑dimension 在高 DPI 螢幕上可能顯得粗糙。將其降低至 **2 像素** 可在可讀性與檔案大小之間取得平衡,特別是之後啟用緊湊模式時。 + +## Step 4: 設定欄位數量 + +PDF417 允許你指定條碼應包含多少欄位。欄位較少會使條碼變窄但變高,欄位較多則產生較寬、較短的條碼。 + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**實用小技巧:** 若行動票證需放在窄標籤內,**3–5** 欄的設定相當合適。若資料量大且希望條碼較短,可增加欄位數。 + +## Step 5: 啟用緊湊模式以截除空白列 + +緊湊模式會移除條碼矩陣中不必要的列,減少整體影像大小,同時不會遺失編碼資料。 + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**何時使用:** 若條碼用於儲存或網路傳輸,緊湊模式可將 PNG 檔案縮小最多 30 %。但某些舊版掃描器可能不支援截除的 PDF417,請以目標硬體測試。 + +## Step 6: 將條碼儲存為 PNG 影像 + +選擇輸出路徑並呼叫 `Save`。`BarCodeImageFormat.Png` 列舉會產生適合大多數應用的無損影像。 + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**結果驗證:** 用任何影像檢視器開啟 PNG 檔案,你應該會看到密集且高對比度的條碼,且文字與範例相符。使用 PDF417 讀取器(如 ZXing 或手機應用)掃描影像,會回傳原始字串 `"Åspóse.Barcóde©"`。 + +![已產生的 PDF417 條碼影像(已儲存為 PNG)](compact-pdf417.png "在 C# 中產生的 PDF417 條碼") + +*上圖示範了本教學程式的最終輸出。* + +## 完整、可執行的範例 + +將所有步驟整合起來,以下是一個完整的 Console 程式,你可以直接複製、貼上並執行。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### 預期輸出 + +執行程式會印出: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +`CompactPdf417.png` 檔案包含一個緊湊的 PDF417 條碼,編碼了提供的 Unicode 字串。使用標準 PDF417 讀取器掃描影像,即可取得完全相同的文字。 + +## 常見變化與邊緣案例 + +| 情況 | 調整方式 | 原因 | +|-----------|------------|--------| +| **較長的資料負載**(例如 > 150 字元) | 將 `generator.Parameters.Barcode.Pdf417.Columns` 增加至 6‑8 | 更多欄位可防止條碼變得過高。 | +| **需要透明背景** | 使用 `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | 透明 PNG 在 UI 疊加時更易整合。 | +| **產生 JPEG 供網頁使用** | 將格式改為 `BarCodeImageFormat.Jpeg`,並可選擇設定 `ImageQuality` | JPEG 可減少檔案大小,但會犧牲無損品質。 | +| **處理 null 或空字串輸入** | 在建立產生器前先檢查輸入:`if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | 防止執行時例外,確保產生有意義的條碼。 | + +## 生產環境使用小技巧 + +* **例外處理:** 將產生邏輯包在 `try/catch` 區塊中,以記錄磁碟空間不足或參數無效等錯誤。 +* **效能:** 若大量產生條碼且設定相同,請重複使用同一個 `BarcodeGenerator` 實例;只在每次儲存前更新 `CodeText` 屬性。 +* **安全性:** 若編碼文字包含敏感資訊,建議在傳入產生器前先加密,掃描後再解密。 + +## 結論 + +你現在已掌握如何在 C# 中使用 Aspose.BarCode 套件 **產生 PDF417 條碼**,並能設定緊湊模式、調整欄位數量,最後將結果匯出為 PNG 影像。本教學從專案設定到邊緣案例處理,提供一套可直接投入使用的條碼解決方案。 + +接下來,可探索 **在 C# 中建立 QR Code**、**批次產生條碼**、以及 **將條碼掃描整合至行動應用** 等相關主題。這些皆建立在你剛剛熟悉的 `BarcodeGenerator` 基礎上。 + +祝編程愉快! + +## 接下來該學什麼? + +以下教學與本指南示範的技巧密切相關,並提供完整的程式範例與逐步說明,協助你掌握更多 API 功能,或在自己的專案中探索替代實作方式。 + +- [如何產生 PDF417 條碼 – 緊湊 PDF417 編碼](/barcode/english/net/compact-pdf417-encoding/) +- [如何建立條碼 – 使用 Aspose.BarCode 的緊湊 PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [如何使用 Aspose.BarCode for .NET 產生自訂長寬比的 Aztec 條碼](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hongkong/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/hongkong/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..5f850d649 --- /dev/null +++ b/barcode/hongkong/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-08-09 +description: 如何在 C# 中使用 BarCodeReader 讀取 PDF417。學習讀取條碼 PNG 檔案、處理多條條碼,並提取擴充的元資料。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: zh-hant +lastmod: 2026-08-09 +og_description: 如何在 C# 中使用 Aspose.BarCode 讀取 PDF417。本教學示範如何讀取條碼 PNG 檔案、在同一張圖片中處理多個條碼,以及取得擴充的 + PDF417 中繼資料。 +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: 如何在 C# 中讀取 PDF417 – 條碼閱讀器教學 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: 如何在 C# 中讀取 PDF417 – 完整條碼閱讀器指南 +url: /zh-hant/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 C# 中讀取 PDF417 – 完整條碼閱讀器指南 + +如果您需要在 .NET 應用程式中 **how to read PDF417**,本指南提供即用的解決方案。您將會看到如何讀取條碼 PNG、在同一張影像中處理多個條碼,以及提取許多掃描器隱藏的擴充 PDF417 欄位。 + +在物流、票務與文件管理領域,讀取 PDF417 條碼相當常見。完成本教學後,您即可解碼 Macro PDF417 影像、顯示所有結果,並在自訂業務邏輯中使用額外資訊(檔案 ID、段落計數、時間戳記等)。 + +## 前置條件 + +- .NET 6.0 或更新版本(此程式碼亦相容於 .NET Framework 4.7+) +- Visual Studio 2022 或任何 C# IDE +- **Aspose.BarCode for .NET**(免費試用或授權 NuGet 套件) +- 包含 Macro PDF417 條碼的 PNG 影像(範例檔案名稱為 `ExtPDF417Meta.png`) + +> **專業提示:** 使用 NuGet 主控台安裝此函式庫: +> `dotnet add package Aspose.BarCode` + +## 如何使用 BarCodeReader 在 C# 中讀取 PDF417 + +此解決方案的核心是 `BarCodeReader` 類別。它接受影像路徑以及一個 `DecodeType` 列舉,用以告訴引擎要尋找哪種符號。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### 為什麼這樣可行 + +- **`DecodeType.MacroPdf417`** 告訴讀取器尋找 Macro PDF417 變體,該變體會儲存您在第 4 步看到的額外欄位。 +- `using` 區塊會自動釋放讀取器,釋放檔案句柄。 +- `ReadBarCodes()` 會回傳 **所有** 符合請求類型的條碼,即使影像僅包含一個,也滿足 *read multiple barcodes* 的需求。 + +執行程式會輸出類似以下內容: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## 使用 C# 條碼讀取器讀取多個條碼 + +如果影像包含多個 Macro PDF417 符號(例如,掃描的頁面上有一批票券),相同的 `foreach` 迴圈會處理每一個。無需額外程式碼;讀取器會在內部彙總結果。 + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### 常見陷阱 + +- **影像格式:** 讀取器支援 PNG、JPEG、BMP 與 TIFF。若嘗試不支援的格式,將得到空集合。這也是教學強調 *read barcode PNG* 的原因。 +- **解析度:** 低解析度影像(< 300 dpi)可能導致遺漏段落。盡可能升級解析度或要求較高品質的掃描。 +- **Macro 標誌:** 若遺漏 `DecodeType.MacroPdf417`,引擎僅會解讀普通 PDF417,並捨棄擴充資料。需要 *read barcode extended* 欄位時,務必指定 macro 類型。 + +## 讀取條碼 PNG 檔案 – 最佳實踐 + +使用 PNG 檔案相當直接,因為此格式保留無損像素資料。以下是快速檢查清單: + +1. 在建立讀取器之前,先確認檔案是否存在。 + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. 僅在需要前置處理(旋轉、裁切)時才使用 `Image.FromFile`。`BarCodeReader` 可直接開啟檔案,避免額外的記憶體分配。 +3. 若 PNG 含有透明度,讀取器仍能正常運作,因為條碼是繪製在不透明像素上。 + +## 取得擴充 PDF417 中繼資料 + +`Extended.Pdf417` 物件會公開 PDF417 規範中定義的所有可選欄位。您可以將這些欄位映射至領域模型、儲存至資料庫,或用於驗證。 + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +填充模型: + + + +## 接下來該學什麼? + +以下教學涵蓋與本指南密切相關的主題,並以此為基礎延伸技術。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助您精通其他 API 功能,並在自己的專案中探索替代實作方式。 + +- [如何使用 Aspose.BarCode for .NET 讀取 DataMatrix 條碼](/barcode/english/net/datamatrix-barcode-reading/) +- [如何使用 Aspose.BarCode 建立條碼 – 緊湊型 PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [讀取 DataMatrix 條碼 C# – 產生 DataMatrix 模式(自動)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hungarian/net/compact-pdf417-encoding/_index.md b/barcode/hungarian/net/compact-pdf417-encoding/_index.md index 17598f023..e3a45a814 100644 --- a/barcode/hungarian/net/compact-pdf417-encoding/_index.md +++ b/barcode/hungarian/net/compact-pdf417-encoding/_index.md @@ -84,22 +84,17 @@ Az alapok mellett itt van néhány gyakorlati tipp a munkafolyamat egyszerűsít ### [Compact PDF417 vonalkódok létrehozása](./compact-pdf417-basic-configuration/) Ismerje meg, hogyan generáljon Compact PDF417 vonalkódokat az Aspose.BarCode for .NET használatával. Átfogó útmutató lépésről‑lépésre utasításokkal és kódrészletekkel. -## Gyakran Ismételt Kérdések +### [Aspose vonalkód példa: Macro PDF417 generálása C#-ban](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Ismerje meg, hogyan generáljon Macro PDF417 vonalkódot C#-ban az Aspose.BarCode for .NET segítségével. -**Q: Mi a maximális adatmennyiség, amelyet egy Compact PDF417 vonalkódban tárolhatok?** -A: Ez a hibajavítási szinttől és a karakterkészlettől függ, de általában több kilobájt adat is kódolható. +### [PDF417 vonalkód generálása C#‑ban – lépésről‑lépésre útmutató](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Ismerje meg, hogyan hozhat létre PDF417 vonalkódot C#‑ban az Aspose.BarCode for .NET segítségével. -**Q: Hogyan különbözik a PDF417 hibajavítása más vonalkódtípusokétól?** -A: A PDF417 Reed‑Solomon kódokat használ, lehetővé téve egy 0‑tól (nincs javítás) 8‑ig (magas redundancia) terjedő szint választását, ami finomhangolt megbízhatóság‑szabályozást biztosít. +### [Vonalkód generálása szövegből C#‑ban – teljes lépésről‑lépésre útmutató](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Ismerje meg, hogyan hozhat létre vonalkódot szöveges adatból C#‑ban az Aspose.BarCode for .NET segítségével. -**Q: Generálhatok-e Compact PDF417 vonalkódot egy .NET Core konzolalkalmazásban?** -A: Igen. Az Aspose.BarCode for .NET teljes mértékben támogatja a .NET Core 3.1-et és az azt követő verziókat. - -**Q: Lehet-e testreszabni a vonalkód előtér és háttér színeit?** -A: Teljes mértékben. Használja a `ForeColor` és `BackColor` tulajdonságokat a generátoron, hogy megfeleljenek az UI témájának. - -**Q: Szükséges-e további betűtípusokat vagy erőforrásokat telepíteni?** -A: Nem szükséges külső betűtípus; a könyvtár minden megjelenítést belsőleg kezel. +### [Hogyan olvassuk be a PDF417-et C#‑ban – teljes vonalkód-olvasó útmutató](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +Ismerje meg, hogyan olvassa be a PDF417 vonalkódot C#‑ban az Aspose.BarCode for .NET segítségével. --- @@ -112,4 +107,4 @@ A: Nem szükséges külső betűtípus; a könyvtár minden megjelenítést bels {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hungarian/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/hungarian/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..18e9e55e3 --- /dev/null +++ b/barcode/hungarian/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-09 +description: Aspose vonalkód példa, amely bemutatja, hogyan használjuk a C# vonalkódgenerátort + Macro PDF417 teljes metaadat‑támogatással történő létrehozásához. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: hu +lastmod: 2026-08-09 +og_description: Az Aspose vonalkód példa bemutatja, hogyan használható egy C#-os vonalkód-generátor + a Macro PDF417 vonalkód előállításához, amely tartalmazza a fájlazonosítót, a szegmensadatokat, + az időbélyeget és egyéb metaadatokat. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Aspose vonalkód példa – Macro PDF417 létrehozása C#‑ban +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Aspose vonalkód példa: Macro PDF417 generálása C#‑ban' +url: /hu/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose vonalkód példa: Macro PDF417 generálása C#-ban + +Ha **aspose barcode példára** van szükséged, amely Macro PDF417 vonalkódot hoz létre, ez az útmutató megmutatja, hogyan teheted ezt **barcode generator C#** segítségével. Meg fogod látni az összes szükséges beállítást, az alapméretektől a Macro PDF417 metaadatmezők teljes készletéig, és egy PNG képet kapsz, amely készen áll a további feldolgozásra. + +Az oktatóanyag lefedi a teljes munkafolyamatot, elmagyarázza, miért fontos minden paraméter, és egy azonnal futtatható kódmintát biztosít. Külső hivatkozásokra nincs szükség; a kódot másolhatod, módosíthatod az értékeket, és azonnal futtathatod. + +## Előfeltételek + +- .NET 6.0 (vagy újabb) telepítve +- Visual Studio 2022 vagy bármely C#‑kompatibilis IDE +- Érvényes licenc a **Aspose.BarCode for .NET**-hez (az ingyenes próba verzió is működik ebben a példában) + +Add the Aspose.BarCode NuGet package to your project: + +```bash +dotnet add package Aspose.BarCode +``` + +## 1. lépés: A barcode generator C# példány létrehozása + +Az első lépés a `BarcodeGenerator` példányosítása a `EncodeTypes.MacroPdf417` enum értékkel és a kódolni kívánt szöveggel. A szöveg tartalmazhat Unicode karaktereket, amelyeket a könyvtár automatikusan kezel. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Miért fontos*: `EncodeTypes.MacroPdf417` azt mondja a motornak, hogy Macro PDF417 szimbólumot állítson elő, amely támogatja a szegmentált adatokat és a további fájlszintű metaadatokat. A `using` utasítás garantálja, hogy a nem kezelt erőforrások felszabadulnak a kép mentése után. + +## 2. lépés: Alapvető vonalkód megjelenés meghatározása + +A Macro PDF417 vonalkód négyzetes modulokból áll. A modulméret és az oszlopszám szabályozása befolyásolja az olvashatóságot és a fájlméretet. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Miért fontos*: `XDimension.Pixels` meghatározza a vizuális sűrűséget; a 2 pixel érték jól működik a képernyőn való megjelenítéshez, miközben a képet kicsi tartja. Állítsd be az oszlopszámot a layout korlátaidhoz – több oszlop szélesebb, rövidebb vonalkódot eredményez. + +## 3. lépés: Macro PDF417 specifikus metaadatok beállítása + +A Macro PDF417 kibővíti a standard PDF417 formátumot olyan mezőkkel, amelyek lehetővé teszik nagy fájlok rekonstrukcióját több vonalkódszegmensből. Minden mező opcionális, de azok beállítása bemutatja az API teljes képességeit. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Miért fontos*: +- `MacroPdf417FileID` összekapcsolja az összes szegmenst, amely ugyanahhoz a logikai fájlhoz tartozik. +- `MacroPdf417SegmentID` és `MacroPdf417SegmentsCount` lehetővé teszi a dekóder számára, hogy a töredékeket helyesen újrarendezze. +- `MacroPdf417Checksum` gyors integritás-ellenőrzést biztosít a teljes payload dekódolása nélkül. +- `MacroPdf417FileSize` és `MacroPdf417TimeStamp` lehetővé teszik a downstream rendszerek számára, hogy ellenőrizzék, a rekonstruált fájl megegyezik-e az eredetivel. +- `MacroPdf417Addressee` / `MacroPdf417Sender` hasznosak logisztikai vagy dokumentumcsere helyzetekben. +- A `MacroPdf417Terminator` `Set` értékre állítása jelzi, hogy ez a vonalkód az utolsó szegmens, ami egyszerűsíti a rekonstrukciós algoritmust. + +## 4. lépés: A generált vonalkód kép mentése + +Végül írd a vonalkódot egy PNG fájlba. Bármely támogatott formátumot választhatod (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Miért fontos*: A PNG veszteségmentes pixel adatokat őriz, biztosítva, hogy a szkennerek pontosan a beállított modulmintát olvassák. A formátum megváltoztatása befolyásolhatja a vizuális minőséget és a fájlméretet. + +### Várható kimenet + +A teljes program futtatása létrehoz egy **ExtPDF417Meta.png** nevű fájlt. A kép megnyitása egy téglalap alakú Macro PDF417 vonalkódot mutat, amely a “Åspóse.Barcóde©” szöveget kódolja, és a vizuális sűrűség megegyezik a beállított 2‑pixel X dimenzióval. A képet PDF417‑kompatibilis olvasóval beolvasva visszakapja a 3. lépésben definiált összes metaadatmezőt. + +## Teljes működő példa + +Másold az alábbi kódot egy új konzolos projektbe (`dotnet new console`), és cseréld le a `YOUR_DIRECTORY`-t egy abszolút vagy relatív útvonalra, amely a gépeden létezik. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Futtasd a programot (`dotnet run`). A végrehajtás után ellenőrizd, hogy a PNG fájl megjelenik-e a megadott helyen. Használj bármilyen vonalkód‑olvasó alkalmazást, amely támogatja a Macro PDF417-et, hogy megerősítsd, a metaadatok helyesen be vannak ágyazva. + +## Gyakori változatok és szélsőséges esetek + +- **Különböző képformátumok**: Cseréld le a `BarCodeImageFormat.Png`-t `Jpeg`, `Bmp` vagy `Tiff`-re, ha a downstream rendszer más formátumot részesít előnyben. +- **Modulméret módosítása**: Nagyobb `XDimension.Pixels` értékek javítják a beolvasás megbízhatóságát alacsony felbontású szkennereknél, de növelik a kép méretét. +- **Több szegmens**: Több szegmensből álló fájl előállításához generálj egy sor vonalkódot, minden egyeshez növeld a `MacroPdf417SegmentID`-t, és tartsd állandóan a `MacroPdf417FileID`-t. Csak az utolsó szegmensnek kell beállítania a `MacroPdf417Terminator`-t. +- **Unicode támogatás**: A generátor automatikusan kódolja a Unicode karaktereket; győződj meg róla, hogy a forráskarakterlánc UTF‑8 kódolást használ, ha külső fájlból olvasod. +- **Hibakezelés**: Tedd a `using` blokkot try‑catch-be, hogy elkapd a `BarCodeException`-t érvénytelen paraméterek esetén (pl. az oszlopszám tartományon kívül). + +## Pro tippek + +- **Teljesítmény**: Használj egyetlen `BarcodeGenerator` példányt sok vonalkód létrehozásához ugyanazzal a beállítással; csak a `CodeText` tulajdonságot változtasd a mentések között. +- **Fájlméret becslés**: A `MacroPdf417FileSize` mezőnek meg kell egyeznie az eredeti payload bájt számával; a eltérések downstream validációs hibákat okozhatnak. +- **Tesztelés**: Validáld a generált vonalkódokat az Aspose beépített dekóderével (`BarCodeReader`) és egy harmadik fél szkennerrel is, hogy biztosítsd az interoperabilitást. + +## Összegzés + +Ez az **aspose barcode példa** + +## Mit kellene legközelebb megtanulnod? + +A következő oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljesen működő kódpéldákat tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsen elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Hogyan hozzunk létre vonalkódot – Compact PDF417 Aspose.BarCode használatával](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Hogyan hozzunk létre vonalkód csendes zónát a Code 16K-hoz az Aspose.BarCode for .NET használatával](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [Hogyan hozzunk létre vonalkód csendes zónát ITF-14-hez az Aspose.BarCode for .NET használatával](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hungarian/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/hungarian/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..0612bc709 --- /dev/null +++ b/barcode/hungarian/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-08-09 +description: Készítsen vonalkódot szövegből C#-ban az Aspose.BarCode segítségével. + Tanulja meg, hogyan generáljon vonalkódot, kezelje a speciális karaktereket, és + gyorsan hozzon létre PDF417 vonalkódot C#-ban. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: hu +lastmod: 2026-08-09 +og_description: Készítsen vonalkódot szövegből C#-ban az Aspose.BarCode használatával. + Ez az útmutató bemutatja, hogyan generáljon vonalkódot, támogassa a speciális karaktereket, + és hozza létre a PDF417 vonalkódot C#-ban a teljes kóddal. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Vonalkód generálása szövegből C#-ban – gyors lépésről‑lépésre útmutató +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Vonalkód generálása szövegből C#‑ban – teljes lépésről‑lépésre útmutató +url: /hu/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vonalkód generálása szövegből C#‑ban – teljes lépésről‑lépésre útmutató + +Ha .NET alkalmazásban **szövegből kell vonalkódot generálni**, ez az útmutató végigvezeti a teljes folyamaton. Megmutatjuk, hogyan generálj vonalkódot, kezeld a speciális karaktereket, és hozz létre egy PDF417 vonalkód C# implementációt, amely azonnal működik. + +A szövegből történő vonalkód generálása gyakori igény készletkezelő rendszerekben, jegykiadási platformokon és dokumentumfolyamatokban. A tutorial végére egy futtatható C# konzolalkalmazást kapsz, amely MicroPdf417 PNG képet hoz létre az Aspose.BarCode használatával. Nem szükséges külső szolgáltatás, és a kód kezeli az Unicode karaktereket, például a „Å”, „©” és „é” karaktereket. + +## Előfeltételek + +- .NET 6.0 SDK vagy újabb (a kód .NET Core 3.1‑el és .NET Framework 4.7+‑tel is működik) +- Visual Studio 2022 (vagy bármely C#‑ot támogató IDE) +- **Aspose.BarCode for .NET** NuGet csomag + ```bash + dotnet add package Aspose.BarCode + ``` +- Alapvető C# szintaxis ismeret + +## Vonalkód generálása szövegből – a generátor beállítása + +Az első lépés egy `BarcodeGenerator` példány létrehozása, amely tudja, mely **vonalkód kódolási típust** szeretnéd használni. Ebben a tutorialban a `EncodeTypes.MicroPdf417`‑et használjuk, amely a PDF417 egy kompakt változata, rövid adatkarakterláncokhoz alkalmas. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Miért működik:** +- `EncodeTypes.MicroPdf417` azt mondja a könyvtárnak, hogy a PDF417 családot használja, ezzel teljesítve a **create pdf417 barcode c#** követelményt. +- A konstruktor a nyers szöveget kapja, ami a **generate barcode from text** lényege. +- Az Unicode támogatás beépített, így a „Å” és „©” karakterek helyesen kódolódnak, megoldva a **barcode with special characters** problémát. + +## Hogyan generáljunk vonalkódot speciális karakterekkel + +Ha az adataid nem‑ASCII szimbólumokat tartalmaznak, biztosítanod kell, hogy a generátor UTF‑8 kódolást használjon. Az Aspose.BarCode automatikusan felismeri az Unicode‑t, de ha problémába ütközöl, kifejezetten beállíthatod a szövegkódolást: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Ennek a sor hozzáadása a `ConfigureGenerator` előtt garantálja, hogy a **barcode with special characters** minden platformon helyesen jelenik meg. + +### Gyakorlati tipp +Ha a kimenet torzultnak tűnik, ellenőrizd, hogy a vonalkód renderelő által használt betűtípus támogatja-e a szükséges glifeket. Egy egyedi TrueType betűtípust a következő módon ágyazhatsz be: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Választható vonalkód kódolási típusok + +Az Aspose.BarCode több tucat **vonalkód kódolási típust** támogat, amelyek mindegyike különböző felhasználási esetekhez alkalmas: + +| Kódolási típus | Tipikus felhasználási eset | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | Szállítási címkék, készletkezelés | +| `EncodeTypes.QR` | Mobil fizetések, URL-ek | +| `EncodeTypes.Pdf417` | Jogosítványok, beszállókártyák | +| `EncodeTypes.MicroPdf417` | Kis adatcsomagok, korlátozott hely | +| `EncodeTypes.DataMatrix` | Apró tárgyak, nagy adat sűrűség | + +A kódolási típus megváltoztatása olyan egyszerű, mint az enum érték cseréje a konstruktorban: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Ez a rugalmasság lehetővé teszi, hogy a **barcode encode types** kérdésekre a fejlesztői környezet elhagyása nélkül válaszolj. + +## PDF417 vonalkód létrehozása C#‑ban – végső lépések és ellenőrzés + +A generátor beállítása után a **create pdf417 barcode c#** utolsó része a kép mentése és az eredmény ellenőrzése. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Futtasd a programot (`dotnet run`), és egy a következőhöz hasonló konzolüzenetet kell látnod: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Nyisd meg a PNG fájlt; egy tiszta MicroPdf417 vonalkódot látsz, amely a „Åspóse.Barcóde©” karakterláncot kódolja. Mobil vonalkódolvasóval (pl. ZXing) beolvasva visszaadja az eredeti szöveget, bizonyítva, hogy a **generate barcode from text** speciális karakterekkel is működik. + +### Szélsőséges eset: nagyon hosszú szöveg + +A MicroPdf417 maximális adatkapacitása 1 KB. Ha a bemenet meghaladja ezt a határt, a könyvtár `ArgumentException`‑t dob. Ennek kifogástalan kezelése: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Nagyobb adatcsomagok esetén válts a teljes `EncodeTypes.Pdf417` vagy `EncodeTypes.DataMatrix` típusra. + +## Gyakori buktatók és hogyan kerüld el őket + +| Probléma | Ok | Megoldás | +|----------------------------------------|--------------------------------------|----------| +| A vonalkód elmosódott | Az XDimension túl alacsony (pl. 1 px) | `XDimension.Pixels` növelése 2‑3 px-re | +| Az Unicode karakterek `?`-ra változnak | Az alapértelmezett szövegkódolás ASCII | `TextEncoding = Encoding.UTF8` beállítása | +| A képfájl nem jön létre | A kimeneti könyvtár nem létezik | `Directory.CreateDirectory` használata a `Save` előtt | +| A szkenner nem tudja beolvasni a vonalkódot | Túl sok oszlop rövid adat esetén | `Pdf417.Columns` csökkentése (pl. 3‑4) | + +## Teljes forráskód (kész a másoláshoz) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Várható kimenet:** egy `MicroPdf417.png` nevű fájl az `output` mappában, amely egy tiszta MicroPdf417 vonalkódot tartalmaz, és a speciális karaktereket is tartalmazó eredeti karakterláncot kódolja. + +## Következtetés + +Most már tudod, hogyan **generate barcode from text** C#‑ban az Aspose.BarCode használatával, hogyan kezeld a **barcode with special characters** esetet, és hogyan **create pdf417 barcode c#** teljes kódolási beállítási kontrollal. A **barcode encode types** módosításával QR kódokat, Code128‑at, DataMatrix‑t vagy bármely más támogatott formátumot tudsz előállítani. + +Ezután fedezd fel a következő témákat, hogy mélyítsd a vonalkód tudásodat: +- **How to generate barcode** kötegelt módon több ezer rekordhoz (használd a `Parallel.ForEach`‑t a sebességért) +- Színek testreszabása és logók hozzáadása a vonalkódba +- Vonalkód generálás integrálása ASP.NET Core API‑kba valós idejű kép kiszolgáláshoz +- Más könyvtárak, például ZXing.Net vagy IronBarcode használata nyílt forráskódú alternatívaként + +Nyugodtan kísérletezz különböző méretekkel, oszlopbeállításokkal és kódolási típusokkal. Boldog kódolást, és legyenek alkalmazásaid hibátlanul olvashatóak! + +## Mit érdemes legközelebb megtanulni? + +A következő tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljes, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Hogyan hozzunk létre vonalkódot – Kompakt PDF417 az Aspose.BarCode‑dal](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Hogyan generáljunk vonalkódot – Code 39 konfiguráció az Aspose.BarCode‑dal](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Hogyan generáljunk vonalkódot – Egy-dimenziós vonalkód típusok](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hungarian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/hungarian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..0ea7f3fb6 --- /dev/null +++ b/barcode/hungarian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-08-09 +description: PDF417 vonalkód generálása C#-ban gyorsan. Tanulja meg, hogyan generáljon + PDF417-et kompakt móddal, oszlopvezérléssel és PNG kimenettel a BarcodeGenerator + API használatával. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: hu +lastmod: 2026-08-09 +og_description: PDF417 vonalkód generálása C#-ban egy tömör példával. Ez az útmutató + megmutatja, hogyan állítható be a kompakt mód, az oszlopok száma, és hogyan menthető + az eredmény PNG képként. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: PDF417 vonalkód generálása C#-ban – teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: PDF417 vonalkód generálása C#‑ban – lépésről‑lépésre útmutató +url: /hu/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF417 vonalkód generálása C#‑ban – lépésről‑lépésre útmutató + +Ha **PDF417 vonalkódot** kell generálnod egy .NET alkalmazásban, ez a tutorial pontosan megmutatja, hogyan teheted meg. Látni fogsz egy teljes, futtatható programot, amely egy kompakt PDF417 vonalkódot hoz létre, testreszabja a méretét, és PNG fájlként menti a képet. + +PDF417 vonalkód generálása gyakori igény a mobiljegyek, készletkövetés és dokumentumbiztonság terén. Ez az útmutató lefedi a lényeges konfigurációs beállításokat, elmagyarázza, miért fontos minden opció, és gyakorlati tippeket ad a valós használathoz. + +## Előkövetelmények + +* .NET 6.0 SDK vagy újabb telepítve +* Visual Studio 2022 vagy Visual Studio Code C# IDE +* A **Aspose.BarCode for .NET** NuGet csomag (23.10 vagy újabb verzió) + +A csomagot a következő CLI paranccsal telepítheted: + +```bash +dotnet add package Aspose.BarCode +``` + +Az alábbi kód feltételezi, hogy a csomag hivatkozásként van megadva, és írási jogosultsággal rendelkezel a kimeneti könyvtárban. + +## 1. lépés: A projekt beállítása és a névterek importálása + +Hozz létre egy új konzolos projektet, és add hozzá a szükséges `using` direktívákat. Ezek a névterek teszik elérhetővé a `BarcodeGenerator` osztályt és a képformátum felsorolást. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Miért fontos:** A megfelelő névterek importálása biztosítja, hogy a fordító megtalálja a `BarcodeGenerator` típust és a `BarCodeImageFormat` enumot. Egy hiányzó névtér fordítási hibát eredményez, ami leállítja a vonalkód generálási folyamatot. + +## 2. lépés: A `BarcodeGenerator` inicializálása PDF417 kódolással + +`BarcodeGenerator` konstruktor két argumentumot kap: a vonalkód szimbólumát (`EncodeTypes.Pdf417`) és a kódolni kívánt szöveget. A PDF417 széles karakterkészletet támogat, beleértve az Unicode szimbólumokat. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Magyarázat:** +* `EncodeTypes.Pdf417` azt mondja a könyvtárnak, hogy a PDF417 szabványt használja. +* A minta szöveg ékezetes karaktereket és egy szerzői jogi szimbólumot tartalmaz, hogy bemutassa az Unicode kezelését. + +Ha csak numerikus adatot kell kódolnod, átadhatsz egy egyszerű karakterláncot, például `"1234567890"`. + +## 3. lépés: Az X‑dimenzió beállítása a finomabb felbontásért + +Az X‑dimenzió szabályozza egyetlen vonalkód modul (a legkisebb fekete vagy fehér elem) szélességét. Egy kisebb pixelérték beállítása magasabb felbontású képet eredményez. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Miért állítsuk be?** Az alapértelmezett 3–4 pixel X‑dimenzió durva vonalkódot eredményezhet magas DPI‑s képernyőkön. **2 pixel** beállítása egyensúlyt teremt az olvashatóság és a fájlméret között, különösen ha később kompakt módot aktiválsz. + +## 4. lépés: Az oszlopok számának beállítása + +A PDF417 lehetővé teszi, hogy meghatározd, hány oszlopot tartalmazzon a vonalkód. Kevesebb oszlop szűkebb, de magasabb vonalkódot eredményez, míg több oszlop szélesebb, alacsonyabb vonalkódot hoz létre. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Gyakorlati tipp:** Mobiljegyekhez, amelyeknek szűk címkén kell elférniük, a **3–5** oszlopos szám jól működik. Növeld az oszlopok számát, ha sok adatod van, és rövidebb vonalkódot szeretnél. + +## 5. lépés: Kompakt mód engedélyezése az üres sorok levágásához + +A kompakt mód eltávolítja a felesleges sorokat a vonalkód mátrixból, ezáltal csökkentve a teljes kép méretét anélkül, hogy elveszítené a kódolt adatokat. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Mikor használjuk:** Ha vonalkódokat tárolásra vagy hálózati átvitelre generálsz, a kompakt mód akár 30 %-kal is csökkentheti a PNG fájl méretét. Azonban egyes régi szkennerek nem támogatják a levágott PDF417‑t; teszteld a célhardverrel. + +## 6. lépés: A vonalkód mentése PNG képként + +Válassz egy kimeneti útvonalat, és hívd meg a `Save` metódust. A `BarCodeImageFormat.Png` felsorolás veszteségmentes képet hoz létre, amely a legtöbb alkalmazáshoz megfelelő. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Eredmény ellenőrzése:** Nyisd meg a PNG fájlt bármely képnézőben. Sűrű, nagy kontrasztú vonalkódot kell látnod, amely megfelel a minta szövegnek. A PDF417 olvasóval (pl. ZXing vagy okostelefon‑alkalmazás) beolvasva visszakapod az eredeti `"Åspóse.Barcóde©"` karakterláncot. + +![Generált PDF417 vonalkód kép PNG‑ként mentve](compact-pdf417.png "Generált PDF417 vonalkód C#‑ban") + +*A fenti kép a tutorial kódjának végső kimenetét mutatja.* + +## Teljes, futtatható példa + +Az összes részt összeillesztve itt egy teljes konzolos program, amelyet másolhatsz, beilleszthetsz és futtathatsz. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Várt kimenet + +A program futtatása a következőt írja ki: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +A `CompactPdf417.png` fájl egy kompakt PDF417 vonalkódot tartalmaz, amely a megadott Unicode karakterláncot kódolja. A képet egy szabványos PDF417 olvasóval beolvasva a pontos szöveget adja vissza. + +## Gyakori változatok és szélső esetek + +| Helyzet | Módosítás | Ok | +|-----------|------------|--------| +| **Hosszabb adatbemenet** (pl. > 150 karakter) | Növeld a `generator.Parameters.Barcode.Pdf417.Columns` értékét 6‑8‑ra | Több oszlop megakadályozza, hogy a vonalkód túl magas legyen. | +| **Átlátszó háttér szükségessége** | Használd a `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | Az átlátszó PNG jobban illeszkedik UI rétegekbe. | +| **JPEG generálása webhez** | Változtasd a formátumot `BarCodeImageFormat.Jpeg`‑re, és opcionálisan állítsd be az `ImageQuality`‑t | A JPEG csökkenti a fájlméretet, de a veszteségmentes pontosság rovására. | +| **Null vagy üres bemenet kezelése** | Ellenőrizd a bemenetet a generátor létrehozása előtt: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Megakadályozza a futásidejű kivételeket és biztosítja a értelmes vonalkódokat. | + +## Tippek a termelésben való használathoz + +* **Kivételkezelés:** A generálási logikát `try/catch` blokkba helyezd, hogy naplózd a hibákat, például a nem elegendő lemezterületet vagy érvénytelen paramétereket. +* **Teljesítmény:** Használj egyetlen `BarcodeGenerator` példányt sok vonalkód generálásához azonos beállításokkal; csak a `CodeText` tulajdonságot frissítsd a mentések között. +* **Biztonság:** Ha a kódolt szöveg érzékeny információt tartalmaz, fontold meg a titkosítást a generátornak való átadás előtt, és a beolvasás után a visszafejtést. + +## Következtetés + +Most már tudod, hogyan **generálj PDF417 vonalkódot** C#‑ban az Aspose.BarCode könyvtárral, beállítsd a kompakt módot, szabályozd az oszlopszámot, és exportáld az eredményt PNG képként. Ez a tutorial minden lépést lefedett a projekt beállításától a szélső esetek kezeléséig, így egy kész megoldást kapsz vonalkód‑alapú alkalmazásokhoz. + +Ezután fedezd fel a kapcsolódó témákat, például **QR kódok létrehozása C#‑ban**, **tömeges vonalkód generálás**, és **vonalkód beolvasás integrálása mobilalkalmazásokba**. Mindegyik az általad most elsajátított `BarcodeGenerator` alapokra épül. + +Boldog kódolást! + +## Mit érdemes még megtanulni? + +Az alábbi tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljes, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy elsajátíthasd a további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Hogyan generáljunk PDF417 vonalkódokat – Kompakt PDF417 kódolás](/barcode/english/net/compact-pdf417-encoding/) +- [Hogyan hozzunk létre vonalkódot – Kompakt PDF417 az Aspose.BarCode‑dal](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Hogyan generáljunk Aztec vonalkódot egyedi képaránnyal az Aspose.BarCode for .NET használatával](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hungarian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/hungarian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..7335e41c6 --- /dev/null +++ b/barcode/hungarian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-09 +description: Hogyan olvassunk PDF417-et C#-ban a BarCodeReader használatával. Tanulja + meg, hogyan olvasson be vonalkód PNG-fájlokat, kezeljen több vonalkódot, és nyerjen + ki kiterjesztett metaadatokat. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: hu +lastmod: 2026-08-09 +og_description: Hogyan olvassuk be a PDF417-et C#-ban az Aspose.BarCode segítségével. + Ez az útmutató megmutatja, hogyan olvassunk be vonalkód PNG fájlokat, hogyan dolgozzunk + fel több vonalkódot egy képen, és hogyan nyerjünk ki kiterjesztett PDF417 metaadatokat. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: PDF417 olvasása C#‑ban – vonalkódolvasó bemutató +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Hogyan olvassuk a PDF417-et C#-ban – teljes vonalkódolvasó útmutató +url: /hu/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan olvassuk a PDF417-et C#‑ban – teljes vonalkódolvasó útmutató + +Ha **hogyan olvassuk a PDF417-et** egy .NET alkalmazásban, ez az útmutató egy azonnal futtatható megoldást nyújt. Megmutatjuk, hogyan olvassunk be egy vonalkód PNG‑t, hogyan dolgozzunk fel több vonalkódot egy képen, és hogyan nyerjük ki a kiterjesztett PDF417 mezőket, amelyeket sok szkenner elrejt. + +A PDF417 vonalkódok olvasása gyakori a logisztikában, jegykezelésben és dokumentumkezelésben. A tutorial végére képes leszel dekódolni egy Macro PDF417 képet, megjeleníteni minden eredményt, és felhasználni a további információkat (fájl‑azonosító, szegmens‑szám, időbélyegek stb.) a saját üzleti logikádban. + +## Előfeltételek + +- .NET 6.0 vagy újabb (a kód .NET Framework 4.7+‑vel is működik) +- Visual Studio 2022 vagy bármely C# IDE +- **Aspose.BarCode for .NET** (ingyenes próba vagy licencelt NuGet csomag) +- Egy PNG kép, amely Macro PDF417 vonalkódot tartalmaz (a minta fájl neve `ExtPDF417Meta.png`) + +> **Pro tipp:** Telepítsd a könyvtárat a NuGet konzollal: +> `dotnet add package Aspose.BarCode` + +## Hogyan olvassuk a PDF417-et a BarCodeReader-rel C#‑ban + +A megoldás központja a `BarCodeReader` osztály. Egy képfájlt és egy `DecodeType` enumot fogad, amely megmondja a motornak, melyik szimbólumot keresse. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Miért működik ez + +- **`DecodeType.MacroPdf417`** azt mondja az olvasónak, hogy a Macro PDF417 változatot keresse, amely a 4. lépésben látható extra mezőket tárolja. +- A `using` blokk automatikusan felszabadítja az olvasót, így a fájlkezelők is lezárulnak. +- A `ReadBarCodes()` **összes** olyan vonalkódot visszaad, amely megfelel a kért típusnak, ezáltal teljesíti a *több vonalkód olvasása* követelményt még akkor is, ha a kép csak egyet tartalmaz. + +A program futtatása hasonló kimenetet eredményez: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## C# vonalkódolvasó használata több vonalkód olvasásához + +Ha egy kép több Macro PDF417 szimbólumot tartalmaz (például egy beolvasott oldal, amely egy tételnyi jegyet tartalmaz), ugyanaz a `foreach` ciklus minden egyeset feldolgoz. Nem szükséges extra kód; az olvasó belsőleg aggregálja az eredményeket. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Gyakori buktatók + +- **Képformátum:** Az olvasó támogatja a PNG, JPEG, BMP és TIFF formátumokat. Ha olyan formátumot próbálsz, amelyet nem tud dekódolni, egy üres gyűjteményt kapsz. Ezért a tutorial a *vonalkód PNG olvasása*‑ra hívja fel a figyelmet. +- **Felbontás:** Alacsony felbontású képek (< 300 dpi) hiányzó szegmenseket eredményezhetnek. Lehetőség szerint növeld a felbontást vagy kérj jobb minőségű beolvasást. +- **Macro jelző:** A `DecodeType.MacroPdf417` elhagyása a motort egyszerű PDF417‑re korlátozza, és eldobja a kiterjesztett adatokat. Mindig add meg a macro típust, ha *kiterjesztett vonalkód mezőket* szeretnél olvasni. + +## Vonalkód PNG fájlok olvasása – legjobb gyakorlatok + +A PNG fájlokkal való munka egyszerű, mivel a formátum veszteségmentes pixeladatot őriz meg. Íme egy gyors ellenőrzőlista: + +1. Ellenőrizd, hogy a fájl létezik-e, mielőtt létrehoznád az olvasót. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Használd az `Image.FromFile`‑t csak akkor, ha előfeldolgozásra (forgatás, vágás) van szükség. A `BarCodeReader` közvetlenül megnyithatja a fájlt, így elkerülve a felesleges memóriafoglalást. +3. Ha a PNG átlátszóságot tartalmaz, az olvasó továbbra is működik, mivel a vonalkód átlátszatlan pixeleken jelenik meg. + +## Kiterjesztett PDF417 metaadatok elérése + +Az `Extended.Pdf417` objektum minden, a PDF417 specifikáció által definiált opcionális mezőt elérhetővé tesz. Ezeket a mezőket leképezheted egy domain modellre, tárolhatod adatbázisban, vagy felhasználhatod validációra. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +A modell feltöltése: + + + +## Mit érdemes még megtanulni? + +Az alábbi tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljes, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API‑funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [How to Read DataMatrix Barcodes with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Read DataMatrix barcode C# – Generate DataMatrix Mode (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/indonesian/net/compact-pdf417-encoding/_index.md b/barcode/indonesian/net/compact-pdf417-encoding/_index.md index e49f3f784..3d774d640 100644 --- a/barcode/indonesian/net/compact-pdf417-encoding/_index.md +++ b/barcode/indonesian/net/compact-pdf417-encoding/_index.md @@ -78,6 +78,18 @@ Aspose.BarCode memungkinkan Anda mengatur properti `Pdf417ErrorCorrectionLevel` ### [Creating Compact PDF417 Barcodes](./compact-pdf417-basic-configuration/) Pelajari cara menghasilkan barcode Compact PDF417 menggunakan Aspose.BarCode untuk .NET. Panduan komprehensif dengan instruksi langkah‑demi‑langkah dan contoh kode. +### [Contoh barcode Aspose: menghasilkan Macro PDF417 dalam C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Contoh kode C# untuk membuat barcode Macro PDF417 menggunakan Aspose.BarCode. + +### [Menghasilkan barcode PDF417 di C# – panduan langkah‑demi‑langkah](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Panduan lengkap untuk membuat barcode PDF417 menggunakan C# dengan Aspose.BarCode, termasuk contoh kode dan konfigurasi. + +### [Menghasilkan barcode dari teks di C# – panduan langkah‑demi‑langkah lengkap](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Panduan lengkap untuk membuat barcode dari teks menggunakan C# dengan Aspose.BarCode, termasuk contoh kode dan konfigurasi. + +### [Cara Membaca PDF417 di C# – Panduan Pembaca Barcode Lengkap](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +Panduan lengkap membaca barcode PDF417 menggunakan C# dengan Aspose.BarCode, termasuk contoh kode dan konfigurasi. + ## Frequently Asked Questions **Q: Apa jumlah maksimum data yang dapat saya simpan dalam barcode Compact PDF417?** @@ -106,4 +118,4 @@ A: Tidak diperlukan font eksternal; pustaka menangani semua rendering secara int {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/indonesian/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/indonesian/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..8722ac945 --- /dev/null +++ b/barcode/indonesian/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-09 +description: Contoh barcode Aspose yang menunjukkan cara menggunakan generator barcode + C# untuk membuat Macro PDF417 dengan dukungan metadata lengkap. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: id +lastmod: 2026-08-09 +og_description: Contoh barcode Aspose menunjukkan penggunaan generator barcode C# + untuk menghasilkan barcode Macro PDF417 yang mencakup ID file, data segmen, stempel + waktu, dan metadata lainnya. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Contoh barcode Aspose – buat Macro PDF417 dengan C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Contoh barcode Aspose: menghasilkan Macro PDF417 dalam C#' +url: /id/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Contoh barcode Aspose: menghasilkan Macro PDF417 dalam C# + +Jika Anda membutuhkan **aspose barcode example** yang membuat barcode Macro PDF417, panduan ini menunjukkan cara melakukannya dengan **barcode generator C#**. Anda akan melihat setiap pengaturan yang diperlukan, mulai dari dimensi dasar hingga set lengkap bidang metadata Macro PDF417, dan Anda akan mendapatkan gambar PNG yang siap untuk pemrosesan selanjutnya. + +Tutorial ini mencakup alur kerja lengkap, menjelaskan mengapa setiap parameter penting, dan menyediakan contoh kode yang siap dijalankan. Tidak diperlukan referensi eksternal; Anda dapat menyalin kode, menyesuaikan nilai, dan menjalankannya segera. + +## Prasyarat + +- .NET 6.0 (atau lebih baru) terpasang +- Visual Studio 2022 atau IDE yang kompatibel dengan C# apa pun +- Lisensi yang valid untuk **Aspose.BarCode for .NET** (versi percobaan gratis berfungsi untuk contoh ini) + +Tambahkan paket NuGet Aspose.BarCode ke proyek Anda: + +```bash +dotnet add package Aspose.BarCode +``` + +## Langkah 1: Buat instance barcode generator C# + +Langkah pertama adalah menginstansiasi `BarcodeGenerator` dengan nilai enum `EncodeTypes.MacroPdf417` dan teks yang ingin Anda enkode. Teks dapat berisi karakter Unicode, yang ditangani secara otomatis oleh pustaka. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Mengapa ini penting*: `EncodeTypes.MacroPdf417` memberi tahu mesin untuk menghasilkan simbol Macro PDF417, yang mendukung data tersegmentasi dan metadata tingkat file tambahan. Pernyataan `using` menjamin bahwa sumber daya yang tidak dikelola dibebaskan setelah gambar disimpan. + +## Langkah 2: Tentukan tampilan dasar barcode + +Barcode Macro PDF417 terdiri dari modul persegi. Mengontrol ukuran modul dan jumlah kolom memengaruhi keterbacaan serta ukuran file. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Mengapa ini penting*: `XDimension.Pixels` menentukan kepadatan visual; nilai 2 pixel bekerja baik untuk tampilan layar sambil menjaga gambar tetap kecil. Sesuaikan jumlah kolom agar sesuai dengan batasan tata letak Anda—lebih banyak kolom menghasilkan barcode yang lebih lebar dan lebih pendek. + +## Langkah 3: Atur metadata khusus Macro PDF417 + +Macro PDF417 memperluas format PDF417 standar dengan bidang yang memungkinkan rekonstruksi file besar dari beberapa segmen barcode. Setiap bidang bersifat opsional, tetapi mengaturnya menunjukkan kemampuan penuh API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Mengapa ini penting*: +- `MacroPdf417FileID` menghubungkan semua segmen yang termasuk dalam file logis yang sama. +- `MacroPdf417SegmentID` dan `MacroPdf417SegmentsCount` memungkinkan decoder menyusun kembali fragmen dengan benar. +- `MacroPdf417Checksum` menyediakan pemeriksaan integritas cepat tanpa mendekode seluruh payload. +- `MacroPdf417FileSize` dan `MacroPdf417TimeStamp` memungkinkan sistem hilir memverifikasi bahwa file yang direkonstruksi cocok dengan yang asli. +- `MacroPdf417Addressee` / `MacroPdf417Sender` berguna dalam skenario logistik atau pertukaran dokumen. +- Menetapkan `MacroPdf417Terminator` ke `Set` menandai barcode ini sebagai segmen akhir, yang menyederhanakan algoritma rekonstruksi. + +## Langkah 4: Simpan gambar barcode yang dihasilkan + +Akhirnya, tulis barcode ke file PNG. Anda dapat memilih format yang didukung mana pun (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Mengapa ini penting*: PNG mempertahankan data piksel lossless, memastikan pemindai membaca pola modul tepat yang Anda konfigurasikan. Mengubah format dapat memengaruhi kualitas visual dan ukuran file. + +### Output yang Diharapkan + +Menjalankan program lengkap menghasilkan file bernama **ExtPDF417Meta.png**. Membuka gambar menampilkan barcode Macro PDF417 berbentuk persegi panjang dengan teks “Åspóse.Barcóde©” yang terenkode, dan kepadatan visual sesuai dengan dimensi X 2‑pixel yang Anda atur. Memindai gambar dengan pembaca yang kompatibel dengan PDF417 mengembalikan semua bidang metadata yang didefinisikan pada Langkah 3. + +## Contoh lengkap yang berfungsi + +Salin kode di bawah ini ke proyek konsol baru (`dotnet new console`) dan ganti `YOUR_DIRECTORY` dengan jalur absolut atau relatif yang ada di mesin Anda. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Jalankan program (`dotnet run`). Setelah eksekusi, verifikasi bahwa file PNG muncul di lokasi yang Anda tentukan. Gunakan aplikasi pembaca barcode apa pun yang mendukung Macro PDF417 untuk memastikan metadata tersemat dengan benar. + +## Variasi umum dan kasus tepi + +- **Format gambar yang berbeda**: Ganti `BarCodeImageFormat.Png` dengan `Jpeg`, `Bmp`, atau `Tiff` jika sistem hilir Anda lebih menyukai format lain. +- **Mengubah ukuran modul**: Nilai `XDimension.Pixels` yang lebih besar meningkatkan keandalan pemindaian pada pemindai beresolusi rendah tetapi meningkatkan ukuran gambar. +- **Beberapa segmen**: Untuk menghasilkan file multi‑segmen, buat serangkaian barcode, tingkatkan `MacroPdf417SegmentID` untuk masing‑masing, dan pertahankan `MacroPdf417FileID` konstan. Hanya segmen terakhir yang harus memiliki `MacroPdf417Terminator` diatur. +- **Dukungan Unicode**: Generator secara otomatis mengenkode karakter Unicode; pastikan string sumber Anda menggunakan enkoding UTF-8 jika Anda membacanya dari file eksternal. +- **Penanganan kesalahan**: Bungkus blok `using` dalam try‑catch untuk menangkap `BarCodeException` untuk parameter tidak valid (mis., jumlah kolom di luar jangkauan). + +## Tips profesional + +- **Kinerja**: Gunakan kembali satu instance `BarcodeGenerator` saat membuat banyak barcode dengan pengaturan yang sama; hanya ubah properti `CodeText` di antara penyimpanan. +- **Perkiraan ukuran file**: Bidang `MacroPdf417FileSize` harus sesuai dengan jumlah byte payload asli; ketidaksesuaian dapat menyebabkan kegagalan validasi hilir. +- **Pengujian**: Validasi barcode yang dihasilkan dengan decoder bawaan Aspose (`BarCodeReader`) dan pemindai pihak ketiga untuk memastikan interoperabilitas. + +## Kesimpulan + +Contoh **aspose barcode** ini + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber daya menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan menjelajahi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to create barcode quiet zone for Code 16K using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/indonesian/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/indonesian/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..54f4416e8 --- /dev/null +++ b/barcode/indonesian/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-08-09 +description: Hasilkan barcode dari teks di C# dengan Aspose.BarCode. Pelajari cara + menghasilkan barcode, menangani karakter khusus, dan membuat barcode PDF417 C# dengan + cepat. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: id +lastmod: 2026-08-09 +og_description: Hasilkan barcode dari teks dalam C# menggunakan Aspose.BarCode. Tutorial + ini menunjukkan cara menghasilkan barcode, mendukung karakter khusus, dan membuat + barcode PDF417 C# dengan kode lengkap. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Hasilkan barcode dari teks di C# – panduan langkah demi langkah cepat +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Menghasilkan barcode dari teks di C# – panduan langkah demi langkah lengkap +url: /id/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hasilkan barcode dari teks di C# – panduan lengkap langkah demi langkah + +Jika Anda perlu **menghasilkan barcode dari teks** dalam aplikasi .NET, panduan ini akan memandu Anda melalui seluruh proses. Anda akan melihat cara menghasilkan barcode, mengelola karakter khusus, dan membuat implementasi barcode PDF417 C# yang langsung dapat digunakan. + +Menghasilkan barcode dari teks adalah kebutuhan umum untuk sistem inventaris, platform tiket, dan alur kerja dokumen. Pada akhir tutorial ini Anda akan memiliki aplikasi konsol C# yang dapat dijalankan dan menghasilkan gambar PNG MicroPdf417 menggunakan Aspose.BarCode. Tidak diperlukan layanan eksternal, dan kode ini menangani karakter Unicode seperti “Å”, “©”, dan “é”. + +## Prerequisites + +- .NET 6.0 SDK atau yang lebih baru (kode ini juga berfungsi dengan .NET Core 3.1 dan .NET Framework 4.7+) +- Visual Studio 2022 (atau IDE apa pun yang mendukung C#) +- **Aspose.BarCode for .NET** paket NuGet + ```bash + dotnet add package Aspose.BarCode + ``` +- Pengetahuan dasar tentang sintaks C# + +## Generate barcode from text – setting up the generator + +Langkah pertama adalah membuat instance `BarcodeGenerator` yang mengetahui **tipe enkode barcode** yang Anda inginkan. Pada tutorial ini kami menggunakan `EncodeTypes.MicroPdf417`, yang merupakan varian kompak dari PDF417 cocok untuk string data pendek. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Mengapa ini berhasil:** +- `EncodeTypes.MicroPdf417` memberi tahu pustaka untuk menggunakan keluarga PDF417, memenuhi kebutuhan **create pdf417 barcode c#**. +- Konstruktor menerima teks mentah, yang merupakan inti dari **generate barcode from text**. +- Dukungan Unicode sudah built‑in, sehingga karakter seperti “Å” dan “©” dienkode dengan benar, menangani **barcode with special characters**. + +## How to generate barcode with special characters + +Ketika data Anda berisi simbol non‑ASCII, Anda harus memastikan generator menggunakan enkoding UTF‑8. Aspose.BarCode secara otomatis mendeteksi Unicode, tetapi Anda dapat secara eksplisit mengatur enkoding teks jika mengalami masalah: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Menambahkan baris ini sebelum `ConfigureGenerator` menjamin bahwa **barcode with special characters** ditampilkan dengan benar di semua platform. + +### Practical tip +Jika output terlihat berantakan, periksa apakah font yang digunakan oleh renderer barcode mendukung glyph yang diperlukan. Anda dapat menyematkan font TrueType khusus melalui: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Barcode encode types you can choose + +Aspose.BarCode mendukung puluhan **tipe enkode barcode**, masing‑masing cocok untuk kasus penggunaan yang berbeda: + +| Encode type | Kasus penggunaan umum | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | Label pengiriman, inventaris | +| `EncodeTypes.QR` | Pembayaran seluler, URL | +| `EncodeTypes.Pdf417` | SIM driver, boarding pass | +| `EncodeTypes.MicroPdf417` | Payload data kecil, ruang terbatas | +| `EncodeTypes.DataMatrix` | Item sangat kecil, kepadatan data tinggi | + +Mengubah tipe enkode semudah mengganti nilai enum di konstruktor: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Fleksibilitas ini memungkinkan Anda menjawab pertanyaan tentang **barcode encode types** tanpa meninggalkan IDE. + +## Create PDF417 barcode C# – final steps and verification + +Setelah mengonfigurasi generator, bagian terakhir dari **create pdf417 barcode c#** adalah menyimpan gambar dan mengonfirmasi hasilnya. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Jalankan program (`dotnet run`) dan Anda akan melihat pesan konsol serupa dengan: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Buka file PNG; Anda akan melihat barcode MicroPdf417 yang tajam yang mengenkripsi string “Åspóse.Barcóde©”. Memindainya dengan pemindai barcode seluler (misalnya ZXing) mengembalikan teks asli, membuktikan bahwa **generate barcode from text** berfungsi bahkan dengan karakter khusus. + +### Edge case: very long text + +MicroPdf417 memiliki kapasitas data maksimum 1 KB. Jika input Anda melebihi batas ini, pustaka akan melempar `ArgumentException`. Untuk menanganinya secara elegan: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Untuk payload yang lebih besar, beralihlah ke `EncodeTypes.Pdf417` penuh atau `EncodeTypes.DataMatrix`. + +## Common pitfalls and how to avoid them + +| Masalah | Penyebab | Solusi | +|---------------------------------------|------------------------------------------|--------| +| Barcode terlihat buram | XDimension terlalu rendah (mis., 1 px) | Tingkatkan `XDimension.Pixels` menjadi 2‑3 px | +| Karakter Unicode menjadi `?` | Enkoding teks default adalah ASCII | Atur `TextEncoding = Encoding.UTF8` | +| File gambar tidak dibuat | Direktori output tidak ada | Gunakan `Directory.CreateDirectory` sebelum `Save` | +| Pemindai tidak dapat membaca barcode | Terlalu banyak kolom untuk data pendek | Kurangi `Pdf417.Columns` (mis., 3‑4) | + +## Full source code (ready to copy) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Output yang diharapkan:** sebuah file bernama `MicroPdf417.png` yang berada di folder `output`, berisi barcode MicroPdf417 yang jelas dan mengenkripsi string asli dengan karakter khusus. + +## Conclusion + +Anda kini tahu cara **menghasilkan barcode dari teks** di C# menggunakan Aspose.BarCode, cara menangani **barcode with special characters**, dan cara **create pdf417 barcode c#** dengan kontrol penuh atas opsi enkoding. Dengan menyesuaikan **barcode encode types** Anda dapat menghasilkan QR code, Code128, DataMatrix, atau format lain yang didukung. + +Selanjutnya, jelajahi topik berikut untuk memperdalam keahlian barcode Anda: + +- **Cara menghasilkan barcode** secara batch untuk ribuan catatan (gunakan `Parallel.ForEach` untuk kecepatan) +- Menyesuaikan warna dan menambahkan logo di dalam barcode +- Mengintegrasikan pembuatan barcode ke dalam API ASP.NET Core untuk pengiriman gambar secara real‑time +- Menggunakan pustaka lain seperti ZXing.Net atau IronBarcode sebagai alternatif open‑source + +Silakan bereksperimen dengan dimensi, pengaturan kolom, dan tipe enkode yang berbeda. Selamat coding, semoga aplikasi Anda dapat memindai dengan sempurna! + +## What Should You Learn Next? + +Tutorial berikut mencakup topik yang sangat terkait dan membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/indonesian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/indonesian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..42424c9c6 --- /dev/null +++ b/barcode/indonesian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-09 +description: Buat kode batang PDF417 dalam C# dengan cepat. Pelajari cara menghasilkan + PDF417 dengan mode kompak, kontrol kolom, dan output PNG menggunakan API BarcodeGenerator. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: id +lastmod: 2026-08-09 +og_description: Hasilkan kode batang PDF417 di C# dengan contoh singkat. Panduan ini + menunjukkan cara mengatur mode kompak, menentukan kolom, dan menyimpan hasilnya + sebagai gambar PNG. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Buat barcode PDF417 di C# – tutorial lengkap +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: Menghasilkan barcode PDF417 di C# – panduan langkah demi langkah +url: /id/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Menghasilkan barcode PDF417 di C# – panduan langkah demi langkah + +Jika Anda perlu **menghasilkan barcode PDF417** dalam aplikasi .NET, tutorial ini menunjukkan secara tepat cara melakukannya. Anda akan melihat program lengkap yang dapat dijalankan yang membuat barcode PDF417 kompak, menyesuaikan ukurannya, dan menyimpan gambar sebagai file PNG. + +Membuat barcode PDF417 adalah kebutuhan umum untuk tiket seluler, pelacakan inventaris, dan keamanan dokumen. Panduan ini mencakup opsi konfigurasi penting, menjelaskan mengapa setiap pengaturan penting, dan memberikan tips praktis untuk penggunaan di dunia nyata. + +## Prasyarat + +* .NET 6.0 SDK atau yang lebih baru terpasang +* IDE C# seperti Visual Studio 2022 atau Visual Studio Code +* Paket NuGet **Aspose.BarCode for .NET** (versi 23.10 atau lebih baru) + +Anda dapat menginstal paket dengan perintah CLI berikut: + +```bash +dotnet add package Aspose.BarCode +``` + +Kode di bawah mengasumsikan paket sudah direferensikan dan Anda memiliki izin menulis ke direktori output. + +## Langkah 1: Siapkan proyek dan impor namespace + +Buat proyek konsol baru dan tambahkan direktif `using` yang diperlukan. Namespace ini menyediakan kelas `BarcodeGenerator` dan enumerasi format gambar. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Mengapa ini penting:** Mengimpor namespace yang tepat memastikan kompilator dapat menemukan tipe `BarcodeGenerator` dan enum `BarCodeImageFormat`. Kehilangan sebuah namespace akan menghasilkan error kompilasi, yang menghentikan proses pembuatan barcode. + +## Langkah 2: Inisialisasi `BarcodeGenerator` dengan enkoding PDF417 + +Konstruktor `BarcodeGenerator` menerima dua argumen: simbol barcode (`EncodeTypes.Pdf417`) dan teks yang ingin Anda enkode. PDF417 mendukung berbagai karakter, termasuk simbol Unicode. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Penjelasan:** +* `EncodeTypes.Pdf417` memberi tahu perpustakaan untuk menggunakan standar PDF417. +* Teks contoh berisi karakter aksen dan simbol hak cipta untuk menunjukkan penanganan Unicode. + +Jika Anda hanya perlu mengenkode data numerik, Anda dapat memberikan string biasa seperti "1234567890". + +## Langkah 3: Sesuaikan dimensi X untuk resolusi lebih halus + +Dimensi X mengontrol lebar satu modul barcode (elemen hitam atau putih terkecil). Menetapkan nilai piksel yang lebih kecil menghasilkan gambar dengan resolusi lebih tinggi. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Mengapa menyesuaikannya?** Dimensi X default 3–4 piksel dapat menghasilkan barcode yang tampak kasar pada layar ber‑DPI tinggi. Menguranginya menjadi **2 piksel** menyeimbangkan keterbacaan dengan ukuran file, terutama ketika Anda kemudian mengaktifkan mode kompak. + +## Langkah 4: Konfigurasikan jumlah kolom + +PDF417 memungkinkan Anda menentukan berapa banyak kolom yang harus dimiliki barcode. Lebih sedikit kolom membuat barcode lebih sempit namun lebih tinggi, sementara lebih banyak kolom menghasilkan barcode yang lebih lebar dan lebih pendek. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Tip praktis:** Untuk tiket seluler yang harus muat dalam label sempit, jumlah kolom **3–5** bekerja dengan baik. Tingkatkan jumlahnya jika Anda memiliki banyak data dan menginginkan barcode yang lebih pendek. + +## Langkah 5: Aktifkan mode kompak untuk memotong baris kosong + +Mode kompak menghapus baris yang tidak diperlukan dari matriks barcode, mengurangi ukuran gambar secara keseluruhan tanpa kehilangan data yang dienkode. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Kapan menggunakannya:** Jika Anda menghasilkan barcode untuk penyimpanan atau transmisi jaringan, mode kompak dapat memperkecil file PNG hingga 30 %. Namun, beberapa pemindai lama mungkin tidak mendukung PDF417 yang dipotong; uji dengan perangkat keras target Anda. + +## Langkah 6: Simpan barcode sebagai gambar PNG + +Pilih jalur output dan panggil `Save`. Enumerasi `BarCodeImageFormat.Png` menghasilkan gambar lossless yang cocok untuk kebanyakan aplikasi. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Verifikasi hasil:** Buka file PNG di penampil gambar apa pun. Anda harus melihat barcode yang padat dan kontras tinggi yang cocok dengan teks contoh. Memindai gambar dengan pembaca PDF417 (mis., ZXing atau aplikasi smartphone) mengembalikan string asli "Åspóse.Barcóde©". + +![Gambar barcode PDF417 yang dihasilkan disimpan sebagai PNG](compact-pdf417.png "Barcode PDF417 yang dihasilkan dalam C#") + +*Gambar di atas menunjukkan output akhir dari kode tutorial.* + +## Contoh lengkap yang dapat dijalankan + +Menggabungkan semua bagian, berikut adalah program konsol lengkap yang dapat Anda salin, tempel, dan jalankan. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Output yang diharapkan + +Menjalankan program mencetak: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +File `CompactPdf417.png` berisi barcode PDF417 kompak yang mengenkripsi string Unicode yang diberikan. Memindai gambar dengan pembaca PDF417 standar mengembalikan teks yang tepat. + +## Variasi umum dan kasus tepi + +| Situasi | Penyesuaian | Alasan | +|-----------|------------|--------| +| **Payload data lebih panjang** (mis., > 150 karakter) | Tingkatkan `generator.Parameters.Barcode.Pdf417.Columns` menjadi 6‑8 | Lebih banyak kolom mencegah barcode menjadi terlalu tinggi. | +| **Butuh latar belakang transparan** | Gunakan `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | PNG transparan lebih mudah diintegrasikan ke dalam overlay UI. | +| **Menghasilkan JPEG untuk web** | Ubah format menjadi `BarCodeImageFormat.Jpeg` dan opsional atur `ImageQuality` | JPEG mengurangi ukuran file dengan mengorbankan kesetiaan lossless. | +| **Menangani input null atau kosong** | Lindungi input sebelum membuat generator: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Mencegah pengecualian runtime dan memastikan barcode yang bermakna. | + +## Tips untuk penggunaan produksi + +* **Penanganan pengecualian:** Bungkus logika pembuatan dalam blok `try/catch` untuk mencatat error seperti ruang disk tidak cukup atau parameter tidak valid. +* **Kinerja:** Gunakan kembali satu instance `BarcodeGenerator` saat menghasilkan banyak barcode dengan pengaturan yang sama; hanya perbarui properti `CodeText` di antara penyimpanan. +* **Keamanan:** Ketika teks yang dienkode berisi informasi sensitif, pertimbangkan untuk mengenkripsinya sebelum diberikan ke generator dan mendekripsinya setelah pemindaian. + +## Kesimpulan + +Anda kini tahu cara **menghasilkan barcode PDF417** di C# menggunakan pustaka Aspose.BarCode, mengonfigurasi mode kompak, mengontrol jumlah kolom, dan mengekspor hasilnya sebagai gambar PNG. Tutorial ini mencakup setiap langkah mulai dari penyiapan proyek hingga penanganan kasus tepi, memberikan Anda solusi siap pakai untuk aplikasi berbasis barcode. + +Selanjutnya, jelajahi topik terkait seperti **membuat QR code di C#**, **pembuatan barcode batch**, dan **mengintegrasikan pemindaian barcode dengan aplikasi seluler**. Masing‑masing topik ini dibangun di atas dasar `BarcodeGenerator` yang sama yang baru saja Anda kuasai. + +Selamat coding! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait yang dibangun di atas teknik yang ditunjukkan dalam panduan ini. Setiap sumber daya menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Cara Menghasilkan Barcode PDF417 – Enkoding PDF417 Kompak](/barcode/english/net/compact-pdf417-encoding/) +- [Cara Membuat Barcode – PDF417 Kompak dengan Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Cara menghasilkan barcode Aztec dengan rasio aspek khusus menggunakan Aspose.BarCode untuk .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/indonesian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/indonesian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..c46b43da8 --- /dev/null +++ b/barcode/indonesian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-09 +description: Cara membaca PDF417 di C# menggunakan BarCodeReader. Pelajari cara membaca + file PNG barcode, menangani beberapa barcode, dan mengekstrak metadata tambahan. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: id +lastmod: 2026-08-09 +og_description: Cara membaca PDF417 di C# dengan Aspose.BarCode. Tutorial ini menunjukkan + cara membaca file PNG barcode, memproses beberapa barcode dalam satu gambar, dan + mengambil metadata PDF417 yang diperluas. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Cara membaca PDF417 di C# – tutorial pembaca barcode +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Cara membaca PDF417 di C# – panduan lengkap pembaca kode batang +url: /id/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara membaca PDF417 di C# – panduan lengkap pembaca barcode + +Jika Anda perlu **cara membaca PDF417** dalam aplikasi .NET, panduan ini memberikan solusi siap‑pakai. Anda akan melihat cara membaca PNG barcode, memproses beberapa barcode dalam gambar yang sama, dan mengambil bidang PDF417 yang diperluas yang disembunyikan oleh banyak pemindai. + +Membaca barcode PDF417 umum dalam logistik, tiket, dan manajemen dokumen. Pada akhir tutorial ini Anda dapat mendekode gambar Macro PDF417, menampilkan setiap hasil, dan menggunakan informasi tambahan (ID file, jumlah segmen, cap waktu, dll.) dalam logika bisnis Anda sendiri. + +## Prasyarat + +- .NET 6.0 atau lebih baru (kode juga bekerja dengan .NET Framework 4.7+) +- Visual Studio 2022 atau IDE C# apa saja +- **Aspose.BarCode for .NET** (versi percobaan gratis atau paket NuGet berlisensi) +- Sebuah gambar PNG yang berisi barcode Macro PDF417 (file contoh bernama `ExtPDF417Meta.png`) + +> **Tip pro:** Instal perpustakaan dengan konsol NuGet: +> `dotnet add package Aspose.BarCode` + +## Cara membaca PDF417 dengan BarCodeReader di C# + +Inti dari solusi ini adalah kelas `BarCodeReader`. Kelas ini menerima jalur gambar dan enum `DecodeType` yang memberi tahu mesin simbol apa yang harus dicari. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Mengapa ini berhasil + +- **`DecodeType.MacroPdf417`** memberi tahu pembaca untuk mencari varian Macro PDF417, yang menyimpan bidang tambahan yang Anda lihat pada langkah 4. +- Blok `using` secara otomatis membuang pembaca, melepaskan handle file. +- `ReadBarCodes()` mengembalikan **semua** barcode yang cocok dengan tipe yang diminta, yang memenuhi persyaratan *membaca beberapa barcode* bahkan jika gambar hanya berisi satu. + +Menjalankan program mencetak output serupa dengan: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## Menggunakan pembaca barcode C# untuk membaca beberapa barcode + +Jika sebuah gambar berisi beberapa simbol Macro PDF417 (misalnya, halaman yang dipindai dengan sekumpulan tiket), loop `foreach` yang sama memproses masing‑masing. Tidak diperlukan kode tambahan; pembaca menggabungkan hasil secara internal. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Kesalahan umum + +- **Format gambar:** Pembaca mendukung PNG, JPEG, BMP, dan TIFF. Jika Anda mencoba format yang tidak dapat didekode, Anda akan mendapatkan koleksi kosong. Itulah mengapa tutorial menekankan *membaca barcode PNG*. +- **Resolusi:** Gambar beresolusi rendah (< 300 dpi) dapat menyebabkan segmen terlewat. Tingkatkan skala atau minta pemindaian dengan kualitas lebih tinggi bila memungkinkan. +- **Flag macro:** Lupa menambahkan `DecodeType.MacroPdf417` membatasi mesin pada PDF417 biasa dan mengabaikan data yang diperluas. Selalu tentukan tipe macro ketika Anda memerlukan bidang *membaca barcode yang diperluas*. + +## Membaca file PNG barcode – praktik terbaik + +Bekerja dengan file PNG mudah karena format ini mempertahankan data piksel lossless. Berikut daftar periksa singkat: + +1. Verifikasi file ada sebelum membuat pembaca. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Gunakan `Image.FromFile` hanya ketika Anda perlu pra‑proses (memutar, memotong). `BarCodeReader` dapat membuka file secara langsung, yang menghindari alokasi memori tambahan. +3. Jika PNG mengandung transparansi, pembaca tetap berfungsi karena barcode ditampilkan pada piksel tidak transparan. + +## Mengakses metadata PDF417 yang diperluas + +Objek `Extended.Pdf417` menampilkan setiap bidang opsional yang didefinisikan oleh spesifikasi PDF417. Anda dapat memetakan bidang-bidang ini ke model domain, menyimpannya di basis data, atau menggunakannya untuk validasi. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Populate the model: + + + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [Cara Membaca Barcode DataMatrix dengan Aspose.BarCode untuk .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Cara Membuat Barcode – PDF417 Kompak dengan Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Baca barcode DataMatrix C# – Hasilkan Mode DataMatrix (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/italian/net/compact-pdf417-encoding/_index.md b/barcode/italian/net/compact-pdf417-encoding/_index.md index 9fd32044d..4c061e9f7 100644 --- a/barcode/italian/net/compact-pdf417-encoding/_index.md +++ b/barcode/italian/net/compact-pdf417-encoding/_index.md @@ -84,7 +84,15 @@ Oltre alle basi, ecco alcuni consigli pratici per ottimizzare il tuo flusso di l ## Tutorial di codifica Compact PDF417 ### [Creating Compact PDF417 Barcodes](./compact-pdf417-basic-configuration/) -Scopri come generare codici a barre Compact PDF417 usando Aspose.BarCode per .NET. Guida completa con istruzioni passo‑per‑passo ed esempi di codice. +Scopri come generare codici a barre Compact PDF417 usando Aspose.BarCode per .NET. Guida completa con istruzioni passo‑per‑step ed esempi di codice. +### [Esempio Aspose Barcode: generare Macro PDF417 in C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Scopri come generare un codice a barre Macro PDF417 in C# con Aspose.BarCode, includendo esempi di codice e configurazioni. +### [Genera codice a barre PDF417 in C# – guida passo‑per‑passo](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Scopri come creare un codice a barre PDF417 in C# con Aspose.BarCode, seguendo una guida dettagliata passo‑per‑passo. +### [Genera codice a barre da testo in C# – guida completa passo‑per‑passo](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Scopri come generare codici a barre a partire da testo in C# con Aspose.BarCode, con istruzioni dettagliate e esempi di codice. +### [Come leggere PDF417 in C# – guida completa al lettore di codici a barre](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +Scopri come leggere codici a barre PDF417 in C# usando Aspose.BarCode, con esempi pratici e configurazioni dettagliate. ## Domande frequenti @@ -114,4 +122,4 @@ R: No, non sono richiesti font esterni; la libreria gestisce tutto il rendering {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/italian/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/italian/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..4efb329f8 --- /dev/null +++ b/barcode/italian/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-09 +description: Esempio di codice a barre Aspose che mostra come utilizzare un generatore + di codici a barre C# per creare un Macro PDF417 con pieno supporto dei metadati. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: it +lastmod: 2026-08-09 +og_description: L'esempio di barcode Aspose dimostra l'utilizzo di un generatore di + barcode C# per produrre un barcode Macro PDF417 che include l'ID del file, i dati + del segmento, il timestamp e altri metadati. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Esempio di codice a barre Aspose – crea Macro PDF417 con C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Esempio di codice a barre Aspose: genera Macro PDF417 in C#' +url: /it/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Esempio di Aspose barcode: generare Macro PDF417 in C# + +Se hai bisogno di un **aspose barcode example** che crei un Macro PDF417 barcode, questa guida ti mostra come farlo con un **barcode generator C#**. Vedrai tutte le impostazioni necessarie, dalle dimensioni di base all'intero set di campi di metadati Macro PDF417, e otterrai un'immagine PNG pronta per l'elaborazione successiva. + +Il tutorial copre l'intero flusso di lavoro, spiega perché ogni parametro è importante e fornisce un esempio di codice pronto all'uso. Non sono necessari riferimenti esterni; puoi copiare il codice, regolare i valori e eseguirlo immediatamente. + +## Prerequisiti + +- .NET 6.0 (o successivo) installato +- Visual Studio 2022 o qualsiasi IDE compatibile con C# +- Una licenza valida per **Aspose.BarCode for .NET** (la versione di prova gratuita funziona per questo esempio) + +Aggiungi il pacchetto NuGet Aspose.BarCode al tuo progetto: + +```bash +dotnet add package Aspose.BarCode +``` + +## Passo 1: Creare l'istanza del barcode generator C# + +Il primo passo è istanziare `BarcodeGenerator` con il valore enum `EncodeTypes.MacroPdf417` e il testo che desideri codificare. Il testo può contenere caratteri Unicode, che la libreria gestisce automaticamente. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Perché è importante*: `EncodeTypes.MacroPdf417` indica al motore di produrre un simbolo Macro PDF417, che supporta dati segmentati e metadati a livello di file aggiuntivi. L'istruzione `using` garantisce che le risorse non gestite vengano rilasciate dopo il salvataggio dell'immagine. + +## Passo 2: Definire l'aspetto di base del codice a barre + +Un Macro PDF417 barcode è composto da moduli quadrati. Controllare la dimensione del modulo e il numero di colonne influisce sia sulla leggibilità sia sulla dimensione del file. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Perché è importante*: `XDimension.Pixels` determina la densità visiva; un valore di 2 pixel funziona bene per la visualizzazione su schermo mantenendo l'immagine piccola. Regola il conteggio delle colonne per adattarlo ai vincoli del tuo layout—più colonne creano un codice a barre più largo e più corto. + +## Passo 3: Impostare i metadati specifici di Macro PDF417 + +Macro PDF417 estende il formato PDF417 standard con campi che consentono la ricostruzione di file di grandi dimensioni da più segmenti di codice a barre. Ogni campo è opzionale, ma impostarli dimostra tutte le capacità dell'API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Perché è importante*: +- `MacroPdf417FileID` collega tutti i segmenti appartenenti allo stesso file logico. +- `MacroPdf417SegmentID` e `MacroPdf417SegmentsCount` consentono al decoder di riordinare correttamente i frammenti. +- `MacroPdf417Checksum` fornisce un rapido controllo di integrità senza decodificare l'intero payload. +- `MacroPdf417FileSize` e `MacroPdf417TimeStamp` consentono ai sistemi a valle di verificare che il file ricostruito corrisponda all'originale. +- `MacroPdf417Addressee` / `MacroPdf417Sender` sono utili in scenari di logistica o scambio di documenti. +- Impostare `MacroPdf417Terminator` su `Set` contrassegna questo codice a barre come segmento finale, semplificando l'algoritmo di ricostruzione. + +## Passo 4: Salvare l'immagine del codice a barre generato + +Infine, scrivi il codice a barre in un file PNG. Puoi scegliere qualsiasi formato supportato (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Perché è importante*: PNG conserva i dati dei pixel senza perdita, garantendo che gli scanner leggano esattamente il pattern dei moduli configurato. Cambiare formato può influire sulla qualità visiva e sulla dimensione del file. + +### Output previsto + +Eseguendo il programma completo viene creato un file chiamato **ExtPDF417Meta.png**. Aprendo l'immagine si vede un codice a barre Macro PDF417 rettangolare con il testo “Åspóse.Barcóde©” codificato, e la densità visiva corrisponde alla dimensione X di 2 pixel impostata. Scansionando l'immagine con un lettore compatibile PDF417 vengono restituiti tutti i campi di metadati definiti nel Passo 3. + +## Esempio completo funzionante + +Copia il codice qui sotto in un nuovo progetto console (`dotnet new console`) e sostituisci `YOUR_DIRECTORY` con un percorso assoluto o relativo che esista sulla tua macchina. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Esegui il programma (`dotnet run`). Dopo l'esecuzione, verifica che il file PNG sia presente nella posizione specificata. Usa qualsiasi app di lettura di codici a barre che supporti Macro PDF417 per confermare che i metadati siano incorporati correttamente. + +## Variazioni comuni e casi limite + +- **Formati immagine diversi**: Sostituisci `BarCodeImageFormat.Png` con `Jpeg`, `Bmp` o `Tiff` se il tuo sistema a valle preferisce un altro formato. +- **Modifica della dimensione del modulo**: Valori più grandi di `XDimension.Pixels` migliorano l'affidabilità della scansione su scanner a bassa risoluzione ma aumentano la dimensione dell'immagine. +- **Segmenti multipli**: Per produrre un file multi‑segmento, genera una serie di codici a barre, incrementa `MacroPdf417SegmentID` per ciascuno e mantieni costante `MacroPdf417FileID`. Solo l'ultimo segmento dovrebbe avere `MacroPdf417Terminator` impostato. +- **Supporto Unicode**: Il generatore codifica automaticamente i caratteri Unicode; assicurati che la tua stringa di origine utilizzi la codifica UTF-8 se la leggi da un file esterno. +- **Gestione degli errori**: Avvolgi il blocco `using` in un try‑catch per catturare `BarCodeException` per parametri non validi (ad esempio, conteggio colonne fuori intervallo). + +## Consigli professionali + +- **Prestazioni**: Riutilizza una singola istanza di `BarcodeGenerator` quando crei molti codici a barre con le stesse impostazioni; cambia solo la proprietà `CodeText` tra i salvataggi. +- **Stima della dimensione del file**: Il campo `MacroPdf417FileSize` dovrebbe corrispondere al conteggio dei byte del payload originale; discrepanze possono causare errori di validazione a valle. +- **Test**: Convalida i codici a barre generati sia con il decoder integrato di Aspose (`BarCodeReader`) sia con uno scanner di terze parti per garantire l'interoperabilità. + +## Conclusione + +Questo **aspose barcode example** + +## Cosa dovresti imparare dopo? + +I seguenti tutorial coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità aggiuntive dell'API ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Come creare un barcode – Compact PDF417 con Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Come creare la zona silenziosa del barcode per Code 16K usando Aspose.BarCode per .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [Come creare la zona silenziosa del barcode per ITF-14 usando Aspose.BarCode per .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/italian/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/italian/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..31f47e6f4 --- /dev/null +++ b/barcode/italian/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-08-09 +description: Genera codice a barre da testo in C# con Aspose.BarCode. Scopri come + generare un codice a barre, gestire i caratteri speciali e creare rapidamente un + codice a barre PDF417 in C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: it +lastmod: 2026-08-09 +og_description: Genera un codice a barre da testo in C# usando Aspose.BarCode. Questo + tutorial mostra come generare un codice a barre, supportare caratteri speciali e + creare un codice a barre PDF417 in C# con il codice completo. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Genera codice a barre da testo in C# – guida rapida passo‑passo +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Genera codice a barre da testo in C# – guida completa passo‑passo +url: /it/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generare barcode da testo in C# – guida completa passo‑passo + +Se hai bisogno di **generare barcode da testo** in un'applicazione .NET, questa guida ti accompagna attraverso l'intero processo. Vedrai come generare barcode, gestire caratteri speciali e creare un'implementazione C# di un codice a barre PDF417 che funziona subito. + +Generare un barcode da testo è una necessità comune per sistemi di inventario, piattaforme di ticketing e flussi di lavoro documentali. Alla fine di questo tutorial avrai un'app console C# eseguibile che produce un'immagine PNG MicroPdf417 usando Aspose.BarCode. Non sono richiesti servizi esterni e il codice gestisce caratteri Unicode come “Å”, “©” e “é”. + +## Prerequisiti + +- .NET 6.0 SDK o successivo (il codice funziona anche con .NET Core 3.1 e .NET Framework 4.7+) +- Visual Studio 2022 (o qualsiasi IDE che supporti C#) +- **Aspose.BarCode for .NET** pacchetto NuGet + ```bash + dotnet add package Aspose.BarCode + ``` +- Conoscenza di base della sintassi C# + +## Generare barcode da testo – configurare il generatore + +Il primo passo è creare un'istanza di `BarcodeGenerator` che sappia quale **barcode encode type** utilizzare. In questo tutorial usiamo `EncodeTypes.MicroPdf417`, una variante compatta di PDF417 adatta a stringhe di dati brevi. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Perché funziona:** +- `EncodeTypes.MicroPdf417` indica alla libreria di usare la famiglia PDF417, soddisfacendo il requisito **create pdf417 barcode c#**. +- Il costruttore riceve il testo grezzo, che è l'essenza di **generate barcode from text**. +- Il supporto Unicode è integrato, quindi caratteri come “Å” e “©” vengono codificati correttamente, affrontando **barcode with special characters**. + +## Come generare barcode con caratteri speciali + +Quando i tuoi dati contengono simboli non ASCII, devi assicurarti che il generatore utilizzi la codifica UTF‑8. Aspose.BarCode rileva automaticamente Unicode, ma puoi impostare esplicitamente la codifica del testo se incontri problemi: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Aggiungere questa riga prima di `ConfigureGenerator` garantisce che **barcode with special characters** venga renderizzato correttamente su qualsiasi piattaforma. + +### Consiglio pratico +Se l'output appare confuso, verifica che il font usato dal renderer del barcode supporti i glifi richiesti. Puoi incorporare un font TrueType personalizzato tramite: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Tipi di codifica barcode disponibili + +Aspose.BarCode supporta decine di **barcode encode types**, ognuno adatto a diversi casi d'uso: + +| Tipo di codifica | Caso d'uso tipico | +|-----------------------------|---------------------------------------| +| `EncodeTypes.Code128` | Etichette di spedizione, inventario | +| `EncodeTypes.QR` | Pagamenti mobili, URL | +| `EncodeTypes.Pdf417` | Patenti di guida, carte d'imbarco | +| `EncodeTypes.MicroPdf417` | Payload di dati piccoli, spazio limitato | +| `EncodeTypes.DataMatrix` | Oggetti minuscoli, alta densità dati | + +Cambiare il tipo di codifica è semplice come sostituire il valore enum nel costruttore: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Questa flessibilità ti consente di rispondere a domande su **barcode encode types** senza uscire dall'IDE. + +## Creare codice a barre PDF417 C# – passaggi finali e verifica + +Dopo aver configurato il generatore, l'ultima parte di **create pdf417 barcode c#** consiste nel salvare l'immagine e confermare il risultato. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Esegui il programma (`dotnet run`) e dovresti vedere un messaggio console simile a: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Apri il file PNG; vedrai un barcode MicroPdf417 nitido che codifica la stringa “Åspóse.Barcóde©”. Scansionandolo con uno scanner mobile (ad es., ZXing) otterrai il testo originale, dimostrando che **generate barcode from text** funziona anche con caratteri speciali. + +### Caso limite: testo molto lungo + +MicroPdf417 ha una capacità massima di dati di 1 KB. Se il tuo input supera questo limite, la libreria lancia un `ArgumentException`. Per gestirlo in modo elegante: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Per payload più grandi, passa al completo `EncodeTypes.Pdf417` o `EncodeTypes.DataMatrix`. + +## Problemi comuni e come evitarli + +| Problema | Causa | Soluzione | +|----------------------------------|-----------------------------------------|-----------| +| Il barcode appare sfocato | XDimension troppo basso (es., 1 px) | Aumenta `XDimension.Pixels` a 2‑3 px | +| I caratteri Unicode diventano `?`| La codifica di testo predefinita è ASCII | Imposta `TextEncoding = Encoding.UTF8` | +| Il file immagine non viene creato| La cartella di output non esiste | Usa `Directory.CreateDirectory` prima di `Save` | +| Lo scanner non legge il barcode | Troppe colonne per dati brevi | Riduci `Pdf417.Columns` (es., 3‑4) | + +## Codice sorgente completo (pronto da copiare) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Output previsto:** un file chiamato `MicroPdf417.png` situato nella cartella `output`, contenente un barcode MicroPdf417 chiaro che codifica la stringa originale con caratteri speciali. + +## Conclusione + +Ora sai come **generare barcode da testo** in C# usando Aspose.BarCode, come gestire **barcode with special characters** e come **create pdf417 barcode c#** con pieno controllo sulle opzioni di codifica. Regolando i **barcode encode types** puoi produrre QR code, Code128, DataMatrix o qualsiasi altro formato supportato. + +Successivamente, approfondisci i seguenti argomenti per ampliare la tua competenza sui barcode: + +- **Come generare barcode** in batch per migliaia di record (usa `Parallel.ForEach` per velocizzare) +- Personalizzare i colori e aggiungere loghi all'interno del barcode +- Integrare la generazione di barcode nelle API ASP.NET Core per la consegna di immagini on‑the‑fly +- Usare altre librerie come ZXing.Net o IronBarcode per alternative open‑source + +Sentiti libero di sperimentare con diverse dimensioni, impostazioni di colonne e tipi di codifica. Buon coding e che le tue applicazioni scansionino perfettamente! + +## Cosa dovresti imparare dopo? + +I tutorial seguenti coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità aggiuntive dell'API ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Come creare barcode – PDF417 compatto con Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Come generare barcode – Configurazione Code 39 con Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Come generare barcode – Tipi di barcode unidimensionali](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/italian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/italian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..9d9d1f4d1 --- /dev/null +++ b/barcode/italian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-08-09 +description: Genera rapidamente codici a barre PDF417 in C#. Scopri come generare + PDF417 con modalità compatta, controllo delle colonne e output PNG utilizzando l'API + BarcodeGenerator. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: it +lastmod: 2026-08-09 +og_description: Genera codice a barre PDF417 in C# con un esempio conciso. Questa + guida ti mostra come configurare la modalità compatta, impostare le colonne e salvare + il risultato come immagine PNG. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Genera codice a barre PDF417 in C# – tutorial completo +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: Genera codice a barre PDF417 in C# – guida passo passo +url: /it/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Genera codice a barre PDF417 in C# – guida passo‑passo + +Se hai bisogno di **generare un codice a barre PDF417** in un'applicazione .NET, questo tutorial ti mostra esattamente come farlo. Vedrai un programma completo e eseguibile che crea un codice a barre PDF417 compatto, ne personalizza le dimensioni e salva l'immagine come file PNG. + +Generare un codice a barre PDF417 è una necessità comune per il ticketing mobile, il tracciamento dell'inventario e la sicurezza dei documenti. Questa guida copre le opzioni di configurazione essenziali, spiega perché ogni impostazione è importante e fornisce consigli pratici per l'uso in scenari reali. + +## Prerequisiti + +Prima di iniziare, assicurati di avere: + +* .NET 6.0 SDK o versioni successive installate +* Un IDE C# come Visual Studio 2022 o Visual Studio Code +* Il pacchetto **Aspose.BarCode for .NET** NuGet (versione 23.10 o più recente) + +Puoi installare il pacchetto con il seguente comando CLI: + +```bash +dotnet add package Aspose.BarCode +``` + +Il codice qui sotto presuppone che il pacchetto sia referenziato e che tu abbia i permessi di scrittura nella cartella di output. + +## Passo 1: Configura il progetto e importa i namespace + +Crea un nuovo progetto console e aggiungi le direttive `using` richieste. Questi namespace espongono la classe `BarcodeGenerator` e l'enumerazione del formato immagine. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Perché è importante:** Importare i namespace corretti garantisce che il compilatore possa trovare il tipo `BarcodeGenerator` e l'enum `BarCodeImageFormat`. L'assenza di un namespace genera un errore di compilazione, che interrompe il processo di generazione del codice a barre. + +## Passo 2: Inizializza il `BarcodeGenerator` con codifica PDF417 + +Il costruttore di `BarcodeGenerator` riceve due argomenti: la simbologia del codice a barre (`EncodeTypes.Pdf417`) e il testo da codificare. PDF417 supporta un'ampia gamma di caratteri, inclusi i simboli Unicode. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Spiegazione:** +* `EncodeTypes.Pdf417` indica alla libreria di utilizzare lo standard PDF417. +* Il testo di esempio contiene caratteri accentati e un simbolo di copyright per dimostrare la gestione di Unicode. + +Se devi codificare solo dati numerici, puoi passare una stringa semplice come `"1234567890"`. + +## Passo 3: Regola la X‑dimension per una risoluzione più fine + +La X‑dimension controlla la larghezza di un singolo modulo del codice a barre (l'elemento più piccolo, nero o bianco). Impostare un valore di pixel più piccolo produce un'immagine a più alta risoluzione. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Perché regolarla?** Una X‑dimension predefinita di 3–4 pixel può produrre un codice a barre dall'aspetto grezzo su schermi ad alta DPI. Ridurla a **2 pixel** bilancia leggibilità e dimensione del file, soprattutto quando attivi la modalità compatta. + +## Passo 4: Configura il numero di colonne + +PDF417 ti permette di specificare quante colonne deve contenere il codice a barre. Meno colonne rendono il codice più stretto ma più alto, mentre più colonne creano un codice più largo e più corto. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Consiglio pratico:** Per i ticket mobili che devono stare entro un'etichetta stretta, un conteggio di colonne **3–5** funziona bene. Aumenta il conteggio se hai molti dati e desideri un codice più corto. + +## Passo 5: Abilita la modalità compatta per troncare le righe vuote + +La modalità compatta rimuove le righe non necessarie dalla matrice del codice a barre, riducendo la dimensione complessiva dell'immagine senza perdere dati codificati. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Quando usarla:** Se generi codici a barre per archiviazione o trasmissione in rete, la modalità compatta può ridurre il file PNG fino al 30 %. Tuttavia, alcuni scanner legacy potrebbero non supportare PDF417 troncati; verifica con l'hardware di destinazione. + +## Passo 6: Salva il codice a barre come immagine PNG + +Scegli un percorso di output e invoca `Save`. L'enumerazione `BarCodeImageFormat.Png` produce un'immagine lossless adatta alla maggior parte delle applicazioni. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Verifica del risultato:** Apri il file PNG in qualsiasi visualizzatore di immagini. Dovresti vedere un codice a barre denso e ad alto contrasto che corrisponde al testo di esempio. Scansionando l'immagine con un lettore PDF417 (ad es. ZXing o un'app per smartphone) otterrai la stringa originale `"Åspóse.Barcóde©"`. + +![Immagine del codice a barre PDF417 generato salvata come PNG](compact-pdf417.png "Generated PDF417 barcode in C#") + +*L'immagine sopra dimostra l'output finale del codice del tutorial.* + +## Esempio completo, eseguibile + +Riunendo tutti i pezzi, ecco un programma console completo che puoi copiare, incollare ed eseguire. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Output previsto + +L'esecuzione del programma stampa: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +Il file `CompactPdf417.png` contiene un codice a barre PDF417 compatto che codifica la stringa Unicode fornita. Scansionando l'immagine con un lettore PDF417 standard si ottiene il testo esatto. + +## Varianti comuni e casi limite + +| Situazione | Regolazione | Motivo | +|------------|-------------|--------| +| **Payload di dati più lungo** (es. > 150 caratteri) | Incrementa `generator.Parameters.Barcode.Pdf417.Columns` a 6‑8 | Più colonne evitano che il codice diventi eccessivamente alto. | +| **Necessità di sfondo trasparente** | Usa `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | Un PNG trasparente si integra meglio in overlay UI. | +| **Generazione JPEG per il web** | Cambia il formato in `BarCodeImageFormat.Jpeg` e opzionalmente imposta `ImageQuality` | JPEG riduce la dimensione del file a costo di perdita di fedeltà. | +| **Gestione di input nullo o vuoto** | Verifica l'input prima di creare il generatore: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Previene eccezioni a runtime e garantisce codici a barre significativi. | + +## Consigli per l'uso in produzione + +* **Gestione delle eccezioni:** Avvolgi la logica di generazione in un blocco `try/catch` per registrare errori come spazio disco insufficiente o parametri non validi. +* **Prestazioni:** Riutilizza un'unica istanza di `BarcodeGenerator` quando generi molti codici a barre con le stesse impostazioni; aggiorna solo la proprietà `CodeText` tra un salvataggio e l'altro. +* **Sicurezza:** Quando il testo codificato contiene informazioni sensibili, considera di crittografarlo prima di passarlo al generatore e di decrittografarlo dopo la scansione. + +## Conclusione + +Ora sai come **generare un codice a barre PDF417** in C# usando la libreria Aspose.BarCode, configurare la modalità compatta, controllare il numero di colonne e esportare il risultato come immagine PNG. Questo tutorial ha coperto ogni passaggio, dalla configurazione del progetto alla gestione dei casi limite, fornendoti una soluzione pronta all'uso per applicazioni basate su codici a barre. + +Successivamente, esplora argomenti correlati come **creare codici QR in C#**, **generazione batch di codici a barre** e **integrazione della scansione di codici a barre con app mobili**. Ognuno di questi si basa sugli stessi fondamenti di `BarcodeGenerator` che hai appena appreso. + +Buona programmazione! + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [How to Generate PDF417 Barcodes – Compact PDF417 Encoding](/barcode/english/net/compact-pdf417-encoding/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/italian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/italian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..3d927459e --- /dev/null +++ b/barcode/italian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-09 +description: Come leggere PDF417 in C# usando BarCodeReader. Impara a leggere file + PNG di codici a barre, gestire più codici a barre ed estrarre metadati estesi. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: it +lastmod: 2026-08-09 +og_description: Come leggere PDF417 in C# con Aspose.BarCode. Questo tutorial ti mostra + come leggere file PNG di codici a barre, elaborare più codici a barre in un'unica + immagine e recuperare i metadati estesi di PDF417. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Come leggere PDF417 in C# – tutorial sul lettore di codici a barre +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Come leggere PDF417 in C# – guida completa al lettore di codici a barre +url: /it/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come leggere PDF417 in C# – guida completa al lettore di codici a barre + +Se hai bisogno di **come leggere PDF417** in un'applicazione .NET, questa guida ti fornisce una soluzione pronta all'uso. Vedrai come leggere un PNG di codice a barre, elaborare più codici a barre nella stessa immagine e recuperare i campi estesi PDF417 che molti scanner nascondono. + +La lettura dei codici a barre PDF417 è comune nella logistica, nella gestione dei biglietti e nella gestione dei documenti. Alla fine di questo tutorial potrai decodificare un'immagine Macro PDF417, visualizzare ogni risultato e utilizzare le informazioni aggiuntive (ID file, conteggio segmenti, timestamp, ecc.) nella tua logica di business. + +## Prerequisiti + +- .NET 6.0 o versioni successive (il codice funziona anche con .NET Framework 4.7+) +- Visual Studio 2022 o qualsiasi IDE C# +- **Aspose.BarCode for .NET** (versione di prova gratuita o pacchetto NuGet con licenza) +- Un'immagine PNG che contiene un codice a barre Macro PDF417 (il file di esempio si chiama `ExtPDF417Meta.png`) + +> **Consiglio professionale:** Installa la libreria con la console NuGet: +> `dotnet add package Aspose.BarCode` + +## Come leggere PDF417 con BarCodeReader in C# + +Il nucleo della soluzione è la classe `BarCodeReader`. Accetta un percorso immagine e un enum `DecodeType` che indica al motore quale simbologia cercare. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Perché funziona + +- `DecodeType.MacroPdf417` indica al lettore di cercare la variante Macro PDF417, che memorizza i campi aggiuntivi visti al passo 4. +- Il blocco `using` elimina automaticamente il lettore, rilasciando i handle dei file. +- `ReadBarCodes()` restituisce **tutti** i codici a barre che corrispondono al tipo richiesto, soddisfacendo il requisito *leggere più codici a barre* anche se l'immagine contiene solo uno. + +L'esecuzione del programma stampa un output simile a: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## Utilizzare il lettore di codici a barre C# per leggere più codici a barre + +Se un'immagine contiene diversi simboli Macro PDF417 (ad esempio, una pagina scannerizzata con un lotto di biglietti), lo stesso ciclo `foreach` elabora ciascuno di essi. Non è necessario alcun codice aggiuntivo; il lettore aggrega i risultati internamente. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Problemi comuni + +- **Formato immagine:** Il lettore supporta PNG, JPEG, BMP e TIFF. Se provi un formato che non può decodificare, otterrai una collezione vuota. Ecco perché il tutorial evidenzia *leggere codice a barre PNG*. +- **Risoluzione:** Immagini a bassa risoluzione (< 300 dpi) possono causare segmenti mancati. Aumenta la scala o richiedi una scansione di qualità superiore quando possibile. +- **Flag macro:** Dimenticare `DecodeType.MacroPdf417` limita il motore al PDF417 semplice e scarta i dati estesi. Specifica sempre il tipo macro quando hai bisogno dei campi *leggere codice a barre esteso*. + +## Lettura di file PNG di codici a barre – migliori pratiche + +Lavorare con file PNG è semplice perché il formato conserva i dati pixel senza perdita. Ecco una rapida checklist: + +1. Verifica che il file esista prima di creare il lettore. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Usa `Image.FromFile` solo quando è necessario pre‑processare (ruotare, ritagliare). Il `BarCodeReader` può aprire il file direttamente, evitando un'allocazione di memoria aggiuntiva. +3. Se il PNG contiene trasparenza, il lettore funziona comunque perché il codice a barre è renderizzato su pixel opachi. + +## Accesso ai metadati PDF417 estesi + +L'oggetto `Extended.Pdf417` espone ogni campo opzionale definito dalla specifica PDF417. Puoi mappare questi campi a un modello di dominio, memorizzarli in un database o usarli per la validazione. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Populate the model: + + + +## Cosa dovresti imparare dopo? + +I seguenti tutorial coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Come leggere i codici a barre DataMatrix con Aspose.BarCode per .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Come creare un codice a barre – Compact PDF417 con Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Leggi il codice a barre DataMatrix C# – Genera modalità DataMatrix (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/japanese/net/compact-pdf417-encoding/_index.md b/barcode/japanese/net/compact-pdf417-encoding/_index.md index a3cc7ebe8..bd04985bb 100644 --- a/barcode/japanese/net/compact-pdf417-encoding/_index.md +++ b/barcode/japanese/net/compact-pdf417-encoding/_index.md @@ -84,7 +84,13 @@ Aspose.BarCode では `Pdf417ErrorCorrectionLevel` プロパティ(0‑8)を ### [Compact PDF417 バーコードの作成](./compact-pdf417-basic-configuration/) -Aspose.BarCode for .NET を使用して Compact PDF417 バーコードを生成する方法を学びます。ステップバイステップの手順とコード例を含む包括的なガイドです。 +### [Aspose バーコード例: C# で Macro PDF417 を生成](./aspose-barcode-example-generate-macro-pdf417-in-c/) + +### [C# で PDF417 バーコードを生成する – ステップバイステップガイド](./generate-pdf417-barcode-in-c-step-by-step-guide/) + +### [C# でテキストからバーコードを生成する – 完全ステップバイステップガイド](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) + +### [C# で PDF417 を読み取る – 完全なバーコードリーダーガイド](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) ## よくある質問 @@ -114,4 +120,4 @@ A: 外部フォントは不要です。ライブラリが内部で全てのレ {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/japanese/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/japanese/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..7db494496 --- /dev/null +++ b/barcode/japanese/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-08-09 +description: Aspose バーコードの例で、C# のバーコードジェネレータを使用して、フルメタデータサポート付きの Macro PDF417 を作成する方法を示しています。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: ja +lastmod: 2026-08-09 +og_description: Aspose バーコードのサンプルは、C# のバーコードジェネレーターを使用して、ファイル ID、セグメント データ、タイムスタンプ、その他のメタデータを含む + Macro PDF417 バーコードを生成する方法を示しています。 +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Aspose バーコードの例 – C#でマクロ PDF417 を作成 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: Aspose バーコードの例:C#でMacro PDF417を生成 +url: /ja/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose バーコード例: C# で Macro PDF417 を生成する + +**aspose barcode example** が必要で、Macro PDF417 バーコードを作成したい場合、このガイドでは **barcode generator C#** を使用した手順を示します。基本的なサイズ設定から Macro PDF417 のメタデータフィールド全体まで、必要な設定をすべて確認でき、下流処理に使用できる PNG 画像が得られます。 + +このチュートリアルは完全なワークフローをカバーし、各パラメータが重要な理由を解説し、すぐに実行できるコードサンプルを提供します。外部参照は不要で、コードをコピーして値を調整し、すぐに実行できます。 + +## 前提条件 + +- .NET 6.0 (またはそれ以降) がインストールされていること +- Visual Studio 2022 または任意の C# 対応 IDE +- **Aspose.BarCode for .NET** の有効なライセンス (この例では無料トライアルでも動作します) + +プロジェクトに Aspose.BarCode NuGet パッケージを追加します: + +```bash +dotnet add package Aspose.BarCode +``` + +## ステップ 1: バーコードジェネレータ C# インスタンスの作成 + +最初のステップは、`EncodeTypes.MacroPdf417` 列挙値とエンコードしたいテキストを指定して `BarcodeGenerator` をインスタンス化することです。テキストには Unicode 文字を含めることができ、ライブラリが自動的に処理します。 + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*この重要性*: `EncodeTypes.MacroPdf417` はエンジンに Macro PDF417 シンボルを生成させ、セグメント化されたデータと追加のファイルレベルメタデータをサポートします。`using` ステートメントは、画像保存後にアンマネージドリソースが解放されることを保証します。 + +## ステップ 2: 基本的なバーコード外観の定義 + +Macro PDF417 バーコードは正方形のモジュールで構成されます。モジュールサイズと列数を制御することで、可読性とファイルサイズの両方に影響を与えます。 + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*この重要性*: `XDimension.Pixels` は視覚的密度を決定します。2 ピクセルの値は画面表示に適しつつ画像を小さく保ちます。レイアウト制約に合わせて列数を調整してください。列数を増やすと、より幅広く短いバーコードになります。 + +## ステップ 3: Macro PDF417 固有のメタデータ設定 + +Macro PDF417 は標準の PDF417 形式に、複数のバーコードセグメントから大きなファイルを再構築できるフィールドを追加します。各フィールドはオプションですが、設定することで API のフル機能を示すことができます。 + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*この重要性*: +- `MacroPdf417FileID` は同一論理ファイルに属するすべてのセグメントをリンクします。 +- `MacroPdf417SegmentID` と `MacroPdf417SegmentsCount` はデコーダがフラグメントを正しく順序付けできるようにします。 +- `MacroPdf417Checksum` はペイロード全体をデコードせずに迅速な整合性チェックを提供します。 +- `MacroPdf417FileSize` と `MacroPdf417TimeStamp` は下流システムが再構築されたファイルが元と一致するか検証できるようにします。 +- `MacroPdf417Addressee` / `MacroPdf417Sender` は物流や文書交換シナリオで有用です。 +- `MacroPdf417Terminator` を `Set` に設定すると、このバーコードが最終セグメントであることを示し、再構築アルゴリズムを簡素化します。 + +## ステップ 4: 生成されたバーコード画像の保存 + +最後に、バーコードを PNG ファイルとして書き出します。`Png`、`Jpeg`、`Bmp`、`Gif`、`Tiff` のいずれか、サポートされている形式を選択できます。 + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*この重要性*: PNG はロスレスのピクセルデータを保持し、スキャナが設定した正確なモジュールパターンを読み取れるようにします。形式を変更すると、視覚品質やファイルサイズに影響する可能性があります。 + +### 期待される出力 + +プログラムを実行すると **ExtPDF417Meta.png** という名前のファイルが作成されます。画像を開くと、テキスト “Åspóse.Barcóde©” がエンコードされた長方形の Macro PDF417 バーコードが表示され、視覚的密度は設定した 2 ピクセルの X 次元と一致します。PDF417 対応リーダで画像をスキャンすると、ステップ 3 で定義したすべてのメタデータフィールドが取得されます。 + +## 完全な動作例 + +以下のコードを新しいコンソールプロジェクト (`dotnet new console`) にコピーし、`YOUR_DIRECTORY` をマシン上に存在する絶対パスまたは相対パスに置き換えてください。 + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +プログラムを実行します (`dotnet run`)。実行後、指定した場所に PNG ファイルが作成されていることを確認してください。Macro PDF417 をサポートする任意のバーコードリーダーアプリを使用して、メタデータが正しく埋め込まれていることを確認します。 + +## 一般的なバリエーションとエッジケース + +- **Different image formats**: 下流システムが別の形式を好む場合、`BarCodeImageFormat.Png` を `Jpeg`、`Bmp`、または `Tiff` に置き換えます。 +- **Changing module size**: `XDimension.Pixels` の値を大きくすると、低解像度スキャナでの読み取り信頼性が向上しますが、画像サイズが大きくなります。 +- **Multiple segments**: マルチセグメントファイルを生成するには、複数のバーコードを作成し、各バーコードで `MacroPdf417SegmentID` をインクリメントし、`MacroPdf417FileID` は一定に保ちます。最後のセグメントだけが `MacroPdf417Terminator` を設定すべきです。 +- **Unicode support**: ジェネレータは Unicode 文字を自動的にエンコードします。外部ファイルから読み込む場合は、ソース文字列が UTF-8 エンコーディングであることを確認してください。 +- **Error handling**: `using` ブロックを try‑catch でラップし、無効なパラメータ(例: 列数が範囲外)の場合に `BarCodeException` を捕捉します。 + +## プロのコツ + +- **Performance**: 同じ設定で多数のバーコードを作成する場合、単一の `BarcodeGenerator` インスタンスを再利用し、保存間で `CodeText` プロパティだけを変更します。 +- **File size estimation**: `MacroPdf417FileSize` フィールドは元のペイロードのバイト数と一致すべきです。不一致は下流の検証失敗を引き起こす可能性があります。 +- **Testing**: 生成したバーコードを Aspose の組み込みデコーダ (`BarCodeReader`) とサードパーティ製スキャナの両方で検証し、相互運用性を確保します。 + +## 結論 + +この **aspose barcode example + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法に基づく密接に関連するトピックを取り上げています。各リソースには、ステップバイステップの解説と完全な動作コード例が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを検討するのに役立ちます。 + +- [バーコードの作成方法 – Compact PDF417 (Aspose.BarCode 使用)](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Aspose.BarCode for .NET を使用した Code 16K の静音領域の作成方法](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [Aspose.BarCode for .NET を使用した ITF-14 の静音領域の作成方法](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/japanese/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/japanese/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..cfb87e7c7 --- /dev/null +++ b/barcode/japanese/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Aspose.BarCode を使用して C# でテキストからバーコードを生成します。バーコードの生成方法、特殊文字の処理、PDF417 + バーコードの C# での作成方法をすぐに学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: ja +lastmod: 2026-08-09 +og_description: Aspose.BarCode を使用して C# でテキストからバーコードを生成します。このチュートリアルでは、バーコードの生成方法、特殊文字のサポート、完全なコード付きで + PDF417 バーコードを C# で作成する方法を示します。 +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: C#でテキストからバーコードを生成する – 簡単ステップバイステップガイド +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: C#でテキストからバーコードを生成する – 完全ステップバイステップガイド +url: /ja/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# でテキストからバーコードを生成する – 完全ステップバイステップガイド + +.NET アプリケーションで **テキストからバーコードを生成** する必要がある場合、このガイドが全工程を案内します。バーコードの生成方法、特殊文字の扱い方、そしてすぐに使える PDF417 バーコード C# 実装の作成方法が分かります。 + +テキストからバーコードを生成することは、在庫管理システム、チケットプラットフォーム、文書ワークフローで一般的な要件です。このチュートリアルの最後までに、Aspose.BarCode を使用して MicroPdf417 PNG 画像を生成する実行可能な C# コンソールアプリが手に入ります。外部サービスは不要で、コードは “Å”、 “©”、 “é” といった Unicode 文字も正しく処理します。 + +## 前提条件 + +- .NET 6.0 SDK 以降(コードは .NET Core 3.1 および .NET Framework 4.7+ でも動作します) +- Visual Studio 2022(または C# をサポートする任意の IDE) +- **Aspose.BarCode for .NET** NuGet パッケージ + ```bash + dotnet add package Aspose.BarCode + ``` +- C# 構文の基本的な知識 + +## テキストからバーコードを生成 – ジェネレータの設定 + +最初のステップは、目的の **バーコードエンコードタイプ** を指定した `BarcodeGenerator` インスタンスを作成することです。このチュートリアルでは `EncodeTypes.MicroPdf417` を使用します。これは短いデータ文字列に適した PDF417 のコンパクトバリアントです。 + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**この動作の理由:** +- `EncodeTypes.MicroPdf417` はライブラリに PDF417 ファミリーを使用させ、**create pdf417 barcode c#** の要件を満たします。 +- コンストラクタは生のテキストを受け取り、これは **generate barcode from text** の本質です。 +- Unicode サポートが組み込まれているため、“Å” や “©” といった文字が正しくエンコードされ、**barcode with special characters** に対応します。 + +## 特殊文字を含むバーコードの生成方法 + +データに非 ASCII 記号が含まれる場合、ジェネレータが UTF‑8 エンコーディングを使用していることを確認する必要があります。Aspose.BarCode は自動的に Unicode を検出しますが、問題が発生した場合はテキストエンコーディングを明示的に設定できます: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +`ConfigureGenerator` の前にこの行を追加することで、**barcode with special characters** がどのプラットフォームでも正しく描画されます。 + +### 実用的なヒント +出力が文字化けしている場合は、バーコードレンダラが使用するフォントが必要なグリフをサポートしているか確認してください。カスタム TrueType フォントを埋め込むには次のようにします: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## 選択できるバーコードエンコードタイプ + +Aspose.BarCode は多数の **barcode encode types** をサポートしており、用途に応じて選択できます: + +| エンコードタイプ | 典型的な使用例 | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | 出荷ラベル、在庫管理 | +| `EncodeTypes.QR` | モバイル決済、URL | +| `EncodeTypes.Pdf417` | 運転免許証、搭乗券 | +| `EncodeTypes.MicroPdf417` | 小容量データ、限られたスペース | +| `EncodeTypes.DataMatrix` | 小さなアイテム、高データ密度 | + +コンストラクタの列挙値を入れ替えるだけでエンコードタイプを変更できます: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +この柔軟性により、IDE を離れることなく **barcode encode types** に関する質問に答えることができます。 + +## PDF417 バーコード C# の作成 – 最終ステップと検証 + +ジェネレータの設定が完了したら、**create pdf417 barcode c#** の最後のステップは画像を保存し、結果を確認することです。 + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +プログラムを実行(`dotnet run`)すると、次のようなコンソールメッセージが表示されます: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +PNG ファイルを開くと、文字列 “Åspóse.Barcóde©” をエンコードした鮮明な MicroPdf417 バーコードが確認できます。モバイルバーコードスキャナ(例: ZXing)で読み取ると元のテキストが返ってきます。これにより **generate barcode from text** が特殊文字でも正しく機能することが証明されます。 + +### エッジケース: 非常に長いテキスト + +MicroPdf417 の最大データ容量は 1 KB です。入力がこの上限を超えると、ライブラリは `ArgumentException` をスローします。これを穏やかに処理するには次のようにします: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +より大きなペイロードが必要な場合は、フルバージョンの `EncodeTypes.Pdf417` または `EncodeTypes.DataMatrix` に切り替えてください。 + +## よくある落とし穴と回避方法 + +| 問題点 | 原因 | 対策 | +|------------------------------|--------------------------------------|----------------------------------------| +| バーコードがぼやけて表示される | XDimension が低すぎる(例: 1 px) | `XDimension.Pixels` を 2‑3 px に増やす | +| Unicode 文字が `?` になる | デフォルトのテキストエンコーディングが ASCII | `TextEncoding = Encoding.UTF8` を設定する | +| 画像ファイルが作成されない | 出力ディレクトリが存在しない | `Save` の前に `Directory.CreateDirectory` を使用する | +| スキャナーがバーコードを読み取れない | 短いデータに対して列数が多すぎる | `Pdf417.Columns` を減らす(例: 3‑4) | + +## 完全なソースコード(コピー用) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**期待される出力:** `output` フォルダーに `MicroPdf417.png` という名前で作成されるファイルで、特殊文字を含む元の文字列をエンコードしたクリアな MicroPdf417 バーコードが格納されています。 + +## 結論 + +これで Aspose.BarCode を使用して C# で **テキストからバーコードを生成** する方法、**特殊文字を含むバーコード** の扱い方、そして **create pdf417 barcode c#** をエンコードオプションをフルコントロールしながら作成する方法が分かりました。**barcode encode types** を調整すれば、QR コード、Code128、DataMatrix など、他のサポート形式も簡単に生成できます。 + +次に、以下のトピックを探求してバーコードの専門知識を深めてください: + +- **大量レコード(数千件)向けにバーコードをバッチ生成**(高速化のために `Parallel.ForEach` を使用) +- バーコード内の色カスタマイズとロゴ追加 +- ASP.NET Core API にバーコード生成を統合し、リアルタイムで画像を配信 +- ZXing.Net や IronBarcode などのオープンソース代替ライブラリの使用 + +さまざまなサイズ、列設定、エンコードタイプを試してみてください。コーディングを楽しみ、アプリケーションがスムーズにスキャンできることを願っています! + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックをカバーしています。各リソースには、ステップバイステップの解説と完全な動作コード例が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを探求するのに役立ちます。 + +- [【バーコード作成方法 – Aspose.BarCode を使用したコンパクト PDF417】](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [【バーコード生成方法 – Aspose.BarCode の Code 39 設定】](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [【バーコード生成方法 – 1 次元バーコードタイプ】](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/japanese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/japanese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..8df68dc8c --- /dev/null +++ b/barcode/japanese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-08-09 +description: C#でPDF417バーコードを素早く生成します。BarcodeGenerator APIを使用して、コンパクトモード、列制御、PNG出力でPDF417を生成する方法を学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: ja +lastmod: 2026-08-09 +og_description: C#でPDF417バーコードを生成する簡潔な例。このガイドでは、コンパクトモードの設定、列数の指定、結果をPNG画像として保存する方法を示します。 +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: C#でPDF417バーコードを生成する – 完全チュートリアル +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: C#でPDF417バーコードを生成する – ステップバイステップガイド +url: /ja/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で PDF417 バーコードを生成する – ステップバイステップ ガイド + +.NET アプリケーションで **PDF417 バーコードを生成** したい場合、このチュートリアルで具体的な手順を示します。コンパクトな PDF417 バーコードを作成し、サイズをカスタマイズし、PNG ファイルとして保存する、完全に実行可能なプログラムをご覧いただけます。 + +PDF417 バーコードの生成は、モバイルチケット、在庫管理、文書のセキュリティなどで一般的に求められます。本ガイドでは必須の設定オプションを解説し、各設定が重要な理由を説明し、実務で役立つヒントを提供します。 + +## 前提条件 + +開始する前に、以下を用意してください。 + +* .NET 6.0 SDK 以降がインストール済み +* Visual Studio 2022 または Visual Studio Code などの C# IDE +* **Aspose.BarCode for .NET** NuGet パッケージ(バージョン 23.10 以上) + +以下の CLI コマンドでパッケージをインストールできます。 + +```bash +dotnet add package Aspose.BarCode +``` + +以下のコードは、パッケージが参照され、出力ディレクトリへの書き込み権限があることを前提としています。 + +## 手順 1: プロジェクトを作成し名前空間をインポート + +新しいコンソールプロジェクトを作成し、必要な `using` ディレクティブを追加します。これらの名前空間は `BarcodeGenerator` クラスと画像フォーマット列挙体を利用可能にします。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**重要ポイント:** 正しい名前空間をインポートすることで、コンパイラが `BarcodeGenerator` 型や `BarCodeImageFormat` 列挙体を見つけられるようになります。名前空間が不足するとコンパイルエラーとなり、バーコード生成が中断されます。 + +## 手順 2: PDF417 エンコードで `BarcodeGenerator` を初期化 + +`BarcodeGenerator` コンストラクタは 2 つの引数を受け取ります: バーコードシンボル(`EncodeTypes.Pdf417`)とエンコードしたいテキストです。PDF417 は Unicode 記号を含む幅広い文字をサポートします。 + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**解説:** +* `EncodeTypes.Pdf417` はライブラリに PDF417 標準を使用するよう指示します。 +* サンプルテキストにはアクセント付き文字と著作権記号が含まれ、Unicode 処理を示しています。 + +数値データのみをエンコードする場合は、`"1234567890"` のようなプレーン文字列を渡すことも可能です。 + +## 手順 3: 解像度向上のため X‑dimension を調整 + +X‑dimension は単一モジュール(最小の黒または白の要素)の幅を制御します。ピクセル値を小さくすると、より高解像度の画像が得られます。 + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**なぜ調整するのか:** デフォルトの X‑dimension が 3〜4 ピクセルだと、高 DPI 画面でバーコードが粗く見えることがあります。**2 ピクセル**に減らすことで、可読性とファイルサイズのバランスが取れ、後でコンパクトモードを有効にした際に効果的です。 + +## 手順 4: カラム数を設定 + +PDF417 ではバーコードが持つカラム数を指定できます。カラム数が少ないとバーコードは細くなりますが縦に長くなり、カラム数が多いと横に広くなり縦が短くなります。 + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**実用的なヒント:** ラベルが狭いモバイルチケットの場合、**3〜5** カラムが適しています。データ量が多く、バーコードを短くしたい場合はカラム数を増やしてください。 + +## 手順 5: コンパクトモードを有効にして空行を削除 + +コンパクトモードはバーコード行列から不要な行を除去し、エンコードデータを失うことなく画像サイズを削減します。 + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**使用シーン:** ストレージやネットワーク転送用にバーコードを生成する場合、コンパクトモードで PNG ファイルサイズを最大 30 % 縮小できます。ただし、古いスキャナの中にはトリミングされた PDF417 をサポートしないものもあるため、対象ハードウェアで必ずテストしてください。 + +## 手順 6: PNG 画像として保存 + +出力パスを指定し `Save` を呼び出します。`BarCodeImageFormat.Png` 列挙体は、ほとんどの用途に適したロスレス画像を生成します。 + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**結果の確認:** 任意の画像ビューアで PNG ファイルを開きます。サンプルテキストに対応した、濃密で高コントラストなバーコードが表示されるはずです。PDF417 リーダー(例: ZXing やスマートフォンアプリ)でスキャンすると、元の文字列 `"Åspóse.Barcóde©"` が取得できます。 + +![生成された PDF417 バーコード画像(PNG)](compact-pdf417.png "C# で生成した PDF417 バーコード") + +*上図はチュートリアルのコードが出力した最終結果を示しています。* + +## 完全な実行可能サンプル + +すべての要素を組み合わせたコンソールプログラムを以下に示します。コピーして貼り付け、実行してください。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### 期待される出力 + +プログラム実行時に次のように表示されます。 + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +`CompactPdf417.png` ファイルには、指定した Unicode 文字列をエンコードしたコンパクト PDF417 バーコードが格納されています。標準的な PDF417 リーダーでスキャンすると、正確なテキストが復元されます。 + +## よくあるバリエーションとエッジケース + +| 状況 | 調整方法 | 理由 | +|-----------|------------|--------| +| **データ量が長い**(例: 150 文字超) | `generator.Parameters.Barcode.Pdf417.Columns` を 6‑8 に増やす | カラム数を増やすと、バーコードが過度に縦長になるのを防げます。 | +| **背景を透過させたい** | `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` を使用 | 透過 PNG は UI オーバーレイに自然に統合できます。 | +| **Web 用に JPEG で生成したい** | フォーマットを `BarCodeImageFormat.Jpeg` に変更し、必要に応じて `ImageQuality` を設定 | JPEG はファイルサイズを削減しますが、ロスレス性は失われます。 | +| **null または空文字列の入力** | ジェネレータ作成前に入力をチェック: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | 実行時例外を防ぎ、意味のあるバーコード生成を保証します。 | + +## 本番環境での活用ポイント + +* **例外処理:** 生成ロジックを `try/catch` で囲み、ディスク容量不足やパラメータ不正などのエラーをログに記録します。 +* **パフォーマンス:** 同一設定で多数のバーコードを生成する場合は、`BarcodeGenerator` インスタンスを再利用し、`CodeText` プロパティだけを保存間で切り替えます。 +* **セキュリティ:** エンコードするテキストに機密情報が含まれる場合は、ジェネレータに渡す前に暗号化し、スキャン後に復号することを検討してください。 + +## 結論 + +Aspose.BarCode ライブラリを使用して C# で **PDF417 バーコードを生成** し、コンパクトモードの設定、カラム数の制御、PNG へのエクスポート方法を習得しました。本チュートリアルはプロジェクトのセットアップからエッジケースの対処まで網羅しており、バーコード駆動アプリケーションにすぐに活用できるソリューションを提供します。 + +次は **C# で QR コードを作成**、**バッチバーコード生成**、**モバイルアプリとのバーコードスキャン連携** など、同じ `BarcodeGenerator` の基礎を応用したトピックを探求してください。 + +Happy coding! + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示した手法を基にした関連トピックを扱っています。各リソースには、ステップバイステップの解説と完全なコード例が含まれており、API の追加機能をマスターしたり、代替実装アプローチを自プロジェクトに取り入れたりするのに役立ちます。 + +- [PDF417 バーコードの生成 – コンパクト PDF417 エンコーディング](/barcode/english/net/compact-pdf417-encoding/) +- [バーコード作成 – Aspose.BarCode を使用したコンパクト PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Aspose.BarCode for .NET でカスタムアスペクト比の Aztec バーコードを生成](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/japanese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/japanese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..c19bc8554 --- /dev/null +++ b/barcode/japanese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-08-09 +description: BarCodeReader を使用して C# で PDF417 を読み取る方法。バーコード PNG ファイルの読み取り、複数のバーコードの処理、拡張メタデータの抽出を学びます。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: ja +lastmod: 2026-08-09 +og_description: C# と Aspose.BarCode を使用して PDF417 を読み取る方法。このチュートリアルでは、バーコード PNG ファイルの読み取り、1 + つの画像内の複数バーコードの処理、そして拡張 PDF417 メタデータの取得方法を示します。 +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: C#でPDF417を読み取る方法 – バーコードリーダーのチュートリアル +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: C#でPDF417を読み取る方法 – 完全なバーコードリーダーガイド +url: /ja/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で PDF417 を読み取る方法 – 完全なバーコードリーダーガイド + +.NET アプリケーションで **PDF417 の読み取り方法** が必要な場合、このガイドはすぐに実行できるソリューションを提供します。バーコード PNG の読み取り方法、同じ画像内の複数のバーコードの処理方法、そして多くのスキャナーが隠す拡張 PDF417 フィールドの取得方法を紹介します。 + +PDF417 バーコードの読み取りは物流、チケット発行、文書管理で一般的です。このチュートリアルの最後までに、Macro PDF417 画像をデコードし、すべての結果を表示し、拡張情報(ファイル ID、セグメント数、タイムスタンプなど)を独自のビジネスロジックで利用できるようになります。 + +## 前提条件 + +- .NET 6.0 以降(コードは .NET Framework 4.7+ でも動作します) +- Visual Studio 2022 または任意の C# IDE +- **Aspose.BarCode for .NET**(無料トライアルまたはライセンス済み NuGet パッケージ) +- Macro PDF417 バーコードを含む PNG 画像(サンプルファイルは `ExtPDF417Meta.png`) + +> **プロのコツ:** NuGet コンソールでライブラリをインストールします: +> `dotnet add package Aspose.BarCode` + +## C# の BarCodeReader で PDF417 を読み取る方法 + +ソリューションの核心は `BarCodeReader` クラスです。画像パスと、エンジンにどのシンボルを探すか指示する `DecodeType` 列挙型を受け取ります。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### なぜこれが機能するのか + +- **`DecodeType.MacroPdf417`** はリーダーに Macro PDF417 バリアントを探すよう指示し、ステップ 4 で確認できる拡張フィールドを格納します。 +- `using` ブロックはリーダーを自動的に破棄し、ファイルハンドルを解放します。 +- `ReadBarCodes()` は要求されたタイプに一致する **すべて** のバーコードを返すため、画像に 1 つだけ含まれていても *複数バーコードの読み取り* 要件を満たします。 + +プログラムを実行すると、以下のような出力が表示されます: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## C# バーコードリーダーで複数のバーコードを読み取る + +画像に複数の Macro PDF417 シンボルが含まれている場合(例: チケットのバッチがスキャンされたページ)、同じ `foreach` ループがそれぞれを処理します。追加コードは不要で、リーダーが内部で結果を集約します。 + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### よくある落とし穴 + +- **画像形式:** リーダーは PNG、JPEG、BMP、TIFF をサポートします。デコードできない形式を使用すると空のコレクションが返ります。これがチュートリアルで *バーコード PNG の読み取り* を強調する理由です。 +- **解像度:** 低解像度画像(< 300 dpi)はセグメントの取りこぼしを引き起こす可能性があります。可能な限り高解像度のスキャンを使用するか、画像を拡大してください。 +- **Macro フラグ:** `DecodeType.MacroPdf417` を忘れるとエンジンは通常の PDF417 のみを対象とし、拡張データが破棄されます。*拡張バーコードフィールドの読み取り* が必要な場合は必ず Macro タイプを指定してください。 + +## バーコード PNG ファイルの読み取り – ベストプラクティス + +PNG はロスレスなピクセルデータを保持するため、取り扱いが簡単です。以下は簡易チェックリストです: + +1. リーダーを作成する前にファイルが存在することを確認します。 + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. `Image.FromFile` は前処理(回転、トリミング)が必要なときだけ使用します。`BarCodeReader` はファイルを直接開くことができ、余分なメモリ割り当てを回避できます。 +3. PNG に透過が含まれていても、バーコードは不透明ピクセル上に描画されているためリーダーは正常に動作します。 + +## 拡張 PDF417 メタデータへのアクセス + +`Extended.Pdf417` オブジェクトは PDF417 仕様で定義されたすべてのオプションフィールドを公開します。これらのフィールドをドメインモデルにマッピングしたり、データベースに保存したり、検証に利用したりできます。 + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +モデルにデータを設定します: + + + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックをカバーしています。各リソースには完全な動作コード例とステップバイステップの解説が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを検討するのに役立ちます。 + +- [Aspose.BarCode for .NET を使用した DataMatrix バーコードの読み取り方法](/barcode/english/net/datamatrix-barcode-reading/) +- [Aspose.BarCode でコンパクト PDF417 バーコードを作成する方法](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [DataMatrix バーコードを C# で読み取る – DataMatrix モード(自動)を生成](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/korean/net/compact-pdf417-encoding/_index.md b/barcode/korean/net/compact-pdf417-encoding/_index.md index 0ecfa04d3..b55c95728 100644 --- a/barcode/korean/net/compact-pdf417-encoding/_index.md +++ b/barcode/korean/net/compact-pdf417-encoding/_index.md @@ -86,6 +86,18 @@ Aspose.BarCode는 `Pdf417ErrorCorrectionLevel` 속성(0‑8)을 설정할 수 ### [Compact PDF417 바코드 만들기](./compact-pdf417-basic-configuration/) Aspose.BarCode for .NET를 사용해 Compact PDF417 바코드를 생성하는 방법을 배웁니다. 단계별 지침과 코드 예제가 포함된 포괄적인 가이드입니다. +### [Aspose 바코드 예제: C#에서 매크로 PDF417 생성](./aspose-barcode-example-generate-macro-pdf417-in-c/) +C#을 사용해 Aspose.BarCode로 매크로 PDF417 바코드를 생성하는 방법을 단계별로 안내합니다. + +### [C#에서 PDF417 바코드 생성 – 단계별 가이드](./generate-pdf417-barcode-in-c-step-by-step-guide/) +C#을 사용해 PDF417 바코드를 생성하는 방법을 단계별로 안내합니다. + +### [C#에서 텍스트로 바코드 생성 – 완전 단계별 가이드](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +C#을 사용해 텍스트로 바코드를 생성하는 완전한 단계별 가이드입니다. + +### [C#에서 PDF417 읽는 방법 – 완전 바코드 리더 가이드](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +C#을 사용해 PDF417 바코드를 읽는 전체 가이드를 제공합니다. + ## 자주 묻는 질문 **Q: Compact PDF417 바코드에 저장할 수 있는 최대 데이터 양은?** @@ -114,4 +126,4 @@ A: 외부 폰트가 필요하지 않으며, 라이브러리가 내부적으로 {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/korean/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/korean/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..8ec7b3e92 --- /dev/null +++ b/barcode/korean/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-09 +description: 'Aspose 바코드 예제: C# 바코드 생성기를 사용하여 전체 메타데이터 지원이 포함된 매크로 PDF417를 만드는 방법을 + 보여줍니다.' +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: ko +lastmod: 2026-08-09 +og_description: Aspose 바코드 예제는 C# 바코드 생성기를 사용하여 파일 ID, 세그먼트 데이터, 타임스탬프 및 기타 메타데이터를 + 포함하는 매크로 PDF417 바코드를 생성하는 방법을 보여줍니다. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Aspose 바코드 예제 – C#로 매크로 PDF417 만들기 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Aspose 바코드 예제: C#로 매크로 PDF417 생성' +url: /ko/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose barcode example: generate Macro PDF417 in C# + +Macro PDF417 바코드를 생성하는 **aspose barcode example**이 필요하다면, 이 가이드는 **barcode generator C#**를 사용하여 만드는 방법을 보여줍니다. 기본 치수부터 Macro PDF417 메타데이터 필드 전체에 이르는 모든 설정을 확인하고, 다운스트림 처리를 위해 사용할 수 있는 PNG 이미지를 얻을 수 있습니다. + +이 튜토리얼은 전체 워크플로우를 다루며, 각 매개변수가 왜 중요한지 설명하고, 바로 실행할 수 있는 코드 샘플을 제공합니다. 외부 참조가 필요 없으며, 코드를 복사하고 값을 조정한 뒤 즉시 실행하면 됩니다. + +## Prerequisites + +시작하기 전에 다음이 설치되어 있는지 확인하세요: + +- .NET 6.0 (또는 그 이후 버전) 설치 +- Visual Studio 2022 또는 C#를 지원하는 IDE +- **Aspose.BarCode for .NET**에 대한 유효한 라이선스 (무료 체험판으로도 이 예제는 동작합니다) + +프로젝트에 Aspose.BarCode NuGet 패키지를 추가합니다: + +```bash +dotnet add package Aspose.BarCode +``` + +## Step 1: Create the barcode generator C# instance + +첫 번째 단계는 `EncodeTypes.MacroPdf417` 열거값과 인코딩하려는 텍스트를 사용해 `BarcodeGenerator`를 인스턴스화하는 것입니다. 텍스트는 유니코드 문자를 포함할 수 있으며, 라이브러리가 자동으로 처리합니다. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*왜 중요한가*: `EncodeTypes.MacroPdf417`은 엔진에게 Macro PDF417 심볼을 생성하도록 지시합니다. 이 심볼은 세그먼트된 데이터와 추가 파일‑레벨 메타데이터를 지원합니다. `using` 문은 이미지 저장 후에 비관리 리소스가 해제되도록 보장합니다. + +## Step 2: Define basic barcode appearance + +Macro PDF417 바코드는 정사각형 모듈로 구성됩니다. 모듈 크기와 열 개수를 제어하면 가독성과 파일 크기에 모두 영향을 줍니다. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*왜 중요한가*: `XDimension.Pixels`는 시각적 밀도를 결정합니다; 2 픽셀 값은 화면 표시에는 적합하면서 이미지 크기를 작게 유지합니다. 레이아웃 제약에 맞게 열 개수를 조정하세요—열이 많을수록 바코드가 넓고 짧아집니다. + +## Step 3: Set Macro PDF417 specific metadata + +Macro PDF417는 표준 PDF417 형식에 여러 필드를 추가해 여러 바코드 세그먼트에서 큰 파일을 재구성할 수 있게 합니다. 각 필드는 선택 사항이지만, 설정하면 API의 전체 기능을 보여줄 수 있습니다. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*왜 중요한가*: +- `MacroPdf417FileID`는 동일 논리 파일에 속하는 모든 세그먼트를 연결합니다. +- `MacroPdf417SegmentID`와 `MacroPdf417SegmentsCount`는 디코더가 조각을 올바르게 재정렬하도록 돕습니다. +- `MacroPdf417Checksum`은 전체 페이로드를 디코딩하지 않아도 빠른 무결성 검사를 제공합니다. +- `MacroPdf417FileSize`와 `MacroPdf417TimeStamp`는 다운스트림 시스템이 재구성된 파일이 원본과 일치하는지 확인하는 데 사용됩니다. +- `MacroPdf417Addressee` / `MacroPdf417Sender`는 물류나 문서 교환 시나리오에서 유용합니다. +- `MacroPdf417Terminator`를 `Set`으로 지정하면 이 바코드가 마지막 세그먼트임을 표시하여 재구성 알고리즘을 단순화합니다. + +## Step 4: Save the generated barcode image + +마지막으로 바코드를 PNG 파일로 저장합니다. 지원되는 형식(`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`) 중 원하는 것을 선택할 수 있습니다. + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*왜 중요한가*: PNG는 손실 없는 픽셀 데이터를 보존하므로 스캐너가 구성한 모듈 패턴을 정확히 읽을 수 있습니다. 형식을 변경하면 시각적 품질과 파일 크기에 영향을 줄 수 있습니다. + +### Expected output + +전체 프로그램을 실행하면 **ExtPDF417Meta.png**라는 파일이 생성됩니다. 이미지를 열면 “Åspóse.Barcóde©” 텍스트가 인코딩된 직사각형 Macro PDF417 바코드가 표시되며, 설정한 2‑픽셀 X 차원에 맞는 시각적 밀도를 확인할 수 있습니다. PDF417‑호환 리더로 이미지를 스캔하면 Step 3에서 정의한 모든 메타데이터 필드가 반환됩니다. + +## Full working example + +아래 코드를 새 콘솔 프로젝트(`dotnet new console`)에 복사하고 `YOUR_DIRECTORY`를 실제 존재하는 절대 경로나 상대 경로로 교체하세요. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +프로그램을 실행합니다(`dotnet run`). 실행이 끝난 후 지정한 위치에 PNG 파일이 생성됐는지 확인합니다. Macro PDF417를 지원하는 바코드 읽기 앱으로 메타데이터가 올바르게 삽입됐는지 검증하세요. + +## Common variations and edge cases + +- **Different image formats**: `BarCodeImageFormat.Png`를 `Jpeg`, `Bmp`, 또는 `Tiff`로 교체하면 다운스트림 시스템이 다른 형식을 선호할 때 사용할 수 있습니다. +- **Changing module size**: 큰 `XDimension.Pixels` 값은 저해상도 스캐너에서 스캔 신뢰성을 높이지만 이미지 크기가 증가합니다. +- **Multiple segments**: 다중 세그먼트 파일을 만들려면 일련의 바코드를 생성하고 각 바코드마다 `MacroPdf417SegmentID`를 증가시키며 `MacroPdf417FileID`는 동일하게 유지합니다. 마지막 세그먼트에만 `MacroPdf417Terminator`를 설정하세요. +- **Unicode support**: 생성기는 유니코드 문자를 자동으로 인코딩합니다; 외부 파일에서 문자열을 읽는 경우 UTF‑8 인코딩을 사용하도록 하세요. +- **Error handling**: `using` 블록을 try‑catch로 감싸 `BarCodeException`을 잡아 잘못된 매개변수(예: 범위를 벗어난 열 개수) 발생 시 처리합니다. + +## Pro tips + +- **Performance**: 동일 설정으로 많은 바코드를 생성할 때는 `BarcodeGenerator` 인스턴스를 재사용하고, 저장 사이에 `CodeText` 속성만 변경하세요. +- **File size estimation**: `MacroPdf417FileSize` 필드는 원본 페이로드의 바이트 수와 일치해야 합니다; 불일치는 다운스트림 검증 실패를 초래할 수 있습니다. +- **Testing**: Aspose의 내장 디코더(`BarCodeReader`)와 서드파티 스캐너 모두로 생성된 바코드를 검증해 상호 운용성을 확인하세요. + +## Conclusion + +This **aspose barcode example + + +## What Should You Learn Next? + +다음 튜토리얼은 이 가이드에서 다룬 기술을 기반으로 하며, 추가 API 기능을 마스터하고 프로젝트에 적용할 수 있도록 단계별 설명과 완전한 코드 예제를 제공합니다. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to create barcode quiet zone for Code 16K using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/korean/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/korean/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..d84969b84 --- /dev/null +++ b/barcode/korean/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Aspose.BarCode를 사용하여 C#에서 텍스트로 바코드를 생성합니다. 바코드 생성 방법, 특수 문자 처리 및 PDF417 + 바코드를 C#에서 빠르게 만드는 방법을 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: ko +lastmod: 2026-08-09 +og_description: Aspose.BarCode를 사용하여 C#에서 텍스트로 바코드를 생성합니다. 이 튜토리얼에서는 바코드 생성 방법, 특수 + 문자 지원 및 전체 코드를 포함한 PDF417 바코드 C# 생성 방법을 보여줍니다. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: C#에서 텍스트로 바코드 생성 – 빠른 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: C#에서 텍스트로 바코드 생성 – 완전 단계별 가이드 +url: /ko/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 텍스트로 바코드 생성 – 완전 단계별 가이드 + +.NET 애플리케이션에서 **텍스트로 바코드 생성**이 필요하다면, 이 가이드는 전체 과정을 단계별로 안내합니다. 바코드 생성 방법, 특수 문자 처리 방법, 그리고 바로 사용할 수 있는 PDF417 바코드 C# 구현을 확인할 수 있습니다. + +텍스트로 바코드를 생성하는 것은 재고 시스템, 티켓 발행 플랫폼, 문서 워크플로우 등에서 흔히 요구되는 기능입니다. 이 튜토리얼을 마치면 Aspose.BarCode를 사용해 MicroPdf417 PNG 이미지를 생성하는 실행 가능한 C# 콘솔 앱을 얻게 됩니다. 외부 서비스는 필요 없으며, “Å”, “©”, “é”와 같은 유니코드 문자도 올바르게 처리됩니다. + +## 사전 요구 사항 + +- .NET 6.0 SDK 이상 (코드는 .NET Core 3.1 및 .NET Framework 4.7+에서도 작동합니다) +- Visual Studio 2022 (또는 C#을 지원하는 모든 IDE) +- **Aspose.BarCode for .NET** NuGet 패키지 + ```bash + dotnet add package Aspose.BarCode + ``` +- C# 문법에 대한 기본 지식 + +## 텍스트로 바코드 생성 – 생성기 설정하기 + +첫 번째 단계는 원하는 **바코드 인코드 유형**을 알고 있는 `BarcodeGenerator` 인스턴스를 만드는 것입니다. 이 튜토리얼에서는 짧은 데이터 문자열에 적합한 PDF417의 컴팩트 변형인 `EncodeTypes.MicroPdf417`을 사용합니다. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**왜 이렇게 동작하나요:** +- `EncodeTypes.MicroPdf417`은 라이브러리에게 PDF417 계열을 사용하도록 알려 주어 **create pdf417 barcode c#** 요구 사항을 충족합니다. +- 생성자는 원시 텍스트를 받아 **generate barcode from text**의 핵심 역할을 수행합니다. +- 유니코드 지원이 기본 제공되므로 “Å”와 “©”와 같은 문자가 올바르게 인코딩되어 **barcode with special characters** 문제를 해결합니다. + +## 특수 문자를 포함한 바코드 생성 방법 + +데이터에 비 ASCII 기호가 포함된 경우, 생성기가 UTF‑8 인코딩을 사용하도록 해야 합니다. Aspose.BarCode는 유니코드를 자동으로 감지하지만, 문제가 발생하면 텍스트 인코딩을 명시적으로 설정할 수 있습니다: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +`ConfigureGenerator` 앞에 이 코드를 추가하면 **barcode with special characters**가 모든 플랫폼에서 올바르게 렌더링됩니다. + +### 실용적인 팁 +출력이 깨져 보이면 바코드 렌더러가 사용하는 폰트가 필요한 글리프를 지원하는지 확인하세요. 다음과 같이 사용자 정의 TrueType 폰트를 삽입할 수 있습니다: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## 선택 가능한 바코드 인코드 유형 + +Aspose.BarCode는 다양한 **barcode encode types**를 지원하며, 각각은 특정 사용 사례에 최적화되어 있습니다: + +| 인코드 유형 | 일반적인 사용 사례 | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | 배송 라벨, 재고 관리 | +| `EncodeTypes.QR` | 모바일 결제, URL | +| `EncodeTypes.Pdf417` | 운전면허증, 탑승권 | +| `EncodeTypes.MicroPdf417` | 작은 데이터 페이로드, 제한된 공간 | +| `EncodeTypes.DataMatrix` | 초소형 아이템, 고밀도 데이터 | + +생성자에서 열거형 값을 교체하기만 하면 인코드 유형을 쉽게 변경할 수 있습니다: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +이 유연성을 통해 IDE를 떠나지 않고도 **barcode encode types**에 대한 질문에 답할 수 있습니다. + +## PDF417 바코드 C# 생성 – 최종 단계 및 검증 + +생성기 설정이 끝나면 **create pdf417 barcode c#**의 마지막 단계인 이미지 저장과 결과 확인을 수행합니다. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +프로그램을 실행(`dotnet run`)하면 다음과 유사한 콘솔 메시지가 표시됩니다: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +PNG 파일을 열면 “Åspóse.Barcóde©” 문자열을 인코딩한 선명한 MicroPdf417 바코드를 확인할 수 있습니다. 모바일 바코드 스캐너(예: ZXing)로 스캔하면 원본 텍스트가 반환되어 **generate barcode from text**가 특수 문자와 함께 정상 작동함을 증명합니다. + +### Edge case: 매우 긴 텍스트 + +MicroPdf417은 최대 1 KB의 데이터 용량을 가집니다. 입력이 이 한도를 초과하면 라이브러리가 `ArgumentException`을 발생시킵니다. 이를 부드럽게 처리하려면 다음과 같이 코딩하세요: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +더 큰 페이로드가 필요하면 전체 `EncodeTypes.Pdf417` 또는 `EncodeTypes.DataMatrix`로 전환하세요. + +## 흔히 발생하는 문제와 해결 방법 + +| 문제 | 원인 | 해결 방법 | +|-----------------------------------|----------------------------------------|----------| +| 바코드가 흐릿하게 보임 | XDimension이 너무 낮음(예: 1 px) | `XDimension.Pixels`를 2‑3 px로 증가 | +| 유니코드 문자가 `?` 로 표시됨 | 기본 텍스트 인코딩이 ASCII임 | `TextEncoding = Encoding.UTF8` 설정 | +| 이미지 파일이 생성되지 않음 | 출력 디렉터리가 존재하지 않음 | `Save` 전에 `Directory.CreateDirectory` 사용 | +| 스캐너가 바코드를 읽지 못함 | 짧은 데이터에 열이 너무 많음 | `Pdf417.Columns`를 3‑4 정도로 감소 | + +## 전체 소스 코드 (복사용) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**예상 출력:** `output` 폴더에 `MicroPdf417.png` 파일이 생성되며, 특수 문자를 포함한 원본 문자열을 인코딩한 선명한 MicroPdf417 바코드가 들어 있습니다. + +## 결론 + +이제 Aspose.BarCode를 사용해 C#에서 **텍스트로 바코드 생성**하는 방법, **특수 문자를 포함한 바코드**를 처리하는 방법, 그리고 **create pdf417 barcode c#**을 완전한 인코딩 옵션 제어와 함께 구현하는 방법을 알게 되었습니다. **barcode encode types**를 조정하면 QR 코드, Code128, DataMatrix 등 다양한 포맷을 손쉽게 만들 수 있습니다. + +다음 주제들을 탐색하여 바코드 전문성을 한층 높여 보세요: + +- 수천 개 레코드에 대해 **바코드 일괄 생성**하기 (`Parallel.ForEach` 활용) +- 색상 커스터마이징 및 바코드 내부에 로고 삽입 +- ASP.NET Core API에 바코드 생성 통합하여 실시간 이미지 제공 +- ZXing.Net, IronBarcode와 같은 오픈소스 대안 라이브러리 사용 + +다양한 크기, 열 설정, 인코드 유형을 실험해 보세요. 즐거운 코딩 되시고, 애플리케이션이 언제나 원활히 스캔되길 바랍니다! + +## 다음에 배울 내용은? + +다음 튜토리얼들은 이 가이드에서 다룬 기술을 기반으로 한 밀접한 주제들을 다룹니다. 각 자료에는 단계별 설명과 완전한 코드 예제가 포함되어 있어 추가 API 기능을 마스터하고 프로젝트에 적용할 수 있는 다양한 구현 방식을 탐색할 수 있습니다. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/korean/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/korean/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..02d146895 --- /dev/null +++ b/barcode/korean/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-08-09 +description: C#에서 PDF417 바코드를 빠르게 생성하세요. BarcodeGenerator API를 사용하여 컴팩트 모드, 컬럼 제어 + 및 PNG 출력으로 PDF417을 생성하는 방법을 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: ko +lastmod: 2026-08-09 +og_description: 간결한 예제로 C#에서 PDF417 바코드를 생성하세요. 이 가이드는 컴팩트 모드를 설정하고, 열 수를 지정하며, 결과를 + PNG 이미지로 저장하는 방법을 보여줍니다. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: C#에서 PDF417 바코드 생성 – 완전 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: C#에서 PDF417 바코드 생성 – 단계별 가이드 +url: /ko/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 PDF417 바코드 생성 – 단계별 가이드 + +.NET 애플리케이션에서 **PDF417 바코드 생성**이 필요하다면, 이 튜토리얼에서 정확한 방법을 보여드립니다. 컴팩트한 PDF417 바코드를 만들고, 크기를 커스터마이징하며, 이미지를 PNG 파일로 저장하는 완전한 실행 가능한 프로그램을 확인할 수 있습니다. + +PDF417 바코드 생성은 모바일 티켓팅, 재고 추적, 문서 보안 등에서 흔히 요구됩니다. 이 가이드는 필수 구성 옵션을 다루고, 각 설정이 왜 중요한지 설명하며, 실제 사용에 도움이 되는 팁을 제공합니다. + +## 사전 요구 사항 + +시작하기 전에 다음이 준비되어 있는지 확인하세요: + +* .NET 6.0 SDK 이상 설치 +* Visual Studio 2022 또는 Visual Studio Code와 같은 C# IDE +* **Aspose.BarCode for .NET** NuGet 패키지 (버전 23.10 이상) + +다음 CLI 명령으로 패키지를 설치할 수 있습니다: + +```bash +dotnet add package Aspose.BarCode +``` + +아래 코드는 패키지가 참조되어 있고, 출력 디렉터리에 대한 쓰기 권한이 있다고 가정합니다. + +## 1단계: 프로젝트 설정 및 네임스페이스 가져오기 + +새 콘솔 프로젝트를 만들고 필요한 `using` 지시문을 추가합니다. 이러한 네임스페이스는 `BarcodeGenerator` 클래스와 이미지 형식 열거형을 노출합니다. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**왜 중요한가:** 올바른 네임스페이스를 가져와야 컴파일러가 `BarcodeGenerator` 타입과 `BarCodeImageFormat` 열거형을 찾을 수 있습니다. 네임스페이스가 누락되면 컴파일 오류가 발생해 바코드 생성 과정이 중단됩니다. + +## 2단계: PDF417 인코딩으로 `BarcodeGenerator` 초기화 + +`BarcodeGenerator` 생성자는 두 개의 인수를 받습니다: 바코드 심볼(`EncodeTypes.Pdf417`)과 인코딩할 텍스트. PDF417은 유니코드 기호를 포함한 다양한 문자 집합을 지원합니다. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**설명:** +* `EncodeTypes.Pdf417`은 라이브러리에 PDF417 표준을 사용하도록 지시합니다. +* 샘플 텍스트에는 유니코드 처리를 보여주기 위해 억양이 있는 문자와 저작권 기호가 포함되어 있습니다. + +숫자 데이터만 인코딩하려면 `"1234567890"`과 같은 일반 문자열을 전달하면 됩니다. + +## 3단계: 더 높은 해상도를 위한 X‑dimension 조정 + +X‑dimension은 단일 바코드 모듈(가장 작은 검은색 또는 흰색 요소)의 너비를 제어합니다. 픽셀 값을 작게 설정하면 해상도가 높은 이미지가 생성됩니다. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**왜 조정하나요?** 기본 X‑dimension 값인 3–4 픽셀은 고 DPI 화면에서 바코드가 거칠게 보일 수 있습니다. **2 픽셀**로 줄이면 파일 크기와 가독성 사이의 균형을 맞출 수 있으며, 특히 컴팩트 모드를 사용할 때 효과적입니다. + +## 4단계: 열 수 설정 + +PDF417은 바코드가 포함할 열 수를 지정할 수 있습니다. 열 수가 적으면 바코드가 좁아지지만 높아지고, 열 수가 많으면 넓어지면서 짧아집니다. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**실용적인 팁:** 좁은 라벨에 맞춰야 하는 모바일 티켓의 경우 **3–5** 열이 적합합니다. 데이터가 많아 짧은 바코드가 필요하면 열 수를 늘리세요. + +## 5단계: 빈 행을 잘라내는 컴팩트 모드 활성화 + +컴팩트 모드는 바코드 매트릭스에서 불필요한 행을 제거해 전체 이미지 크기를 줄이면서 인코딩된 데이터는 유지합니다. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**사용 시점:** 저장이나 네트워크 전송을 위해 바코드를 생성한다면, 컴팩트 모드가 PNG 파일 크기를 최대 30 %까지 줄일 수 있습니다. 다만, 일부 레거시 스캐너는 잘라낸 PDF417을 지원하지 않을 수 있으니 대상 하드웨어에서 테스트하세요. + +## 6단계: PNG 이미지로 바코드 저장 + +출력 경로를 지정하고 `Save`를 호출합니다. `BarCodeImageFormat.Png` 열거형은 대부분의 애플리케이션에 적합한 무손실 이미지를 생성합니다. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**결과 확인:** PNG 파일을 이미지 뷰어에서 열어보세요. 샘플 텍스트와 일치하는 고대비, 촘촘한 바코드가 표시됩니다. PDF417 리더(예: ZXing 또는 스마트폰 앱)로 스캔하면 원본 문자열 `"Åspóse.Barcóde©"`가 반환됩니다. + +![PNG로 저장된 생성된 PDF417 바코드 이미지](compact-pdf417.png "C#에서 생성된 PDF417 바코드") + +*위 이미지는 튜토리얼 코드의 최종 출력 결과를 보여줍니다.* + +## 전체 실행 가능한 예제 + +모든 요소를 합친 완전한 콘솔 프로그램은 다음과 같습니다. 복사·붙여넣기 후 바로 실행할 수 있습니다. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### 예상 출력 + +프로그램을 실행하면 다음이 출력됩니다: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +`CompactPdf417.png` 파일에는 제공된 유니코드 문자열을 인코딩한 컴팩트 PDF417 바코드가 들어 있습니다. 표준 PDF417 리더로 스캔하면 정확히 동일한 텍스트가 반환됩니다. + +## 일반적인 변형 및 엣지 케이스 + +| 상황 | 조정 | 이유 | +|-----------|------------|--------| +| **데이터 양이 더 긴 경우** (예: > 150 문자) | `generator.Parameters.Barcode.Pdf417.Columns`를 6‑8로 증가 | 열 수를 늘려 바코드가 과도하게 높아지는 것을 방지합니다. | +| **투명 배경이 필요할 때** | `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` 사용 | 투명 PNG는 UI 오버레이에 더 잘 어울립니다. | +| **웹용 JPEG 생성** | 포맷을 `BarCodeImageFormat.Jpeg`으로 변경하고 필요 시 `ImageQuality` 설정 | JPEG는 파일 크기를 줄이지만 무손실 품질은 감소합니다. | +| **null 또는 빈 입력 처리** | 생성기 생성 전에 입력을 검사: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | 런타임 예외를 방지하고 의미 있는 바코드를 보장합니다. | + +## 프로덕션 사용 팁 + +* **예외 처리:** 디스크 공간 부족이나 잘못된 매개변수와 같은 오류를 로깅하기 위해 바코드 생성 로직을 `try/catch` 블록으로 감싸세요. +* **성능:** 동일한 설정으로 여러 바코드를 생성할 경우 `BarcodeGenerator` 인스턴스를 재사용하고, 저장 사이에 `CodeText` 속성만 업데이트하세요. +* **보안:** 인코딩된 텍스트에 민감한 정보가 포함된 경우, 생성기에 전달하기 전에 암호화하고 스캔 후 복호화하는 방식을 고려하세요. + +## 결론 + +이제 Aspose.BarCode 라이브러리를 사용해 C#에서 **PDF417 바코드 생성** 방법, 컴팩트 모드 설정, 열 수 제어, PNG 이미지로 내보내는 전체 과정을 익혔습니다. 프로젝트 설정부터 엣지 케이스 처리까지 모든 단계를 다뤘으니, 바코드 기반 애플리케이션에 바로 적용할 수 있는 솔루션을 갖추게 되었습니다. + +다음으로 **C#에서 QR 코드 생성**, **배치 바코드 생성**, **모바일 앱과의 바코드 스캔 연동** 등 관련 주제를 탐색해 보세요. 모두 이번에 익힌 `BarcodeGenerator` 기본기를 기반으로 합니다. + +행복한 코딩 되세요! + + +## 다음에 배워야 할 내용 + + +다음 튜토리얼은 이 가이드에서 시연한 기술을 기반으로 하며, 밀접하게 연관된 주제를 다룹니다. 각 리소스는 단계별 설명과 완전한 코드 예제를 제공해 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용할 수 있도록 돕습니다. + +- [PDF417 바코드 생성 – 컴팩트 PDF417 인코딩](/barcode/english/net/compact-pdf417-encoding/) +- [바코드 만들기 – Aspose.BarCode를 이용한 컴팩트 PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Aspose.BarCode for .NET을 사용해 사용자 정의 종횡비로 Aztec 바코드 생성](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/korean/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/korean/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..14617bc57 --- /dev/null +++ b/barcode/korean/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-08-09 +description: BarCodeReader를 사용하여 C#에서 PDF417을 읽는 방법. 바코드 PNG 파일을 읽고, 여러 바코드를 처리하며, + 확장 메타데이터를 추출하는 방법을 배웁니다. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: ko +lastmod: 2026-08-09 +og_description: C#와 Aspose.BarCode를 사용하여 PDF417을 읽는 방법. 이 튜토리얼에서는 바코드 PNG 파일을 읽고, + 하나의 이미지에서 여러 바코드를 처리하며, 확장된 PDF417 메타데이터를 검색하는 방법을 보여줍니다. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: C#에서 PDF417 읽는 방법 – 바코드 리더 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: C#에서 PDF417 읽는 방법 – 완전 바코드 리더 가이드 +url: /ko/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 PDF417 읽는 방법 – 완전한 바코드 리더 가이드 + +.NET 애플리케이션에서 **PDF417을 읽는 방법**이 필요하다면, 이 가이드는 바로 실행할 수 있는 솔루션을 제공합니다. 바코드 PNG를 읽는 방법, 동일한 이미지에서 여러 바코드를 처리하는 방법, 그리고 많은 스캐너가 숨기는 확장 PDF417 필드를 추출하는 방법을 확인할 수 있습니다. + +PDF417 바코드 읽기는 물류, 티켓 발행, 문서 관리에서 일반적입니다. 이 튜토리얼을 마치면 Macro PDF417 이미지를 디코딩하고, 모든 결과를 표시하며, 추가 정보(파일 ID, 세그먼트 수, 타임스탬프 등)를 자체 비즈니스 로직에 활용할 수 있습니다. + +## 전제 조건 + +- .NET 6.0 이상 (코드는 .NET Framework 4.7+에서도 작동합니다) +- Visual Studio 2022 또는 기타 C# IDE +- **Aspose.BarCode for .NET** (무료 체험 또는 라이선스가 있는 NuGet 패키지) +- Macro PDF417 바코드가 포함된 PNG 이미지 (샘플 파일 이름은 `ExtPDF417Meta.png`) + +> **Pro tip:** NuGet 콘솔을 사용하여 라이브러리를 설치합니다: +> `dotnet add package Aspose.BarCode` + +## C#에서 BarCodeReader를 사용하여 PDF417 읽는 방법 + +솔루션의 핵심은 `BarCodeReader` 클래스입니다. 이 클래스는 이미지 경로와 엔진에게 어떤 심볼을 찾아야 하는지 알려주는 `DecodeType` 열거형을 받습니다. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### 왜 이렇게 동작하는가 + +- **`DecodeType.MacroPdf417`**는 리더에게 Macro PDF417 변형을 찾도록 지시하며, 이는 4단계에서 본 추가 필드를 저장합니다. +- `using` 블록은 리더를 자동으로 해제하여 파일 핸들을 해제합니다. +- `ReadBarCodes()`는 요청된 유형과 일치하는 **모든** 바코드를 반환하므로, 이미지에 하나만 있더라도 *read multiple barcodes* 요구 사항을 충족합니다. + +프로그램을 실행하면 다음과 유사한 출력이 표시됩니다: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## C# 바코드 리더를 사용하여 여러 바코드 읽기 + +이미지에 여러 개의 Macro PDF417 심볼이 포함되어 있는 경우(예: 티켓 배치가 스캔된 페이지), 동일한 `foreach` 루프가 각각을 처리합니다. 추가 코드가 필요 없으며, 리더가 내부적으로 결과를 집계합니다. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### 흔히 발생하는 실수 + +- **Image format:** 리더는 PNG, JPEG, BMP, TIFF를 지원합니다. 디코딩할 수 없는 형식을 사용하면 빈 컬렉션이 반환됩니다. 그래서 튜토리얼에서 *read barcode PNG*를 강조합니다. +- **Resolution:** 저해상도 이미지(< 300 dpi)는 세그먼트를 놓칠 수 있습니다. 가능하면 해상도를 높이거나 고품질 스캔을 요청하세요. +- **Macro flag:** `DecodeType.MacroPdf417`를 빼먹으면 엔진이 일반 PDF417으로 제한되고 확장 데이터가 버려집니다. *read barcode extended* 필드가 필요할 때는 항상 매크로 유형을 지정하세요. + +## 바코드 PNG 파일 읽기 – 모범 사례 + +PNG 파일 작업은 손실 없는 픽셀 데이터를 보존하기 때문에 간단합니다. 다음은 빠른 체크리스트입니다: + +1. 리더를 만들기 전에 파일이 존재하는지 확인합니다. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. `Image.FromFile`은 사전 처리(회전, 자르기)가 필요할 때만 사용합니다. `BarCodeReader`는 파일을 직접 열 수 있어 추가 메모리 할당을 피합니다. +3. PNG에 투명성이 포함되어 있어도 바코드가 불투명 픽셀에 렌더링되므로 리더는 정상 작동합니다. + +## 확장 PDF417 메타데이터 접근 + +`Extended.Pdf417` 객체는 PDF417 사양에 정의된 모든 선택적 필드를 노출합니다. 이러한 필드를 도메인 모델에 매핑하거나 데이터베이스에 저장하거나 검증에 사용할 수 있습니다. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +모델을 채웁니다: + + + +## 다음에 배워야 할 내용은? + +다음 튜토리얼은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료에는 전체 작동 코드 예제와 단계별 설명이 포함되어 있어 추가 API 기능을 마스터하고 자체 프로젝트에서 대체 구현 방식을 탐색하는 데 도움이 됩니다. + +- [Aspose.BarCode for .NET로 DataMatrix 바코드 읽는 방법](/barcode/english/net/datamatrix-barcode-reading/) +- [Aspose.BarCode로 Compact PDF417 바코드 생성하기](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [DataMatrix 바코드 C# 읽기 – 자동 모드 생성](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/polish/net/compact-pdf417-encoding/_index.md b/barcode/polish/net/compact-pdf417-encoding/_index.md index 90d161b27..d2d3671d7 100644 --- a/barcode/polish/net/compact-pdf417-encoding/_index.md +++ b/barcode/polish/net/compact-pdf417-encoding/_index.md @@ -88,6 +88,22 @@ Poza podstawami, oto kilka praktycznych wskazówek, które usprawnią Twój prze Dowiedz się, jak generować kody Compact PDF417 przy użyciu Aspose.BarCode dla .NET. Kompleksowy przewodnik z instrukcjami krok po kroku i przykładami kodu. +### [Przykład Aspose Barcode: generowanie Macro PDF417 w C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) + +Przykład pokazujący, jak wygenerować kod Macro PDF417 w języku C# przy użyciu biblioteki Aspose.BarCode. + +### [Generowanie kodu kreskowego PDF417 w C# – przewodnik krok po kroku](./generate-pdf417-barcode-in-c-step-by-step-guide/) + +Szczegółowy przewodnik, jak wygenerować kod kreskowy PDF417 w C# przy użyciu Aspose.BarCode, z pełnym przykładem kodu. + +### [Generowanie kodu kreskowego z tekstu w C# – kompletny przewodnik krok po kroku](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) + +Pełny przewodnik, jak w C# wygenerować kod kreskowy z dowolnego tekstu przy użyciu Aspose.BarCode. + +### [Jak odczytać PDF417 w C# – kompletny przewodnik czytnika kodów kreskowych](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) + +Pełny przewodnik, jak w C# odczytywać kody PDF417 przy użyciu Aspose.BarCode, z przykładami kodu i wskazówkami. + ## Najczęściej zadawane pytania **Q:** Jaką maksymalną ilość danych mogę przechowywać w kodzie Compact PDF417? @@ -116,4 +132,4 @@ Dowiedz się, jak generować kody Compact PDF417 przy użyciu Aspose.BarCode dla {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/polish/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/polish/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..b04b5a904 --- /dev/null +++ b/barcode/polish/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-09 +description: Przykład kodu kreskowego Aspose pokazujący, jak używać generatora kodów + kreskowych w C# do tworzenia Macro PDF417 z pełnym wsparciem metadanych. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: pl +lastmod: 2026-08-09 +og_description: Przykład kodu kreskowego Aspose demonstruje użycie generatora kodów + kreskowych w C# do tworzenia kodu Macro PDF417, który zawiera identyfikator pliku, + dane segmentu, znacznik czasu i inne metadane. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Przykład kodu kreskowego Aspose – tworzenie Macro PDF417 w C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Przykład kodu kreskowego Aspose: generowanie Macro PDF417 w C#' +url: /pl/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Przykład Aspose barcode: generowanie Macro PDF417 w C# + +Jeśli potrzebujesz **aspose barcode example**, które tworzy kod kreskowy Macro PDF417, ten przewodnik pokaże Ci, jak zrobić to za pomocą **barcode generator C#**. Zobaczysz wszystkie wymagane ustawienia, od podstawowych wymiarów po pełny zestaw pól metadanych Macro PDF417, i otrzymasz obraz PNG gotowy do dalszego przetwarzania. + +Samouczek obejmuje kompletny przepływ pracy, wyjaśnia, dlaczego każdy parametr ma znaczenie, i dostarcza gotowy do uruchomienia przykład kodu. Nie są wymagane żadne zewnętrzne odwołania; możesz skopiować kod, dostosować wartości i uruchomić go od razu. + +## Wymagania wstępne + +- .NET 6.0 (lub nowszy) zainstalowany +- Visual Studio 2022 lub dowolne IDE kompatybilne z C# +- Ważna licencja na **Aspose.BarCode for .NET** (bezpłatna wersja próbna działa w tym przykładzie) + +Dodaj pakiet NuGet Aspose.BarCode do swojego projektu: + +```bash +dotnet add package Aspose.BarCode +``` + +## Krok 1: Utwórz instancję generatora kodów kreskowych C# + +Pierwszym krokiem jest utworzenie instancji `BarcodeGenerator` z wartością wyliczenia `EncodeTypes.MacroPdf417` oraz tekstem, który chcesz zakodować. Tekst może zawierać znaki Unicode, które biblioteka obsługuje automatycznie. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Dlaczego to jest ważne*: `EncodeTypes.MacroPdf417` informuje silnik, aby wygenerował symbol Macro PDF417, który obsługuje segmentowane dane oraz dodatkowe metadane na poziomie pliku. Instrukcja `using` zapewnia zwolnienie niezarządzanych zasobów po zapisaniu obrazu. + +## Krok 2: Zdefiniuj podstawowy wygląd kodu kreskowego + +Kod kreskowy Macro PDF417 składa się z kwadratowych modułów. Kontrola rozmiaru modułu i liczby kolumn wpływa zarówno na czytelność, jak i rozmiar pliku. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Dlaczego to jest ważne*: `XDimension.Pixels` określa gęstość wizualną; wartość 2 piksele dobrze sprawdza się na wyświetlaczach, jednocześnie utrzymując obraz małym. Dostosuj liczbę kolumn do ograniczeń układu — więcej kolumn tworzy szerszy, krótszy kod kreskowy. + +## Krok 3: Ustaw specyficzne metadane Macro PDF417 + +Macro PDF417 rozszerza standardowy format PDF417 o pola, które umożliwiają odtworzenie dużych plików z wielu segmentów kodu kreskowego. Każde pole jest opcjonalne, ale ich ustawienie demonstruje pełne możliwości API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Dlaczego to jest ważne*: +- `MacroPdf417FileID` łączy wszystkie segmenty należące do tego samego logicznego pliku. +- `MacroPdf417SegmentID` i `MacroPdf417SegmentsCount` umożliwiają dekoderowi prawidłowe uporządkowanie fragmentów. +- `MacroPdf417Checksum` zapewnia szybkie sprawdzenie integralności bez dekodowania całego ładunku. +- `MacroPdf417FileSize` i `MacroPdf417TimeStamp` pozwalają systemom downstream zweryfikować, że odtworzony plik jest zgodny z oryginałem. +- `MacroPdf417Addressee` / `MacroPdf417Sender` są przydatne w scenariuszach logistycznych lub wymiany dokumentów. +- Ustawienie `MacroPdf417Terminator` na `Set` oznacza, że ten kod kreskowy jest ostatnim segmentem, co upraszcza algorytm rekonstrukcji. + +## Krok 4: Zapisz wygenerowany obraz kodu kreskowego + +Na koniec zapisz kod kreskowy do pliku PNG. Możesz wybrać dowolny obsługiwany format (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Dlaczego to jest ważne*: PNG zachowuje bezstratne dane pikseli, zapewniając, że skanery odczytają dokładny wzór modułów, który skonfigurowałeś. Zmiana formatu może wpłynąć na jakość wizualną i rozmiar pliku. + +### Oczekiwany wynik + +Uruchomienie pełnego programu tworzy plik o nazwie **ExtPDF417Meta.png**. Otwarcie obrazu pokazuje prostokątny kod kreskowy Macro PDF417 z zakodowanym tekstem „Åspóse.Barcóde©”, a gęstość wizualna odpowiada ustawionej 2‑pikselowej wymiarowi X. Skanowanie obrazu przy użyciu czytnika kompatybilnego z PDF417 zwraca wszystkie pola metadanych zdefiniowane w Kroku 3. + +## Pełny działający przykład + +Skopiuj poniższy kod do nowego projektu konsolowego (`dotnet new console`) i zamień `YOUR_DIRECTORY` na ścieżkę bezwzględną lub względną, która istnieje na Twoim komputerze. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Uruchom program (`dotnet run`). Po wykonaniu sprawdź, czy plik PNG pojawił się w określonym miejscu. Użyj dowolnej aplikacji do odczytu kodów kreskowych obsługującej Macro PDF417, aby potwierdzić, że metadane zostały poprawnie osadzone. + +## Typowe warianty i przypadki brzegowe + +- **Różne formaty obrazu**: Zastąp `BarCodeImageFormat.Png` przez `Jpeg`, `Bmp` lub `Tiff`, jeśli Twój system downstream preferuje inny format. +- **Zmiana rozmiaru modułu**: Większe wartości `XDimension.Pixels` poprawiają niezawodność skanowania na skanerach o niskiej rozdzielczości, ale zwiększają rozmiar obrazu. +- **Wiele segmentów**: Aby wygenerować plik wielosegmentowy, utwórz serię kodów kreskowych, zwiększaj `MacroPdf417SegmentID` dla każdego i utrzymuj stały `MacroPdf417FileID`. Tylko ostatni segment powinien mieć ustawiony `MacroPdf417Terminator`. +- **Obsługa Unicode**: Generator automatycznie koduje znaki Unicode; upewnij się, że Twój ciąg źródłowy używa kodowania UTF-8, jeśli odczytujesz go z zewnętrznego pliku. +- **Obsługa błędów**: Owiń blok `using` w try‑catch, aby przechwycić `BarCodeException` w przypadku nieprawidłowych parametrów (np. liczba kolumn poza zakresem). + +## Porady profesjonalne + +- **Wydajność**: Ponownie używaj jednej instancji `BarcodeGenerator` przy tworzeniu wielu kodów kreskowych z tymi samymi ustawieniami; zmieniaj tylko właściwość `CodeText` pomiędzy zapisami. +- **Szacowanie rozmiaru pliku**: Pole `MacroPdf417FileSize` powinno odpowiadać liczbie bajtów oryginalnego ładunku; niezgodności mogą powodować błędy walidacji w downstream. +- **Testowanie**: Waliduj wygenerowane kody kreskowe zarówno przy użyciu wbudowanego dekodera Aspose (`BarCodeReader`), jak i skanera zewnętrznego, aby zapewnić interoperacyjność. + +## Zakończenie + +Ten **aspose barcode example + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każde źródło zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Jak utworzyć kod kreskowy – Compact PDF417 przy użyciu Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Jak utworzyć strefę ciszy kodu kreskowego dla Code 16K przy użyciu Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [Jak utworzyć strefę ciszy kodu kreskowego dla ITF-14 przy użyciu Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/polish/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/polish/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..014cced15 --- /dev/null +++ b/barcode/polish/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-08-09 +description: Generuj kod kreskowy z tekstu w C# przy użyciu Aspose.BarCode. Dowiedz + się, jak generować kod kreskowy, obsługiwać znaki specjalne i szybko tworzyć kod + PDF417 w C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: pl +lastmod: 2026-08-09 +og_description: Generuj kod kreskowy z tekstu w C# przy użyciu Aspose.BarCode. Ten + samouczek pokazuje, jak generować kod kreskowy, obsługiwać znaki specjalne oraz + tworzyć kod PDF417 w C# z pełnym kodem. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Generowanie kodu kreskowego z tekstu w C# – szybki przewodnik krok po kroku +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Generowanie kodu kreskowego z tekstu w C# – kompletny przewodnik krok po kroku +url: /pl/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wygeneruj kod kreskowy z tekstu w C# – kompletny przewodnik krok po kroku + +Jeśli potrzebujesz **generate barcode from text** w aplikacji .NET, ten przewodnik poprowadzi Cię przez cały proces. Zobaczysz, jak generować kod kreskowy, obsługiwać znaki specjalne i stworzyć implementację kodu kreskowego PDF417 w C#, która działa od razu. + +Generowanie kodu kreskowego z tekstu jest powszechnym wymaganiem w systemach inwentaryzacji, platformach biletowych i przepływach dokumentów. Po zakończeniu tego samouczka będziesz mieć działającą aplikację konsolową C#, która tworzy obraz PNG MicroPdf417 przy użyciu Aspose.BarCode. Nie są wymagane żadne zewnętrzne usługi, a kod obsługuje znaki Unicode, takie jak „Å”, „©” i „é”. + +## Prerequisites + +- .NET 6.0 SDK lub nowszy (kod działa również z .NET Core 3.1 i .NET Framework 4.7+) +- Visual Studio 2022 (lub dowolne IDE obsługujące C#) +- **Aspose.BarCode for .NET** NuGet package + ```bash + dotnet add package Aspose.BarCode + ``` +- Podstawowa znajomość składni C# + +## Wygeneruj kod kreskowy z tekstu – konfiguracja generatora + +Pierwszym krokiem jest utworzenie instancji `BarcodeGenerator`, która wie, jaki **barcode encode type** jest potrzebny. W tym samouczku używamy `EncodeTypes.MicroPdf417`, który jest kompaktową odmianą PDF417 odpowiednią dla krótkich ciągów danych. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Why this works:** +- `EncodeTypes.MicroPdf417` informuje bibliotekę, aby użyła rodziny PDF417, spełniając wymaganie **create pdf417 barcode c#**. +- Konstruktor przyjmuje surowy tekst, co jest istotą **generate barcode from text**. +- Obsługa Unicode jest wbudowana, więc znaki takie jak „Å” i „©” są kodowane poprawnie, co rozwiązuje problem **barcode with special characters**. + +## Jak generować kod kreskowy ze znakami specjalnymi + +Gdy Twoje dane zawierają symbole nie‑ASCII, musisz zapewnić, że generator używa kodowania UTF‑8. Aspose.BarCode automatycznie wykrywa Unicode, ale możesz jawnie ustawić kodowanie tekstu, jeśli napotkasz problemy: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Dodanie tej linii przed `ConfigureGenerator` zapewnia, że **barcode with special characters** renderuje się poprawnie na każdej platformie. + +### Praktyczna wskazówka +Jeśli wynik wygląda na zniekształcony, sprawdź, czy czcionka używana przez renderer kodu kreskowego obsługuje wymagane glify. Możesz osadzić własną czcionkę TrueType za pomocą: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Typy kodowania kodów kreskowych, które możesz wybrać + +Aspose.BarCode obsługuje dziesiątki **barcode encode types**, z których każdy jest odpowiedni dla różnych zastosowań: + +| Typ kodowania | Typowe zastosowanie | +|------------------------------|------------------------------------------| +| `EncodeTypes.Code128` | Etykiety wysyłkowe, inwentaryzacja | +| `EncodeTypes.QR` | Płatności mobilne, adresy URL | +| `EncodeTypes.Pdf417` | Prawo jazdy, karty pokładowe | +| `EncodeTypes.MicroPdf417` | Małe ładunki danych, ograniczona przestrzeń | +| `EncodeTypes.DataMatrix` | Małe przedmioty, wysoka gęstość danych | + +Zmiana typu kodowania jest tak prosta, jak zamiana wartości wyliczenia w konstruktorze: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Ta elastyczność pozwala odpowiadać na pytania dotyczące **barcode encode types** bez opuszczania IDE. + +## Utwórz kod kreskowy PDF417 w C# – końcowe kroki i weryfikacja + +Po skonfigurowaniu generatora, ostatnia część **create pdf417 barcode c#** to zapisanie obrazu i potwierdzenie wyniku. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Uruchom program (`dotnet run`) i powinieneś zobaczyć komunikat w konsoli podobny do: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Otwórz plik PNG; zobaczysz wyraźny kod MicroPdf417, który koduje ciąg „Åspóse.Barcóde©”. Skanowanie go za pomocą mobilnego skanera kodów kreskowych (np. ZXing) zwraca oryginalny tekst, co dowodzi, że **generate barcode from text** działa nawet ze znakami specjalnymi. + +### Przypadek brzegowy: bardzo długi tekst + +MicroPdf417 ma maksymalną pojemność danych wynoszącą 1 KB. Jeśli Twój wejściowy tekst przekracza ten limit, biblioteka zgłasza `ArgumentException`. Aby obsłużyć to elegancko: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Dla większych ładunków danych przełącz się na pełny `EncodeTypes.Pdf417` lub `EncodeTypes.DataMatrix`. + +## Typowe pułapki i jak ich unikać + +| Problem | Przyczyna | Rozwiązanie | +|---------------------------------------|---------------------------------------------|-------------| +| Kod kreskowy jest rozmyty | XDimension jest zbyt niska (np. 1 px) | Zwiększ `XDimension.Pixels` do 2‑3 px | +| Znaki Unicode zamieniają się na `?` | Domyślne kodowanie tekstu to ASCII | Ustaw `TextEncoding = Encoding.UTF8` | +| Plik obrazu nie został utworzony | Katalog wyjściowy nie istnieje | Użyj `Directory.CreateDirectory` przed `Save` | +| Skaner nie może odczytać kodu kreskowego | Zbyt wiele kolumn dla krótkich danych | Zmniejsz `Pdf417.Columns` (np. 3‑4) | + +## Pełny kod źródłowy (gotowy do skopiowania) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Expected output:** plik o nazwie `MicroPdf417.png` znajdujący się w folderze `output`, zawierający wyraźny kod MicroPdf417, który koduje oryginalny ciąg ze znakami specjalnymi. + +## Zakończenie + +Teraz wiesz, jak **generate barcode from text** w C# przy użyciu Aspose.BarCode, jak obsługiwać **barcode with special characters**, oraz jak **create pdf417 barcode c#** z pełną kontrolą nad opcjami kodowania. Dostosowując **barcode encode types**, możesz generować kody QR, Code128, DataMatrix lub dowolny inny obsługiwany format. + +Następnie, zapoznaj się z poniższymi tematami, aby pogłębić swoją wiedzę o kodach kreskowych: + +- **How to generate barcode** w partiach dla tysięcy rekordów (użyj `Parallel.ForEach` dla zwiększenia szybkości) +- Dostosowywanie kolorów i dodawanie logo wewnątrz kodu kreskowego +- Integracja generowania kodów kreskowych z API ASP.NET Core w celu dostarczania obrazów w locie +- Używanie innych bibliotek, takich jak ZXing.Net lub IronBarcode, jako otwarto‑źródłowych alternatyw + +Śmiało eksperymentuj z różnymi wymiarami, ustawieniami kolumn i typami kodowania. Powodzenia w kodowaniu i niech Twoje aplikacje skanują bezbłędnie! + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Jak stworzyć kod kreskowy – kompaktowy PDF417 z Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Jak wygenerować kod kreskowy – konfiguracja Code 39 z Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Jak wygenerować kod kreskowy – typy kodów jednowymiarowych](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/polish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/polish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..b835c523a --- /dev/null +++ b/barcode/polish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-09 +description: Szybko generuj kod kreskowy PDF417 w C#. Dowiedz się, jak generować PDF417 + w trybie kompaktowym, z kontrolą kolumn i wyjściem PNG przy użyciu API BarcodeGenerator. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: pl +lastmod: 2026-08-09 +og_description: Generuj kod kreskowy PDF417 w C# przy użyciu zwięzłego przykładu. + Ten przewodnik pokazuje, jak skonfigurować tryb kompaktowy, ustawić liczbę kolumn + i zapisać wynik jako obraz PNG. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Generowanie kodu kreskowego PDF417 w C# – kompletny poradnik +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: Generowanie kodu kreskowego PDF417 w C# – przewodnik krok po kroku +url: /pl/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wygeneruj kod kreskowy PDF417 w C# – przewodnik krok po kroku + +Jeśli potrzebujesz **wygenerować kod kreskowy PDF417** w aplikacji .NET, ten tutorial pokaże Ci dokładnie, jak to zrobić. Zobaczysz kompletny, działający program, który tworzy kompaktowy kod kreskowy PDF417, dostosowuje jego rozmiar i zapisuje obraz jako plik PNG. + +Generowanie kodu kreskowego PDF417 jest powszechnym wymogiem w przypadku biletów mobilnych, śledzenia zapasów i zabezpieczania dokumentów. Ten przewodnik obejmuje niezbędne opcje konfiguracji, wyjaśnia, dlaczego każde ustawienie ma znaczenie, i dostarcza praktycznych wskazówek do zastosowań w rzeczywistym świecie. + +## Wymagania wstępne + +* .NET 6.0 SDK lub nowszy zainstalowany +* IDE C# takie jak Visual Studio 2022 lub Visual Studio Code +* Pakiet NuGet **Aspose.BarCode for .NET** (wersja 23.10 lub nowsza) + +Możesz zainstalować pakiet przy użyciu następującego polecenia CLI: + +```bash +dotnet add package Aspose.BarCode +``` + +Poniższy kod zakłada, że pakiet jest odwołany i że masz uprawnienia do zapisu w katalogu wyjściowym. + +## Krok 1: Utwórz projekt i zaimportuj przestrzenie nazw + +Utwórz nowy projekt konsolowy i dodaj wymagane dyrektywy `using`. Te przestrzenie nazw udostępniają klasę `BarcodeGenerator` oraz wyliczenie formatu obrazu. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Dlaczego to ważne:** Importowanie właściwych przestrzeni nazw zapewnia, że kompilator może znaleźć typ `BarcodeGenerator` oraz wyliczenie `BarCodeImageFormat`. Brak przestrzeni nazw powoduje błąd kompilacji, który zatrzymuje proces generowania kodu kreskowego. + +## Krok 2: Zainicjalizuj `BarcodeGenerator` z kodowaniem PDF417 + +Konstruktor `BarcodeGenerator` przyjmuje dwa argumenty: symbolikę kodu kreskowego (`EncodeTypes.Pdf417`) oraz tekst, który chcesz zakodować. PDF417 obsługuje szeroki zakres znaków, w tym symbole Unicode. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Wyjaśnienie:** +* `EncodeTypes.Pdf417` informuje bibliotekę, aby użyła standardu PDF417. +* Przykładowy tekst zawiera znaki diakrytyczne oraz symbol praw autorskich, aby zademonstrować obsługę Unicode. + +Jeśli potrzebujesz zakodować wyłącznie dane numeryczne, możesz przekazać zwykły ciąg znaków, np. `"1234567890"`. + +## Krok 3: Dostosuj wymiar X dla wyższej rozdzielczości + +Wymiar X kontroluje szerokość pojedynczego modułu kodu kreskowego (najmniejszego czarnego lub białego elementu). Ustawienie mniejszej wartości w pikselach daje obraz o wyższej rozdzielczości. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Dlaczego to dostosować?** Domyślny wymiar X wynoszący 3–4 piksele może powodować, że kod kreskowy wygląda surowo na ekranach o wysokiej rozdzielczości DPI. Zmniejszenie go do **2 pikseli** równoważy czytelność z rozmiarem pliku, szczególnie gdy później włączysz tryb kompaktowy. + +## Krok 4: Skonfiguruj liczbę kolumn + +PDF417 pozwala określić, ile kolumn ma zawierać kod kreskowy. Mniej kolumn sprawia, że kod jest węższy, ale wyższy, natomiast więcej kolumn tworzy szerszy, niższy kod. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Praktyczna wskazówka:** Dla biletów mobilnych, które muszą zmieścić się w wąskiej etykiecie, liczba kolumn **3–5** sprawdza się dobrze. Zwiększ liczbę, jeśli masz dużo danych i chcesz krótszy kod kreskowy. + +## Krok 5: Włącz tryb kompaktowy, aby usunąć puste wiersze + +Tryb kompaktowy usuwa niepotrzebne wiersze z macierzy kodu kreskowego, zmniejszając całkowity rozmiar obrazu bez utraty zakodowanych danych. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Kiedy używać:** Jeśli generujesz kody kreskowe do przechowywania lub transmisji sieciowej, tryb kompaktowy może zmniejszyć plik PNG nawet o 30 %. Jednak niektóre starsze skanery mogą nie obsługiwać przyciętego PDF417; przetestuj na docelowym sprzęcie. + +## Krok 6: Zapisz kod kreskowy jako obraz PNG + +Wybierz ścieżkę wyjściową i wywołaj `Save`. Wyliczenie `BarCodeImageFormat.Png` generuje obraz bezstratny, odpowiedni dla większości zastosowań. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Weryfikacja wyniku:** Otwórz plik PNG w dowolnym przeglądarce obrazów. Powinieneś zobaczyć gęsty, wysokokontrastowy kod kreskowy, który odpowiada przykładowemu tekstowi. Zeskanowanie obrazu przy użyciu czytnika PDF417 (np. ZXing lub aplikacji na smartfon) zwraca oryginalny ciąg `"Åspóse.Barcóde©"`. + +![Wygenerowany obraz kodu kreskowego PDF417 zapisany jako PNG](compact-pdf417.png "Wygenerowany kod kreskowy PDF417 w C#") + +*Powyższy obraz przedstawia końcowy wynik kodu z tutorialu.* + +## Pełny, działający przykład + +Łącząc wszystkie elementy, oto kompletny program konsolowy, który możesz skopiować, wkleić i uruchomić. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Oczekiwany wynik + +Uruchomienie programu wypisuje: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +Plik `CompactPdf417.png` zawiera kompaktowy kod kreskowy PDF417, który koduje podany ciąg Unicode. Zeskanowanie obrazu standardowym czytnikiem PDF417 zwraca dokładny tekst. + +## Typowe warianty i przypadki brzegowe + +| Sytuacja | Dostosowanie | Powód | +|-----------|------------|--------| +| **Dłuższy ładunek danych** (np. > 150 znaków) | Zwiększ `generator.Parameters.Barcode.Pdf417.Columns` do 6‑8 | Więcej kolumn zapobiega nadmiernemu wydłużeniu kodu. | +| **Potrzeba przezroczystego tła** | Użyj `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | Przezroczysty PNG lepiej integruje się z nakładkami UI. | +| **Generowanie JPEG dla sieci** | Zmień format na `BarCodeImageFormat.Jpeg` i opcjonalnie ustaw `ImageQuality` | JPEG zmniejsza rozmiar pliku kosztem utraty bezstratnej jakości. | +| **Obsługa null lub pustego wejścia** | Zabezpiecz wejście przed utworzeniem generatora: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Zapobiega wyjątkom w czasie wykonywania i zapewnia sensowne kody kreskowe. | + +## Wskazówki do użycia w produkcji + +* **Obsługa wyjątków:** Otocz logikę generowania w blok `try/catch`, aby rejestrować błędy, takie jak niewystarczająca przestrzeń dyskowa lub nieprawidłowe parametry. +* **Wydajność:** Ponownie używaj jednej instancji `BarcodeGenerator` przy generowaniu wielu kodów kreskowych z tymi samymi ustawieniami; aktualizuj jedynie właściwość `CodeText` pomiędzy zapisami. +* **Bezpieczeństwo:** Gdy zakodowany tekst zawiera wrażliwe informacje, rozważ jego szyfrowanie przed przekazaniem do generatora oraz odszyfrowanie po zeskanowaniu. + +## Podsumowanie + +Teraz wiesz, jak **wygenerować kod kreskowy PDF417** w C# przy użyciu biblioteki Aspose.BarCode, skonfigurować tryb kompaktowy, kontrolować liczbę kolumn i wyeksportować wynik jako obraz PNG. Ten tutorial omówił każdy krok, od konfiguracji projektu po obsługę przypadków brzegowych, dostarczając gotowe rozwiązanie dla aplikacji opartych na kodach kreskowych. + +Następnie, zapoznaj się z powiązanymi tematami, takimi jak **tworzenie kodów QR w C#**, **generowanie kodów kreskowych w partiach** oraz **integracja skanowania kodów kreskowych z aplikacjami mobilnymi**. Każdy z nich opiera się na tych samych podstawach `BarcodeGenerator`, które właśnie opanowałeś. + +Miłego kodowania! + +## Co powinieneś nauczyć się dalej? + +Poniższe tutoriale obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Jak generować kody kreskowe PDF417 – kompaktowe kodowanie PDF417](/barcode/english/net/compact-pdf417-encoding/) +- [Jak utworzyć kod kreskowy – kompaktowy PDF417 z Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Jak generować kod kreskowy Aztec z niestandardowym współczynnikiem proporcji przy użyciu Aspose.BarCode dla .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/polish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/polish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..53af381c6 --- /dev/null +++ b/barcode/polish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-09 +description: Jak odczytać PDF417 w C# przy użyciu BarCodeReader. Dowiedz się, jak + odczytywać pliki PNG z kodami kreskowymi, obsługiwać wiele kodów kreskowych i wyodrębniać + rozszerzone metadane. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: pl +lastmod: 2026-08-09 +og_description: Jak odczytać PDF417 w C# przy użyciu Aspose.BarCode. Ten samouczek + pokazuje, jak odczytywać pliki PNG z kodami kreskowymi, przetwarzać wiele kodów + kreskowych na jednym obrazie oraz pobierać rozszerzone metadane PDF417. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Jak odczytać PDF417 w C# – samouczek czytnika kodów kreskowych +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Jak odczytać PDF417 w C# – kompletny przewodnik po czytniku kodów kreskowych +url: /pl/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak odczytać PDF417 w C# – kompletny przewodnik po czytniku kodów kreskowych + +Jeśli potrzebujesz **jak odczytać PDF417** w aplikacji .NET, ten przewodnik zapewnia gotowe do uruchomienia rozwiązanie. Zobaczysz, jak odczytać PNG z kodem kreskowym, przetworzyć kilka kodów w tym samym obrazie oraz wyciągnąć rozszerzone pola PDF417, które wiele skanerów ukrywa. + +Odczytywanie kodów PDF417 jest powszechne w logistyce, biletowaniu i zarządzaniu dokumentami. Po zakończeniu tego samouczka będziesz mógł zdekodować obraz Macro PDF417, wyświetlić każdy wynik i wykorzystać dodatkowe informacje (identyfikator pliku, liczba segmentów, znaczniki czasu itp.) w swojej logice biznesowej. + +## Wymagania wstępne + +- .NET 6.0 lub nowszy (kod działa również z .NET Framework 4.7+) +- Visual Studio 2022 lub dowolne IDE C# +- **Aspose.BarCode for .NET** (bezpłatna wersja próbna lub licencjonowany pakiet NuGet) +- Obraz PNG zawierający kod Macro PDF417 (przykładowy plik nosi nazwę `ExtPDF417Meta.png`) + +> **Wskazówka:** Zainstaluj bibliotekę za pomocą konsoli NuGet: +> `dotnet add package Aspose.BarCode` + +## Jak odczytać PDF417 za pomocą BarCodeReader w C# + +Głównym elementem rozwiązania jest klasa `BarCodeReader`. Przyjmuje ona ścieżkę do obrazu oraz wyliczenie `DecodeType`, które informuje silnik, jaką symbologię ma szukać. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Dlaczego to działa + +- **`DecodeType.MacroPdf417`** informuje czytnik, aby szukał wariantu Macro PDF417, który przechowuje dodatkowe pola widoczne w kroku 4. +- Blok `using` automatycznie zwalnia czytnik, uwalniając uchwyty plików. +- `ReadBarCodes()` zwraca **wszystkie** kody kreskowe pasujące do żądanego typu, co spełnia wymóg *odczytu wielu kodów kreskowych* nawet jeśli obraz zawiera tylko jeden. + +Uruchomienie programu wypisuje wynik podobny do: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## Używanie czytnika kodów kreskowych w C# do odczytu wielu kodów + +Jeśli obraz zawiera kilka symboli Macro PDF417 (na przykład zeskanowaną stronę z partią biletów), ta sama pętla `foreach` przetwarza każdy z nich. Nie jest wymagany dodatkowy kod; czytnik wewnętrznie agreguje wyniki. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Częste pułapki + +- **Format obrazu:** Czytnik obsługuje PNG, JPEG, BMP i TIFF. Jeśli spróbujesz użyć formatu, którego nie potrafi zdekodować, otrzymasz pustą kolekcję. Dlatego w samouczku podkreślono *odczyt kodu kreskowego PNG*. +- **Rozdzielczość:** Obrazy o niskiej rozdzielczości (< 300 dpi) mogą powodować pominięcie segmentów. Zwiększ rozmiar lub poproś o skan o wyższej jakości, gdy to możliwe. +- **Flaga Macro:** Zapomnienie o `DecodeType.MacroPdf417` ogranicza silnik do zwykłego PDF417 i odrzuca rozszerzone dane. Zawsze określaj typ macro, gdy potrzebujesz pól *odczytu rozszerzonych kodów kreskowych*. + +## Odczytywanie plików PNG z kodami kreskowymi – najlepsze praktyki + +Praca z plikami PNG jest prosta, ponieważ format zachowuje bezstratne dane pikseli. Oto szybka lista kontrolna: + +1. Sprawdź, czy plik istnieje przed utworzeniem czytnika. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Używaj `Image.FromFile` tylko wtedy, gdy potrzebujesz wstępnej obróbki (obrót, przycięcie). `BarCodeReader` może otworzyć plik bezpośrednio, co unika dodatkowej alokacji pamięci. +3. Jeśli PNG zawiera przezroczystość, czytnik nadal działa, ponieważ kod kreskowy jest renderowany na nieprzezroczystych pikselach. + +## Dostęp do rozszerzonych metadanych PDF417 + +Obiekt `Extended.Pdf417` udostępnia każde opcjonalne pole zdefiniowane w specyfikacji PDF417. Możesz mapować te pola na model domenowy, przechowywać je w bazie danych lub używać do walidacji. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Wypełnij model: + + + +## Co warto nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każde źródło zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Jak odczytać kody DataMatrix za pomocą Aspose.BarCode dla .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Jak stworzyć kod kreskowy – Compact PDF417 z Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Odczyt kodu DataMatrix w C# – Generowanie trybu DataMatrix (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/portuguese/net/compact-pdf417-encoding/_index.md b/barcode/portuguese/net/compact-pdf417-encoding/_index.md index 9b00326c0..4b7253a7b 100644 --- a/barcode/portuguese/net/compact-pdf417-encoding/_index.md +++ b/barcode/portuguese/net/compact-pdf417-encoding/_index.md @@ -85,6 +85,18 @@ Beyond the basics, here are some practical tips to streamline your workflow: ### [Criando Códigos de Barras Compact PDF417](./compact-pdf417-basic-configuration/) Learn how to generate Compact PDF417 barcodes using Aspose.BarCode for .NET. Comprehensive guide with step-by-step instructions and code examples. +### [Exemplo Aspose Barcode: gerar Macro PDF417 em C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Exemplo de como gerar códigos de barras Macro PDF417 usando Aspose.BarCode para .NET em C#. + +### [Gerar código de barras PDF417 em C# – guia passo a passo](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Aprenda a gerar códigos de barras PDF417 em C# com instruções detalhadas e exemplos de código. + +### [Gerar código de barras a partir de texto em C# – guia completo passo a passo](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Aprenda a gerar códigos de barras a partir de texto em C# com instruções detalhadas e exemplos completos. + +### [Como ler PDF417 em C# – guia completo de leitor de código de barras](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +Aprenda a ler códigos de barras PDF417 em C# com um guia completo, incluindo exemplos de código e melhores práticas. + ## Perguntas Frequentes **Q: Qual é a quantidade máxima de dados que posso armazenar em um código de barras Compact PDF417?** @@ -113,4 +125,4 @@ A: Não são necessárias fontes externas; a biblioteca lida com toda a renderiz {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/portuguese/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/portuguese/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..b5a187fac --- /dev/null +++ b/barcode/portuguese/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-09 +description: Exemplo de código de barras Aspose mostrando como usar um gerador de + código de barras C# para criar um Macro PDF417 com suporte total a metadados. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: pt +lastmod: 2026-08-09 +og_description: O exemplo de código de barras Aspose demonstra o uso de um gerador + de código de barras C# para produzir um código de barras Macro PDF417 que inclui + ID do arquivo, dados de segmento, carimbo de data/hora e outros metadados. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Exemplo de código de barras Aspose – criar Macro PDF417 com C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Exemplo de código de barras Aspose: gerar Macro PDF417 em C#' +url: /pt/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Exemplo Aspose Barcode: gerar Macro PDF417 em C# + +Se você precisa de um **exemplo Aspose Barcode** que cria um código de barras Macro PDF417, este guia mostra como fazer isso com um **gerador de código de barras C#**. Você verá todas as configurações necessárias, desde dimensões básicas até o conjunto completo de campos de metadados Macro PDF417, e terminará com uma imagem PNG pronta para processamento posterior. + +O tutorial cobre todo o fluxo de trabalho, explica por que cada parâmetro é importante e fornece um exemplo de código pronto‑para‑executar. Nenhuma referência externa é necessária; basta copiar o código, ajustar os valores e executá‑lo imediatamente. + +## Pré‑requisitos + +Antes de começar, certifique‑se de que você tem: + +- .NET 6.0 (ou superior) instalado +- Visual Studio 2022 ou qualquer IDE compatível com C# +- Uma licença válida para **Aspose.BarCode for .NET** (a versão de avaliação gratuita funciona para este exemplo) + +Adicione o pacote NuGet Aspose.BarCode ao seu projeto: + +```bash +dotnet add package Aspose.BarCode +``` + +## Etapa 1: Criar a instância do gerador de código de barras C# + +O primeiro passo é instanciar `BarcodeGenerator` com o valor enum `EncodeTypes.MacroPdf417` e o texto que você deseja codificar. O texto pode conter caracteres Unicode, que a biblioteca trata automaticamente. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Por que isso importa*: `EncodeTypes.MacroPdf417` indica ao motor que ele deve produzir um símbolo Macro PDF417, que suporta dados segmentados e metadados adicionais ao nível de arquivo. A instrução `using` garante que recursos não gerenciados sejam liberados após a imagem ser salva. + +## Etapa 2: Definir a aparência básica do código de barras + +Um código de barras Macro PDF417 consiste em módulos quadrados. Controlar o tamanho do módulo e a contagem de colunas influencia tanto a legibilidade quanto o tamanho do arquivo. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Por que isso importa*: `XDimension.Pixels` determina a densidade visual; um valor de 2 pixels funciona bem para exibição em tela enquanto mantém a imagem pequena. Ajuste a contagem de colunas para atender às restrições do seu layout—mais colunas criam um código de barras mais largo e mais curto. + +## Etapa 3: Definir os metadados específicos do Macro PDF417 + +Macro PDF417 estende o formato padrão PDF417 com campos que permitem a reconstrução de arquivos grandes a partir de múltiplos segmentos de código de barras. Cada campo é opcional, mas configurá‑los demonstra todo o potencial da API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Por que isso importa*: +- `MacroPdf417FileID` vincula todos os segmentos que pertencem ao mesmo arquivo lógico. +- `MacroPdf417SegmentID` e `MacroPdf417SegmentsCount` permitem que o decodificador reordene os fragmentos corretamente. +- `MacroPdf417Checksum` fornece uma verificação rápida de integridade sem decodificar todo o payload. +- `MacroPdf417FileSize` e `MacroPdf417TimeStamp` permitem que sistemas posteriores verifiquem se o arquivo reconstruído corresponde ao original. +- `MacroPdf417Addressee` / `MacroPdf417Sender` são úteis em cenários de logística ou troca de documentos. +- Definir `MacroPdf417Terminator` como `Set` marca este código de barras como o segmento final, o que simplifica o algoritmo de reconstrução. + +## Etapa 4: Salvar a imagem do código de barras gerado + +Por fim, grave o código de barras em um arquivo PNG. Você pode escolher qualquer formato suportado (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Por que isso importa*: PNG preserva os dados de pixel sem perdas, garantindo que os scanners leiam exatamente o padrão de módulos que você configurou. Alterar o formato pode afetar a qualidade visual e o tamanho do arquivo. + +### Saída esperada + +Executar o programa completo cria um arquivo chamado **ExtPDF417Meta.png**. Ao abrir a imagem, você verá um código de barras Macro PDF417 retangular com o texto “Åspóse.Barcóde©” codificado, e a densidade visual corresponde à dimensão X de 2 pixels que você definiu. Escanear a imagem com um leitor compatível com PDF417 retorna todos os campos de metadados definidos na Etapa 3. + +## Exemplo completo em funcionamento + +Copie o código abaixo para um novo projeto de console (`dotnet new console`) e substitua `YOUR_DIRECTORY` por um caminho absoluto ou relativo que exista na sua máquina. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Execute o programa (`dotnet run`). Após a execução, verifique se o arquivo PNG aparece no local especificado. Use qualquer aplicativo de leitura de código de barras que suporte Macro PDF417 para confirmar que os metadados foram incorporados corretamente. + +## Variações comuns e casos de borda + +- **Formatos de imagem diferentes**: Substitua `BarCodeImageFormat.Png` por `Jpeg`, `Bmp` ou `Tiff` se seu sistema posterior preferir outro formato. +- **Alterar o tamanho do módulo**: Valores maiores de `XDimension.Pixels` melhoram a confiabilidade de leitura em scanners de baixa resolução, mas aumentam o tamanho da imagem. +- **Múltiplos segmentos**: Para gerar um arquivo de vários segmentos, crie uma série de códigos de barras, incremente `MacroPdf417SegmentID` para cada um e mantenha `MacroPdf417FileID` constante. Apenas o último segmento deve ter `MacroPdf417Terminator` definido. +- **Suporte a Unicode**: O gerador codifica automaticamente caracteres Unicode; assegure‑se de que sua string de origem use codificação UTF‑8 se você a ler de um arquivo externo. +- **Tratamento de erros**: Envolva o bloco `using` em um try‑catch para capturar `BarCodeException` em caso de parâmetros inválidos (por exemplo, contagem de colunas fora do intervalo). + +## Dicas avançadas + +- **Desempenho**: Reutilize uma única instância de `BarcodeGenerator` ao criar muitos códigos de barras com as mesmas configurações; altere apenas a propriedade `CodeText` entre as gravações. +- **Estimativa de tamanho de arquivo**: O campo `MacroPdf417FileSize` deve corresponder à contagem de bytes do payload original; divergências podem causar falhas de validação em sistemas posteriores. +- **Testes**: Valide os códigos de barras gerados tanto com o decodificador interno da Aspose (`BarCodeReader`) quanto com um scanner de terceiros para garantir interoperabilidade. + +## Conclusão + +Este **exemplo Aspose Barcode + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to create barcode quiet zone for Code 16K using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/portuguese/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/portuguese/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..32b9deff5 --- /dev/null +++ b/barcode/portuguese/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-09 +description: Gere código de barras a partir de texto em C# com Aspose.BarCode. Aprenda + como gerar código de barras, lidar com caracteres especiais e criar código de barras + PDF417 em C# rapidamente. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: pt +lastmod: 2026-08-09 +og_description: Gere código de barras a partir de texto em C# usando Aspose.BarCode. + Este tutorial mostra como gerar código de barras, suportar caracteres especiais + e criar código de barras PDF417 em C# com código completo. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Gerar código de barras a partir de texto em C# – guia rápido passo a passo +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Gerar código de barras a partir de texto em C# – guia completo passo a passo +url: /pt/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Gerar código de barras a partir de texto em C# – guia completo passo a passo + +Se você precisa **gerar código de barras a partir de texto** em uma aplicação .NET, este guia o conduzirá por todo o processo. Você verá como gerar código de barras, gerenciar caracteres especiais e criar uma implementação de código de barras PDF417 em C# que funciona pronto para uso. + +Gerar um código de barras a partir de texto é uma necessidade comum para sistemas de inventário, plataformas de bilhetagem e fluxos de trabalho de documentos. Ao final deste tutorial você terá um aplicativo console C# executável que produz uma imagem PNG MicroPdf417 usando Aspose.BarCode. Nenhum serviço externo é necessário, e o código lida com caracteres Unicode como “Å”, “©” e “é”. + +## Pré-requisitos + +- .NET 6.0 SDK ou posterior (o código também funciona com .NET Core 3.1 e .NET Framework 4.7+) +- Visual Studio 2022 (ou qualquer IDE que suporte C#) +- **Aspose.BarCode for .NET** NuGet package + ```bash + dotnet add package Aspose.BarCode + ``` +- Conhecimento básico de sintaxe C# + +## Gerar código de barras a partir de texto – configurando o gerador + +O primeiro passo é criar uma instância `BarcodeGenerator` que saiba qual **tipo de codificação de código de barras** você deseja. Neste tutorial usamos `EncodeTypes.MicroPdf417`, que é uma variante compacta do PDF417 adequada para strings de dados curtas. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Por que isso funciona:** +- `EncodeTypes.MicroPdf417` indica à biblioteca que use a família PDF417, atendendo ao requisito de **criar código de barras pdf417 c#**. +- O construtor recebe o texto bruto, que é a essência de **gerar código de barras a partir de texto**. +- O suporte a Unicode está embutido, então caracteres como “Å” e “©” são codificados corretamente, atendendo a **código de barras com caracteres especiais**. + +## Como gerar código de barras com caracteres especiais + +Quando seus dados contêm símbolos não‑ASCII, você deve garantir que o gerador use codificação UTF‑8. Aspose.BarCode detecta Unicode automaticamente, mas você pode definir explicitamente a codificação do texto caso encontre problemas: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Adicionar esta linha antes de `ConfigureGenerator` garante que **código de barras com caracteres especiais** seja renderizado corretamente em qualquer plataforma. + +### Dica prática +Se a saída parecer corrompida, verifique se a fonte usada pelo renderizador de código de barras suporta os glifos necessários. Você pode incorporar uma fonte TrueType personalizada via: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Tipos de codificação de código de barras que você pode escolher + +Aspose.BarCode suporta dezenas de **tipos de codificação de código de barras**, cada um adequado para diferentes casos de uso: + +| Tipo de codificação | Caso de uso típico | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | Etiquetas de envio, inventário | +| `EncodeTypes.QR` | Pagamentos móveis, URLs | +| `EncodeTypes.Pdf417` | Carteiras de motorista, cartões de embarque | +| `EncodeTypes.MicroPdf417` | Carga de dados pequena, espaço limitado | +| `EncodeTypes.DataMatrix` | Itens pequenos, alta densidade de dados | + +Alterar o tipo de codificação é tão simples quanto trocar o valor do enum no construtor: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +## Criar código de barras PDF417 C# – etapas finais e verificação + +Depois de configurar o gerador, a última parte de **criar código de barras pdf417 c#** é salvar a imagem e confirmar o resultado. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Execute o programa (`dotnet run`) e você deverá ver uma mensagem no console semelhante a: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Abra o arquivo PNG; você verá um código de barras MicroPdf417 nítido que codifica a string “Åspóse.Barcóde©”. Escaneá‑lo com um leitor de código de barras móvel (por exemplo, ZXing) devolve o texto original, provando que **gerar código de barras a partir de texto** funciona mesmo com caracteres especiais. + +### Caso extremo: texto muito longo + +MicroPdf417 tem uma capacidade máxima de dados de 1 KB. Se sua entrada exceder esse limite, a biblioteca lança uma `ArgumentException`. Para lidar com isso de forma elegante: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Para cargas maiores, troque para o `EncodeTypes.Pdf417` completo ou `EncodeTypes.DataMatrix`. + +## Armadilhas comuns e como evitá‑las + +| Problema | Causa | Solução | +|------------------------------------|-----------------------------------------|---------| +| Código de barras aparece borrado | XDimension muito baixo (ex.: 1 px) | Aumente `XDimension.Pixels` para 2‑3 px | +| Caracteres Unicode tornam‑se `?` | Codificação de texto padrão é ASCII | Defina `TextEncoding = Encoding.UTF8` | +| Arquivo de imagem não criado | Diretório de saída não existe | Use `Directory.CreateDirectory` antes de `Save` | +| Leitor não consegue ler o código de barras | Muitas colunas para dados curtos | Reduza `Pdf417.Columns` (ex.: 3‑4) | + +## Código fonte completo (pronto para copiar) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Saída esperada:** um arquivo chamado `MicroPdf417.png` localizado na pasta `output`, contendo um código de barras MicroPdf417 claro que codifica a string original com caracteres especiais. + +## Conclusão + +Agora você sabe como **gerar código de barras a partir de texto** em C# usando Aspose.BarCode, como lidar com **código de barras com caracteres especiais** e como **criar código de barras pdf417 c#** com controle total sobre as opções de codificação. Ajustando os **tipos de codificação de código de barras** você pode produzir QR codes, Code128, DataMatrix ou qualquer outro formato suportado. + +Em seguida, explore os tópicos abaixo para aprofundar sua expertise em códigos de barras: + +- **Como gerar código de barras** em lote para milhares de registros (use `Parallel.ForEach` para velocidade) +- Personalização de cores e adição de logotipos dentro do código de barras +- Integração da geração de códigos de barras em APIs ASP.NET Core para entrega de imagens em tempo real +- Uso de outras bibliotecas como ZXing.Net ou IronBarcode para alternativas de código aberto + +Sinta‑se à vontade para experimentar diferentes dimensões, configurações de colunas e tipos de codificação. Boa codificação, e que suas aplicações escaneiem perfeitamente! + +## O que você deve aprender a seguir? + +Os tutoriais a seguir cobrem tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Como criar código de barras – PDF417 compacto com Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Como gerar código de barras – Configuração Code 39 com Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Como gerar código de barras – Tipos de código de barras unidimensionais](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/portuguese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/portuguese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..180c81054 --- /dev/null +++ b/barcode/portuguese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-09 +description: Gere código de barras PDF417 em C# rapidamente. Aprenda como gerar PDF417 + com modo compacto, controle de colunas e saída PNG usando a API BarcodeGenerator. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: pt +lastmod: 2026-08-09 +og_description: Gere código de barras PDF417 em C# com um exemplo conciso. Este guia + mostra como configurar o modo compacto, definir colunas e salvar o resultado como + uma imagem PNG. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Gerar código de barras PDF417 em C# – tutorial completo +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: Gerar código de barras PDF417 em C# – guia passo a passo +url: /pt/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Gerar código de barras PDF417 em C# – guia passo a passo + +Se você precisa **gerar código de barras PDF417** em uma aplicação .NET, este tutorial mostra exatamente como fazer isso. Você verá um programa completo e executável que cria um código de barras PDF417 compacto, personaliza seu tamanho e salva a imagem como um arquivo PNG. + +Gerar um código de barras PDF417 é uma necessidade comum para bilhetagem móvel, rastreamento de inventário e segurança de documentos. Este guia cobre as opções de configuração essenciais, explica por que cada ajuste é importante e fornece dicas práticas para uso no mundo real. + +## Pré-requisitos + +* .NET 6.0 SDK ou posterior instalado +* Uma IDE C# como Visual Studio 2022 ou Visual Studio Code +* O pacote NuGet **Aspose.BarCode for .NET** (versão 23.10 ou mais recente) + +Você pode instalar o pacote com o seguinte comando CLI: + +```bash +dotnet add package Aspose.BarCode +``` + +O código abaixo assume que o pacote está referenciado e que você tem permissão de escrita no diretório de saída. + +## Etapa 1: Configurar o projeto e importar namespaces + +Crie um novo projeto de console e adicione as diretivas `using` necessárias. Esses namespaces expõem a classe `BarcodeGenerator` e a enumeração de formatos de imagem. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Por que isso importa:** Importar os namespaces corretos garante que o compilador consiga localizar o tipo `BarcodeGenerator` e a enumeração `BarCodeImageFormat`. A falta de um namespace resulta em um erro de compilação, que interrompe o processo de geração do código de barras. + +## Etapa 2: Inicializar o `BarcodeGenerator` com codificação PDF417 + +O construtor `BarcodeGenerator` recebe dois argumentos: a simbologia do código de barras (`EncodeTypes.Pdf417`) e o texto que você deseja codificar. PDF417 suporta uma ampla gama de caracteres, incluindo símbolos Unicode. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Explicação:** +* `EncodeTypes.Pdf417` indica à biblioteca que deve usar o padrão PDF417. +* O texto de exemplo contém caracteres acentuados e um símbolo de copyright para demonstrar o tratamento de Unicode. + +Se você precisar codificar apenas dados numéricos, pode passar uma string simples como `"1234567890"`. + +## Etapa 3: Ajustar a X‑dimensão para maior resolução + +A X‑dimensão controla a largura de um único módulo do código de barras (o menor elemento preto ou branco). Definir um valor de pixel menor produz uma imagem de maior resolução. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Por que ajustá‑la?** Uma X‑dimensão padrão de 3–4 pixels pode gerar um código de barras que parece grosseiro em telas de alta DPI. Reduzi‑la para **2 pixels** equilibra a legibilidade com o tamanho do arquivo, especialmente quando você habilita o modo compacto posteriormente. + +## Etapa 4: Configurar o número de colunas + +PDF417 permite especificar quantas colunas o código de barras deve conter. Menos colunas tornam o código de barras mais estreito, mas mais alto, enquanto mais colunas criam um código de barras mais largo e curto. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Dica prática:** Para bilhetes móveis que precisam caber em uma etiqueta estreita, uma contagem de colunas de **3–5** funciona bem. Aumente a contagem se você tiver muitos dados e quiser um código de barras mais curto. + +## Etapa 5: Habilitar modo compacto para truncar linhas vazias + +Modo compacto remove linhas desnecessárias da matriz do código de barras, reduzindo o tamanho geral da imagem sem perder os dados codificados. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Quando usar:** Se você estiver gerando códigos de barras para armazenamento ou transmissão de rede, o modo compacto pode reduzir o arquivo PNG em até 30 %. No entanto, alguns leitores legados podem não suportar PDF417 truncado; teste com o hardware alvo. + +## Etapa 6: Salvar o código de barras como imagem PNG + +Escolha um caminho de saída e invoque `Save`. A enumeração `BarCodeImageFormat.Png` produz uma imagem sem perdas adequada para a maioria das aplicações. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Verificação do resultado:** Abra o arquivo PNG em qualquer visualizador de imagens. Você deve ver um código de barras denso e de alto contraste que corresponde ao texto de exemplo. Escanear a imagem com um leitor PDF417 (por exemplo, ZXing ou um aplicativo de smartphone) retorna a string original `"Åspóse.Barcóde©"`. + +![Generated PDF417 barcode image saved as PNG](compact-pdf417.png "Generated PDF417 barcode in C#") + +*The image above demonstrates the final output of the tutorial’s code.* + +## Exemplo completo e executável + +Juntando todas as peças, aqui está um programa de console completo que você pode copiar, colar e executar. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Saída esperada + +Executar o programa imprime: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +O arquivo `CompactPdf417.png` contém um código de barras PDF417 compacto que codifica a string Unicode fornecida. Escanear a imagem com um leitor PDF417 padrão retorna o texto exato. + +## Variações comuns e casos de borda + +| Situação | Ajuste | Motivo | +|-----------|------------|--------| +| **Carga de dados mais longa** (por exemplo, > 150 caracteres) | Aumentar `generator.Parameters.Barcode.Pdf417.Columns` para 6‑8 | Mais colunas evitam que o código de barras fique excessivamente alto. | +| **Necessidade de fundo transparente** | Usar `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | PNG transparente integra melhor em sobreposições de UI. | +| **Gerando JPEG para web** | Alterar o formato para `BarCodeImageFormat.Jpeg` e opcionalmente definir `ImageQuality` | JPEG reduz o tamanho do arquivo ao custo da fidelidade sem perdas. | +| **Manipulação de entrada nula ou vazia** | Proteger a entrada antes de criar o gerador: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Previne exceções em tempo de execução e garante códigos de barras significativos. | + +## Dicas para uso em produção + +* **Manipulação de exceções:** Envolva a lógica de geração em um bloco `try/catch` para registrar erros como espaço em disco insuficiente ou parâmetros inválidos. +* **Desempenho:** Reutilize uma única instância de `BarcodeGenerator` ao gerar muitos códigos de barras com as mesmas configurações; apenas atualize a propriedade `CodeText` entre as gravações. +* **Segurança:** Quando o texto codificado contém informações sensíveis, considere criptografá‑lo antes de passá‑lo ao gerador e descriptografá‑lo após a leitura. + +## Conclusão + +Agora você sabe como **gerar código de barras PDF417** em C# usando a biblioteca Aspose.BarCode, configurar o modo compacto, controlar a contagem de colunas e exportar o resultado como uma imagem PNG. Este tutorial cobriu cada passo, desde a configuração do projeto até o tratamento de casos de borda, oferecendo uma solução pronta para uso em aplicações baseadas em códigos de barras. + +Em seguida, explore tópicos relacionados como **criar códigos QR em C#**, **geração em lote de códigos de barras** e **integração de leitura de códigos de barras com aplicativos móveis**. Cada um desses se baseia nos mesmos fundamentos do `BarcodeGenerator` que você acabou de dominar. + +Boa codificação! + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos estreitamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Como gerar códigos de barras PDF417 – Codificação PDF417 Compacta](/barcode/english/net/compact-pdf417-encoding/) +- [Como criar código de barras – PDF417 Compacto com Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Como gerar código de barras Aztec com proporção personalizada usando Aspose.BarCode para .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/portuguese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/portuguese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..75e133733 --- /dev/null +++ b/barcode/portuguese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-09 +description: Como ler PDF417 em C# usando o BarCodeReader. Aprenda a ler arquivos + PNG de código de barras, lidar com múltiplos códigos de barras e extrair metadados + estendidos. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: pt +lastmod: 2026-08-09 +og_description: Como ler PDF417 em C# com Aspose.BarCode. Este tutorial mostra como + ler arquivos PNG de códigos de barras, processar vários códigos de barras em uma + única imagem e recuperar metadados estendidos do PDF417. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Como ler PDF417 em C# – tutorial de leitor de código de barras +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Como ler PDF417 em C# – guia completo de leitor de código de barras +url: /pt/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como ler PDF417 em C# – guia completo de leitor de código de barras + +Se você precisa **como ler PDF417** em uma aplicação .NET, este guia fornece uma solução pronta‑para‑usar. Você verá como ler um PNG de código de barras, processar vários códigos de barras na mesma imagem e extrair os campos estendidos do PDF417 que muitos scanners ocultam. + +A leitura de códigos de barras PDF417 é comum em logística, bilhetagem e gerenciamento de documentos. Ao final deste tutorial você poderá decodificar uma imagem Macro PDF417, exibir cada resultado e usar as informações extras (ID do arquivo, contagem de segmentos, timestamps, etc.) na sua própria lógica de negócio. + +## Pré-requisitos + +- .NET 6.0 ou superior (o código também funciona com .NET Framework 4.7+) +- Visual Studio 2022 ou qualquer IDE C# +- **Aspose.BarCode for .NET** (versão de avaliação gratuita ou pacote NuGet licenciado) +- Uma imagem PNG que contenha um código de barras Macro PDF417 (o arquivo de exemplo se chama `ExtPDF417Meta.png`) + +> **Dica Pro:** Instale a biblioteca via console NuGet: +> `dotnet add package Aspose.BarCode` + +## Como ler PDF417 com BarCodeReader em C# + +O núcleo da solução é a classe `BarCodeReader`. Ela aceita um caminho de imagem e um enum `DecodeType` que indica ao motor qual simbologia procurar. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Por que isso funciona + +- **`DecodeType.MacroPdf417`** informa ao leitor para buscar a variante Macro PDF417, que armazena os campos extras que você vê na etapa 4. +- O bloco `using` descarta o leitor automaticamente, liberando os manipuladores de arquivo. +- `ReadBarCodes()` retorna **todos** os códigos de barras que correspondem ao tipo solicitado, atendendo ao requisito de *ler múltiplos códigos de barras* mesmo que a imagem contenha apenas um. + +Executar o programa exibe uma saída semelhante a: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## Usando o leitor de código de barras C# para ler múltiplos códigos de barras + +Se uma imagem contém vários símbolos Macro PDF417 (por exemplo, uma página escaneada com um lote de ingressos), o mesmo loop `foreach` processa cada um. Nenhum código extra é necessário; o leitor agrega os resultados internamente. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Armadilhas comuns + +- **Formato da imagem:** O leitor suporta PNG, JPEG, BMP e TIFF. Se você tentar um formato que ele não consegue decodificar, receberá uma coleção vazia. Por isso o tutorial destaca *read barcode PNG*. +- **Resolução:** Imagens de baixa resolução (< 300 dpi) podem causar perda de segmentos. Aumente a escala ou solicite uma digitalização de maior qualidade quando possível. +- **Flag Macro:** Esquecer `DecodeType.MacroPdf417` limita o motor ao PDF417 simples e descarta os dados estendidos. Sempre especifique o tipo macro quando precisar de campos *read barcode extended*. + +## Lendo arquivos PNG de código de barras – melhores práticas + +Trabalhar com arquivos PNG é simples porque o formato preserva dados de pixel sem perdas. Aqui está uma lista rápida de verificação: + +1. Verifique se o arquivo existe antes de criar o leitor. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Use `Image.FromFile` somente quando precisar pré‑processar (rotacionar, recortar). O `BarCodeReader` pode abrir o arquivo diretamente, evitando alocação extra de memória. +3. Se o PNG contiver transparência, o leitor ainda funciona porque o código de barras é renderizado sobre pixels opacos. + +## Acessando metadados estendidos do PDF417 + +O objeto `Extended.Pdf417` expõe todos os campos opcionais definidos pela especificação PDF417. Você pode mapear esses campos para um modelo de domínio, armazená‑los em um banco de dados ou usá‑los para validação. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Preencha o modelo: + + + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Como ler códigos de barras DataMatrix com Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Como criar código de barras – PDF417 Compacto com Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Ler código de barras DataMatrix C# – Gerar modo DataMatrix (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/russian/net/compact-pdf417-encoding/_index.md b/barcode/russian/net/compact-pdf417-encoding/_index.md index 18a43fe66..b2ebbe778 100644 --- a/barcode/russian/net/compact-pdf417-encoding/_index.md +++ b/barcode/russian/net/compact-pdf417-encoding/_index.md @@ -84,6 +84,14 @@ Aspose.BarCode позволяет задать свойство `Pdf417ErrorCorr ## Руководства по Compact PDF417 Encoding ### [Creating Compact PDF417 Barcodes](./compact-pdf417-basic-configuration/) Узнайте, как генерировать Compact PDF417 штрих‑коды с помощью Aspose.BarCode для .NET. Полное руководство с пошаговыми инструкциями и примерами кода. +### [Пример Aspose.BarCode: создание Macro PDF417 на C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Узнайте, как сгенерировать Macro PDF417 штрих‑код в C# с помощью Aspose.BarCode. +### [Генерация штрих‑кода PDF417 в C# – пошаговое руководство](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Подробное пошаговое руководство по созданию штрих‑кода PDF417 в C# с использованием Aspose.BarCode. +### [Генерация штрих‑кода из текста на C# – полное пошаговое руководство](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Полное пошаговое руководство по генерации штрих‑кода из текста на C# с использованием Aspose.BarCode. +### [Как считывать PDF417 в C# – полное руководство по чтению штрих‑кода](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +Полное руководство по чтению штрих‑кода PDF417 в C# с использованием Aspose.BarCode. ## Часто задаваемые вопросы @@ -113,4 +121,4 @@ Aspose.BarCode позволяет задать свойство `Pdf417ErrorCorr {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/russian/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/russian/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..2b646ea7d --- /dev/null +++ b/barcode/russian/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-09 +description: Пример Aspose Barcode, показывающий, как с помощью генератора штрихкодов + на C# создать Macro PDF417 с полной поддержкой метаданных. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: ru +lastmod: 2026-08-09 +og_description: Пример штрихкода Aspose демонстрирует использование генератора штрихкодов + C# для создания штрихкода Macro PDF417, который включает идентификатор файла, данные + сегмента, метку времени и другие метаданные. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Пример штрихкода Aspose – создание Macro PDF417 с помощью C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Пример штрихкода Aspose: генерация Macro PDF417 на C#' +url: /ru/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Пример Aspose barcode: генерация Macro PDF417 на C# + +Если вам нужен **aspose barcode example**, который создает штрих‑код Macro PDF417, это руководство покажет, как сделать это с помощью **barcode generator C#**. Вы увидите все необходимые настройки, от базовых размеров до полного набора полей метаданных Macro PDF417, и получите PNG‑изображение, готовое для последующей обработки. + +В руководстве описан полный рабочий процесс, объясняется, почему каждый параметр важен, и предоставляется готовый к запуску пример кода. Внешние ссылки не требуются; вы можете скопировать код, скорректировать значения и сразу запустить его. + +## Требования + +- .NET 6.0 (или новее) установлен +- Visual Studio 2022 или любая IDE, совместимая с C# +- Действительная лицензия на **Aspose.BarCode for .NET** (бесплатная пробная версия подходит для этого примера) + +Add the Aspose.BarCode NuGet package to your project: + +```bash +dotnet add package Aspose.BarCode +``` + +## Шаг 1: Создание экземпляра barcode generator C# + +Первый шаг — создать экземпляр `BarcodeGenerator`, передав значение перечисления `EncodeTypes.MacroPdf417` и текст, который необходимо закодировать. Текст может содержать символы Unicode, которые библиотека обрабатывает автоматически. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Почему это важно*: `EncodeTypes.MacroPdf417` указывает движку генерировать символ Macro PDF417, который поддерживает сегментированные данные и дополнительные метаданные уровня файла. Оператор `using` гарантирует освобождение неуправляемых ресурсов после сохранения изображения. + +## Шаг 2: Определение базового внешнего вида штрих‑кода + +Штрих‑код Macro PDF417 состоит из квадратных модулей. Управление размером модуля и количеством колонок влияет как на читаемость, так и на размер файла. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Почему это важно*: `XDimension.Pixels` определяет визуальную плотность; значение 2 пикселя хорошо подходит для отображения на экране при небольшом размере изображения. Настройте количество колонок в соответствии с ограничениями макета — больше колонок создают более широкий и короткий штрих‑код. + +## Шаг 3: Установка специфических метаданных Macro PDF417 + +Macro PDF417 расширяет стандартный формат PDF417 полями, позволяющими восстанавливать большие файлы из нескольких сегментов штрих‑кода. Каждое поле необязательно, но их установка демонстрирует полные возможности API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Почему это важно*: +- `MacroPdf417FileID` связывает все сегменты, принадлежащие одному логическому файлу. +- `MacroPdf417SegmentID` и `MacroPdf417SegmentsCount` позволяют декодеру правильно упорядочить фрагменты. +- `MacroPdf417Checksum` обеспечивает быструю проверку целостности без декодирования всей полезной нагрузки. +- `MacroPdf417FileSize` и `MacroPdf417TimeStamp` позволяют системам downstream проверять, что восстановленный файл соответствует оригиналу. +- `MacroPdf417Addressee` / `MacroPdf417Sender` полезны в сценариях логистики или обмена документами. +- Установка `MacroPdf417Terminator` в `Set` помечает этот штрих‑код как последний сегмент, что упрощает алгоритм восстановления. + +## Шаг 4: Сохранение сгенерированного изображения штрих‑кода + +Наконец, запишите штрих‑код в файл PNG. Вы можете выбрать любой поддерживаемый формат (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Почему это важно*: PNG сохраняет пиксельные данные без потерь, гарантируя, что сканеры считывают точно такой же шаблон модулей, который вы настроили. Изменение формата может повлиять на визуальное качество и размер файла. + +### Ожидаемый результат + +Запуск полной программы создаёт файл с именем **ExtPDF417Meta.png**. При открытии изображения отображается прямоугольный штрих‑код Macro PDF417 с закодированным текстом «Åspóse.Barcóde©», а визуальная плотность соответствует установленному 2‑пиксельному X‑размеру. Сканирование изображения с помощью считывателя, совместимого с PDF417, возвращает все поля метаданных, определённые в Шаге 3. + +## Полный рабочий пример + +Скопируйте код ниже в новый консольный проект (`dotnet new console`) и замените `YOUR_DIRECTORY` на абсолютный или относительный путь, существующий на вашем компьютере. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Запустите программу (`dotnet run`). После выполнения проверьте, что файл PNG появился в указанном месте. Используйте любое приложение для чтения штрих‑кодов, поддерживающее Macro PDF417, чтобы убедиться, что метаданные правильно внедрены. + +## Распространённые варианты и граничные случаи + +- **Разные форматы изображений**: замените `BarCodeImageFormat.Png` на `Jpeg`, `Bmp` или `Tiff`, если ваша downstream‑система предпочитает другой формат. +- **Изменение размера модуля**: большие значения `XDimension.Pixels` повышают надёжность сканирования на сканерах с низким разрешением, но увеличивают размер изображения. +- **Несколько сегментов**: для создания многосегментного файла генерируйте серию штрих‑кодов, увеличивая `MacroPdf417SegmentID` для каждого, и оставляйте `MacroPdf417FileID` постоянным. Только последний сегмент должен иметь установленный `MacroPdf417Terminator`. +- **Поддержка Unicode**: генератор автоматически кодирует символы Unicode; убедитесь, что ваша исходная строка использует кодировку UTF‑8, если вы читаете её из внешнего файла. +- **Обработка ошибок**: оберните блок `using` в try‑catch, чтобы перехватывать `BarCodeException` при недопустимых параметрах (например, количество колонок вне диапазона). + +## Профессиональные советы + +- **Производительность**: переиспользуйте один экземпляр `BarcodeGenerator` при создании множества штрих‑кодов с одинаковыми настройками; меняйте только свойство `CodeText` между сохранениями. +- **Оценка размера файла**: поле `MacroPdf417FileSize` должно соответствовать количеству байт оригинальной полезной нагрузки; несоответствия могут привести к ошибкам проверки downstream‑систем. +- **Тестирование**: проверяйте сгенерированные штрих‑коды как встроенным декодером Aspose (`BarCodeReader`), так и сторонним сканером, чтобы обеспечить совместимость. + +## Заключение + +Этот **aspose barcode example + +## Что вам следует изучить дальше? + +Следующие руководства охватывают тесно связанные темы, которые опираются на техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [Как создать штрих‑код – Compact PDF417 с Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Как создать тихую зону штрих‑кода для Code 16K с использованием Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [Как создать тихую зону штрих‑кода для ITF-14 с использованием Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/russian/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/russian/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..0ed35eded --- /dev/null +++ b/barcode/russian/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-08-09 +description: Генерировать штрих‑код из текста в C# с помощью Aspose.BarCode. Узнайте, + как создавать штрих‑коды, обрабатывать специальные символы и быстро создавать PDF417‑штрих‑коды + в C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: ru +lastmod: 2026-08-09 +og_description: Генерировать штрих‑код из текста в C# с использованием Aspose.BarCode. + Этот учебник показывает, как генерировать штрих‑код, поддерживать специальные символы + и создавать PDF417‑штрих‑код в C# с полным кодом. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Создание штрих‑кода из текста в C# – быстрый пошаговый гид +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Генерация штрих‑кода из текста в C# – полное пошаговое руководство +url: /ru/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание штрихкода из текста в C# – полное пошаговое руководство + +Если вам нужно **generate barcode from text** в приложении .NET, это руководство проведёт вас через весь процесс. Вы увидите, как generate barcode, управлять специальными символами и создать реализацию PDF417 barcode C# , которая работает сразу из коробки. + +Создание штрихкода из текста является распространённой задачей для систем учёта, платформ продажи билетов и документооборотов. К концу этого руководства у вас будет исполняемое консольное приложение C#, которое генерирует PNG‑изображение MicroPdf417 с помощью Aspose.BarCode. Внешние сервисы не требуются, а код обрабатывает Unicode‑символы, такие как “Å”, “©” и “é”. + +## Требования + +- .NET 6.0 SDK или новее (код также работает с .NET Core 3.1 и .NET Framework 4.7+) +- Visual Studio 2022 (или любой IDE, поддерживающий C#) +- **Aspose.BarCode for .NET** NuGet package + ```bash + dotnet add package Aspose.BarCode + ``` +- Базовые знания синтаксиса C# + +## Создание штрихкода из текста – настройка генератора + +Первый шаг — создать экземпляр `BarcodeGenerator`, который знает, какой **barcode encode type** вам нужен. В этом руководстве мы используем `EncodeTypes.MicroPdf417`, который является компактным вариантом PDF417, подходящим для коротких строк данных. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Почему это работает:** +- `EncodeTypes.MicroPdf417` указывает библиотеке использовать семью PDF417, удовлетворяя требование **create pdf417 barcode c#**. +- Конструктор получает исходный текст, что является сутью **generate barcode from text**. +- Поддержка Unicode встроена, поэтому символы вроде “Å” и “©” кодируются правильно, решая задачу **barcode with special characters**. + +## Как generate barcode со специальными символами + +Когда ваши данные содержат символы, не входящие в ASCII, необходимо убедиться, что генератор использует кодировку UTF‑8. Aspose.BarCode автоматически определяет Unicode, но при возникновении проблем вы можете явно задать кодировку текста: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Добавление этой строки перед `ConfigureGenerator` гарантирует, что **barcode with special characters** отрисовывается корректно на любой платформе. + +### Практический совет +Если вывод выглядит искажённым, проверьте, поддерживает ли шрифт, используемый рендерером штрихкода, необходимые глифы. Вы можете встроить пользовательский TrueType‑шрифт с помощью: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Типы кодирования штрихкода, которые вы можете выбрать + +Aspose.BarCode поддерживает десятки **barcode encode types**, каждый из которых подходит для различных сценариев: + +| Encode type | Типичный сценарий использования | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | Транспортные этикетки, учёт | +| `EncodeTypes.QR` | Мобильные платежи, URL-адреса | +| `EncodeTypes.Pdf417` | Водительские удостоверения, посадочные талоны | +| `EncodeTypes.MicroPdf417` | Небольшие объёмы данных, ограниченное пространство | +| `EncodeTypes.DataMatrix` | Маленькие предметы, высокая плотность данных | + +Изменить тип кодирования так же просто, как заменить значение enum в конструкторе: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Эта гибкость позволяет отвечать на вопросы о **barcode encode types** не выходя из IDE. + +## Создание PDF417 barcode C# – финальные шаги и проверка + +После настройки генератора последняя часть **create pdf417 barcode c#** — сохранение изображения и подтверждение результата. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Запустите программу (`dotnet run`), и вы должны увидеть сообщение в консоли, похожее на: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Откройте PNG‑файл; вы увидите чёткий MicroPdf417 barcode, который кодирует строку “Åspóse.Barcóde©”. Сканирование его мобильным сканером штрихкодов (например, ZXing) возвращает исходный текст, доказывая, что **generate barcode from text** работает даже со специальными символами. + +### Пограничный случай: очень длинный текст + +MicroPdf417 имеет максимальную ёмкость данных 1 KB. Если ваш ввод превышает этот предел, библиотека бросает `ArgumentException`. Чтобы обработать это корректно: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Для больших объёмов данных переключитесь на полный `EncodeTypes.Pdf417` или `EncodeTypes.DataMatrix`. + +## Распространённые подводные камни и как их избежать + +| Issue | Cause | Fix | +|-------------------------------------|-----------------------------------------|-----| +| Штрихкод выглядит размытым | XDimension слишком низкое (например, 1 px) | Увеличьте `XDimension.Pixels` до 2‑3 px | +| Unicode‑символы становятся `?` | Кодировка текста по умолчанию — ASCII | Установите `TextEncoding = Encoding.UTF8` | +| Файл изображения не создан | Каталог вывода не существует | Вызовите `Directory.CreateDirectory` перед `Save` | +| Сканер не может прочитать штрихкод | Слишком много столбцов для коротких данных | Уменьшите `Pdf417.Columns` (например, 3‑4) | + +## Полный исходный код (готов к копированию) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Ожидаемый результат:** файл с именем `MicroPdf417.png`, расположенный в папке `output`, содержащий чёткий MicroPdf417 barcode, который кодирует исходную строку со специальными символами. + +## Заключение + +Теперь вы знаете, как **generate barcode from text** в C# с помощью Aspose.BarCode, как работать с **barcode with special characters**, и как **create pdf417 barcode c#** с полным контролем над параметрами кодирования. Регулируя **barcode encode types**, вы можете создавать QR‑коды, Code128, DataMatrix или любой другой поддерживаемый формат. + +Далее изучите следующие темы, чтобы углубить свои знания о штрихкодах: + +- **How to generate barcode** пакетно для тысяч записей (используйте `Parallel.ForEach` для ускорения) +- Настройка цветов и добавление логотипов внутрь штрихкода +- Интеграция генерации штрихкода в ASP.NET Core API для мгновенной доставки изображений +- Использование других библиотек, таких как ZXing.Net или IronBarcode, в качестве открытых альтернатив + +Не стесняйтесь экспериментировать с различными размерами, настройками столбцов и типами кодирования. Приятного кодирования, и пусть ваши приложения сканируют безупречно! + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, основанные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и изучить альтернативные подходы к реализации в ваших проектах. + +- [Как создать штрихкод – компактный PDF417 с Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Как сгенерировать штрихкод – конфигурация Code 39 с Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Как сгенерировать штрихкод – односторонние типы штрихкодов](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/russian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/russian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..7d13a30b8 --- /dev/null +++ b/barcode/russian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-08-09 +description: Быстро генерируйте штрих‑код PDF417 на C#. Узнайте, как создавать PDF417 + в компактном режиме, управлять колонками и получать PNG‑вывод с помощью API BarcodeGenerator. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: ru +lastmod: 2026-08-09 +og_description: Создайте штрих‑код PDF417 на C# с лаконичным примером. Это руководство + показывает, как настроить компактный режим, установить количество столбцов и сохранить + результат в виде PNG‑изображения. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Создание штрих‑кода PDF417 в C# – полный учебник +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: Создание штрих‑кода PDF417 в C# — пошаговое руководство +url: /ru/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание штрих‑кода PDF417 в C# – пошаговое руководство + +Если вам нужно **создавать штрих‑код PDF417** в приложении .NET, этот учебник покажет вам точный способ сделать это. Вы увидите полностью готовую, исполняемую программу, которая создает компактный штрих‑код PDF417, настраивает его размер и сохраняет изображение в файл PNG. + +Создание штрих‑кода PDF417 является распространённой задачей для мобильных билетов, отслеживания инвентаря и защиты документов. В этом руководстве рассматриваются основные параметры конфигурации, объясняется, почему каждый из них важен, и даются практические советы для реального использования. + +## Предварительные требования + +Перед началом убедитесь, что у вас есть: + +* .NET 6.0 SDK или более поздняя версия установлен +* IDE для C#, например Visual Studio 2022 или Visual Studio Code +* Пакет NuGet **Aspose.BarCode for .NET** (версия 23.10 или новее) + +Вы можете установить пакет с помощью следующей команды CLI: + +```bash +dotnet add package Aspose.BarCode +``` + +Код ниже предполагает, что пакет подключён и у вас есть права записи в каталог вывода. + +## Шаг 1: Настройка проекта и импорт пространств имён + +Создайте новый консольный проект и добавьте необходимые директивы `using`. Эти пространства имён предоставляют класс `BarcodeGenerator` и перечисление форматов изображений. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Почему это важно:** Импорт правильных пространств имён гарантирует, что компилятор сможет найти тип `BarcodeGenerator` и перечисление `BarCodeImageFormat`. Отсутствие нужного пространства имён приводит к ошибке компиляции, что останавливает процесс генерации штрих‑кода. + +## Шаг 2: Инициализация `BarcodeGenerator` с кодировкой PDF417 + +Конструктор `BarcodeGenerator` принимает два аргумента: символьный набор штрих‑кода (`EncodeTypes.Pdf417`) и текст, который нужно закодировать. PDF417 поддерживает широкий диапазон символов, включая Unicode‑символы. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Объяснение:** +* `EncodeTypes.Pdf417` указывает библиотеке использовать стандарт PDF417. +* Пример текста содержит символы с диакритическими знаками и знак копирайта, чтобы продемонстрировать работу с Unicode. + +Если нужно кодировать только числовые данные, можно передать простую строку, например `"1234567890"`. + +## Шаг 3: Регулировка X‑размера для более высокой разрешающей способности + +X‑размер контролирует ширину отдельного модуля штрих‑кода (самого маленького чёрного или белого элемента). Установка меньшего значения в пикселях даёт изображение более высокого разрешения. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Зачем это менять?** Стандартный X‑размер 3–4 пикселя может давать штрих‑код, выглядящий грубо на экранах с высоким DPI. Уменьшение до **2 пикселей** обеспечивает баланс между читаемостью и размером файла, особенно если позже включить компактный режим. + +## Шаг 4: Настройка количества столбцов + +PDF417 позволяет указать, сколько столбцов должно содержать изображение штрих‑кода. Меньшее количество столбцов делает штрих‑код уже, но выше, тогда как больше столбцов создаёт более широкий и короткий штрих‑код. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Практический совет:** Для мобильных билетов, которые должны помещаться в узкой этикетке, количество столбцов **3–5** обычно работает хорошо. Увеличьте количество, если у вас много данных и нужен более короткий штрих‑код. + +## Шаг 5: Включение компактного режима для обрезки пустых строк + +Компактный режим удаляет ненужные строки из матрицы штрих‑кода, уменьшая общий размер изображения без потери закодированных данных. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Когда использовать:** Если вы генерируете штрих‑коды для хранения или передачи по сети, компактный режим может уменьшить PNG‑файл до 30 %. Однако некоторые старые сканеры могут не поддерживать обрезанный PDF417; проверьте совместимость с вашим оборудованием. + +## Шаг 6: Сохранение штрих‑кода как PNG‑изображения + +Выберите путь вывода и вызовите `Save`. Перечисление `BarCodeImageFormat.Png` создаёт безпотерьное изображение, подходящее для большинства приложений. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Проверка результата:** Откройте PNG‑файл в любом просмотрщике изображений. Вы должны увидеть плотный, контрастный штрих‑код, соответствующий примеру текста. Сканирование изображения с помощью считывателя PDF417 (например, ZXing или мобильного приложения) вернёт исходную строку `"Åspóse.Barcóde©"`. + +![Созданный штрих‑код PDF417, сохранённый как PNG](compact-pdf417.png "Созданный штрих‑код PDF417 в C#") + +*Изображение выше демонстрирует окончательный результат кода из учебника.* + +## Полный, исполняемый пример + +Объединив все части, получаем полностью готовую консольную программу, которую можно скопировать, вставить и запустить. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Ожидаемый вывод + +Запуск программы выводит: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +Файл `CompactPdf417.png` содержит компактный штрих‑код PDF417, который кодирует предоставленную Unicode‑строку. Сканирование изображения стандартным считывателем PDF417 возвращает точный текст. + +## Общие варианты и граничные случаи + +| Ситуация | Настройка | Причина | +|-----------|------------|--------| +| **Более длинный набор данных** (например, > 150 символов) | Увеличьте `generator.Parameters.Barcode.Pdf417.Columns` до 6‑8 | Большее количество столбцов предотвращает чрезмерную высоту штрих‑кода. | +| **Необходимость прозрачного фона** | Используйте `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | Прозрачный PNG лучше интегрируется в наложения пользовательского интерфейса. | +| **Создание JPEG для веба** | Измените формат на `BarCodeImageFormat.Jpeg` и при необходимости задайте `ImageQuality` | JPEG уменьшает размер файла за счёт потери безупречного качества. | +| **Обработка null или пустого ввода** | Защитите ввод перед созданием генератора: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Предотвращает исключения во время выполнения и обеспечивает осмысленные штрих‑коды. | + +## Советы для продакшн‑использования + +* **Обработка исключений:** Оберните логику генерации в блок `try/catch`, чтобы регистрировать ошибки, такие как недостаток места на диске или неверные параметры. +* **Производительность:** Переиспользуйте один экземпляр `BarcodeGenerator` при генерации множества штрих‑кодов с одинаковыми настройками; обновляйте только свойство `CodeText` между сохранениями. +* **Безопасность:** Если кодируемый текст содержит конфиденциальную информацию, рассмотрите возможность её шифрования перед передачей в генератор и расшифровки после сканирования. + +## Заключение + +Теперь вы знаете, как **создавать штрих‑код PDF417** в C# с помощью библиотеки Aspose.BarCode, настраивать компактный режим, управлять количеством столбцов и экспортировать результат в PNG‑изображение. Этот учебник охватывает каждый шаг от настройки проекта до обработки граничных случаев, предоставляя готовое решение для приложений, работающих со штрих‑кодами. + +Далее изучайте связанные темы, такие как **создание QR‑кодов в C#**, **пакетная генерация штрих‑кодов** и **интеграция сканирования штрих‑кодов в мобильные приложения**. Все они опираются на те же фундаментальные возможности `BarcodeGenerator`, которые вы только что освоили. + +Удачной разработки! + +## Что изучать дальше? + +Следующие учебники охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полные рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в собственных проектах. + +- [Как генерировать штрих‑коды PDF417 – компактное кодирование PDF417](/barcode/english/net/compact-pdf417-encoding/) +- [Как создать штрих‑код – компактный PDF417 с Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Как генерировать штрих‑код Aztec с пользовательским соотношением сторон, используя Aspose.BarCode для .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/russian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/russian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..bcb612a99 --- /dev/null +++ b/barcode/russian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-09 +description: Как считывать PDF417 в C# с помощью BarCodeReader. Узнайте, как читать + PNG‑файлы штрихкодов, обрабатывать несколько штрихкодов и извлекать расширенные + метаданные. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: ru +lastmod: 2026-08-09 +og_description: Как считывать PDF417 в C# с помощью Aspose.BarCode. Этот учебник показывает, + как читать PNG‑файлы штрихкодов, обрабатывать несколько штрихкодов на одном изображении + и получать расширенные метаданные PDF417. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Как читать PDF417 в C# – руководство по считыванию штрихкода +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Как считывать PDF417 в C# – полное руководство по чтению штрихкодов +url: /ru/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как читать PDF417 в C# – полное руководство по считыванию штрихкодов + +Если вам нужно **как читать PDF417** в приложении .NET, это руководство предоставляет готовое к запуску решение. Вы увидите, как считывать PNG‑изображение со штрихкодом, обрабатывать несколько штрихкодов на одном изображении и извлекать расширенные поля PDF417, которые скрывают многие сканеры. + +Считывание штрихкодов PDF417 широко используется в логистике, билетных системах и управлении документами. К концу этого урока вы сможете декодировать изображение Macro PDF417, отобразить каждый результат и использовать дополнительную информацию (ID файла, количество сегментов, метки времени и т.д.) в своей бизнес‑логике. + +## Prerequisites + +- .NET 6.0 или новее (код также работает с .NET Framework 4.7+) +- Visual Studio 2022 или любой IDE для C# +- **Aspose.BarCode for .NET** (бесплатная пробная версия или лицензированный пакет NuGet) +- PNG‑изображение, содержащее штрихкод Macro PDF417 (пример файла называется `ExtPDF417Meta.png`) + +> **Совет:** Установите библиотеку через консоль NuGet: +> `dotnet add package Aspose.BarCode` + +## Как читать PDF417 с помощью BarCodeReader в C# + +Ядром решения является класс `BarCodeReader`. Он принимает путь к изображению и перечисление `DecodeType`, которое указывает движку, какую символьную систему искать. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Почему это работает + +- **`DecodeType.MacroPdf417`** указывает считывателю искать вариант Macro PDF417, который хранит дополнительные поля, показанные на шаге 4. +- Блок `using` автоматически освобождает читатель, закрывая файловые дескрипторы. +- `ReadBarCodes()` возвращает **все** штрихкоды, соответствующие запрошенному типу, что удовлетворяет требованию *чтения нескольких штрихкодов*, даже если изображение содержит только один. + +Запуск программы выводит результат, похожий на: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## Использование считывателя штрихкодов C# для чтения нескольких штрихкодов + +Если изображение содержит несколько символов Macro PDF417 (например, отсканированную страницу с набором билетов), тот же цикл `foreach` обрабатывает каждый из них. Дополнительный код не нужен; считыватель агрегирует результаты внутри. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Распространённые подводные камни + +- **Формат изображения:** Считыватель поддерживает PNG, JPEG, BMP и TIFF. Если попытаться использовать неподдерживаемый формат, вы получите пустую коллекцию. Поэтому в руководстве подчеркивается *чтение штрихкода PNG*. +- **Разрешение:** Изображения с низким разрешением (< 300 dpi) могут приводить к пропуску сегментов. При возможности увеличьте масштаб или запросите скан более высокого качества. +- **Флаг Macro:** Если забыть указать `DecodeType.MacroPdf417`, движок будет работать только с обычным PDF417 и отбросит расширенные данные. Всегда указывайте тип macro, когда нужны *расширенные поля штрихкода*. + +## Чтение PNG‑файлов со штрихкодами – лучшие практики + +Работа с PNG‑файлами проста, так как формат сохраняет пиксельные данные без потерь. Ниже краткий чек‑лист: + +1. Убедитесь, что файл существует перед созданием считывателя. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Используйте `Image.FromFile` только при необходимости предварительной обработки (поворот, обрезка). `BarCodeReader` может открыть файл напрямую, что экономит дополнительную память. +3. Если PNG содержит прозрачность, считыватель всё равно работает, поскольку штрихкод отображается на непрозрачных пикселях. + +## Доступ к расширенным метаданным PDF417 + +Объект `Extended.Pdf417` раскрывает все необязательные поля, определённые спецификацией PDF417. Вы можете сопоставить эти поля с доменной моделью, сохранить их в базе данных или использовать для валидации. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Populate the model: + + + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и изучить альтернативные подходы к реализации в своих проектах. + +- [Как читать DataMatrix штрихкоды с помощью Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Как создать штрихкод – Compact PDF417 с Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Чтение DataMatrix штрихкода C# – Генерация режима DataMatrix (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/spanish/net/compact-pdf417-encoding/_index.md b/barcode/spanish/net/compact-pdf417-encoding/_index.md index 6c5e3bd09..6be64bf93 100644 --- a/barcode/spanish/net/compact-pdf417-encoding/_index.md +++ b/barcode/spanish/net/compact-pdf417-encoding/_index.md @@ -85,6 +85,14 @@ Más allá de lo básico, aquí tienes algunos consejos prácticos para optimiza ## Tutoriales de codificación Compact PDF417 ### [Crear códigos de barras Compact PDF417](./compact-pdf417-basic-configuration/) Aprende a generar códigos de barras Compact PDF417 usando Aspose.BarCode para .NET. Guía completa con instrucciones paso a paso y ejemplos de código. +### [Ejemplo de Aspose.BarCode: generar Macro PDF417 en C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Aprende a generar códigos de barras Macro PDF417 en C# usando Aspose.BarCode. Guía paso a paso con ejemplo completo. +### [Generar código de barras PDF417 en C# – guía paso a paso](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Aprende a crear códigos de barras PDF417 en C# con Aspose.BarCode, siguiendo una guía detallada paso a paso. +### [Generar código de barras a partir de texto en C# – guía completa paso a paso](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Aprende a generar códigos de barras a partir de texto en C# con Aspose.BarCode, siguiendo una guía completa paso a paso. +### [Cómo leer PDF417 en C# – guía completa del lector de códigos de barras](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +Aprende a leer códigos de barras PDF417 en C# usando Aspose.BarCode, con ejemplos completos y mejores prácticas. ## Preguntas frecuentes @@ -114,4 +122,4 @@ R: No se requieren fuentes externas; la biblioteca maneja todo el renderizado in {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/spanish/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/spanish/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..e761e0802 --- /dev/null +++ b/barcode/spanish/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-09 +description: Ejemplo de Aspose Barcode que muestra cómo usar un generador de códigos + de barras en C# para crear un Macro PDF417 con soporte completo de metadatos. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: es +lastmod: 2026-08-09 +og_description: El ejemplo de código de barras de Aspose muestra cómo usar un generador + de códigos de barras en C# para producir un código de barras Macro PDF417 que incluye + el ID del archivo, datos del segmento, marca de tiempo y otros metadatos. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Ejemplo de código de barras Aspose – crear Macro PDF417 con C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Ejemplo de código de barras Aspose: generar Macro PDF417 en C#' +url: /es/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ejemplo de Aspose barcode: generar Macro PDF417 en C# + +Si necesita un **aspose barcode example** que cree un Macro PDF417 barcode, esta guía le muestra cómo hacerlo con un **barcode generator C#**. Verá cada configuración requerida, desde dimensiones básicas hasta el conjunto completo de campos de metadatos Macro PDF417, y obtendrá una imagen PNG lista para el procesamiento posterior. + +El tutorial cubre el flujo de trabajo completo, explica por qué cada parámetro es importante y proporciona un ejemplo de código listo para ejecutar. No se requieren referencias externas; puede copiar el código, ajustar los valores y ejecutarlo de inmediato. + +## Prerequisites + +Antes de comenzar, asegúrese de tener: + +- .NET 6.0 (o posterior) instalado +- Visual Studio 2022 o cualquier IDE compatible con C# +- Una licencia válida para **Aspose.BarCode for .NET** (la prueba gratuita funciona para este ejemplo) + +Add the Aspose.BarCode NuGet package to your project: + +```bash +dotnet add package Aspose.BarCode +``` + +## Paso 1: Crear la instancia del generador de códigos de barras C# + +El primer paso es instanciar `BarcodeGenerator` con el valor enum `EncodeTypes.MacroPdf417` y el texto que desea codificar. El texto puede contener caracteres Unicode, que la biblioteca maneja automáticamente. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Por qué es importante*: `EncodeTypes.MacroPdf417` indica al motor que produzca un símbolo Macro PDF417, que admite datos segmentados y metadatos a nivel de archivo adicionales. La instrucción `using` garantiza que los recursos no administrados se liberen después de guardar la imagen. + +## Paso 2: Definir la apariencia básica del código de barras + +Un Macro PDF417 barcode consiste en módulos cuadrados. Controlar el tamaño del módulo y la cantidad de columnas influye tanto en la legibilidad como en el tamaño del archivo. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Por qué es importante*: `XDimension.Pixels` determina la densidad visual; un valor de 2 píxeles funciona bien para la visualización en pantalla mientras mantiene la imagen pequeña. Ajuste la cantidad de columnas para adaptarse a sus limitaciones de diseño—más columnas crean un código de barras más ancho y corto. + +## Paso 3: Establecer los metadatos específicos de Macro PDF417 + +Macro PDF417 amplía el formato estándar PDF417 con campos que permiten la reconstrucción de archivos grandes a partir de múltiples segmentos de código de barras. Cada campo es opcional, pero configurarlos demuestra todas las capacidades de la API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Por qué es importante*: +- `MacroPdf417FileID` enlaza todos los segmentos que pertenecen al mismo archivo lógico. +- `MacroPdf417SegmentID` y `MacroPdf417SegmentsCount` permiten al decodificador reordenar los fragmentos correctamente. +- `MacroPdf417Checksum` proporciona una verificación rápida de integridad sin decodificar toda la carga útil. +- `MacroPdf417FileSize` y `MacroPdf417TimeStamp` permiten a los sistemas posteriores verificar que el archivo reconstruido coincide con el original. +- `MacroPdf417Addressee` / `MacroPdf417Sender` son útiles en escenarios de logística o intercambio de documentos. +- Configurar `MacroPdf417Terminator` a `Set` marca este código de barras como el segmento final, lo que simplifica el algoritmo de reconstrucción. + +## Paso 4: Guardar la imagen del código de barras generado + +Finalmente, guarde el código de barras en un archivo PNG. Puede elegir cualquier formato compatible (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Por qué es importante*: PNG conserva los datos de píxeles sin pérdida, garantizando que los escáneres lean el patrón de módulos exacto que configuró. Cambiar el formato puede afectar la calidad visual y el tamaño del archivo. + +### Salida esperada + +Ejecutar el programa completo crea un archivo llamado **ExtPDF417Meta.png**. Al abrir la imagen se muestra un código de barras rectangular Macro PDF417 con el texto “Åspóse.Barcóde©” codificado, y la densidad visual coincide con la dimensión X de 2 píxeles que estableció. Escanear la imagen con un lector compatible con PDF417 devuelve todos los campos de metadatos definidos en el Paso 3. + +## Ejemplo completo funcional + +Copie el código a continuación en un nuevo proyecto de consola (`dotnet new console`) y reemplace `YOUR_DIRECTORY` con una ruta absoluta o relativa que exista en su máquina. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Ejecute el programa (`dotnet run`). Después de la ejecución, verifique que el archivo PNG aparezca en la ubicación que especificó. Use cualquier aplicación de lectura de códigos de barras que admita Macro PDF417 para confirmar que los metadatos están incrustados correctamente. + +## Variaciones comunes y casos límite + +- **Diferentes formatos de imagen**: Reemplace `BarCodeImageFormat.Png` por `Jpeg`, `Bmp` o `Tiff` si su sistema posterior prefiere otro formato. +- **Cambiar el tamaño del módulo**: Valores mayores de `XDimension.Pixels` mejoran la fiabilidad del escaneo en escáneres de baja resolución pero aumentan el tamaño de la imagen. +- **Múltiples segmentos**: Para producir un archivo multi‑segmento, genere una serie de códigos de barras, incremente `MacroPdf417SegmentID` para cada uno y mantenga `MacroPdf417FileID` constante. Sólo el último segmento debe tener `MacroPdf417Terminator` configurado. +- **Soporte Unicode**: El generador codifica automáticamente caracteres Unicode; asegúrese de que su cadena fuente use codificación UTF‑8 si la lee de un archivo externo. +- **Manejo de errores**: Envuelva el bloque `using` en un try‑catch para capturar `BarCodeException` por parámetros inválidos (p. ej., recuento de columnas fuera de rango). + +## Consejos profesionales + +- **Rendimiento**: Reutilice una única instancia de `BarcodeGenerator` al crear muchos códigos de barras con la misma configuración; solo cambie la propiedad `CodeText` entre guardados. +- **Estimación del tamaño de archivo**: El campo `MacroPdf417FileSize` debe coincidir con el recuento de bytes de la carga útil original; las discrepancias pueden causar fallas de validación posteriores. +- **Pruebas**: Valide los códigos de barras generados tanto con el decodificador incorporado de Aspose (`BarCodeReader`) como con un escáner de terceros para garantizar la interoperabilidad. + +## Conclusión + +Este **aspose barcode example + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarle a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en sus propios proyectos. + +- [Cómo crear códigos de barras – Compact PDF417 con Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Cómo crear zona silenciosa de código de barras para Code 16K usando Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [Cómo crear zona silenciosa de código de barras para ITF-14 usando Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/spanish/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/spanish/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..63864bd59 --- /dev/null +++ b/barcode/spanish/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-08-09 +description: Genera códigos de barras a partir de texto en C# con Aspose.BarCode. + Aprende cómo generar códigos de barras, manejar caracteres especiales y crear códigos + de barras PDF417 en C# rápidamente. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: es +lastmod: 2026-08-09 +og_description: Genera códigos de barras a partir de texto en C# usando Aspose.BarCode. + Este tutorial muestra cómo generar códigos de barras, admitir caracteres especiales + y crear códigos de barras PDF417 en C# con el código completo. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Generar código de barras a partir de texto en C# – guía rápida paso a paso +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Generar código de barras a partir de texto en C# – guía completa paso a paso +url: /es/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generar código de barras a partir de texto en C# – guía completa paso a paso + +Si necesitas **generar código de barras a partir de texto** en una aplicación .NET, esta guía te lleva a través de todo el proceso. Verás cómo generar el código de barras, gestionar caracteres especiales y crear una implementación de código de barras PDF417 en C# que funciona listo para usar. + +Generar un código de barras a partir de texto es un requisito común para sistemas de inventario, plataformas de tickets y flujos de trabajo de documentos. Al final de este tutorial tendrás una aplicación de consola C# ejecutable que produce una imagen PNG MicroPdf417 usando Aspose.BarCode. No se requieren servicios externos, y el código maneja caracteres Unicode como “Å”, “©” y “é”. + +## Prerrequisitos + +- SDK .NET 6.0 o posterior (el código también funciona con .NET Core 3.1 y .NET Framework 4.7+) +- Visual Studio 2022 (o cualquier IDE que soporte C#) +- **Aspose.BarCode for .NET** paquete NuGet + ```bash + dotnet add package Aspose.BarCode + ``` +- Conocimientos básicos de sintaxis C# + +## Generar código de barras a partir de texto – configurando el generador + +El primer paso es crear una instancia de `BarcodeGenerator` que sepa qué **tipo de codificación de código de barras** deseas. En este tutorial usamos `EncodeTypes.MicroPdf417`, que es una variante compacta de PDF417 adecuada para cadenas de datos cortas. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Por qué funciona:** +- `EncodeTypes.MicroPdf417` indica a la biblioteca que use la familia PDF417, cumpliendo con el requisito **create pdf417 barcode c#**. +- El constructor recibe el texto sin procesar, que es la esencia de **generate barcode from text**. +- El soporte Unicode está incorporado, por lo que caracteres como “Å” y “©” se codifican correctamente, abordando **barcode with special characters**. + +## Cómo generar código de barras con caracteres especiales + +Cuando tus datos contienen símbolos no ASCII, debes asegurarte de que el generador use codificación UTF‑8. Aspose.BarCode detecta Unicode automáticamente, pero puedes establecer explícitamente la codificación del texto si encuentras problemas: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Agregar esta línea antes de `ConfigureGenerator` garantiza que **barcode with special characters** se renderice correctamente en cualquier plataforma. + +### Consejo práctico +Si la salida se ve distorsionada, verifica que la fuente usada por el renderizador de códigos de barras admita los glifos requeridos. Puedes incrustar una fuente TrueType personalizada mediante: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Tipos de codificación de código de barras que puedes elegir + +Aspose.BarCode soporta docenas de **tipos de codificación de código de barras**, cada uno adecuado para diferentes casos de uso: + +| Tipo de codificación | Caso de uso típico | +|-----------------------------|----------------------------------------| +| `EncodeTypes.Code128` | Etiquetas de envío, inventario | +| `EncodeTypes.QR` | Pagos móviles, URLs | +| `EncodeTypes.Pdf417` | Licencias de conducir, tarjetas de embarque | +| `EncodeTypes.MicroPdf417` | Cargas de datos pequeñas, espacio limitado | +| `EncodeTypes.DataMatrix` | Artículos diminutos, alta densidad de datos | + +Cambiar el tipo de codificación es tan simple como intercambiar el valor del enum en el constructor: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Esta flexibilidad te permite responder preguntas sobre **barcode encode types** sin salir del IDE. + +## Crear código de barras PDF417 en C# – pasos finales y verificación + +Después de configurar el generador, la última parte de **create pdf417 barcode c#** es guardar la imagen y confirmar el resultado. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Ejecuta el programa (`dotnet run`) y deberías ver un mensaje en la consola similar a: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Abre el archivo PNG; verás un código de barras MicroPdf417 nítido que codifica la cadena “Åspóse.Barcóde©”. Escanearlo con un lector de códigos de barras móvil (p. ej., ZXing) devuelve el texto original, demostrando que **generate barcode from text** funciona incluso con caracteres especiales. + +### Caso límite: texto muy largo + +MicroPdf417 tiene una capacidad máxima de datos de 1 KB. Si tu entrada supera este límite, la biblioteca lanza una `ArgumentException`. Para manejarlo de forma elegante: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Para cargas útiles mayores, cambia a `EncodeTypes.Pdf417` completo o a `EncodeTypes.DataMatrix`. + +## Errores comunes y cómo evitarlos + +| Problema | Causa | Solución | +|----------------------------------|---------------------------------------|----------| +| El código de barras aparece borroso | XDimension demasiado bajo (p. ej., 1 px) | Incrementa `XDimension.Pixels` a 2‑3 px | +| Los caracteres Unicode aparecen como `?` | La codificación de texto predeterminada es ASCII | Establece `TextEncoding = Encoding.UTF8` | +| No se crea el archivo de imagen | El directorio de salida no existe | Usa `Directory.CreateDirectory` antes de `Save` | +| El escáner no puede leer el código | Demasiadas columnas para datos cortos | Reduce `Pdf417.Columns` (p. ej., 3‑4) | + +## Código fuente completo (listo para copiar) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Salida esperada:** un archivo llamado `MicroPdf417.png` ubicado en la carpeta `output`, que contiene un código de barras MicroPdf417 claro que codifica la cadena original con caracteres especiales. + +## Conclusión + +Ahora sabes cómo **generar código de barras a partir de texto** en C# usando Aspose.BarCode, cómo manejar **barcode with special characters**, y cómo **create pdf417 barcode c#** con control total sobre las opciones de codificación. Al ajustar los **barcode encode types** puedes producir códigos QR, Code128, DataMatrix o cualquier otro formato soportado. + +A continuación, explora los siguientes temas para profundizar tu experiencia con códigos de barras: + +- **Cómo generar códigos de barras** en lote para miles de registros (usa `Parallel.ForEach` para mayor velocidad) +- Personalizar colores y añadir logotipos dentro del código de barras +- Integrar la generación de códigos de barras en APIs ASP.NET Core para entrega de imágenes bajo demanda +- Usar otras bibliotecas como ZXing.Net o IronBarcode para alternativas de código abierto + +¡Siéntete libre de experimentar con diferentes dimensiones, configuraciones de columnas y tipos de codificación! Feliz codificación, y que tus aplicaciones escaneen sin problemas. + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/spanish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/spanish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..138abdc77 --- /dev/null +++ b/barcode/spanish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-08-09 +description: Genera códigos de barras PDF417 en C# rápidamente. Aprende cómo generar + PDF417 con modo compacto, control de columnas y salida PNG usando la API BarcodeGenerator. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: es +lastmod: 2026-08-09 +og_description: Genera código de barras PDF417 en C# con un ejemplo conciso. Esta + guía muestra cómo configurar el modo compacto, establecer columnas y guardar el + resultado como una imagen PNG. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Generar código de barras PDF417 en C# – tutorial completo +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: Generar código de barras PDF417 en C# – guía paso a paso +url: /es/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generar código de barras PDF417 en C# – guía paso a paso + +Si necesitas **generar un código de barras PDF417** en una aplicación .NET, este tutorial te muestra exactamente cómo hacerlo. Verás un programa completo y ejecutable que crea un código de barras PDF417 compacto, personaliza su tamaño y guarda la imagen como un archivo PNG. + +Generar un código de barras PDF417 es un requisito común para la emisión de tickets móviles, el seguimiento de inventario y la seguridad de documentos. Esta guía cubre las opciones de configuración esenciales, explica por qué cada ajuste es importante y ofrece consejos prácticos para su uso en entornos reales. + +## Prerrequisitos + +Antes de comenzar, asegúrate de tener: + +* SDK de .NET 6.0 o posterior instalado +* Un IDE de C# como Visual Studio 2022 o Visual Studio Code +* El paquete **Aspose.BarCode for .NET** de NuGet (versión 23.10 o más reciente) + +Puedes instalar el paquete con el siguiente comando CLI: + +```bash +dotnet add package Aspose.BarCode +``` + +El código a continuación asume que el paquete está referenciado y que tienes permiso de escritura en el directorio de salida. + +## Paso 1: Configurar el proyecto e importar espacios de nombres + +Crea un nuevo proyecto de consola y agrega las directivas `using` requeridas. Estos espacios de nombres exponen la clase `BarcodeGenerator` y la enumeración de formatos de imagen. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Por qué es importante:** Importar los espacios de nombres correctos garantiza que el compilador pueda localizar el tipo `BarcodeGenerator` y la enumeración `BarCodeImageFormat`. La falta de un espacio de nombres produce un error de compilación, lo que detiene el proceso de generación del código de barras. + +## Paso 2: Inicializar el `BarcodeGenerator` con codificación PDF417 + +El constructor de `BarcodeGenerator` recibe dos argumentos: la simbología del código de barras (`EncodeTypes.Pdf417`) y el texto que deseas codificar. PDF417 admite una amplia gama de caracteres, incluidos símbolos Unicode. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Explicación:** +* `EncodeTypes.Pdf417` indica a la biblioteca que use el estándar PDF417. +* El texto de ejemplo contiene caracteres acentuados y un símbolo de copyright para demostrar el manejo de Unicode. + +Si solo necesitas codificar datos numéricos, puedes pasar una cadena simple como `"1234567890"`. + +## Paso 3: Ajustar la dimensión X para mayor resolución + +La dimensión X controla el ancho de un solo módulo del código de barras (el elemento negro o blanco más pequeño). Establecer un valor de píxel menor produce una imagen de mayor resolución. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**¿Por qué ajustarla?** Una dimensión X predeterminada de 3–4 píxeles puede generar un código de barras que se ve grueso en pantallas de alta DPI. Reducirla a **2 píxeles** equilibra la legibilidad con el tamaño del archivo, especialmente cuando activas el modo compacto. + +## Paso 4: Configurar el número de columnas + +PDF417 permite especificar cuántas columnas debe contener el código de barras. Menos columnas hacen que el código sea más estrecho pero más alto, mientras que más columnas crean un código más ancho y corto. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Consejo práctico:** Para tickets móviles que deben caber en una etiqueta estrecha, un recuento de columnas de **3–5** funciona bien. Incrementa el recuento si tienes muchos datos y deseas un código de barras más corto. + +## Paso 5: Habilitar el modo compacto para truncar filas vacías + +El modo compacto elimina filas innecesarias de la matriz del código de barras, reduciendo el tamaño total de la imagen sin perder datos codificados. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Cuándo usarlo:** Si generas códigos de barras para almacenamiento o transmisión por red, el modo compacto puede reducir el archivo PNG hasta en un 30 %. Sin embargo, algunos escáneres heredados pueden no soportar PDF417 truncado; pruébalo con tu hardware objetivo. + +## Paso 6: Guardar el código de barras como imagen PNG + +Elige una ruta de salida e invoca `Save`. La enumeración `BarCodeImageFormat.Png` produce una imagen sin pérdida adecuada para la mayoría de las aplicaciones. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Verificación del resultado:** Abre el archivo PNG en cualquier visor de imágenes. Deberías ver un código de barras denso y de alto contraste que coincide con el texto de ejemplo. Escanear la imagen con un lector PDF417 (p. ej., ZXing o una aplicación móvil) devuelve la cadena original `"Åspóse.Barcóde©"`. + +![Imagen generada del código de barras PDF417 guardada como PNG](compact-pdf417.png "Código de barras PDF417 generado en C#") + +*La imagen anterior muestra la salida final del código del tutorial.* + +## Ejemplo completo y ejecutable + +Uniendo todas las piezas, aquí tienes un programa de consola completo que puedes copiar, pegar y ejecutar. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Salida esperada + +Al ejecutar el programa se imprime: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +El archivo `CompactPdf417.png` contiene un código de barras PDF417 compacto que codifica la cadena Unicode proporcionada. Escanear la imagen con un lector PDF417 estándar devuelve el texto exacto. + +## Variaciones comunes y casos límite + +| Situación | Ajuste | Razón | +|-----------|--------|-------| +| **Carga de datos más larga** (p. ej., > 150 caracteres) | Incrementar `generator.Parameters.Barcode.Pdf417.Columns` a 6‑8 | Más columnas evitan que el código de barras se vuelva excesivamente alto. | +| **Necesidad de fondo transparente** | Usar `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | PNG transparente se integra mejor en superposiciones de UI. | +| **Generar JPEG para web** | Cambiar el formato a `BarCodeImageFormat.Jpeg` y opcionalmente establecer `ImageQuality` | JPEG reduce el tamaño del archivo a costa de la fidelidad sin pérdida. | +| **Manejo de entrada nula o vacía** | Validar la entrada antes de crear el generador: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Previene excepciones en tiempo de ejecución y asegura códigos de barras significativos. | + +## Consejos para uso en producción + +* **Manejo de excepciones:** Envuelve la lógica de generación en un bloque `try/catch` para registrar errores como espacio insuficiente en disco o parámetros inválidos. +* **Rendimiento:** Reutiliza una única instancia de `BarcodeGenerator` cuando generes muchos códigos de barras con la misma configuración; solo actualiza la propiedad `CodeText` entre guardados. +* **Seguridad:** Cuando el texto codificado contiene información sensible, considera encriptarlo antes de pasarlo al generador y desencriptarlo después de escanearlo. + +## Conclusión + +Ahora sabes cómo **generar un código de barras PDF417** en C# usando la biblioteca Aspose.BarCode, configurar el modo compacto, controlar el número de columnas y exportar el resultado como una imagen PNG. Este tutorial cubrió cada paso, desde la configuración del proyecto hasta el manejo de casos límite, brindándote una solución lista para usar en aplicaciones impulsadas por códigos de barras. + +A continuación, explora temas relacionados como **crear códigos QR en C#**, **generación masiva de códigos de barras** e **integración de escaneo de códigos de barras con aplicaciones móviles**. Cada uno de estos se basa en los mismos fundamentos de `BarcodeGenerator` que acabas de dominar. + +¡Feliz codificación! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [How to Generate PDF417 Barcodes – Compact PDF417 Encoding](/barcode/english/net/compact-pdf417-encoding/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/spanish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/spanish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..9b9f3dcdf --- /dev/null +++ b/barcode/spanish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-09 +description: Cómo leer PDF417 en C# usando BarCodeReader. Aprende a leer archivos + PNG de códigos de barras, manejar múltiples códigos de barras y extraer metadatos + extendidos. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: es +lastmod: 2026-08-09 +og_description: Cómo leer PDF417 en C# con Aspose.BarCode. Este tutorial le muestra + cómo leer archivos PNG de códigos de barras, procesar varios códigos de barras en + una sola imagen y obtener metadatos extendidos de PDF417. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Cómo leer PDF417 en C# – tutorial de lector de códigos de barras +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Cómo leer PDF417 en C# – guía completa del lector de códigos de barras +url: /es/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo leer PDF417 en C# – guía completa del lector de códigos de barras + +Si necesitas **cómo leer PDF417** en una aplicación .NET, esta guía te ofrece una solución lista para ejecutar. Verás cómo leer un PNG de código de barras, procesar varios códigos en la misma imagen y extraer los campos extendidos de PDF417 que muchos escáneres ocultan. + +Leer códigos de barras PDF417 es común en logística, emisión de entradas y gestión documental. Al final de este tutorial podrás decodificar una imagen Macro PDF417, mostrar cada resultado y usar la información adicional (ID de archivo, recuento de segmentos, marcas de tiempo, etc.) en tu propia lógica de negocio. + +## Requisitos previos + +- .NET 6.0 o posterior (el código también funciona con .NET Framework 4.7+) +- Visual Studio 2022 o cualquier IDE de C# +- **Aspose.BarCode for .NET** (prueba gratuita o paquete NuGet con licencia) +- Una imagen PNG que contenga un código de barras Macro PDF417 (el archivo de ejemplo se llama `ExtPDF417Meta.png`) + +> **Consejo profesional:** Instala la biblioteca con la consola NuGet: +> `dotnet add package Aspose.BarCode` + +## Cómo leer PDF417 con BarCodeReader en C# + +El núcleo de la solución es la clase `BarCodeReader`. Acepta una ruta de imagen y un enumerado `DecodeType` que indica al motor qué simbología buscar. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Por qué funciona + +- **`DecodeType.MacroPdf417`** indica al lector que busque la variante Macro PDF417, que almacena los campos extra que ves en el paso 4. +- El bloque `using` elimina automáticamente el lector, liberando los manejadores de archivo. +- `ReadBarCodes()` devuelve **todos** los códigos de barras que coinciden con el tipo solicitado, cumpliendo el requisito de *leer varios códigos de barras* incluso si la imagen contiene solo uno. + +Ejecutar el programa muestra una salida similar a: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## Uso del lector de códigos de barras en C# para leer múltiples códigos + +Si una imagen contiene varios símbolos Macro PDF417 (por ejemplo, una página escaneada con un lote de entradas), el mismo bucle `foreach` procesa cada uno. No se requiere código adicional; el lector agrega los resultados internamente. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Trampas comunes + +- **Formato de imagen:** El lector admite PNG, JPEG, BMP y TIFF. Si intentas un formato que no puede decodificar, obtendrás una colección vacía. Por eso el tutorial destaca *leer código de barras PNG*. +- **Resolución:** Las imágenes de baja resolución (< 300 dpi) pueden provocar segmentos perdidos. Aumenta la escala o solicita un escaneo de mayor calidad cuando sea posible. +- **Bandera Macro:** Olvidar `DecodeType.MacroPdf417` limita el motor a PDF417 simple y descarta los datos extendidos. Siempre especifica el tipo macro cuando necesites *leer campos extendidos del código de barras*. + +## Lectura de archivos PNG de códigos de barras – mejores prácticas + +Trabajar con archivos PNG es sencillo porque el formato conserva datos de píxeles sin pérdida. Aquí tienes una lista de verificación rápida: + +1. Verifica que el archivo exista antes de crear el lector. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Usa `Image.FromFile` solo cuando necesites pre‑procesar (rotar, recortar). El `BarCodeReader` puede abrir el archivo directamente, lo que evita asignaciones de memoria extra. +3. Si el PNG contiene transparencia, el lector sigue funcionando porque el código de barras se renderiza sobre píxeles opacos. + +## Acceso a los metadatos extendidos de PDF417 + +El objeto `Extended.Pdf417` expone cada campo opcional definido por la especificación PDF417. Puedes mapear estos campos a un modelo de dominio, almacenarlos en una base de datos o utilizarlos para validación. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Poblar el modelo: + + + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Cómo leer códigos de barras DataMatrix con Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Cómo crear códigos de barras – PDF417 compacto con Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Leer código de barras DataMatrix C# – Generar modo DataMatrix (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/swedish/net/compact-pdf417-encoding/_index.md b/barcode/swedish/net/compact-pdf417-encoding/_index.md index cc613e6f8..c7c634e4c 100644 --- a/barcode/swedish/net/compact-pdf417-encoding/_index.md +++ b/barcode/swedish/net/compact-pdf417-encoding/_index.md @@ -84,6 +84,14 @@ Utöver grunderna, här är några praktiska tips för att effektivisera ditt ar ## Kompakt PDF417-kodningshandledning ### [Skapa kompakta PDF417-streckkoder](./compact-pdf417-basic-configuration/) Lär dig hur du genererar Compact PDF417‑streckkoder med Aspose.BarCode för .NET. Omfattande guide med steg‑för‑steg‑instruktioner och kodexempel. +### [Aspose streckkodsexempel: generera Macro PDF417 i C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Exempel på hur du skapar en Macro PDF417‑streckkod med Aspose.BarCode i C#. +### [Generera PDF417-streckkod i C# – steg‑för‑steg‑guide](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Steg‑för‑steg‑guide för att generera PDF417‑streckkoder i C# med Aspose.BarCode. +### [Generera streckkod från text i C# – komplett steg‑för‑steg‑guide](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Fullständig guide för att skapa streckkoder från text i C# med Aspose.BarCode, inklusive kodexempel och konfiguration. +### [Hur man läser PDF417 i C# – komplett streckkodsläsarguide](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +Fullständig guide för att läsa PDF417‑streckkoder i C# med Aspose.BarCode, inklusive kodexempel och konfiguration. ## Vanliga frågor @@ -113,4 +121,4 @@ A: Inga externa typsnitt krävs; biblioteket hanterar all rendering internt. {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/swedish/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/swedish/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..57812b77e --- /dev/null +++ b/barcode/swedish/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-09 +description: Aspose streckkodsexempel som visar hur man använder en streckkodsgenerator + i C# för att skapa en Macro PDF417 med fullt metadata‑stöd. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: sv +lastmod: 2026-08-09 +og_description: Aspose barcode-exempel visar hur man använder en streckkodgenerator + i C# för att skapa en Macro PDF417-streckkod som innehåller fil‑ID, segmentdata, + tidsstämpel och annan metadata. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Aspose streckkodsexempel – skapa Macro PDF417 med C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Aspose streckkodsexempel: generera Macro PDF417 i C#' +url: /sv/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose streckkodsexempel: generera Macro PDF417 i C# + +Om du behöver ett **aspose barcode example** som skapar en Macro PDF417‑streckkod, visar den här guiden hur du gör det med en **barcode generator C#**. Du kommer att se alla nödvändiga inställningar, från grundläggande dimensioner till hela uppsättningen av Macro PDF417‑metadatafält, och du får en PNG‑bild klar för nedströmsbehandling. + +Tutorialen täcker hela arbetsflödet, förklarar varför varje parameter är viktig, och ger ett färdigt kodexempel som kan köras direkt. Inga externa referenser krävs; du kan kopiera koden, justera värdena och köra den omedelbart. + +## Förutsättningar + +Innan du börjar, se till att du har: + +- .NET 6.0 (eller senare) installerat +- Visual Studio 2022 eller någon C#‑kompatibel IDE +- En giltig licens för **Aspose.BarCode for .NET** (gratis provversion fungerar för detta exempel) + +Lägg till Aspose.BarCode NuGet‑paketet i ditt projekt: + +```bash +dotnet add package Aspose.BarCode +``` + +## Steg 1: Skapa barcode‑generator‑instansen i C# + +Det första steget är att instansiera `BarcodeGenerator` med enum‑värdet `EncodeTypes.MacroPdf417` och den text du vill koda. Texten kan innehålla Unicode‑tecken, vilket biblioteket hanterar automatiskt. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Varför detta är viktigt*: `EncodeTypes.MacroPdf417` talar om för motorn att producera en Macro PDF417‑symbol, som stödjer segmenterad data och extra fil‑nivå‑metadata. `using`‑satsen garanterar att ohanterade resurser frigörs efter att bilden har sparats. + +## Steg 2: Definiera grundläggande streckkodens utseende + +En Macro PDF417‑streckkod består av fyrkantiga moduler. Att kontrollera modulstorlek och kolumnantal påverkar både läsbarhet och filstorlek. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Varför detta är viktigt*: `XDimension.Pixels` bestämmer den visuella densiteten; ett värde på 2 pixlar fungerar bra för skärmvisning samtidigt som bilden hålls liten. Justera kolumnantalet för att passa dina layoutbegränsningar—fler kolumner ger en bredare, kortare streckkod. + +## Steg 3: Ange Macro PDF417‑specifik metadata + +Macro PDF417 utökar standard‑PDF417‑formatet med fält som möjliggör återuppbyggnad av stora filer från flera streckkodsegment. Varje fält är valfritt, men att ange dem demonstrerar API:ets fulla kapacitet. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Varför detta är viktigt*: +- `MacroPdf417FileID` länkar alla segment som tillhör samma logiska fil. +- `MacroPdf417SegmentID` och `MacroPdf417SegmentsCount` gör att avkodaren kan sortera fragmenten korrekt. +- `MacroPdf417Checksum` ger en snabb integritetskontroll utan att avkoda hela nyttolasten. +- `MacroPdf417FileSize` och `MacroPdf417TimeStamp` låter nedströmsystem verifiera att den återuppbyggda filen matchar originalet. +- `MacroPdf417Addressee` / `MacroPdf417Sender` är användbara i logistik‑ eller dokumentutbytesscenario. +- Att sätta `MacroPdf417Terminator` till `Set` markerar denna streckkod som det sista segmentet, vilket förenklar återuppbyggnadsalgoritmen. + +## Steg 4: Spara den genererade streckkodsbilden + +Till sist skriver du streckkoden till en PNG‑fil. Du kan välja vilket som helst av de stödjade formaten (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Varför detta är viktigt*: PNG bevarar förlustfri pixeldata, vilket säkerställer att skannrar läser exakt det modulmönster du konfigurerat. Att byta format kan påverka den visuella kvaliteten och filstorleken. + +### Förväntat resultat + +När programmet körs skapas en fil med namnet **ExtPDF417Meta.png**. När du öppnar bilden visas en rektangulär Macro PDF417‑streckkod med texten “Åspóse.Barcóde©” kodad, och den visuella densiteten matchar den 2‑pixel X‑dimension du angav. Att skanna bilden med en PDF417‑kompatibel läsare returnerar alla metadatafält som definierades i Steg 3. + +## Fullt fungerande exempel + +Kopiera koden nedan till ett nytt konsolprojekt (`dotnet new console`) och ersätt `YOUR_DIRECTORY` med en absolut eller relativ sökväg som finns på din maskin. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Kör programmet (`dotnet run`). Efter körning, verifiera att PNG‑filen finns på den plats du angav. Använd någon streckkodsläsare som stödjer Macro PDF417 för att bekräfta att metadata är korrekt inbäddad. + +## Vanliga variationer och kantfall + +- **Olika bildformat**: Byt `BarCodeImageFormat.Png` mot `Jpeg`, `Bmp` eller `Tiff` om ditt nedströmsystem föredrar ett annat format. +- **Ändra modulstorlek**: Större `XDimension.Pixels`‑värden förbättrar skanningspålitlighet på lågupplösta skannrar men ökar bildstorleken. +- **Flera segment**: För att producera en fler‑segment‑fil, generera en serie streckkoder, öka `MacroPdf417SegmentID` för varje och håll `MacroPdf417FileID` konstant. Endast det sista segmentet ska ha `MacroPdf417Terminator` satt. +- **Unicode‑stöd**: Generatorn kodar automatiskt Unicode‑tecken; säkerställ att din källsträng använder UTF‑8‑kodning om du läser den från en extern fil. +- **Felhantering**: Omge `using`‑blocket med en try‑catch för att fånga `BarCodeException` vid ogiltiga parametrar (t.ex. kolumnantal utanför intervall). + +## Pro‑tips + +- **Prestanda**: Återanvänd en enda `BarcodeGenerator`‑instans när du skapar många streckkoder med samma inställningar; ändra bara `CodeText`‑egenskapen mellan sparningar. +- **Filstorleksestimering**: `MacroPdf417FileSize`‑fältet bör matcha byte‑antalet av den ursprungliga nyttolasten; avvikelser kan orsaka valideringsfel i nedströmsystem. +- **Testning**: Validera genererade streckkoder med både Asposes inbyggda avkodare (`BarCodeReader`) och en tredjeparts‑skanner för att säkerställa interoperabilitet. + +## Slutsats + +Detta **aspose barcode example + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger vidare på teknikerna som demonstreras i denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Hur man skapar streckkod – Compact PDF417 med Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Hur man skapar tyst zon för Code 16K med Aspose.BarCode för .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [Hur man skapar tyst zon för ITF-14 med Aspose.BarCode för .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/swedish/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/swedish/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..11f3937b8 --- /dev/null +++ b/barcode/swedish/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-08-09 +description: Generera streckkod från text i C# med Aspose.BarCode. Lär dig hur du + genererar streckkod, hanterar specialtecken och snabbt skapar PDF417-streckkod i + C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: sv +lastmod: 2026-08-09 +og_description: Generera streckkod från text i C# med Aspose.BarCode. Denna handledning + visar hur man genererar streckkod, stödjer specialtecken och skapar PDF417‑streckkod + i C# med fullständig kod. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Generera streckkod från text i C# – snabb steg‑för‑steg‑guide +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Generera streckkod från text i C# – komplett steg‑för‑steg‑guide +url: /sv/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generera streckkod från text i C# – komplett steg‑för‑steg‑guide + +Om du behöver **generera streckkod från text** i en .NET‑applikation, guidar den här guiden dig genom hela processen. Du kommer att se hur du genererar streckkod, hanterar specialtecken och skapar en PDF417‑streckkod C#‑implementation som fungerar direkt ur lådan. + +Att generera en streckkod från text är ett vanligt krav för lagerhanteringssystem, biljettplattformar och dokumentarbetsflöden. I slutet av den här tutorialen har du en körbar C#‑konsolapp som producerar en MicroPdf417 PNG‑bild med Aspose.BarCode. Inga externa tjänster krävs, och koden hanterar Unicode‑tecken som “Å”, “©” och “é”. + +## Förutsättningar + +- .NET 6.0 SDK eller senare (koden fungerar också med .NET Core 3.1 och .NET Framework 4.7+) +- Visual Studio 2022 (eller någon IDE som stödjer C#) +- **Aspose.BarCode for .NET** NuGet‑paket + ```bash + dotnet add package Aspose.BarCode + ``` +- Grundläggande kunskap om C#‑syntax + +## Generera streckkod från text – konfigurera generatorn + +Det första steget är att skapa en `BarcodeGenerator`‑instans som vet vilken **barcode encode type** du vill ha. I den här tutorialen använder vi `EncodeTypes.MicroPdf417`, vilket är en kompakt variant av PDF417 lämplig för korta datasträngar. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Varför detta fungerar:** +- `EncodeTypes.MicroPdf417` talar om för biblioteket att använda PDF417‑familjen, vilket uppfyller kravet **create pdf417 barcode c#**. +- Konstruktorn tar emot den råa texten, vilket är kärnan i **generate barcode from text**. +- Unicode‑stöd är inbyggt, så tecken som “Å” och “©” kodas korrekt, vilket hanterar **barcode with special characters**. + +## Så genererar du streckkod med specialtecken + +När dina data innehåller icke‑ASCII‑symboler måste du säkerställa att generatorn använder UTF‑8‑kodning. Aspose.BarCode upptäcker automatiskt Unicode, men du kan explicit ange textkodning om du stöter på problem: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Att lägga till den här raden före `ConfigureGenerator` garanterar att **barcode with special characters** renderas korrekt på alla plattformar. + +### Praktiskt tips +Om utdata ser förvrängda ut, verifiera att det teckensnitt som används av streckkodsgenereraren stödjer de nödvändiga glyferna. Du kan bädda in ett eget TrueType‑teckensnitt via: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Streckkodskodningstyper du kan välja + +Aspose.BarCode stödjer dussintals **barcode encode types**, var och en lämpad för olika användningsområden: + +| Encode type | Typiskt användningsområde | +|----------------------------|-----------------------------------------------| +| `EncodeTypes.Code128` | Fraktetiketter, lager | +| `EncodeTypes.QR` | Mobila betalningar, URL:er | +| `EncodeTypes.Pdf417` | Körkort, boardingkort | +| `EncodeTypes.MicroPdf417` | Små datamängder, begränsat utrymme | +| `EncodeTypes.DataMatrix` | Små objekt, hög datadensitet | + +Att byta kodningstyp är så enkelt som att byta enum‑värdet i konstruktorn: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Detta ger dig möjlighet att svara på frågor om **barcode encode types** utan att lämna IDE:n. + +## Skapa PDF417‑streckkod C# – sista stegen och verifiering + +Efter att ha konfigurerat generatorn är den sista delen av **create pdf417 barcode c#** att spara bilden och bekräfta resultatet. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Kör programmet (`dotnet run`) så bör du se ett konsolmeddelande liknande: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Öppna PNG‑filen; du ser en skarp MicroPdf417‑streckkod som kodar strängen “Åspóse.Barcóde©”. Att skanna den med en mobil streckkodsläsare (t.ex. ZXing) returnerar den ursprungliga texten, vilket bevisar att **generate barcode from text** fungerar även med specialtecken. + +### Edge case: mycket lång text + +MicroPdf417 har en maximal datakapacitet på 1 KB. Om ditt indata överskrider denna gräns kastar biblioteket ett `ArgumentException`. För att hantera detta på ett smidigt sätt: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +För större nyttolaster, byt till den fullständiga `EncodeTypes.Pdf417` eller `EncodeTypes.DataMatrix`. + +## Vanliga fallgropar och hur du undviker dem + +| Problem | Orsak | Lösning | +|---------------------------------------|-----------------------------------------|---------| +| Streckkoden blir suddig | XDimension för låg (t.ex. 1 px) | Öka `XDimension.Pixels` till 2‑3 px | +| Unicode‑tecken blir `?` | Standardtextkodning är ASCII | Set `TextEncoding = Encoding.UTF8` | +| Bildfilen skapades inte | Utdatamappen finns inte | Use `Directory.CreateDirectory` before `Save` | +| Skannern kan inte läsa streckkoden | För många kolumner för kort data | Reduce `Pdf417.Columns` (e.g., 3‑4) | + +## Fullständig källkod (klar att kopiera) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Förväntad utdata:** en fil med namnet `MicroPdf417.png` i mappen `output`, innehållande en tydlig MicroPdf417‑streckkod som kodar den ursprungliga strängen med specialtecken. + +## Slutsats + +Du vet nu hur du **genererar streckkod från text** i C# med Aspose.BarCode, hur du hanterar **barcode with special characters**, och hur du **create pdf417 barcode c#** med full kontroll över kodningsalternativ. Genom att justera **barcode encode types** kan du producera QR‑koder, Code128, DataMatrix eller något annat stödformat. + +Utforska sedan följande ämnen för att fördjupa din streckkodsexpertis: + +- **Hur man genererar streckkod** i batch för tusentals poster (använd `Parallel.ForEach` för hastighet) +- Anpassa färger och lägga till logotyper i streckkoden +- Integrera streckkodsgenerering i ASP.NET Core‑API:er för dynamisk bildleverans +- Använda andra bibliotek som ZXing.Net eller IronBarcode för öppen‑källkods‑alternativ + +Känn dig fri att experimentera med olika dimensioner, kolumninställningar och kodningstyper. Lycka till med kodandet, och må dina applikationer skanna felfritt! + +## Vad bör du lära dig härnäst? + +Följande tutorialer täcker närbesläktade ämnen som bygger vidare på teknikerna som demonstrerats i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Hur man skapar streckkod – kompakt PDF417 med Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Hur man genererar streckkod – Code 39‑konfiguration med Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Hur man genererar streckkod – endimensionella streckkodstyper](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/swedish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/swedish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..45c0bd5f8 --- /dev/null +++ b/barcode/swedish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,228 @@ +--- +category: general +date: 2026-08-09 +description: Generera PDF417‑streckkod i C# snabbt. Lär dig hur du genererar PDF417 + med kompakt läge, kolumnkontroll och PNG‑utdata med BarcodeGenerator‑API:n. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: sv +lastmod: 2026-08-09 +og_description: Generera PDF417‑streckkod i C# med ett kortfattat exempel. Denna guide + visar hur du konfigurerar kompakt läge, ställer in kolumner och sparar resultatet + som en PNG‑bild. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Generera PDF417-streckkod i C# – komplett handledning +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: Generera PDF417-streckkod i C# – steg‑för‑steg‑guide +url: /sv/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generera PDF417‑streckkod i C# – steg‑för‑steg‑guide + +Om du behöver **generera PDF417‑streckkod** i en .NET‑applikation visar den här handledningen exakt hur du gör. Du får ett komplett, körbart program som skapar en kompakt PDF417‑streckkod, anpassar dess storlek och sparar bilden som en PNG‑fil. + +Att generera en PDF417‑streckkod är ett vanligt krav för mobila biljetter, lagerhantering och dokumentsäkerhet. Denna guide täcker de viktigaste konfigurationsalternativen, förklarar varför varje inställning är viktig och ger praktiska tips för verklig användning. + +## Förutsättningar + +Innan du börjar, se till att du har: + +* .NET 6.0 SDK eller senare installerat +* En C#‑IDE såsom Visual Studio 2022 eller Visual Studio Code +* **Aspose.BarCode for .NET** NuGet‑paketet (version 23.10 eller nyare) + +Du kan installera paketet med följande CLI‑kommando: + +```bash +dotnet add package Aspose.BarCode +``` + +Koden nedan förutsätter att paketet är refererat och att du har skrivrättigheter till mål‑katalogen. + +## Steg 1: Skapa projektet och importera namnrymder + +Skapa ett nytt konsol‑projekt och lägg till de nödvändiga `using`‑direktiven. Dessa namnrymder exponerar klassen `BarcodeGenerator` och uppräkningen för bildformat. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Varför detta är viktigt:** Att importera rätt namnrymder säkerställer att kompilatorn kan hitta typen `BarcodeGenerator` och enum‑värdet `BarCodeImageFormat`. Saknas en namnrymd får du ett kompileringsfel, vilket stoppar streckkodsgenereringen. + +## Steg 2: Initiera `BarcodeGenerator` med PDF417‑kodning + +Konstruktorn för `BarcodeGenerator` tar två argument: streckkodssymbologin (`EncodeTypes.Pdf417`) och den text du vill koda. PDF417 stödjer ett brett teckenspektrum, inklusive Unicode‑symboler. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Förklaring:** +* `EncodeTypes.Pdf417` talar om för biblioteket att använda PDF417‑standarden. +* Exempeltexten innehåller accentuerade tecken och en copyright‑symbol för att demonstrera Unicode‑hantering. + +Om du bara behöver koda numerisk data kan du skicka en enkel sträng som `"1234567890"`. + +## Steg 3: Justera X‑dimensionen för finare upplösning + +X‑dimensionen styr bredden på en enskild streckkodsenhet (det minsta svarta eller vita elementet). Ett mindre pixelvärde ger en bild med högre upplösning. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Varför justera den?** En standard‑X‑dimension på 3–4 pixlar kan ge en grov streckkod på hög‑DPI‑skärmar. Att minska den till **2 pixlar** balanserar läsbarhet och filstorlek, särskilt när du senare aktiverar kompakt läge. + +## Steg 4: Konfigurera antalet kolumner + +PDF417 låter dig ange hur många kolumner streckkoden ska ha. Färre kolumner gör streckkoden smalare men högre, medan fler kolumner ger en bredare, kortare streckkod. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Praktiskt tips:** För mobila biljetter som måste passa på en smal etikett fungerar ett kolumnantal på **3–5** bra. Öka antalet om du har mycket data och vill ha en kortare streckkod. + +## Steg 5: Aktivera kompakt läge för att ta bort tomma rader + +Kompakt läge tar bort onödiga rader från streckkodsmatrisen, vilket minskar den totala bildstorleken utan att förlora kodad data. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**När du ska använda det:** Om du genererar streckkoder för lagring eller nätverkstransmission kan kompakt läge minska PNG‑filen med upp till 30 %. Vissa äldre skannrar kanske dock inte stödjer trunkerade PDF417‑koder; testa med din mål‑hårdvara. + +## Steg 6: Spara streckkoden som en PNG‑bild + +Välj en utskrivningssökväg och anropa `Save`. Uppräkningen `BarCodeImageFormat.Png` skapar en förlustfri bild som passar de flesta tillämpningar. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Resultatkontroll:** Öppna PNG‑filen i en bildvisare. Du bör se en tät, högkontrast‑streckkod som motsvarar exempeltexten. Att skanna bilden med en PDF417‑läsare (t.ex. ZXing eller en smartphone‑app) returnerar den ursprungliga strängen `"Åspóse.Barcóde©"`. + +![Genererad PDF417‑streckkod sparad som PNG](compact-pdf417.png "Genererad PDF417‑streckkod i C#") + +*Bilden ovan visar det slutgiltiga resultatet av handledningens kod.* + +## Fullt, körbart exempel + +När alla delar sätts ihop får du ett komplett konsolprogram som du kan kopiera, klistra in och köra. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Förväntad utskrift + +När programmet körs skrivs följande ut: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +Filen `CompactPdf417.png` innehåller en kompakt PDF417‑streckkod som kodar den Unicode‑sträng som angavs. Att skanna bilden med en standard‑PDF417‑läsare ger exakt samma text. + +## Vanliga variationer och kantfall + +| Situation | Justering | Orsak | +|-----------|-----------|-------| +| **Längre datapayload** (t.ex. > 150 tecken) | Öka `generator.Parameters.Barcode.Pdf417.Columns` till 6‑8 | Fler kolumner förhindrar att streckkoden blir alltför hög. | +| **Behov av transparent bakgrund** | Använd `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | Transparent PNG integreras bättre i UI‑överlägg. | +| **Generera JPEG för webben** | Ändra formatet till `BarCodeImageFormat.Jpeg` och sätt eventuellt `ImageQuality` | JPEG minskar filstorleken på bekostnad av förlustfri kvalitet. | +| **Hantera null eller tom inmatning** | Kontrollera inmatningen innan generatorn skapas: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Förhindrar körningsfel och säkerställer meningsfulla streckkoder. | + +## Tips för produktion + +* **Undantagshantering:** Omslut genereringslogiken med ett `try/catch`‑block för att logga fel såsom otillräckligt diskutrymme eller ogiltiga parametrar. +* **Prestanda:** Återanvänd en enda `BarcodeGenerator`‑instans när du genererar många streckkoder med samma inställningar; uppdatera bara egenskapen `CodeText` mellan sparningar. +* **Säkerhet:** När den kodade texten innehåller känslig information, överväg att kryptera den innan du skickar den till generatorn och dekryptera efter skanning. + +## Slutsats + +Du vet nu hur du **genererar PDF417‑streckkod** i C# med Aspose.BarCode‑biblioteket, konfigurerar kompakt läge, styr kolumnantalet och exporterar resultatet som en PNG‑bild. Denna handledning gick igenom varje steg från projektuppsättning till hantering av kantfall, och ger dig en färdig lösning för streckkod‑drivna applikationer. + +Utforska sedan relaterade ämnen som **skapa QR‑koder i C#**, **batch‑generering av streckkoder** och **integrering av streckkodsskanning i mobila appar**. Alla bygger på samma `BarcodeGenerator`‑grundprinciper som du just har lärt dig. + +Lycka till med kodningen! + + +## Vad bör du lära dig härnäst? + + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstrerats i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationssätt i dina egna projekt. + +- [How to Generate PDF417 Barcodes – Compact PDF417 Encoding](/barcode/english/net/compact-pdf417-encoding/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/swedish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/swedish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..121ab10b0 --- /dev/null +++ b/barcode/swedish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-09 +description: Hur man läser PDF417 i C# med BarCodeReader. Lär dig att läsa streckkod‑PNG‑filer, + hantera flera streckkoder och extrahera utökad metadata. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: sv +lastmod: 2026-08-09 +og_description: Hur man läser PDF417 i C# med Aspose.BarCode. Denna handledning visar + hur du läser streckkod PNG‑filer, bearbetar flera streckkoder i en bild och hämtar + utökad PDF417‑metadata. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Hur man läser PDF417 i C# – streckkodsläsarhandledning +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Hur man läser PDF417 i C# – komplett guide för streckkodsläsare +url: /sv/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hur man läser PDF417 i C# – komplett guide för streckkodsläsare + +Om du behöver **läsa PDF417** i en .NET‑applikation, ger den här guiden en färdig‑att‑köra‑lösning. Du får se hur du läser en streckkod‑PNG, bearbetar flera streckkoder i samma bild och hämtar de utökade PDF417‑fälten som många skannrar döljer. + +Att läsa PDF417‑streckkoder är vanligt inom logistik, biljettförsäljning och dokumenthantering. När du är klar med den här tutorialen kan du avkoda en Macro PDF417‑bild, visa varje resultat och använda den extra informationen (fil‑ID, segmentantal, tidsstämplar osv.) i din egen affärslogik. + +## Förutsättningar + +- .NET 6.0 eller senare (koden fungerar också med .NET Framework 4.7+) +- Visual Studio 2022 eller någon annan C#‑IDE +- **Aspose.BarCode for .NET** (gratis provversion eller licensierat NuGet‑paket) +- En PNG‑bild som innehåller en Macro PDF417‑streckkod (exempel‑filen heter `ExtPDF417Meta.png`) + +> **Proffstips:** Installera biblioteket via NuGet‑konsolen: +> `dotnet add package Aspose.BarCode` + +## Hur man läser PDF417 med BarCodeReader i C# + +Kärnan i lösningen är klassen `BarCodeReader`. Den tar emot en bildsökväg och en `DecodeType`‑enum som talar om för motorn vilken symbolik som ska sökas efter. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Varför detta fungerar + +- **`DecodeType.MacroPdf417`** talar om för läsaren att leta efter Macro PDF417‑varianten, som lagrar de extra fält du ser i steg 4. +- `using`‑blocket disponerar läsaren automatiskt och frigör filhandtag. +- `ReadBarCodes()` returnerar **alla** streckkoder som matchar den begärda typen, vilket uppfyller kravet *läsa flera streckkoder* även om bilden bara innehåller en. + +När programmet körs skrivs en output liknande följande ut: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## Använda C#‑streckkodsläsare för att läsa flera streckkoder + +Om en bild innehåller flera Macro PDF417‑symboler (t.ex. en skannad sida med en bunt biljetter), bearbetar samma `foreach`‑loop varje symbol. Ingen extra kod behövs; läsaren samlar resultaten internt. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Vanliga fallgropar + +- **Bildformat:** Läsaren stödjer PNG, JPEG, BMP och TIFF. Om du försöker med ett format som den inte kan avkoda får du en tom samling. Därför betonas *läsa streckkod PNG* i tutorialen. +- **Upplösning:** Låguppslösta bilder (< 300 dpi) kan leda till missade segment. Skala upp eller begär en högkvalitativ skanning när det är möjligt. +- **Macro‑flagga:** Att glömma `DecodeType.MacroPdf417` begränsar motorn till vanlig PDF417 och kastar bort den utökade datan. Ange alltid macro‑typen när du behöver *läsa streckkodens utökade* fält. + +## Läsa streckkod PNG‑filer – bästa praxis + +Att arbeta med PNG‑filer är enkelt eftersom formatet bevarar förlustfri pixeldata. Här är en snabb checklista: + +1. Verifiera att filen finns innan du skapar läsaren. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Använd `Image.FromFile` endast när du behöver förbehandla (rotera, beskära). `BarCodeReader` kan öppna filen direkt, vilket undviker extra minnesallokering. +3. Om PNG‑filen innehåller transparens fungerar läsaren fortfarande eftersom streckkoden renderas på opaka pixlar. + +## Åtkomst till utökad PDF417‑metadata + +Objektet `Extended.Pdf417` exponerar varje valfritt fält som definieras i PDF417‑specifikationen. Du kan mappa dessa fält till en domänmodell, lagra dem i en databas eller använda dem för validering. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Fyll i modellen: + + + +## Vad bör du lära dig härnäst? + +De följande tutorialerna täcker närbesläktade ämnen som bygger vidare på teknikerna som demonstreras i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Hur man läser DataMatrix‑streckkoder med Aspose.BarCode för .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Hur man skapar streckkod – Compact PDF417 med Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Läs DataMatrix‑streckkod C# – Generera DataMatrix‑läge (Auto)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/thai/net/compact-pdf417-encoding/_index.md b/barcode/thai/net/compact-pdf417-encoding/_index.md index 642025381..92f30da97 100644 --- a/barcode/thai/net/compact-pdf417-encoding/_index.md +++ b/barcode/thai/net/compact-pdf417-encoding/_index.md @@ -84,6 +84,14 @@ Aspose.BarCode ให้คุณตั้งค่าคุณสมบัต ## บทแนะนำการเข้ารหัส Compact PDF417 ### [Creating Compact PDF417 Barcodes](./compact-pdf417-basic-configuration/) เรียนรู้วิธีสร้างบาร์โค้ด Compact PDF417 ด้วย Aspose.BarCode for .NET คู่มือครบถ้วนพร้อมขั้นตอนและตัวอย่างโค้ด +### [ตัวอย่าง Aspose Barcode: สร้าง Macro PDF417 ด้วย C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +เรียนรู้วิธีสร้าง Macro PDF417 ด้วย C# โดยใช้ Aspose.BarCode +### [สร้างบาร์โค้ด PDF417 ด้วย C# – คู่มือขั้นตอนโดยขั้นตอน](./generate-pdf417-barcode-in-c-step-by-step-guide/) +เรียนรู้วิธีสร้างบาร์โค้ด PDF417 ด้วย C# อย่างละเอียด +### [สร้างบาร์โค้ดจากข้อความใน C# – คู่มือขั้นตอนโดยละเอียด](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +เรียนรู้วิธีสร้างบาร์โค้ดจากข้อความด้วย C# อย่างละเอียดตามขั้นตอน +### [วิธีอ่าน PDF417 ด้วย C# – คู่มืออ่านบาร์โค้ดเต็มรูปแบบ](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +เรียนรู้วิธีอ่านบาร์โค้ด PDF417 ด้วย C# อย่างครบถ้วน ## คำถามที่พบบ่อย @@ -113,4 +121,4 @@ A: ไม่จำเป็นต้องใช้ฟอนต์ภายน {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/thai/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/thai/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..07292a39e --- /dev/null +++ b/barcode/thai/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-08-09 +description: ตัวอย่างบาร์โค้ดของ Aspose แสดงวิธีใช้ตัวสร้างบาร์โค้ด C# เพื่อสร้าง + Macro PDF417 พร้อมการสนับสนุนเมตาดาต้าเต็มรูปแบบ. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: th +lastmod: 2026-08-09 +og_description: ตัวอย่างบาร์โค้ดของ Aspose แสดงการใช้ตัวสร้างบาร์โค้ด C# เพื่อสร้างบาร์โค้ด + Macro PDF417 ที่รวมไฟล์ ID, ข้อมูลเซกเมนต์, เวลาและเมตาดาต้าอื่น ๆ +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: ตัวอย่างบาร์โค้ด Aspose – สร้าง Macro PDF417 ด้วย C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'ตัวอย่างบาร์โค้ด Aspose: สร้าง Macro PDF417 ด้วย C#' +url: /th/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ตัวอย่าง Aspose barcode: สร้าง Macro PDF417 ด้วย C# + +หากคุณต้องการ **ตัวอย่าง aspose barcode** ที่สร้างบาร์โค้ด Macro PDF417 คำแนะนำนี้จะแสดงวิธีทำด้วย **barcode generator C#** คุณจะได้เห็นการตั้งค่าที่จำเป็นทั้งหมด ตั้งแต่ขนาดพื้นฐานจนถึงชุดเต็มของฟิลด์เมตาดาต้า Macro PDF417 และสุดท้ายจะได้ภาพ PNG ที่พร้อมสำหรับการประมวลผลต่อไป + +บทเรียนนี้ครอบคลุมขั้นตอนการทำงานทั้งหมด อธิบายว่าทำไมแต่ละพารามิเตอร์จึงสำคัญ และให้ตัวอย่างโค้ดที่พร้อมรัน ไม่ต้องอ้างอิงภายนอก คุณสามารถคัดลอกโค้ด ปรับค่า แล้วรันได้ทันที + +## ข้อกำหนดเบื้องต้น + +ก่อนเริ่มทำงาน ให้ตรวจสอบว่าคุณมี: + +- .NET 6.0 (หรือใหม่กว่า) ที่ติดตั้งแล้ว +- Visual Studio 2022 หรือ IDE ที่รองรับ C# ใดก็ได้ +- ไลเซนส์ที่ถูกต้องสำหรับ **Aspose.BarCode for .NET** (รุ่นทดลองฟรีใช้งานได้กับตัวอย่างนี้) + +เพิ่มแพคเกจ Aspose.BarCode NuGet ลงในโปรเจกต์ของคุณ: + +```bash +dotnet add package Aspose.BarCode +``` + +## ขั้นตอนที่ 1: สร้างอินสแตนซ์ barcode generator C# + +ขั้นตอนแรกคือการสร้างอ็อบเจ็กต์ `BarcodeGenerator` ด้วยค่า enum `EncodeTypes.MacroPdf417` และข้อความที่ต้องการเข้ารหัส ข้อความสามารถมีอักขระ Unicode ซึ่งไลบรารีจะจัดการให้โดยอัตโนมัติ + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*ทำไมจึงสำคัญ*: `EncodeTypes.MacroPdf417` บอกให้เอนจินสร้างสัญลักษณ์ Macro PDF417 ซึ่งรองรับข้อมูลแบบแบ่งส่วนและเมตาดาต้าระดับไฟล์เพิ่มเติม คำสั่ง `using` รับประกันว่าทรัพยากรที่ไม่ได้จัดการจะถูกปล่อยหลังจากบันทึกภาพเสร็จ + +## ขั้นตอนที่ 2: กำหนดลักษณะพื้นฐานของบาร์โค้ด + +บาร์โค้ด Macro PDF417 ประกอบด้วยโมดูลสี่เหลี่ยมจัตุรัส การควบคุมขนาดโมดูลและจำนวนคอลัมน์มีผลต่อความอ่านง่ายและขนาดไฟล์ + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*ทำไมจึงสำคัญ*: `XDimension.Pixels` กำหนดความหนาแน่นของภาพ; ค่า 2 pixels ทำงานได้ดีสำหรับการแสดงบนหน้าจอพร้อมคงขนาดภาพให้เล็ก ปรับจำนวนคอลัมน์ให้สอดคล้องกับข้อจำกัดการออกแบบของคุณ—คอลัมน์มากขึ้นจะทำให้บาร์โค้ดกว้างและสั้นลง + +## ขั้นตอนที่ 3: ตั้งค่าเมตาดาต้าเฉพาะ Macro PDF417 + +Macro PDF417 ขยายรูปแบบ PDF417 มาตรฐานด้วยฟิลด์ที่ช่วยให้สามารถสร้างไฟล์ขนาดใหญ่จากหลายส่วนบาร์โค้ดได้ ฟิลด์แต่ละอันเป็นตัวเลือก แต่การตั้งค่าจะทำให้คุณเห็นความสามารถเต็มของ API + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*ทำไมจึงสำคัญ*: +- `MacroPdf417FileID` เชื่อมโยงทุกส่วนที่เป็นของไฟล์ตรรกะเดียวกัน +- `MacroPdf417SegmentID` และ `MacroPdf417SegmentsCount` ช่วยให้ตัวถอดรหัสจัดลำดับส่วนย่อยได้อย่างถูกต้อง +- `MacroPdf417Checksum` ให้การตรวจสอบความสมบูรณ์อย่างรวดเร็วโดยไม่ต้องถอดรหัสทั้งหมด +- `MacroPdf417FileSize` และ `MacroPdf417TimeStamp` ช่วยระบบต่อท้ายตรวจสอบว่าไฟล์ที่สร้างขึ้นตรงกับไฟล์ต้นฉบับหรือไม่ +- `MacroPdf417Addressee` / `MacroPdf417Sender` มีประโยชน์ในสถานการณ์โลจิสติกส์หรือการแลกเปลี่ยนเอกสาร +- การตั้งค่า `MacroPdf417Terminator` เป็น `Set` ทำเครื่องหมายบาร์โค้ดนี้เป็นส่วนสุดท้าย ซึ่งทำให้ขั้นตอนการรวมไฟล์ง่ายขึ้น + +## ขั้นตอนที่ 4: บันทึกภาพบาร์โค้ดที่สร้างขึ้น + +สุดท้ายให้บันทึกบาร์โค้ดเป็นไฟล์ PNG คุณสามารถเลือกฟอร์แมตที่รองรับได้ทุกแบบ (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`) + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*ทำไมจึงสำคัญ*: PNG เก็บข้อมูลพิกเซลแบบ lossless ทำให้เครื่องสแกนอ่านรูปแบบโมดูลที่คุณกำหนดได้อย่างแม่นยำ การเปลี่ยนฟอร์แมตอาจส่งผลต่อคุณภาพภาพและขนาดไฟล์ + +### ผลลัพธ์ที่คาดหวัง + +เมื่อรันโปรแกรมครบถ้วนจะสร้างไฟล์ชื่อ **ExtPDF417Meta.png** การเปิดภาพจะแสดงบาร์โค้ด Macro PDF417 รูปสี่เหลี่ยมที่เข้ารหัสข้อความ “Åspóse.Barcóde©” และความหนาแน่นของภาพตรงกับค่า X‑dimension 2‑pixel ที่คุณตั้งไว้ การสแกนภาพด้วยรีดเดอร์ที่รองรับ PDF417 จะคืนค่าฟิลด์เมตาดาต้าทั้งหมดที่กำหนดในขั้นตอน 3 + +## ตัวอย่างทำงานเต็มรูปแบบ + +คัดลอกโค้ดด้านล่างไปยังโปรเจกต์คอนโซลใหม่ (`dotnet new console`) แล้วแทนที่ `YOUR_DIRECTORY` ด้วยพาธแบบ absolute หรือ relative ที่มีอยู่บนเครื่องของคุณ + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +รันโปรแกรม (`dotnet run`) หลังจากทำงานเสร็จ ให้ตรวจสอบว่าไฟล์ PNG ปรากฏในตำแหน่งที่คุณระบุ ใช้แอปอ่านบาร์โค้ดใดก็ได้ที่รองรับ Macro PDF417 เพื่อยืนยันว่าเมตาดาต้าถูกฝังอย่างถูกต้อง + +## ความแตกต่างทั่วไปและกรณีขอบ + +- **ฟอร์แมตภาพต่าง ๆ**: แทนที่ `BarCodeImageFormat.Png` ด้วย `Jpeg`, `Bmp` หรือ `Tiff` หากระบบต่อท้ายของคุณต้องการฟอร์แมตอื่น +- **การเปลี่ยนขนาดโมดูล**: ค่า `XDimension.Pixels` ที่ใหญ่ขึ้นช่วยเพิ่มความน่าเชื่อถือในการสแกนบนสแกนเนอร์ความละเอียดต่ำ แต่จะทำให้ไฟล์ใหญ่ขึ้น +- **หลายส่วน**: หากต้องการสร้างไฟล์หลายส่วน ให้สร้างบาร์โค้ดชุดต่อเนื่อง เพิ่มค่า `MacroPdf417SegmentID` สำหรับแต่ละส่วนและคงค่า `MacroPdf417FileID` คงที่ ส่วนสุดท้ายควรตั้ง `MacroPdf417Terminator` เป็น `Set` เท่านั้น +- **การสนับสนุน Unicode**: ตัวสร้างจะเข้ารหัสอักขระ Unicode อัตโนมัติ; ตรวจสอบให้แน่ใจว่า string ต้นทางของคุณใช้การเข้ารหัส UTF‑8 หากอ่านจากไฟล์ภายนอก +- **การจัดการข้อผิดพลาด**: ห่อบล็อก `using` ด้วย try‑catch เพื่อดักจับ `BarCodeException` สำหรับพารามิเตอร์ที่ไม่ถูกต้อง (เช่น จำนวนคอลัมน์อยู่นอกช่วง) + +## เคล็ดลับระดับมืออาชีพ + +- **ประสิทธิภาพ**: ใช้อ็อบเจ็กต์ `BarcodeGenerator` ตัวเดียวซ้ำเมื่อสร้างบาร์โค้ดหลาย ๆ ตัวที่มีการตั้งค่าเดียวกัน; เพียงเปลี่ยนค่า `CodeText` ระหว่างการบันทึก +- **การประมาณขนาดไฟล์**: ฟิลด์ `MacroPdf417FileSize` ควรตรงกับจำนวนไบต์ของข้อมูลต้นฉบับ; ความไม่ตรงกันอาจทำให้การตรวจสอบของระบบต่อท้ายล้มเหลว +- **การทดสอบ**: ตรวจสอบบาร์โค้ดที่สร้างด้วยตัวถอดรหัสในตัวของ Aspose (`BarCodeReader`) และสแกนเนอร์ของบุคคลที่สามเพื่อยืนยันความเข้ากันได้ + +## สรุป + +ตัวอย่าง **aspose barcode** นี้แสดงให้เห็นวิธีสร้าง Macro PDF417 ด้วย C# ตั้งแต่การกำหนดค่าเบื้องต้นจนถึงการบันทึกภาพพร้อมเมตาดาต้าเต็มรูปแบบ คุณสามารถนำไปปรับใช้ในโครงการของคุณเพื่อสร้างบาร์โค้ดที่รองรับการแบ่งส่วนไฟล์และข้อมูลเมตาดาต้าได้อย่างง่ายดาย + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอน‑ขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการใช้งานอื่น ๆ ในโปรเจกต์ของคุณ + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to create barcode quiet zone for Code 16K using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/thai/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/thai/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..9a18e10e9 --- /dev/null +++ b/barcode/thai/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2026-08-09 +description: สร้างบาร์โค้ดจากข้อความใน C# ด้วย Aspose.BarCode. เรียนรู้วิธีสร้างบาร์โค้ด, + จัดการอักขระพิเศษ, และสร้างบาร์โค้ด PDF417 ด้วย C# อย่างรวดเร็ว. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: th +lastmod: 2026-08-09 +og_description: สร้างบาร์โค้ดจากข้อความใน C# ด้วย Aspose.BarCode บทเรียนนี้แสดงวิธีสร้างบาร์โค้ด + รองรับอักขระพิเศษ และสร้างบาร์โค้ด PDF417 ด้วย C# พร้อมโค้ดเต็ม +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: สร้างบาร์โค้ดจากข้อความใน C# – คู่มือขั้นตอนเร็ว +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: สร้างบาร์โค้ดจากข้อความใน C# – คู่มือขั้นตอนเต็มแบบละเอียด +url: /th/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างบาร์โค้ดจากข้อความใน C# – คู่มือขั้นตอนเต็ม + +หากคุณต้องการ **generate barcode from text** ในแอปพลิเคชัน .NET คู่มือนี้จะพาคุณผ่านขั้นตอนทั้งหมด คุณจะได้เห็นวิธีการ generate barcode, จัดการอักขระพิเศษ, และสร้างการใช้งาน PDF417 barcode C# ที่ทำงานได้ทันที การสร้างบาร์โค้ดจากข้อความเป็นความต้องการทั่วไปสำหรับระบบสินค้าคงคลัง, แพลตฟอร์มการออกตั๋ว, และกระบวนการทำงานเอกสาร เมื่อจบบทเรียนนี้คุณจะมีแอปคอนโซล C# ที่สามารถรันได้ซึ่งสร้างภาพ PNG MicroPdf417 โดยใช้ Aspose.BarCode ไม่ต้องใช้บริการภายนอก และโค้ดสามารถจัดการอักขระ Unicode เช่น “Å”, “©”, และ “é” + +## สิ่งที่ต้องเตรียม + +- .NET 6.0 SDK หรือเวอร์ชันใหม่กว่า (โค้ดนี้ยังทำงานได้กับ .NET Core 3.1 และ .NET Framework 4.7+) +- Visual Studio 2022 (หรือ IDE ใด ๆ ที่รองรับ C#) +- **Aspose.BarCode for .NET** NuGet package + ```bash + dotnet add package Aspose.BarCode + ``` +- ความรู้พื้นฐานของไวยากรณ์ C# + +## สร้างบาร์โค้ดจากข้อความ – ตั้งค่าตัวสร้าง + +ขั้นตอนแรกคือการสร้างอินสแตนซ์ `BarcodeGenerator` ที่รู้ว่าคุณต้องการ **barcode encode type** ใด ในบทเรียนนี้เราใช้ `EncodeTypes.MicroPdf417` ซึ่งเป็นรูปแบบย่อของ PDF417 ที่เหมาะกับสตริงข้อมูลสั้น + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**ทำไมวิธีนี้ถึงได้ผล:** +- `EncodeTypes.MicroPdf417` บอกไลบรารีให้ใช้ตระกูล PDF417 ซึ่งตอบสนองความต้องการของ **create pdf417 barcode c#** +- ตัวสร้างรับข้อความดิบ ซึ่งเป็นแก่นของ **generate barcode from text** +- การสนับสนุน Unicode มีมาในตัว ทำให้อักขระเช่น “Å” และ “©” ถูกเข้ารหัสอย่างถูกต้อง ซึ่งแก้ปัญหา **barcode with special characters** + +## วิธีการ generate barcode with special characters + +เมื่อข้อมูลของคุณมีสัญลักษณ์ที่ไม่ใช่ ASCII คุณต้องมั่นใจว่าตัวสร้างใช้การเข้ารหัส UTF‑8 Aspose.BarCode จะตรวจจับ Unicode อัตโนมัติ แต่คุณสามารถตั้งค่าการเข้ารหัสข้อความอย่างชัดเจนหากเจอปัญหา: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +การเพิ่มบรรทัดนี้ก่อน `ConfigureGenerator` จะรับประกันว่า **barcode with special characters** จะแสดงผลอย่างถูกต้องบนทุกแพลตฟอร์ม + +### เคล็ดลับปฏิบัติ +หากผลลัพธ์ดูเป็นอักขระผิดพลาด ให้ตรวจสอบว่าแบบอักษรที่ใช้โดยตัวเรนเดอร์บาร์โค้ดรองรับ glyph ที่ต้องการหรือไม่ คุณสามารถฝังฟอนต์ TrueType แบบกำหนดเองได้โดยใช้: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## ประเภทการเข้ารหัสบาร์โค้ดที่คุณสามารถเลือกได้ + +Aspose.BarCode รองรับหลายสิบ **barcode encode types** ซึ่งแต่ละประเภทเหมาะกับกรณีการใช้งานที่แตกต่างกัน: + +| Encode type | Typical use case | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | ป้ายจัดส่ง, สินค้าคงคลัง | +| `EncodeTypes.QR` | การชำระเงินผ่านมือถือ, URLs | +| `EncodeTypes.Pdf417` | ใบขับขี่, บัตรโดยสาร | +| `EncodeTypes.MicroPdf417` | ข้อมูลขนาดเล็ก, พื้นที่จำกัด | +| `EncodeTypes.DataMatrix` | รายการขนาดเล็ก, ความหนาแน่นข้อมูลสูง | + +การเปลี่ยนประเภทการเข้ารหัสทำได้ง่ายโดยการสลับค่า enum ในตัวสร้าง: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +ความยืดหยุ่นนี้ทำให้คุณตอบคำถามเกี่ยวกับ **barcode encode types** ได้โดยไม่ต้องออกจาก IDE + +## สร้าง PDF417 barcode C# – ขั้นตอนสุดท้ายและการตรวจสอบ + +หลังจากตั้งค่าตัวสร้างแล้ว ส่วนสุดท้ายของ **create pdf417 barcode c#** คือการบันทึกรูปภาพและยืนยันผลลัพธ์ + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +เรียกใช้โปรแกรม (`dotnet run`) แล้วคุณควรเห็นข้อความคอนโซลคล้ายกับ: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +เปิดไฟล์ PNG; คุณจะเห็นบาร์โค้ด MicroPdf417 ที่คมชัดซึ่งเข้ารหัสสตริง “Åspóse.Barcóde©”. การสแกนด้วยเครื่องสแกนบาร์โค้ดบนมือถือ (เช่น ZXing) จะคืนข้อความต้นฉบับ แสดงให้เห็นว่า **generate barcode from text** ทำงานได้แม้กับอักขระพิเศษ + +### กรณีขอบ: ข้อความยาวมาก + +MicroPdf417 มีขีดจำกัดความจุข้อมูลสูงสุดที่ 1 KB หากอินพุตของคุณเกินขีดจำกัดนี้ ไลบรารีจะโยน `ArgumentException`. เพื่อจัดการอย่างราบรื่น: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +สำหรับข้อมูลขนาดใหญ่กว่า ให้เปลี่ยนไปใช้ `EncodeTypes.Pdf417` หรือ `EncodeTypes.DataMatrix` เต็มรูปแบบ + +## ข้อผิดพลาดทั่วไปและวิธีหลีกเลี่ยง + +| Issue | Cause | Fix | +|-------------------------------------|-----------------------------------------|-----| +| บาร์โค้ดดูเบลอ | XDimension ต่ำเกินไป (เช่น 1 px) | เพิ่ม `XDimension.Pixels` เป็น 2‑3 px | +| อักขระ Unicode แสดงเป็น `?` | การเข้ารหัสข้อความเริ่มต้นเป็น ASCII | ตั้งค่า `TextEncoding = Encoding.UTF8` | +| ไฟล์ภาพไม่ถูกสร้าง | ไดเรกทอรีปลายทางไม่มีอยู่ | ใช้ `Directory.CreateDirectory` ก่อน `Save` | +| สแกนเนอร์ไม่สามารถอ่านบาร์โค้ดได้ | คอลัมน์มากเกินไปสำหรับข้อมูลสั้น | ลด `Pdf417.Columns` (เช่น 3‑4) | + +## โค้ดต้นฉบับเต็ม (พร้อมคัดลอก) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**ผลลัพธ์ที่คาดหวัง:** ไฟล์ชื่อ `MicroPdf417.png` อยู่ในโฟลเดอร์ `output` ซึ่งมีบาร์โค้ด MicroPdf417 ที่ชัดเจนและเข้ารหัสสตริงต้นฉบับพร้อมอักขระพิเศษ + +## สรุป + +ตอนนี้คุณรู้วิธี **generate barcode from text** ใน C# ด้วย Aspose.BarCode, วิธีจัดการ **barcode with special characters**, และวิธี **create pdf417 barcode c#** พร้อมการควบคุมตัวเลือกการเข้ารหัสอย่างเต็มที่ โดยการปรับ **barcode encode types** คุณสามารถสร้าง QR code, Code128, DataMatrix หรือรูปแบบอื่นที่รองรับได้ + +ต่อไปสำรวจหัวข้อต่อไปนี้เพื่อเพิ่มพูนความเชี่ยวชาญด้านบาร์โค้ดของคุณ: + +- **How to generate barcode** ในแบบแบตช์สำหรับหลายพันรายการ (ใช้ `Parallel.ForEach` เพื่อความเร็ว) +- ปรับแต่งสีและเพิ่มโลโก้ภายในบาร์โค้ด +- ผสานการสร้างบาร์โค้ดเข้ากับ ASP.NET Core APIs เพื่อส่งภาพแบบเรียลไทม์ +- ใช้ไลบรารีอื่น ๆ เช่น ZXing.Net หรือ IronBarcode สำหรับทางเลือกแบบโอเพนซอร์ส + +ลองทดลองกับมิติ, การตั้งค่าคอลัมน์, และประเภทการเข้ารหัสต่าง ๆ ได้ตามต้องการ ขอให้สนุกกับการเขียนโค้ดและแอปพลิเคชันของคุณสแกนได้อย่างไม่มีข้อผิดพลาด! + +## สิ่งที่คุณควรเรียนต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดซึ่งต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานครบถ้วนพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการนำไปใช้แบบอื่นในโครงการของคุณ + +- [วิธีสร้างบาร์โค้ด – Compact PDF417 ด้วย Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [วิธีสร้างบาร์โค้ด – การกำหนดค่า Code 39 ด้วย Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [วิธีสร้างบาร์โค้ด - ประเภทบาร์โค้ดหนึ่งมิติ](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/thai/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/thai/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..16f71dd2e --- /dev/null +++ b/barcode/thai/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-08-09 +description: สร้างบาร์โค้ด PDF417 ด้วย C# อย่างรวดเร็ว เรียนรู้วิธีสร้าง PDF417 ด้วยโหมดคอมแพคท์ + การควบคุมคอลัมน์ และการส่งออกเป็น PNG โดยใช้ BarcodeGenerator API. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: th +lastmod: 2026-08-09 +og_description: สร้างบาร์โค้ด PDF417 ด้วย C# พร้อมตัวอย่างสั้น ๆ คู่มือนี้จะแสดงวิธีตั้งค่าโหมดคอมแพคท์ + กำหนดจำนวนคอลัมน์ และบันทึกผลลัพธ์เป็นภาพ PNG. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: สร้างบาร์โค้ด PDF417 ด้วย C# – บทเรียนครบถ้วน +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: สร้างบาร์โค้ด PDF417 ด้วย C# – คู่มือแบบทีละขั้นตอน +url: /th/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างบาร์โค้ด PDF417 ใน C# – คู่มือทีละขั้นตอน + +หากคุณต้องการ **สร้างบาร์โค้ด PDF417** ในแอปพลิเคชัน .NET นี้เป็นบทแนะนำที่แสดงวิธีทำอย่างละเอียด คุณจะได้เห็นโปรแกรมที่ทำงานได้เต็มรูปแบบซึ่งสร้างบาร์โค้ด PDF417 แบบกะทัดรัด ปรับขนาดตามต้องการ และบันทึกเป็นไฟล์ PNG + +การสร้างบาร์โค้ด PDF417 เป็นความต้องการทั่วไปสำหรับการออกบัตรมือถือ การติดตามสินค้าคงคลัง และความปลอดภัยของเอกสาร คู่มือนี้ครอบคลุมตัวเลือกการกำหนดค่าที่สำคัญ อธิบายเหตุผลของแต่ละการตั้งค่า และให้เคล็ดลับการใช้งานจริงสำหรับสถานการณ์ต่าง ๆ + +## ข้อกำหนดเบื้องต้น + +ก่อนเริ่มทำงาน ให้ตรวจสอบว่าคุณมี: + +* .NET 6.0 SDK หรือใหม่กว่า +* IDE สำหรับ C# เช่น Visual Studio 2022 หรือ Visual Studio Code +* แพคเกจ **Aspose.BarCode for .NET** จาก NuGet (เวอร์ชัน 23.10 หรือใหม่กว่า) + +คุณสามารถติดตั้งแพคเกจด้วยคำสั่ง CLI ด้านล่าง: + +```bash +dotnet add package Aspose.BarCode +``` + +โค้ดต่อไปนี้สมมติว่าแพคเกจถูกอ้างอิงแล้วและคุณมีสิทธิ์เขียนในไดเรกทอรีผลลัพธ์ + +## ขั้นตอนที่ 1: ตั้งค่าโครงการและนำเข้า namespace + +สร้างโปรเจกต์คอนโซลใหม่และเพิ่ม `using` directives ที่จำเป็น namespace เหล่านี้ทำให้เข้าถึงคลาส `BarcodeGenerator` และ enumeration ของรูปแบบภาพได้ + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**ทำไมต้องทำเช่นนี้:** การนำเข้า namespace ที่ถูกต้องทำให้คอมไพเลอร์ค้นพบประเภท `BarcodeGenerator` และ enum `BarCodeImageFormat` หากขาด namespace จะเกิดข้อผิดพลาดการคอมไพล์และกระบวนการสร้างบาร์โค้ดจะหยุดทำงาน + +## ขั้นตอนที่ 2: เริ่มต้น `BarcodeGenerator` ด้วยการเข้ารหัส PDF417 + +คอนสตรัคเตอร์ของ `BarcodeGenerator` รับอาร์กิวเมนต์สองค่า: สัญลักษณ์บาร์โค้ด (`EncodeTypes.Pdf417`) และข้อความที่ต้องการเข้ารหัส PDF417 รองรับอักขระหลายประเภทรวมถึงสัญลักษณ์ Unicode + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**คำอธิบาย:** +* `EncodeTypes.Pdf417` บอกไลบรารีให้ใช้มาตรฐาน PDF417 +* ตัวอย่างข้อความมีอักขระที่มีสำเนียงและสัญลักษณ์ลิขสิทธิ์เพื่อแสดงการจัดการ Unicode + +หากคุณต้องการเข้ารหัสเฉพาะตัวเลข สามารถส่งสตริงธรรมดาเช่น `"1234567890"` ได้ + +## ขั้นตอนที่ 3: ปรับ X‑dimension เพื่อความละเอียดที่ละเอียดกว่า + +X‑dimension ควบคุมความกว้างของโมดูลบาร์โค้ดแต่ละตัว (องค์ประกอบสีดำหรือสีขาวที่เล็กที่สุด) การตั้งค่าค่าพิกเซลที่เล็กลงจะให้ภาพที่ความละเอียดสูงขึ้น + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**ทำไมต้องปรับ?** X‑dimension เริ่มต้นที่ 3–4 พิกเซลอาจทำให้บาร์โค้ดดูหยาบบนหน้าจอ DPI สูง การลดลงเป็น **2 พิกเซล** จะทำให้ความอ่านง่ายและขนาดไฟล์สมดุลกัน โดยเฉพาะเมื่อเปิดใช้โหมดกะทัดรัดต่อไป + +## ขั้นตอนที่ 4: กำหนดจำนวนคอลัมน์ + +PDF417 ให้คุณระบุจำนวนคอลัมน์ที่บาร์โค้ดควรมี คอลัมน์น้อยทำให้บาร์โค้ดแคบแต่สูงขึ้น ส่วนคอลัมน์มากทำให้บาร์โค้ดกว้างแต่สั้นลง + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**เคล็ดลับปฏิบัติ:** สำหรับบัตรมือถือที่ต้องใส่ในป้ายแคบ จำนวนคอลัมน์ **3–5** ทำงานได้ดี หากมีข้อมูลมากและต้องการบาร์โค้ดสั้นลง ให้เพิ่มจำนวนคอลัมน์ + +## ขั้นตอนที่ 5: เปิดใช้งานโหมดกะทัดรัดเพื่อตัดแถวที่ว่างเปล่า + +โหมดกะทัดรัดจะลบแถวที่ไม่จำเป็นออกจากเมทริกซ์บาร์โค้ด ลดขนาดภาพโดยไม่สูญเสียข้อมูลที่เข้ารหัส + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**เมื่อใดควรใช้:** หากคุณสร้างบาร์โค้ดเพื่อจัดเก็บหรือส่งผ่านเครือข่าย โหมดกะทัดรัดสามารถทำให้ไฟล์ PNG ลดลงได้ถึง 30 % อย่างไรก็ตาม เครื่องสแกนรุ่นเก่าอาจไม่รองรับ PDF417 ที่ถูกตัดแถว; ควรทดสอบกับฮาร์ดแวร์เป้าหมายของคุณ + +## ขั้นตอนที่ 6: บันทึกบาร์โค้ดเป็นภาพ PNG + +กำหนดเส้นทางผลลัพธ์และเรียก `Save` enum `BarCodeImageFormat.Png` จะสร้างภาพที่ไม่มีการสูญเสียคุณภาพ เหมาะกับการใช้งานส่วนใหญ่ + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**การตรวจสอบผลลัพธ์:** เปิดไฟล์ PNG ด้วยโปรแกรมดูภาพใดก็ได้ คุณควรเห็นบาร์โค้ดที่หนาแน่นและคอนทราสต์สูงซึ่งตรงกับข้อความตัวอย่าง การสแกนภาพด้วยโปรแกรมอ่าน PDF417 (เช่น ZXing หรือแอปบนสมาร์ทโฟน) จะคืนสตริงต้นฉบับ `"Åspóse.Barcóde©"` + +![บาร์โค้ด PDF417 ที่สร้างและบันทึกเป็น PNG](compact-pdf417.png "บาร์โค้ด PDF417 ที่สร้างใน C#") + +*ภาพด้านบนแสดงผลลัพธ์สุดท้ายของโค้ดในบทแนะนำ* + +## ตัวอย่างเต็มที่สามารถรันได้ + +รวมทุกส่วนเข้าด้วยกัน นี่คือโปรแกรมคอนโซลที่สมบูรณ์ คุณสามารถคัดลอก วาง และรันได้เลย + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +เมื่อรันโปรแกรมจะพิมพ์: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +ไฟล์ `CompactPdf417.png` จะมีบาร์โค้ด PDF417 กะทัดรัดที่เข้ารหัสสตริง Unicode ที่ให้ไว้ การสแกนภาพด้วยโปรแกรมอ่าน PDF417 มาตรฐานจะคืนข้อความเดิมอย่างแม่นยำ + +## ความแปรผันทั่วไปและกรณีขอบ + +| สถานการณ์ | การปรับ | เหตุผล | +|-----------|------------|--------| +| **ข้อมูลปริมาณมาก** (เช่น > 150 อักขระ) | เพิ่ม `generator.Parameters.Barcode.Pdf417.Columns` เป็น 6‑8 | คอลัมน์เพิ่มจะป้องกันบาร์โค้ดสูงเกินไป | +| **ต้องการพื้นหลังโปร่งใส** | ใช้ `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | PNG โปร่งใสทำให้รวมกับ UI ได้ดีขึ้น | +| **สร้าง JPEG สำหรับเว็บ** | เปลี่ยนฟอร์แมตเป็น `BarCodeImageFormat.Jpeg` และตั้งค่า `ImageQuality` ตามต้องการ | JPEG ลดขนาดไฟล์แต่เสียความคมชัดแบบ lossless | +| **รับค่า null หรือค่าว่าง** | ตรวจสอบอินพุตก่อนสร้าง generator: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | ป้องกันข้อยกเว้นขณะรันและทำให้บาร์โค้ดมีความหมาย | + +## เคล็ดลับสำหรับการใช้งานในผลิตภัณฑ์ + +* **การจัดการข้อยกเว้น:** ห่อโลจิกการสร้างในบล็อก `try/catch` เพื่อบันทึกข้อผิดพลาดเช่น พื้นที่ดิสก์ไม่พอหรือพารามิเตอร์ไม่ถูกต้อง +* **ประสิทธิภาพ:** ใช้ instance ของ `BarcodeGenerator` เพียงตัวเดียวเมื่อสร้างบาร์โค้ดหลายรายการที่มีการตั้งค่าเดียวกัน; เพียงอัปเดตคุณสมบัติ `CodeText` ระหว่างการบันทึก +* **ความปลอดภัย:** หากข้อความที่เข้ารหัสมีข้อมูลสำคัญ ควรเข้ารหัสก่อนส่งให้ generator และถอดรหัสหลังสแกน + +## สรุป + +คุณได้เรียนรู้วิธี **สร้างบาร์โค้ด PDF417** ใน C# ด้วยไลบรารี Aspose.BarCode ตั้งค่าโหมดกะทัดรัด ควบคุมจำนวนคอลัมน์ และส่งออกเป็นภาพ PNG บทแนะนำนี้ครอบคลุมทุกขั้นตอนตั้งแต่การตั้งค่าโครงการจนถึงการจัดการกรณีขอบ ทำให้คุณมีโซลูชันพร้อมใช้งานสำหรับแอปพลิเคชันที่ขับเคลื่อนด้วยบาร์โค้ด + +ต่อไปสำรวจหัวข้อที่เกี่ยวข้อง เช่น **การสร้าง QR code ใน C#**, **การสร้างบาร์โค้ดเป็นชุด**, และ **การรวมการสแกนบาร์โค้ดกับแอปมือถือ** ทุกหัวข้ออ้างอิงพื้นฐาน `BarcodeGenerator` ที่คุณเพิ่งเชี่ยวชาญ + +Happy coding! + +## สิ่งที่คุณควรเรียนต่อไป + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโครงการของคุณ + +- [How to Generate PDF417 Barcodes – Compact PDF417 Encoding](/barcode/english/net/compact-pdf417-encoding/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/thai/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/thai/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..850ddc4c6 --- /dev/null +++ b/barcode/thai/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-09 +description: วิธีอ่าน PDF417 ใน C# ด้วย BarCodeReader. เรียนรู้การอ่านไฟล์ PNG ของบาร์โค้ด, + จัดการบาร์โค้ดหลายรายการ, และดึงข้อมูลเมตาเพิ่มเติม. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: th +lastmod: 2026-08-09 +og_description: วิธีอ่าน PDF417 ด้วย C# และ Aspose.BarCode บทเรียนนี้จะแสดงวิธีอ่านไฟล์ + PNG ของบาร์โค้ด, ประมวลผลบาร์โค้ดหลายรายการในภาพเดียว, และดึงข้อมูลเมตาดาต้า PDF417 + ที่ขยายเพิ่มเติม +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: วิธีอ่าน PDF417 ด้วย C# – บทแนะนำการอ่านบาร์โค้ด +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: วิธีอ่าน PDF417 ใน C# – คู่มือการอ่านบาร์โค้ดแบบครบถ้วน +url: /th/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีอ่าน PDF417 ด้วย C# – คู่มือการอ่านบาร์โค้ดแบบครบถ้วน + +หากคุณต้องการ **วิธีอ่าน PDF417** ในแอปพลิเคชัน .NET คู่มือนี้จะให้โซลูชันที่พร้อมใช้งาน คุณจะได้เห็นวิธีอ่านไฟล์ PNG ของบาร์โค้ด, ประมวลผลหลายบาร์โค้ดในภาพเดียวกัน, และดึงฟิลด์ PDF417 ที่ขยายซึ่งหลายสแกนเนอร์ซ่อนไว้ + +การอ่านบาร์โค้ด PDF417 เป็นเรื่องทั่วไปในโลจิสติกส์, การจำหน่ายตั๋ว, และการจัดการเอกสาร เมื่อจบบทเรียนนี้คุณจะสามารถถอดรหัสภาพ Macro PDF417, แสดงผลลัพธ์ทั้งหมด, และใช้ข้อมูลเพิ่มเติม (ไฟล์ ID, จำนวนเซกเมนต์, เวลา, ฯลฯ) ในตรรกะธุรกิจของคุณเอง + +## ข้อกำหนดเบื้องต้น + +- .NET 6.0 หรือใหม่กว่า (โค้ดนี้ยังทำงานกับ .NET Framework 4.7+ ด้วย) +- Visual Studio 2022 หรือ IDE C# ใดก็ได้ +- **Aspose.BarCode for .NET** (รุ่นทดลองฟรีหรือแพคเกจ NuGet ที่มีลิขสิทธิ์) +- ภาพ PNG ที่มีบาร์โค้ด Macro PDF417 (ไฟล์ตัวอย่างชื่อ `ExtPDF417Meta.png`) + +> **เคล็ดลับมืออาชีพ:** ติดตั้งไลบรารีด้วยคอนโซล NuGet: +> `dotnet add package Aspose.BarCode` + +## วิธีอ่าน PDF417 ด้วย BarCodeReader ใน C# + +หัวใจของโซลูชันคือคลาส `BarCodeReader` ซึ่งรับพาธของภาพและ enum `DecodeType` ที่บอกให้เอนจินรู้ว่าจะค้นหา symbology ใด + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### ทำไมวิธีนี้ถึงได้ผล + +- **`DecodeType.MacroPdf417`** บอกให้รีดเดอร์มองหาเวอร์ชัน Macro PDF417 ซึ่งเก็บฟิลด์เพิ่มเติมที่คุณเห็นในขั้นตอน 4. +- บล็อก `using` จะทำการปล่อยรีดเดอร์โดยอัตโนมัติ ปล่อยการจัดการไฟล์ +- `ReadBarCodes()` คืนค่า **ทั้งหมด** ของบาร์โค้ดที่ตรงกับประเภทที่ร้องขอ ซึ่งตอบสนองความต้องการ *อ่านหลายบาร์โค้ด* แม้ภาพจะมีเพียงหนึ่งบาร์โค้ดก็ตาม + +การรันโปรแกรมจะแสดงผลลัพธ์ที่คล้ายกับ: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## การใช้รีดเดอร์บาร์โค้ด C# เพื่ออ่านหลายบาร์โค้ด + +หากภาพมีสัญลักษณ์ Macro PDF417 หลายตัว (เช่น หน้าสแกนที่มีชุดตั๋ว), ลูป `foreach` เดียวกันจะประมวลผลแต่ละอัน ไม่จำเป็นต้องเขียนโค้ดเพิ่มเติม; รีดเดอร์จะรวมผลลัพธ์ภายในโดยอัตโนมัติ. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### ข้อผิดพลาดทั่วไป + +- **รูปแบบภาพ:** รีดเดอร์รองรับ PNG, JPEG, BMP, และ TIFF หากคุณลองใช้รูปแบบที่รีดเดอร์ไม่สามารถถอดรหัสได้ จะได้คอลเลกชันว่าง นั่นคือเหตุผลที่บทเรียนเน้น *อ่านบาร์โค้ด PNG*. +- **ความละเอียด:** ภาพความละเอียดต่ำ (< 300 dpi) อาจทำให้พลาดเซกเมนต์ ควรเพิ่มขนาดหรือขอสแกนคุณภาพสูงกว่าเมื่อทำได้. +- **แฟล็ก Macro:** หากลืมใช้ `DecodeType.MacroPdf417` จะทำให้เอนจินจำกัดเฉพาะ PDF417 ธรรมดาและละทิ้งข้อมูลที่ขยาย ควรระบุประเภท macro เสมอเมื่อคุณต้องการฟิลด์ *อ่านบาร์โค้ดที่ขยาย*. + +## การอ่านไฟล์ PNG ของบาร์โค้ด – แนวทางปฏิบัติที่ดีที่สุด + +การทำงานกับไฟล์ PNG เป็นเรื่องง่ายเพราะรูปแบบนี้รักษาข้อมูลพิกเซลแบบไม่สูญเสีย นี่คือเช็คลิสต์สั้น ๆ: + +1. ตรวจสอบว่าไฟล์มีอยู่ก่อนสร้างรีดเดอร์. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. ใช้ `Image.FromFile` เฉพาะเมื่อคุณต้องการทำการประมวลผลล่วงหน้า (หมุน, ครอบ) เท่านั้น `BarCodeReader` สามารถเปิดไฟล์โดยตรง ซึ่งช่วยหลีกเลี่ยงการจัดสรรหน่วยความจำเพิ่มเติม. +3. หาก PNG มีความโปร่งใส รีดเดอร์ยังทำงานได้เนื่องจากบาร์โค้ดถูกแสดงบนพิกเซลทึบ. + +## การเข้าถึงเมตาดาต้า PDF417 ที่ขยาย + +อ็อบเจ็กต์ `Extended.Pdf417` เปิดเผยทุกฟิลด์ทางเลือกที่กำหนดโดยสเปค PDF417 คุณสามารถแมปฟิลด์เหล่านี้ไปยังโมเดลโดเมน, เก็บไว้ในฐานข้อมูล, หรือใช้สำหรับการตรวจสอบความถูกต้อง. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Populate the model: + + + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดซึ่งต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลรวมตัวอย่างโค้ดที่ทำงานครบถ้วนพร้อมคำอธิบายทีละขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานทางเลือกในโครงการของคุณเอง. + +- [วิธีอ่านบาร์โค้ด DataMatrix ด้วย Aspose.BarCode สำหรับ .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [วิธีสร้างบาร์โค้ด – Compact PDF417 ด้วย Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [อ่านบาร์โค้ด DataMatrix C# – สร้างโหมด DataMatrix (อัตโนมัติ)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/turkish/net/compact-pdf417-encoding/_index.md b/barcode/turkish/net/compact-pdf417-encoding/_index.md index ea67f016b..66596bc14 100644 --- a/barcode/turkish/net/compact-pdf417-encoding/_index.md +++ b/barcode/turkish/net/compact-pdf417-encoding/_index.md @@ -83,6 +83,18 @@ Temellerin ötesinde, iş akışınızı hızlandıracak bazı pratik ipuçları ### [Compact PDF417 Barkodları Oluşturma](./compact-pdf417-basic-configuration/) Aspose.BarCode for .NET'i kullanarak Compact PDF417 barkodlarını nasıl oluşturacağınızı öğrenin. Adım‑adım talimatları ve kod örnekleri içeren kapsamlı bir rehber. +### [Aspose barkod örneği: C#'ta Macro PDF417 oluşturma](./aspose-barcode-example-generate-macro-pdf417-in-c/) +C# kullanarak Macro PDF417 barkodu oluşturmak için Aspose.BarCode örnek kodu. + +### [C#'ta PDF417 barkodu oluşturma – adım adım rehber](./generate-pdf417-barcode-in-c-step-by-step-guide/) +C# kullanarak PDF417 barkodu oluşturmayı adım adım öğrenin. + +### [C#'ta metinden barkod oluşturma – eksiksiz adım adım rehber](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +C# kullanarak metinden barkod oluşturmayı adım adım öğrenin. + +### [C#'ta PDF417 Okuma – Tam Barkod Okuyucu Rehberi](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) +C# kullanarak PDF417 barkodlarını okuma adımlarını ve örnek kodları içeren kapsamlı bir rehber. + ## Sıkça Sorulan Sorular **Q:** Compact PDF417 barkodunda saklayabileceğim maksimum veri miktarı nedir? @@ -111,4 +123,4 @@ Aspose.BarCode for .NET'i kullanarak Compact PDF417 barkodlarını nasıl oluşt {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/turkish/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/turkish/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..ab7329377 --- /dev/null +++ b/barcode/turkish/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-09 +description: Aspose barkod örneği, C# barkod üreteci kullanarak tam meta veri desteğiyle + Macro PDF417 oluşturmayı gösterir. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: tr +lastmod: 2026-08-09 +og_description: Aspose barkod örneği, bir barcode generator C# kullanarak dosya kimliği, + segment verisi, zaman damgası ve diğer meta verileri içeren bir Macro PDF417 barkodu + üretmeyi gösterir. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Aspose barkod örneği – C# ile Macro PDF417 oluşturma +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Aspose barkod örneği: C#''ta Macro PDF417 oluşturma' +url: /tr/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose barkod örneği: C#'ta Macro PDF417 oluşturma + +Macro PDF417 barkod oluşturan bir **aspose barcode example**'a ihtiyacınız varsa, bu kılavuz **barcode generator C#** ile nasıl yapılacağını gösterir. Temel boyutlardan Macro PDF417 meta veri alanlarının tam setine kadar gerekli tüm ayarları göreceksiniz ve ardından sonraki işlemler için hazır bir PNG görüntüsü elde edeceksiniz. + +Bu öğretici tam iş akışını kapsar, her parametrenin neden önemli olduğunu açıklar ve çalıştırmaya hazır bir kod örneği sunar. Harici referanslara gerek yoktur; kodu kopyalayabilir, değerleri ayarlayabilir ve hemen çalıştırabilirsiniz. + +## Önkoşullar + +- .NET 6.0 (veya daha yeni) yüklü +- Visual Studio 2022 veya herhangi bir C# uyumlu IDE +- **Aspose.BarCode for .NET** için geçerli bir lisans (ücretsiz deneme bu örnek için çalışır) + +Projenize Aspose.BarCode NuGet paketini ekleyin: + +```bash +dotnet add package Aspose.BarCode +``` + +## Adım 1: barcode generator C# örneğini oluşturun + +İlk adım, `BarcodeGenerator`'ı `EncodeTypes.MacroPdf417` enum değeri ve kodlamak istediğiniz metinle örneklemektir. Metin Unicode karakterler içerebilir; kütüphane bunları otomatik olarak işler. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Neden önemli*: `EncodeTypes.MacroPdf417` motorun bir Macro PDF417 sembolü üretmesini sağlar; bu, segmentlenmiş veri ve ek dosya‑seviyesi meta veriyi destekler. `using` ifadesi, görüntü kaydedildikten sonra yönetilmeyen kaynakların serbest bırakılmasını garanti eder. + +## Adım 2: temel barkod görünümünü tanımlayın + +Macro PDF417 barkod, kare modüllerden oluşur. Modül boyutunu ve sütun sayısını kontrol etmek, okunabilirliği ve dosya boyutunu etkiler. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Neden önemli*: `XDimension.Pixels` görsel yoğunluğu belirler; 2 piksel değeri ekran görüntüsü için iyidir ve görüntüyü küçük tutar. Sütun sayısını düzeninizin kısıtlamalarına göre ayarlayın—daha fazla sütun daha geniş, daha kısa bir barkod oluşturur. + +## Adım 3: Macro PDF417 özel meta verilerini ayarlayın + +Macro PDF417, standart PDF417 formatını birden çok barkod segmentinden büyük dosyaların yeniden oluşturulmasını sağlayan alanlarla genişletir. Her alan isteğe bağlıdır, ancak bunları ayarlamak API'nin tam yeteneklerini gösterir. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Neden önemli*: +- `MacroPdf417FileID` aynı mantıksal dosyaya ait tüm segmentleri bağlar. +- `MacroPdf417SegmentID` ve `MacroPdf417SegmentsCount` çözücünün parçaları doğru şekilde yeniden sıralamasını sağlar. +- `MacroPdf417Checksum` tüm yükü çözmeden hızlı bir bütünlük kontrolü sunar. +- `MacroPdf417FileSize` ve `MacroPdf417TimeStamp` sonraki sistemlerin yeniden oluşturulan dosyanın orijinaliyle eşleştiğini doğrulamasına izin verir. +- `MacroPdf417Addressee` / `MacroPdf417Sender` lojistik veya belge‑değişim senaryolarında faydalıdır. +- `MacroPdf417Terminator`'ı `Set` olarak ayarlamak, bu barkodu son segment olarak işaretler ve yeniden oluşturma algoritmasını basitleştirir. + +## Adım 4: oluşturulan barkod görüntüsünü kaydedin + +Son olarak, barkodu bir PNG dosyasına yazın. Desteklenen herhangi bir formatı (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`) seçebilirsiniz. + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Neden önemli*: PNG kayıpsız piksel verisini korur, tarayıcıların yapılandırdığınız tam modül desenini okumasını sağlar. Formatı değiştirmek görsel kaliteyi ve dosya boyutunu etkileyebilir. + +### Beklenen çıktı + +Tam programı çalıştırmak **ExtPDF417Meta.png** adlı bir dosya oluşturur. Görüntüyü açtığınızda kodlanmış “Åspóse.Barcóde©” metniyle dikdörtgen bir Macro PDF417 barkod gösterilir ve görsel yoğunluk ayarladığınız 2‑piksel X boyutuna eşittir. Görüntüyü PDF417‑uyumlu bir okuyucu ile taradığınızda Adım 3'te tanımlanan tüm meta veri alanları döndürülür. + +## Tam çalışan örnek + +Aşağıdaki kodu yeni bir konsol projesine (`dotnet new console`) kopyalayın ve `YOUR_DIRECTORY` ifadesini makinenizde mevcut olan mutlak ya da göreli bir yol ile değiştirin. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Programı çalıştırın (`dotnet run`). Çalıştırmadan sonra PNG dosyasının belirttiğiniz konumda göründüğünden emin olun. Meta verinin doğru şekilde gömülü olduğunu doğrulamak için Macro PDF417 destekleyen herhangi bir barkod okuma uygulaması kullanın. + +## Yaygın varyasyonlar ve uç durumlar + +- **Farklı görüntü formatları**: `BarCodeImageFormat.Png` yerine `Jpeg`, `Bmp` veya `Tiff` kullanın, eğer sonraki sisteminiz başka bir format tercih ediyorsa. +- **Modül boyutunu değiştirme**: Daha büyük `XDimension.Pixels` değerleri düşük çözünürlüklü tarayıcılarda tarama güvenilirliğini artırır ancak görüntü boyutunu büyütür. +- **Birden çok segment**: Çok segmentli bir dosya üretmek için bir dizi barkod oluşturun, her biri için `MacroPdf417SegmentID` değerini artırın ve `MacroPdf417FileID` sabit kalsın. Sadece son segmentte `MacroPdf417Terminator` ayarlanmalıdır. +- **Unicode desteği**: Üreteç Unicode karakterleri otomatik olarak kodlar; dış bir dosyadan okurken kaynak dizeyi UTF‑8 kodlamasıyla kullandığınızdan emin olun. +- **Hata yönetimi**: `using` bloğunu bir try‑catch içinde sararak geçersiz parametreler için `BarCodeException` yakalayın (ör. sütun sayısı aralık dışı). + +## Profesyonel ipuçları + +- **Performans**: Aynı ayarlarla birçok barkod oluştururken tek bir `BarcodeGenerator` örneğini yeniden kullanın; sadece kaydetmeler arasında `CodeText` özelliğini değiştirin. +- **Dosya boyutu tahmini**: `MacroPdf417FileSize` alanı, orijinal yükün bayt sayısıyla eşleşmelidir; eşleşmemeler sonraki doğrulama hatalarına yol açabilir. +- **Test**: Oluşturulan barkodları hem Aspose'un yerleşik çözücüsü (`BarCodeReader`) hem de üçüncü taraf bir tarayıcı ile doğrulayarak birlikte çalışabilirliği sağlayın. + +## Sonuç + +Bu **aspose barcode example + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanan ve yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olmak için adım adım açıklamalar içeren tam çalışan kod örnekleri sunar. + +- [Nasıl Barcode Oluşturulur – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Nasıl Code 16K için barcode sessiz bölgesi oluşturulur using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [Nasıl ITF-14 için Barcode Sessiz Bölgesi Oluşturulur Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/turkish/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/turkish/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..343b318cd --- /dev/null +++ b/barcode/turkish/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-08-09 +description: Aspose.BarCode ile C#'ta metinden barkod oluşturun. Barkod oluşturmayı, + özel karakterleri nasıl ele alacağınızı ve PDF417 barkodunu C#'ta hızlıca nasıl + oluşturacağınızı öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: tr +lastmod: 2026-08-09 +og_description: C#'ta Aspose.BarCode kullanarak metinden barkod oluşturun. Bu öğreticide + barkod oluşturma, özel karakterleri destekleme ve tam kodla PDF417 barkodu C#'ta + oluşturma gösterilmektedir. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: C#'ta metinden barkod oluşturma – hızlı adım adım rehber +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: C#'ta Metinden Barkod Oluşturma – Tam Adım Adım Rehber +url: /tr/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Metinden barkod oluşturma C# – eksiksiz adım‑adım kılavuz + +Bir .NET uygulamasında **metinden barkod oluşturma** ihtiyacınız varsa, bu kılavuz sizi tüm süreç boyunca yönlendirecek. Barkod oluşturmayı, özel karakterleri yönetmeyi ve kutudan çıkar çıkmaz çalışan bir PDF417 barkod C# uygulamasını nasıl oluşturacağınızı göreceksiniz. + +Metinden barkod oluşturma, envanter sistemleri, biletleme platformları ve belge iş akışları için yaygın bir gereksinimdir. Bu öğreticinin sonunda, Aspose.BarCode kullanarak bir MicroPdf417 PNG görüntüsü üreten çalıştırılabilir bir C# konsol uygulamanız olacak. Harici hizmetlere ihtiyaç yoktur ve kod “Å”, “©” ve “é” gibi Unicode karakterleri işler. + +## Önkoşullar + +- .NET 6.0 SDK veya daha yeni (kod ayrıca .NET Core 3.1 ve .NET Framework 4.7+ ile de çalışır) +- Visual Studio 2022 (veya C# destekleyen herhangi bir IDE) +- **Aspose.BarCode for .NET** NuGet paketi + ```bash + dotnet add package Aspose.BarCode + ``` +- C# sözdizimi hakkında temel bilgi + +## Metinden barkod oluşturma – oluşturucuyu ayarlama + +İlk adım, istediğiniz **barcode encode type**’ı bilen bir `BarcodeGenerator` örneği oluşturmaktır. Bu öğreticide `EncodeTypes.MicroPdf417` kullanıyoruz; bu, kısa veri dizileri için uygun, PDF417’nin kompakt bir varyantıdır. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Neden bu çalışır:** +- `EncodeTypes.MicroPdf417` kütüphaneye PDF417 ailesini kullanmasını söyler, **create pdf417 barcode c#** gereksinimini karşılar. +- Yapıcı, ham metni alır; bu da **generate barcode from text** işleminin özüdür. +- Unicode desteği yerleşiktir, bu sayede “Å” ve “©” gibi karakterler doğru şekilde kodlanır, **barcode with special characters** sorununu çözer. + +## Özel karakterlerle barkod oluşturma + +Veriniz ASCII olmayan semboller içeriyorsa, oluşturucunun UTF‑8 kodlamasını kullandığından emin olmalısınız. Aspose.BarCode Unicode’u otomatik algılar, ancak sorun yaşarsanız metin kodlamasını açıkça ayarlayabilirsiniz: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +`ConfigureGenerator` öncesinde bu satırı eklemek, **barcode with special characters**’ın herhangi bir platformda doğru şekilde görüntülenmesini garanti eder. + +### Pratik ipucu +Çıktı bozuk görünüyorsa, barkod renderleyicisinin kullandığı yazı tipinin gerekli glifleri desteklediğini doğrulayın. Özel bir TrueType yazı tipini şu şekilde gömebilirsiniz: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Seçebileceğiniz barkod kodlama türleri + +Aspose.BarCode, farklı kullanım senaryolarına uygun **barcode encode types**’ların onlarca çeşidini destekler: + +| Encode type | Typical use case | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | Gönderi etiketleri, envanter | +| `EncodeTypes.QR` | Mobil ödemeler, URL'ler | +| `EncodeTypes.Pdf417` | Sürücü belgeleri, biniş kartları | +| `EncodeTypes.MicroPdf417` | Küçük veri yükleri, sınırlı alan | +| `EncodeTypes.DataMatrix` | Küçük öğeler, yüksek veri yoğunluğu | + +Kodlayıcı türünü değiştirmek, yapıcıdaki enum değerini takas etmek kadar basittir: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Bu esneklik, **barcode encode types** sorularını IDE’den çıkmadan yanıtlamanızı sağlar. + +## PDF417 barkod C# oluşturma – son adımlar ve doğrulama + +Oluşturucuyu yapılandırdıktan sonra, **create pdf417 barcode c#**’ın son kısmı görüntüyü kaydetmek ve sonucu doğrulamaktır. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Programı çalıştırın (`dotnet run`) ve aşağıdakine benzer bir konsol mesajı görmelisiniz: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +PNG dosyasını açın; “Åspóse.Barcóde©” dizesini kodlayan net bir MicroPdf417 barkodu göreceksiniz. Mobil bir barkod tarayıcı (ör. ZXing) ile tarandığında orijinal metni döndürür; bu da **generate barcode from text**’in özel karakterlerle bile çalıştığını kanıtlar. + +### Kenar durumu: çok uzun metin + +MicroPdf417’nin maksimum veri kapasitesi 1 KB’tır. Girişiniz bu sınırı aşarsa, kütüphane bir `ArgumentException` fırlatır. Bunu nazikçe ele almak için: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Daha büyük veri yükleri için tam `EncodeTypes.Pdf417` veya `EncodeTypes.DataMatrix`’e geçiş yapın. + +## Yaygın tuzaklar ve nasıl önlenir + +| Issue | Cause | Fix | +|-------------------------------------|-----------------------------------------|-----| +| Barkod bulanık görünüyor | XDimension çok düşük (ör. 1 px) | `XDimension.Pixels` değerini 2‑3 px olarak artırın | +| Unicode karakterler `?` olarak görünüyor | Varsayılan metin kodlaması ASCII | `TextEncoding = Encoding.UTF8` olarak ayarlayın | +| Görüntü dosyası oluşturulmadı | Çıktı dizini mevcut değil | `Save` işleminden önce `Directory.CreateDirectory` kullanın | +| Tarayıcı barkodu okuyamıyor | Kısa veri için çok fazla sütun | `Pdf417.Columns` değerini azaltın (ör. 3‑4) | + +## Tam kaynak kodu (kopyalamaya hazır) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Beklenen çıktı:** `output` klasöründe bulunan, özel karakterli orijinal dizeyi kodlayan net bir MicroPdf417 barkodu içeren `MicroPdf417.png` adlı dosya. + +## Sonuç + +Artık Aspose.BarCode kullanarak C#’ta **metinden barkod oluşturma**, **barcode with special characters**’ı yönetme ve **create pdf417 barcode c#** işlemini kodlama seçenekleri üzerinde tam kontrolle yapma konusunda bilgi sahibisiniz. **barcode encode types**’ı ayarlayarak QR kodları, Code128, DataMatrix veya desteklenen diğer formatları üretebilirsiniz. + +Sonraki adımda, barkod uzmanlığınızı derinleştirmek için aşağıdaki konuları inceleyin: + +- **How to generate barcode**'ı binlerce kayıt için toplu olarak üretmek (hız için `Parallel.ForEach` kullanın) +- Renk özelleştirme ve barkod içine logo ekleme +- Barkod üretimini ASP.NET Core API’lerine entegre ederek anlık görüntü teslimi +- Açık kaynak alternatifleri için ZXing.Net veya IronBarcode gibi diğer kütüphaneleri kullanma + +Farklı boyutları, sütun ayarlarını ve kodlama türlerini denemekten çekinmeyin. İyi kodlamalar, uygulamalarınız sorunsuz taransın! + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan ve yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak tam çalışan kod örnekleri ve adım‑adım açıklamalar içerir. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/turkish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/turkish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..300effa5f --- /dev/null +++ b/barcode/turkish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-08-09 +description: C#'ta PDF417 barkodu hızlı bir şekilde oluşturun. BarcodeGenerator API'sini + kullanarak kompakt mod, sütun kontrolü ve PNG çıktısı ile PDF417 oluşturmayı öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: tr +lastmod: 2026-08-09 +og_description: Kısa bir örnekle C#'ta PDF417 barkod oluşturun. Bu rehber, kompakt + modu nasıl yapılandıracağınızı, sütunları nasıl ayarlayacağınızı ve sonucu PNG görüntüsü + olarak nasıl kaydedeceğinizi gösterir. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: C#'te PDF417 barkod oluşturma – tam rehber +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: C#'ta PDF417 barkod oluşturma – adım adım rehber +url: /tr/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#’ta PDF417 barkod oluşturma – adım adım kılavuz + +Bir .NET uygulamasında **PDF417 barkod oluşturmanız** gerekiyorsa, bu öğretici tam olarak nasıl yapılacağını gösterir. Tam, çalıştırılabilir bir program göreceksiniz; bu program kompakt bir PDF417 barkod oluşturur, boyutunu özelleştirir ve görüntüyü PNG dosyası olarak kaydeder. + +PDF417 barkod oluşturma, mobil biletleme, envanter takibi ve belge güvenliği gibi senaryolar için yaygın bir gereksinimdir. Bu kılavuz temel yapılandırma seçeneklerini kapsar, her ayarın neden önemli olduğunu açıklar ve gerçek dünya kullanımına yönelik pratik ipuçları sunar. + +## Prerequisites + +Başlamadan önce şunların yüklü olduğundan emin olun: + +* .NET 6.0 SDK veya daha yeni bir sürüm +* Visual Studio 2022 veya Visual Studio Code gibi bir C# IDE’si +* **Aspose.BarCode for .NET** NuGet paketi (sürüm 23.10 veya daha yenisi) + +Paketi aşağıdaki CLI komutuyla kurabilirsiniz: + +```bash +dotnet add package Aspose.BarCode +``` + +Aşağıdaki kod, paketin referans alındığını ve çıktı dizinine yazma izniniz olduğunu varsayar. + +## Step 1: Set up the project and import namespaces + +Yeni bir console projesi oluşturun ve gerekli `using` yönergelerini ekleyin. Bu ad alanları `BarcodeGenerator` sınıfını ve görüntü formatı enumunu ortaya çıkarır. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Why this matters:** Doğru ad alanlarını içe aktarmak, derleyicinin `BarcodeGenerator` tipini ve `BarCodeImageFormat` enumunu bulmasını sağlar. Bir ad alanı eksik olduğunda derleme hatası alınır ve barkod oluşturma süreci durur. + +## Step 2: Initialize the `BarcodeGenerator` with PDF417 encoding + +`BarcodeGenerator` yapıcı metodu iki argüman alır: barkod simgesi (`EncodeTypes.Pdf417`) ve kodlamak istediğiniz metin. PDF417, Unicode semboller dahil geniş bir karakter yelpazesini destekler. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Explanation:** +* `EncodeTypes.Pdf417` kütüphaneye PDF417 standardını kullanmasını söyler. +* Örnek metin, Unicode işleme örneği olarak aksanlı karakterler ve bir telif hakkı simgesi içerir. + +Yalnızca sayısal veri kodlamanız gerekiyorsa, `"1234567890"` gibi düz bir dize geçirebilirsiniz. + +## Step 3: Adjust the X‑dimension for finer resolution + +X‑dimension, tek bir barkod modülünün (en küçük siyah veya beyaz eleman) genişliğini kontrol eder. Daha küçük bir piksel değeri, daha yüksek çözünürlüklü bir görüntü elde etmenizi sağlar. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Why adjust it?** Varsayılan 3–4 piksel X‑dimension, yüksek DPI ekranlarda kaba görünebilen bir barkod üretebilir. **2 piksel** olarak azaltmak, özellikle daha sonra kompakt modu etkinleştirdiğinizde, okunabilirlik ile dosya boyutu arasında denge kurar. + +## Step 4: Configure the number of columns + +PDF417, barkodun kaç sütun içereceğini belirlemenize izin verir. Daha az sütun barkodu daha dar ama daha yüksek yapar, daha çok sütun ise daha geniş ve daha kısa bir barkod oluşturur. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Practical tip:** Dar bir etiket içinde yer alması gereken mobil biletler için **3–5** sütun sayısı iyi çalışır. Çok fazla veri varsa ve daha kısa bir barkod isteniyorsa sütun sayısını artırın. + +## Step 5: Enable compact mode to truncate empty rows + +Kompakt mod, barkod matrisindeki gereksiz satırları kaldırarak kodlanmış veriyi kaybetmeden toplam görüntü boyutunu azaltır. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**When to use it:** Barkodları depolama veya ağ üzerinden iletim amaçlı oluşturuyorsanız, kompakt mod PNG dosyasını %30’a kadar küçültebilir. Ancak bazı eski tarayıcılar kırpılmış PDF417’yı desteklemeyebilir; hedef donanımınızda test edin. + +## Step 6: Save the barcode as a PNG image + +Bir çıktı yolu seçin ve `Save` metodunu çağırın. `BarCodeImageFormat.Png` enumu, çoğu uygulama için uygun kayıpsız bir görüntü üretir. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Result verification:** PNG dosyasını herhangi bir görüntü görüntüleyicide açın. Örnek metinle eşleşen yoğun, yüksek kontrastlı bir barkod görmelisiniz. Görüntüyü bir PDF417 okuyucu (ör. ZXing veya bir akıllı telefon uygulaması) ile taradığınızda orijinal `"Åspóse.Barcóde©"` dizesi geri döner. + +![Generated PDF417 barcode image saved as PNG](compact-pdf417.png "Generated PDF417 barcode in C#") + +*Yukarıdaki görüntü, öğreticinin kodunun nihai çıktısını göstermektedir.* + +## Full, runnable example + +Tüm parçaları bir araya getirerek, kopyalayıp yapıştırıp çalıştırabileceğiniz eksiksiz bir console programı aşağıdadır. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Expected output + +Program çalıştırıldığında şunları yazdırır: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +`CompactPdf417.png` dosyası, sağlanan Unicode dizesini kodlayan kompakt bir PDF417 barkod içerir. Görüntüyü standart bir PDF417 okuyucu ile taradığınızda tam metin elde edilir. + +## Common variations and edge cases + +| Durum | Ayar | Sebep | +|-----------|------------|--------| +| **Daha uzun veri yükü** (ör. > 150 karakter) | `generator.Parameters.Barcode.Pdf417.Columns` değerini 6‑8’e artırın | Daha fazla sütun, barkodun aşırı uzun olmasını engeller. | +| **Şeffaf arka plan ihtiyacı** | `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` kullanın | Şeffaf PNG, UI katmanlarına daha iyi entegre olur. | +| **Web için JPEG oluşturma** | Formatı `BarCodeImageFormat.Jpeg` olarak değiştirin ve isteğe bağlı olarak `ImageQuality` ayarlayın | JPEG, kayıpsız kaliteyi feda ederek dosya boyutunu azaltır. | +| **Null veya boş giriş işleme** | Üreteci oluşturmadan önce girişi kontrol edin: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Çalışma zamanı istisnalarını önler ve anlamlı barkodlar sağlar. | + +## Tips for production use + +* **Exception handling:** Üretim mantığını bir `try/catch` bloğu içinde sararak yetersiz disk alanı veya geçersiz parametreler gibi hataları günlüğe kaydedin. +* **Performance:** Aynı ayarlarla birden çok barkod üretirken tek bir `BarcodeGenerator` örneğini yeniden kullanın; sadece `CodeText` özelliğini kaydetmeler arasında güncelleyin. +* **Security:** Kodlanan metin hassas bilgi içeriyorsa, üreticiye göndermeden önce şifrelemeyi, taramadan sonra da şifre çözmeyi düşünün. + +## Conclusion + +Artık **PDF417 barkod oluşturmayı** C# içinde Aspose.BarCode kütüphanesiyle, kompakt modu yapılandırarak, sütun sayısını kontrol ederek ve sonucu PNG görüntüsü olarak dışa aktararak biliyorsunuz. Bu öğretici, proje kurulumundan kenar‑durum yönetimine kadar her adımı kapsayarak barkod‑odaklı uygulamalar için kullanıma hazır bir çözüm sundu. + +Sonraki adımda, **C#’ta QR kod oluşturma**, **toplu barkod üretimi** ve **mobil uygulamalarla barkod tarama entegrasyonu** gibi ilgili konuları keşfedin. Bu konular, az önce öğrendiğiniz `BarcodeGenerator` temelleri üzerine inşa edilmiştir. + +Kodlamaktan keyif alın! + +## What Should You Learn Next? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanarak yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak eksiksiz çalışan kod örnekleri ve adım adım açıklamalar içerir. + +- [How to Generate PDF417 Barcodes – Compact PDF417 Encoding](/barcode/english/net/compact-pdf417-encoding/) +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/turkish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/turkish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..d47b25785 --- /dev/null +++ b/barcode/turkish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-09 +description: BarCodeReader kullanarak C#'ta PDF417 nasıl okunur. Barkod PNG dosyalarını + okumayı öğrenin, birden fazla barkodu işleyin ve genişletilmiş meta verileri çıkarın. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: tr +lastmod: 2026-08-09 +og_description: Aspose.BarCode ile C#'ta PDF417 nasıl okunur. Bu öğreticide, barkod + PNG dosyalarını nasıl okuyacağınızı, tek bir görüntüde birden fazla barkodu nasıl + işleyeceğinizi ve genişletilmiş PDF417 meta verilerini nasıl alacağınızı gösteriyoruz. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: C#'ta PDF417 nasıl okunur – barkod okuyucu öğretici +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: C#'ta PDF417 Nasıl Okunur – Tam Barkod Okuyucu Rehberi +url: /tr/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta PDF417 Nasıl Okunur – Tam Barkod Okuyucu Kılavuzu + +Bir .NET uygulamasında **PDF417 nasıl okunur** ihtiyacınız varsa, bu kılavuz size hazır‑çalıştır bir çözüm sunar. Bir barkod PNG'sini nasıl okuyacağınızı, aynı görüntüde birden fazla barkodu nasıl işleyeceğinizi ve birçok tarayıcının gizlediği genişletilmiş PDF417 alanlarını nasıl çekeceğinizi göreceksiniz. + +PDF417 barkodlarını okumak lojistik, biletleme ve belge yönetiminde yaygındır. Bu öğreticinin sonunda bir Macro PDF417 görüntüsünü çözüp, her sonucu görüntüleyebilir ve ekstra bilgileri (dosya kimliği, segment sayısı, zaman damgaları, vb.) kendi iş mantığınızda kullanabilirsiniz. + +## Önkoşullar + +- .NET 6.0 veya üzeri (kod .NET Framework 4.7+ ile de çalışır) +- Visual Studio 2022 veya herhangi bir C# IDE +- **Aspose.BarCode for .NET** (ücretsiz deneme veya lisanslı NuGet paketi) +- Macro PDF417 barkodu içeren bir PNG görüntüsü (örnek dosya adı `ExtPDF417Meta.png`) + +> **Pro tip:** Kütüphaneyi NuGet konsolu ile kurun: +> `dotnet add package Aspose.BarCode` + +## C#'ta BarCodeReader ile PDF417 Nasıl Okunur + +Çözümün çekirdeği `BarCodeReader` sınıfıdır. Bir görüntü yolu ve motorun hangi sembolojiyi arayacağını belirten bir `DecodeType` enum alır. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Bunun Neden Çalıştığı + +- **`DecodeType.MacroPdf417`** okuyucuya Macro PDF417 varyantını aramasını söyler; bu, adım 4'te gördüğünüz ekstra alanları depolar. +- `using` bloğu okuyucuyu otomatik olarak dispose eder, dosya tutamaçlarını serbest bırakır. +- `ReadBarCodes()` istenen tipe uyan **tüm** barkodları döndürür, bu da görüntü sadece bir tane içeriyor olsa bile *birden fazla barkod okuma* gereksinimini karşılar. + +Programı çalıştırmak, aşağıdakine benzer bir çıktı verir: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## C# barkod okuyucusunu birden fazla barkod okumak için kullanma + +Bir görüntü birden fazla Macro PDF417 sembolü içeriyorsa (örneğin, bir grup biletin taranmış sayfası), aynı `foreach` döngüsü her birini işler. Ek bir kod gerekmez; okuyucu sonuçları dahili olarak toplar. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Yaygın Tuzaklar + +- **Görüntü formatı:** Okuyucu PNG, JPEG, BMP ve TIFF formatlarını destekler. Çözemediği bir format denerseniz boş bir koleksiyon alırsınız. Bu yüzden öğreticide *barkod PNG okuma* vurgulanır. +- **Çözünürlük:** Düşük çözünürlüklü görüntüler (< 300 dpi) segment kaçırılmasına neden olabilir. Mümkün olduğunda ölçeklendirin veya daha yüksek kaliteli bir tarama isteyin. +- **Macro bayrağı:** `DecodeType.MacroPdf417` unutulması motoru sadece düz PDF417 ile sınırlar ve genişletilmiş verileri atar. *barkod genişletilmiş* alanlarına ihtiyacınız olduğunda her zaman macro tipini belirtin. + +## Barkod PNG Dosyalarını Okuma – En İyi Uygulamalar + +PNG dosyalarıyla çalışmak basittir çünkü format kayıpsız piksel verisini korur. İşte hızlı bir kontrol listesi: + +1. Okuyucuyu oluşturmadan önce dosyanın varlığını doğrulayın. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. `Image.FromFile`'ı yalnızca ön‑işleme (döndürme, kırpma) gerektiğinde kullanın. `BarCodeReader` dosyayı doğrudan açabilir, bu da ekstra bellek tahsisinden kaçınır. +3. PNG şeffaflık içeriyorsa bile okuyucu çalışır çünkü barkod opak pikseller üzerinde render edilir. + +## Genişletilmiş PDF417 Metaverisine Erişim + +`Extended.Pdf417` nesnesi PDF417 spesifikasyonu tarafından tanımlanan tüm isteğe bağlı alanları ortaya çıkarır. Bu alanları bir domain modeline eşleyebilir, veritabanında saklayabilir veya doğrulama için kullanabilirsiniz. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Modeli doldurun: + + + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanan yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini ustalaşmanıza ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olmak için adım adım açıklamalar içeren tam çalışan kod örnekleri içerir. + +- [Aspose.BarCode for .NET ile DataMatrix Barkodlarını Okuma](/barcode/english/net/datamatrix-barcode-reading/) +- [Aspose.BarCode ile Barkod Oluşturma – Compact PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [DataMatrix barkodunu C# ile Okuma – DataMatrix Modu (Otomatik) Oluştur](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/vietnamese/net/compact-pdf417-encoding/_index.md b/barcode/vietnamese/net/compact-pdf417-encoding/_index.md index 8c0240726..7dbb78644 100644 --- a/barcode/vietnamese/net/compact-pdf417-encoding/_index.md +++ b/barcode/vietnamese/net/compact-pdf417-encoding/_index.md @@ -84,6 +84,13 @@ Ngoài các kiến thức cơ bản, dưới đây là một số mẹo thực t ## Hướng dẫn Mã Hóa Compact PDF417 ### [Tạo Mã Vạch Compact PDF417](./compact-pdf417-basic-configuration/) Tìm hiểu cách tạo mã vạch Compact PDF417 bằng Aspose.BarCode cho .NET. Hướng dẫn chi tiết với các bước thực hiện và ví dụ mã nguồn. +### [Ví dụ Aspose Barcode: tạo Macro PDF417 bằng C#](./aspose-barcode-example-generate-macro-pdf417-in-c/) +Hướng dẫn cách tạo mã vạch Macro PDF417 bằng C# sử dụng Aspose.BarCode. +### [Tạo mã vạch PDF417 bằng C# – hướng dẫn từng bước](./generate-pdf417-barcode-in-c-step-by-step-guide/) +Hướng dẫn chi tiết cách tạo mã vạch PDF417 trong C# sử dụng Aspose.BarCode, bao gồm các bước thực hiện và ví dụ mã nguồn. +### [Tạo mã vạch từ văn bản trong C# – hướng dẫn chi tiết từng bước](./generate-barcode-from-text-in-c-complete-step-by-step-guide/) +Hướng dẫn chi tiết cách tạo mã vạch từ văn bản trong C# sử dụng Aspose.BarCode. +### [Cách đọc PDF417 trong C# – hướng dẫn đầy đủ về trình đọc mã vạch](./how-to-read-pdf417-in-c-complete-barcode-reader-guide/) ## Câu hỏi thường gặp @@ -111,4 +118,4 @@ A: Không cần font bên ngoài; thư viện tự xử lý việc render nội {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/vietnamese/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md b/barcode/vietnamese/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md new file mode 100644 index 000000000..c23b74658 --- /dev/null +++ b/barcode/vietnamese/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-09 +description: Ví dụ mã vạch Aspose cho thấy cách sử dụng trình tạo mã vạch C# để tạo + Macro PDF417 với hỗ trợ đầy đủ siêu dữ liệu. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- aspose barcode example +- barcode generator c# +language: vi +lastmod: 2026-08-09 +og_description: Ví dụ mã vạch Aspose trình bày cách sử dụng trình tạo mã vạch C# để + tạo mã Macro PDF417 bao gồm ID tệp, dữ liệu phân đoạn, dấu thời gian và các siêu + dữ liệu khác. +og_image_alt: Screenshot of a Macro PDF417 barcode generated with Aspose.BarCode in + C# +og_title: Ví dụ mã vạch Aspose – tạo Macro PDF417 bằng C# +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Aspose barcode example showing how to use a barcode generator C# to + create a Macro PDF417 with full metadata support. + headline: 'Aspose barcode example: generate Macro PDF417 in C#' + type: TechArticle +tags: +- Aspose.BarCode +- C# +- Macro PDF417 +title: 'Ví dụ mã vạch Aspose: tạo Macro PDF417 trong C#' +url: /vi/net/compact-pdf417-encoding/aspose-barcode-example-generate-macro-pdf417-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ví dụ Aspose Barcode: tạo Macro PDF417 bằng C# + +Nếu bạn cần một **aspose barcode example** tạo ra một mã vạch Macro PDF417, hướng dẫn này sẽ chỉ cho bạn cách thực hiện bằng **barcode generator C#**. Bạn sẽ thấy mọi cài đặt cần thiết, từ kích thước cơ bản đến toàn bộ các trường metadata của Macro PDF417, và cuối cùng sẽ có một hình ảnh PNG sẵn sàng cho quá trình xử lý tiếp theo. + +Bài hướng dẫn bao gồm toàn bộ quy trình, giải thích lý do mỗi tham số quan trọng, và cung cấp một mẫu mã sẵn sàng chạy. Không cần tham chiếu bên ngoài; bạn có thể sao chép mã, điều chỉnh các giá trị và chạy ngay lập tức. + +## Yêu cầu trước + +- .NET 6.0 (hoặc mới hơn) đã được cài đặt +- Visual Studio 2022 hoặc bất kỳ IDE nào hỗ trợ C# +- Giấy phép hợp lệ cho **Aspose.BarCode for .NET** (bản dùng thử miễn phí cũng hoạt động cho ví dụ này) + +Add the Aspose.BarCode NuGet package to your project: + +```bash +dotnet add package Aspose.BarCode +``` + +## Bước 1: Tạo thể hiện barcode generator C# instance + +Bước đầu tiên là khởi tạo `BarcodeGenerator` với giá trị enum `EncodeTypes.MacroPdf417` và văn bản bạn muốn mã hoá. Văn bản có thể chứa ký tự Unicode, thư viện sẽ tự động xử lý. + +```csharp +using Aspose.BarCode.Generation; +using System; + +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // Subsequent steps are performed inside this using block. +``` + +*Tại sao điều này quan trọng*: `EncodeTypes.MacroPdf417` chỉ cho engine tạo ra một ký hiệu Macro PDF417, hỗ trợ dữ liệu phân đoạn và metadata ở mức tệp bổ sung. Câu lệnh `using` đảm bảo các tài nguyên không quản lý được giải phóng sau khi hình ảnh được lưu. + +## Bước 2: Định nghĩa giao diện cơ bản của mã vạch + +Mã vạch Macro PDF417 bao gồm các mô-đun hình vuông. Kiểm soát kích thước mô-đun và số cột ảnh hưởng đến độ đọc được và kích thước tệp. + +```csharp + // Pixel size of a single module (X dimension) + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Number of columns in the symbol; fewer columns produce a taller barcode + generator.Parameters.Barcode.Pdf417.Columns = 5; +``` + +*Tại sao điều này quan trọng*: `XDimension.Pixels` xác định mật độ hiển thị; giá trị 2 pixel hoạt động tốt cho hiển thị trên màn hình đồng thời giữ hình ảnh nhỏ. Điều chỉnh số cột để phù hợp với ràng buộc bố cục—nhiều cột hơn tạo ra mã vạch rộng hơn, ngắn hơn. + +## Bước 3: Đặt metadata đặc thù cho Macro PDF417 + +Macro PDF417 mở rộng định dạng PDF417 tiêu chuẩn bằng các trường cho phép tái tạo các tệp lớn từ nhiều đoạn mã vạch. Mỗi trường là tùy chọn, nhưng việc đặt chúng thể hiện đầy đủ khả năng của API. + +```csharp + // Unique identifier for the entire file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + + // Identifier of the current segment (zero‑based) + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + + // Total number of segments that compose the file + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + + // Logical name of the source file + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + + // 16‑bit CCITT checksum for error detection + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; + + // Approximate size of the original file in bytes + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + + // Timestamp when the file was generated + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + + // Optional address fields for routing information + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + + // Terminator indicates that this is the last segment + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +*Tại sao điều này quan trọng*: +- `MacroPdf417FileID` liên kết tất cả các đoạn thuộc cùng một tệp logic. +- `MacroPdf417SegmentID` và `MacroPdf417SegmentsCount` cho phép bộ giải mã sắp xếp lại các đoạn đúng thứ tự. +- `MacroPdf417Checksum` cung cấp kiểm tra tính toàn vẹn nhanh mà không cần giải mã toàn bộ payload. +- `MacroPdf417FileSize` và `MacroPdf417TimeStamp` cho phép hệ thống downstream xác minh rằng tệp đã tái tạo khớp với bản gốc. +- `MacroPdf417Addressee` / `MacroPdf417Sender` hữu ích trong các kịch bản logistics hoặc trao đổi tài liệu. +- Đặt `MacroPdf417Terminator` thành `Set` đánh dấu mã vạch này là đoạn cuối cùng, giúp đơn giản hoá thuật toán tái tạo. + +## Bước 4: Lưu hình ảnh mã vạch đã tạo + +Cuối cùng, ghi mã vạch ra tệp PNG. Bạn có thể chọn bất kỳ định dạng hỗ trợ nào (`Png`, `Jpeg`, `Bmp`, `Gif`, `Tiff`). + +```csharp + // Save the barcode image to the specified path + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +} +``` + +*Tại sao điều này quan trọng*: PNG giữ nguyên dữ liệu pixel không mất mát, đảm bảo máy quét đọc đúng mẫu mô-đun bạn đã cấu hình. Thay đổi định dạng có thể ảnh hưởng đến chất lượng hình ảnh và kích thước tệp. + +### Kết quả mong đợi + +Chạy toàn bộ chương trình sẽ tạo một tệp có tên **ExtPDF417Meta.png**. Mở hình ảnh sẽ hiển thị một mã vạch Macro PDF417 hình chữ nhật với văn bản “Åspóse.Barcóde©” đã được mã hoá, và mật độ hiển thị khớp với kích thước X 2‑pixel mà bạn đã đặt. Quét hình ảnh bằng trình đọc hỗ trợ PDF417 sẽ trả về tất cả các trường metadata được định nghĩa ở Bước 3. + +## Ví dụ hoàn chỉnh hoạt động + +Sao chép đoạn mã dưới đây vào một dự án console mới (`dotnet new console`) và thay thế `YOUR_DIRECTORY` bằng đường dẫn tuyệt đối hoặc tương đối tồn tại trên máy của bạn. + +```csharp +using Aspose.BarCode.Generation; +using System; + +namespace MacroPdf417Demo +{ + class Program + { + static void Main() + { + // Step 1: Create a barcode generator for Macro PDF417 with the desired text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Step 2: Define the basic barcode appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; // pixel size of a single module + generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns in the symbol + + // Step 3: Set Macro PDF417 specific metadata + generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; + generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; + generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 example + generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; + generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); + generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; + generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; + + // Step 4: Save the generated barcode image + generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode generated successfully."); + } + } +} +``` + +Chạy chương trình (`dotnet run`). Sau khi thực thi, kiểm tra xem tệp PNG có xuất hiện ở vị trí bạn đã chỉ định không. Sử dụng bất kỳ ứng dụng đọc mã vạch nào hỗ trợ Macro PDF417 để xác nhận metadata đã được nhúng đúng. + +## Các biến thể thường gặp và trường hợp đặc biệt + +- **Different image formats**: Thay `BarCodeImageFormat.Png` bằng `Jpeg`, `Bmp`, hoặc `Tiff` nếu hệ thống downstream của bạn ưu tiên định dạng khác. +- **Changing module size**: Giá trị `XDimension.Pixels` lớn hơn cải thiện độ tin cậy khi quét trên máy quét độ phân giải thấp nhưng làm tăng kích thước hình ảnh. +- **Multiple segments**: Để tạo tệp đa đoạn, tạo một loạt mã vạch, tăng `MacroPdf417SegmentID` cho mỗi đoạn và giữ `MacroPdf417FileID` cố định. Chỉ đoạn cuối cùng mới nên có `MacroPdf417Terminator` được đặt. +- **Unicode support**: Trình tạo tự động mã hoá ký tự Unicode; đảm bảo chuỗi nguồn của bạn sử dụng mã hoá UTF‑8 nếu đọc từ tệp bên ngoài. +- **Error handling**: Bao bọc khối `using` trong một try‑catch để bắt `BarCodeException` cho các tham số không hợp lệ (ví dụ: số cột vượt phạm vi). + +## Mẹo chuyên nghiệp + +- **Performance**: Tái sử dụng một thể hiện `BarcodeGenerator` duy nhất khi tạo nhiều mã vạch với cùng cài đặt; chỉ thay đổi thuộc tính `CodeText` giữa các lần lưu. +- **File size estimation**: Trường `MacroPdf417FileSize` nên khớp với số byte của payload gốc; sự không khớp có thể gây lỗi xác thực downstream. +- **Testing**: Xác thực các mã vạch đã tạo bằng cả bộ giải mã tích hợp của Aspose (`BarCodeReader`) và một trình quét bên thứ ba để đảm bảo tính tương thích. + +## Kết luận + +Đây là **aspose barcode example** + +## Bạn nên học gì tiếp theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng dựa trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên đều có các ví dụ mã hoàn chỉnh kèm giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Cách tạo Barcode – Compact PDF417 với Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Cách tạo vùng yên tĩnh cho Code 16K bằng Aspose.BarCode cho .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) +- [Cách tạo vùng yên tĩnh cho ITF-14 bằng Aspose.BarCode cho .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/vietnamese/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md b/barcode/vietnamese/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..a61909eef --- /dev/null +++ b/barcode/vietnamese/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-08-09 +description: Tạo mã vạch từ văn bản trong C# với Aspose.BarCode. Tìm hiểu cách tạo + mã vạch, xử lý ký tự đặc biệt và nhanh chóng tạo mã PDF417 bằng C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- barcode with special characters +- barcode encode types +- create pdf417 barcode c# +language: vi +lastmod: 2026-08-09 +og_description: Tạo mã vạch từ văn bản trong C# bằng Aspose.BarCode. Hướng dẫn này + chỉ cách tạo mã vạch, hỗ trợ ký tự đặc biệt và tạo mã PDF417 bằng C# kèm mã nguồn + đầy đủ. +og_image_alt: Screenshot of a generated MicroPdf417 barcode saved as PNG +og_title: Tạo mã vạch từ văn bản trong C# – hướng dẫn nhanh từng bước +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate barcode from text in C# with Aspose.BarCode. Learn how to + generate barcode, handle special characters, and create PDF417 barcode C# quickly. + headline: Generate barcode from text in C# – complete step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +- Aspose +- encoding +title: Tạo mã vạch từ văn bản trong C# – hướng dẫn chi tiết từng bước +url: /vi/net/compact-pdf417-encoding/generate-barcode-from-text-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo mã vạch từ văn bản trong C# – hướng dẫn chi tiết từng bước + +Nếu bạn cần **tạo mã vạch từ văn bản** trong một ứng dụng .NET, hướng dẫn này sẽ đưa bạn qua toàn bộ quá trình. Bạn sẽ thấy cách tạo mã vạch, quản lý các ký tự đặc biệt, và tạo một triển khai mã vạch PDF417 C# hoạt động ngay lập tức. + +Việc tạo mã vạch từ văn bản là yêu cầu phổ biến cho các hệ thống quản lý tồn kho, nền tảng bán vé và quy trình tài liệu. Khi kết thúc tutorial này, bạn sẽ có một ứng dụng console C# có thể chạy được, tạo ra ảnh PNG MicroPdf417 bằng Aspose.BarCode. Không cần dịch vụ bên ngoài, và mã nguồn xử lý các ký tự Unicode như “Å”, “©”, và “é”. + +## Yêu cầu trước + +- .NET 6.0 SDK hoặc mới hơn (mã cũng hoạt động với .NET Core 3.1 và .NET Framework 4.7+) +- Visual Studio 2022 (hoặc bất kỳ IDE nào hỗ trợ C#) +- **Aspose.BarCode for .NET** gói NuGet + ```bash + dotnet add package Aspose.BarCode + ``` +- Kiến thức cơ bản về cú pháp C# + +## Tạo mã vạch từ văn bản – thiết lập trình tạo + +Bước đầu tiên là tạo một thể hiện `BarcodeGenerator` biết loại **barcode encode type** bạn muốn. Trong tutorial này chúng ta sử dụng `EncodeTypes.MicroPdf417`, một biến thể gọn gàng của PDF417 phù hợp cho các chuỗi dữ liệu ngắn. + +```csharp +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Create a barcode generator for MicroPdf417 with the desired text + // This demonstrates "generate barcode from text" with Unicode characters. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Continue with configuration (see next sections) + ConfigureGenerator(generator); + SaveBarcode(generator); + } + + // Configuration is split into its own method for clarity. + static void ConfigureGenerator(BarcodeGenerator generator) + { + // Step 2: Define the X dimension of the barcode modules (in pixels) + // XDimension controls the width of the smallest bar; 2 px gives a clear image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // Step 3: Set the number of columns for the PDF417 layout. + // Fewer columns produce a taller barcode; 4 columns works well for short strings. + generator.Parameters.Barcode.Pdf417.Columns = 4; + } + + static void SaveBarcode(BarcodeGenerator generator) + { + // Step 4: Save the generated barcode as a PNG image. + // You can change BarCodeImageFormat to Jpeg, Gif, etc., if needed. + string outputPath = Path.Combine( + Environment.CurrentDirectory, + "MicroPdf417.png" + ); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } +} +``` + +**Tại sao cách này hoạt động:** +- `EncodeTypes.MicroPdf417` báo cho thư viện sử dụng họ PDF417, đáp ứng yêu cầu **create pdf417 barcode c#**. +- Constructor nhận văn bản thô, là cốt lõi của **generate barcode from text**. +- Hỗ trợ Unicode được tích hợp sẵn, vì vậy các ký tự như “Å” và “©” được mã hoá đúng, giải quyết **barcode with special characters**. + +## Cách tạo mã vạch với ký tự đặc biệt + +Khi dữ liệu của bạn chứa các ký hiệu không phải ASCII, bạn phải đảm bảo trình tạo sử dụng mã hoá UTF‑8. Aspose.BarCode tự động phát hiện Unicode, nhưng bạn có thể đặt rõ mã hoá văn bản nếu gặp vấn đề: + +```csharp +generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; +``` + +Thêm dòng này trước `ConfigureGenerator` sẽ đảm bảo **barcode with special characters** hiển thị đúng trên mọi nền tảng. + +### Mẹo thực tế +Nếu kết quả bị rối, hãy kiểm tra phông chữ mà bộ render mã vạch sử dụng có hỗ trợ các glyph cần thiết không. Bạn có thể nhúng phông chữ TrueType tùy chỉnh bằng cách: + +```csharp +generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; +``` + +## Các loại mã vạch bạn có thể chọn + +Aspose.BarCode hỗ trợ hàng chục **barcode encode types**, mỗi loại phù hợp với các trường hợp sử dụng khác nhau: + +| Encode type | Typical use case | +|----------------------------|--------------------------------------| +| `EncodeTypes.Code128` | Nhãn vận chuyển, quản lý tồn kho | +| `EncodeTypes.QR` | Thanh toán di động, URL | +| `EncodeTypes.Pdf417` | Giấy phép lái xe, vé lên máy bay | +| `EncodeTypes.MicroPdf417` | Payload dữ liệu nhỏ, không gian hạn chế | +| `EncodeTypes.DataMatrix` | Vật phẩm siêu nhỏ, mật độ dữ liệu cao | + +Thay đổi loại mã hoá chỉ cần hoán đổi giá trị enum trong constructor: + +```csharp +BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.QR, "https://example.com"); +``` + +Sự linh hoạt này cho phép bạn trả lời các câu hỏi về **barcode encode types** mà không rời khỏi IDE. + +## Tạo mã vạch PDF417 C# – các bước cuối cùng và kiểm tra + +Sau khi cấu hình trình tạo, phần cuối của **create pdf417 barcode c#** là lưu ảnh và xác nhận kết quả. + +```csharp +// Save as PNG (lossless, ideal for further processing) +generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +``` + +Chạy chương trình (`dotnet run`) và bạn sẽ thấy thông báo console tương tự: + +``` +Barcode saved to: C:\YourProject\bin\Debug\net6.0\MicroPdf417.png +``` + +Mở file PNG; bạn sẽ thấy một mã vạch MicroPdf417 sắc nét mã hoá chuỗi “Åspóse.Barcóde©”. Quét nó bằng một trình quét mã vạch di động (ví dụ ZXing) sẽ trả về văn bản gốc, chứng minh rằng **generate barcode from text** hoạt động ngay cả với ký tự đặc biệt. + +### Trường hợp đặc biệt: văn bản rất dài + +MicroPdf417 có khả năng chứa dữ liệu tối đa 1 KB. Nếu đầu vào của bạn vượt quá giới hạn này, thư viện sẽ ném `ArgumentException`. Để xử lý một cách nhẹ nhàng: + +```csharp +try +{ + generator.Save("MicroPdf417.png", BarCodeImageFormat.Png); +} +catch (ArgumentException ex) +{ + Console.Error.WriteLine($"Data too long for MicroPdf417: {ex.Message}"); +} +``` + +Đối với payload lớn hơn, chuyển sang `EncodeTypes.Pdf417` đầy đủ hoặc `EncodeTypes.DataMatrix`. + +## Những lỗi thường gặp và cách tránh + +| Issue | Cause | Fix | +|-------------------------------------|-----------------------------------------|-----| +| Mã vạch xuất hiện mờ | XDimension quá thấp (ví dụ, 1 px) | Tăng `XDimension.Pixels` lên 2‑3 px | +| Ký tự Unicode hiển thị thành `?` | Mã hoá văn bản mặc định là ASCII | Đặt `TextEncoding = Encoding.UTF8` | +| Không tạo được file ảnh | Thư mục đầu ra không tồn tại | Dùng `Directory.CreateDirectory` trước `Save` | +| Máy quét không đọc được mã vạch | Quá nhiều cột cho dữ liệu ngắn | Giảm `Pdf417.Columns` (ví dụ, 3‑4) | + +## Toàn bộ mã nguồn (sẵn sàng sao chép) + +```csharp +using System; +using System.IO; +using System.Text; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create the generator – this is the core of "generate barcode from text" + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.MicroPdf417, + "Åspóse.Barcóde©" + ); + + // Ensure Unicode characters are handled correctly + generator.Parameters.Barcode.TextEncoding = Encoding.UTF8; + + // Optional: set a font that contains the required glyphs + generator.Parameters.Barcode.Font.FontFamily = "Arial Unicode MS"; + + // Configure visual appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 4; + + // Prepare output directory + string outputDir = Path.Combine(Environment.CurrentDirectory, "output"); + Directory.CreateDirectory(outputDir); + string outputPath = Path.Combine(outputDir, "MicroPdf417.png"); + + // Save the barcode image + try + { + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to: {outputPath}"); + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"Failed to generate barcode: {ex.Message}"); + } + } +} +``` + +**Kết quả mong đợi:** một file tên `MicroPdf417.png` nằm trong thư mục `output`, chứa mã vạch MicroPdf417 rõ ràng mã hoá chuỗi gốc với các ký tự đặc biệt. + +## Kết luận + +Bạn đã biết cách **generate barcode from text** trong C# bằng Aspose.BarCode, cách xử lý **barcode with special characters**, và cách **create pdf417 barcode c#** với kiểm soát đầy đủ các tùy chọn mã hoá. Bằng cách điều chỉnh **barcode encode types** bạn có thể tạo QR code, Code128, DataMatrix, hoặc bất kỳ định dạng nào được hỗ trợ. + +Tiếp theo, khám phá các chủ đề sau để nâng cao kiến thức về mã vạch: + +- **How to generate barcode** hàng loạt cho hàng ngàn bản ghi (sử dụng `Parallel.ForEach` để tăng tốc) +- Tùy chỉnh màu sắc và thêm logo vào trong mã vạch +- Tích hợp việc tạo mã vạch vào API ASP.NET Core để cung cấp ảnh ngay lập tức +- Sử dụng các thư viện khác như ZXing.Net hoặc IronBarcode cho các giải pháp mã nguồn mở + +Hãy thoải mái thử nghiệm với các kích thước, cài đặt cột và loại mã hoá khác nhau. Chúc bạn lập trình vui vẻ và ứng dụng của bạn luôn quét được một cách hoàn hảo! + +## Bạn Nên Học Gì Tiếp Theo? + +Các tutorial sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh với giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/vietnamese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md b/barcode/vietnamese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..51df081d0 --- /dev/null +++ b/barcode/vietnamese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-08-09 +description: Tạo mã vạch PDF417 trong C# nhanh chóng. Tìm hiểu cách tạo PDF417 với + chế độ nén, kiểm soát cột và xuất PNG bằng API BarcodeGenerator. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to generate pdf417 +- create pdf417 barcode c# +- barcode generator c# +- compact pdf417 settings +- pdf417 png output +language: vi +lastmod: 2026-08-09 +og_description: Tạo mã vạch PDF417 trong C# với một ví dụ ngắn gọn. Hướng dẫn này + chỉ cho bạn cách cấu hình chế độ compact, đặt số cột và lưu kết quả dưới dạng ảnh + PNG. +og_image_alt: Generated PDF417 barcode image saved as PNG +og_title: Tạo mã vạch PDF417 bằng C# – hướng dẫn đầy đủ +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: Generate PDF417 barcode in C# quickly. Learn how to generate PDF417 + with compact mode, column control, and PNG output using the BarcodeGenerator API. + headline: Generate PDF417 barcode in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- pdf417 +- C# +- Aspose.BarCode +title: Tạo mã vạch PDF417 trong C# – hướng dẫn từng bước +url: /vi/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo mã vạch PDF417 trong C# – hướng dẫn từng bước + +Nếu bạn cần **tạo mã vạch PDF417** trong một ứng dụng .NET, bài hướng dẫn này sẽ chỉ cho bạn cách thực hiện. Bạn sẽ thấy một chương trình đầy đủ, có thể chạy được, tạo một mã vạch PDF417 gọn gàng, tùy chỉnh kích thước và lưu hình ảnh dưới dạng file PNG. + +Việc tạo mã vạch PDF417 là yêu cầu phổ biến cho vé điện thoại di động, theo dõi tồn kho và bảo mật tài liệu. Hướng dẫn này bao gồm các tùy chọn cấu hình thiết yếu, giải thích lý do mỗi thiết lập quan trọng và cung cấp các mẹo thực tiễn cho việc sử dụng trong thực tế. + +## Yêu cầu trước + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +* .NET 6.0 SDK hoặc phiên bản mới hơn đã được cài đặt +* Một IDE C# như Visual Studio 2022 hoặc Visual Studio Code +* Gói **Aspose.BarCode for .NET** từ NuGet (phiên bản 23.10 hoặc mới hơn) + +Bạn có thể cài đặt gói bằng lệnh CLI sau: + +```bash +dotnet add package Aspose.BarCode +``` + +Mã dưới đây giả định rằng gói đã được tham chiếu và bạn có quyền ghi vào thư mục đầu ra. + +## Bước 1: Thiết lập dự án và nhập các namespace + +Tạo một dự án console mới và thêm các chỉ thị `using` cần thiết. Các namespace này cung cấp lớp `BarcodeGenerator` và kiểu liệt kê định dạng ảnh. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; +``` + +**Tại sao lại quan trọng:** Việc nhập đúng namespace giúp trình biên dịch tìm thấy kiểu `BarcodeGenerator` và enum `BarCodeImageFormat`. Thiếu namespace sẽ gây lỗi biên dịch, làm dừng quá trình tạo mã vạch. + +## Bước 2: Khởi tạo `BarcodeGenerator` với mã hoá PDF417 + +Constructor của `BarcodeGenerator` nhận hai đối số: loại mã vạch (`EncodeTypes.Pdf417`) và chuỗi bạn muốn mã hoá. PDF417 hỗ trợ một dải ký tự rộng, bao gồm các ký tự Unicode. + +```csharp +// Step 2: Create a PDF417 barcode generator with the desired text +var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +**Giải thích:** +* `EncodeTypes.Pdf417` báo cho thư viện sử dụng chuẩn PDF417. +* Văn bản mẫu chứa các ký tự có dấu và ký hiệu bản quyền để minh họa việc xử lý Unicode. + +Nếu bạn chỉ cần mã hoá dữ liệu số, có thể truyền một chuỗi đơn giản như `"1234567890"`. + +## Bước 3: Điều chỉnh X‑dimension để tăng độ phân giải + +X‑dimension kiểm soát độ rộng của một mô-đun mã vạch (phần tử đen hoặc trắng nhỏ nhất). Đặt giá trị pixel nhỏ hơn sẽ cho ra hình ảnh có độ phân giải cao hơn. + +```csharp +// Step 3: Adjust the module (X) dimension for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Tại sao cần điều chỉnh?** X‑dimension mặc định 3–4 pixel có thể tạo ra mã vạch trông thô trên màn hình DPI cao. Giảm xuống **2 pixel** giúp cân bằng giữa khả năng đọc và kích thước file, đặc biệt khi bạn bật chế độ gọn gàng. + +## Bước 4: Cấu hình số cột + +PDF417 cho phép bạn chỉ định số cột mà mã vạch sẽ chứa. Ít cột hơn làm mã vạch hẹp hơn nhưng cao hơn, trong khi nhiều cột hơn tạo ra mã vạch rộng hơn, thấp hơn. + +```csharp +// Step 4: Set the number of columns to control the barcode width +generator.Parameters.Barcode.Pdf417.Columns = 3; +``` + +**Mẹo thực tế:** Đối với vé di động cần vừa trong một nhãn hẹp, số cột **3–5** thường hoạt động tốt. Tăng số cột nếu bạn có nhiều dữ liệu và muốn mã vạch ngắn hơn. + +## Bước 5: Bật chế độ compact để cắt bỏ các hàng trống + +Chế độ compact loại bỏ các hàng không cần thiết khỏi ma trận mã vạch, giảm kích thước ảnh tổng thể mà không mất dữ liệu đã mã hoá. + +```csharp +// Step 5: Enable compact mode to truncate the barcode and reduce size +generator.Parameters.Barcode.Pdf417.Truncate = true; +``` + +**Khi nào nên dùng:** Nếu bạn tạo mã vạch để lưu trữ hoặc truyền qua mạng, chế độ compact có thể giảm kích thước file PNG tới 30 %. Tuy nhiên, một số máy quét cũ có thể không hỗ trợ PDF417 đã bị cắt; hãy kiểm tra với phần cứng mục tiêu của bạn. + +## Bước 6: Lưu mã vạch dưới dạng ảnh PNG + +Chọn đường dẫn đầu ra và gọi `Save`. Kiểu liệt kê `BarCodeImageFormat.Png` tạo ra ảnh không mất dữ liệu, phù hợp với hầu hết các ứng dụng. + +```csharp +// Step 6: Save the generated barcode as a PNG image +string outputPath = @"C:\Barcodes\CompactPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +**Xác minh kết quả:** Mở file PNG bằng bất kỳ trình xem ảnh nào. Bạn sẽ thấy một mã vạch dày đặc, độ tương phản cao, khớp với văn bản mẫu. Quét ảnh bằng trình đọc PDF417 (ví dụ: ZXing hoặc ứng dụng trên điện thoại) sẽ trả về chuỗi gốc `"Åspóse.Barcóde©"`. + +![Generated PDF417 barcode image saved as PNG](compact-pdf417.png "Generated PDF417 barcode in C#") + +*Hình ảnh trên minh họa kết quả cuối cùng của mã trong tutorial.* + +## Ví dụ đầy đủ, có thể chạy + +Kết hợp tất cả các phần lại, đây là một chương trình console hoàn chỉnh mà bạn có thể sao chép, dán và chạy. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.Image; + +namespace Pdf417GeneratorDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with PDF417 encoding + var generator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Fine‑tune module size for sharper output + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set a narrow column count to keep the barcode slim + generator.Parameters.Barcode.Pdf417.Columns = 3; + + // 4️⃣ Activate compact mode to drop empty rows + generator.Parameters.Barcode.Pdf417.Truncate = true; + + // 5️⃣ Define where the PNG will be written + string outputPath = @"C:\Barcodes\CompactPdf417.png"; + + // 6️⃣ Save the image + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath}"); + } + } +} +``` + +### Kết quả mong đợi + +Chạy chương trình sẽ in ra: + +``` +Barcode saved to C:\Barcodes\CompactPdf417.png +``` + +File `CompactPdf417.png` chứa một mã vạch PDF417 gọn gàng mã hoá chuỗi Unicode đã cung cấp. Quét ảnh bằng trình đọc PDF417 tiêu chuẩn sẽ trả về chính xác văn bản đó. + +## Các biến thể phổ biến và trường hợp đặc biệt + +| Tình huống | Điều chỉnh | Lý do | +|-----------|------------|--------| +| **Dữ liệu dài hơn** (ví dụ: > 150 ký tự) | Tăng `generator.Parameters.Barcode.Pdf417.Columns` lên 6‑8 | Thêm cột giúp mã vạch không trở nên quá cao. | +| **Cần nền trong suốt** | Dùng `generator.Save(outputPath, BarCodeImageFormat.Png, new ImageSaveOptions { BackgroundColor = Color.Transparent })` | PNG trong suốt dễ tích hợp hơn vào giao diện UI. | +| **Tạo JPEG cho web** | Thay đổi định dạng thành `BarCodeImageFormat.Jpeg` và tùy chọn `ImageQuality` | JPEG giảm kích thước file nhưng mất độ chính xác không mất dữ liệu. | +| **Xử lý đầu vào null hoặc rỗng** | Kiểm tra đầu vào trước khi tạo generator: `if (string.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty.");` | Ngăn lỗi thời gian chạy và đảm bảo mã vạch có ý nghĩa. | + +## Mẹo cho môi trường production + +* **Xử lý ngoại lệ:** Bao bọc logic tạo mã trong khối `try/catch` để ghi log lỗi như không đủ dung lượng đĩa hoặc tham số không hợp lệ. +* **Hiệu năng:** Tái sử dụng một thể hiện `BarcodeGenerator` duy nhất khi tạo nhiều mã vạch với cùng cài đặt; chỉ cập nhật thuộc tính `CodeText` giữa các lần lưu. +* **Bảo mật:** Khi văn bản đã mã hoá chứa thông tin nhạy cảm, cân nhắc mã hoá trước khi truyền vào generator và giải mã sau khi quét. + +## Kết luận + +Bây giờ bạn đã biết cách **tạo mã vạch PDF417** trong C# bằng thư viện Aspose.BarCode, cấu hình chế độ compact, điều chỉnh số cột và xuất kết quả dưới dạng ảnh PNG. Tutorial này đã bao phủ mọi bước từ thiết lập dự án đến xử lý các trường hợp đặc biệt, cung cấp cho bạn một giải pháp sẵn sàng sử dụng cho các ứng dụng dựa trên mã vạch. + +Tiếp theo, khám phá các chủ đề liên quan như **tạo mã QR trong C#**, **tạo hàng loạt mã vạch**, và **tích hợp quét mã vạch với ứng dụng di động**. Mỗi chủ đề đều dựa trên các nguyên tắc cơ bản của `BarcodeGenerator` mà bạn vừa nắm vững. + +Chúc lập trình vui vẻ! + +## Bạn nên học gì tiếp theo? + +Các tutorial sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã đầy đủ, kèm theo giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Cách tạo mã vạch PDF417 – Mã hoá PDF417 Compact](/barcode/english/net/compact-pdf417-encoding/) +- [Cách tạo mã vạch – PDF417 Compact với Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Cách tạo mã vạch Aztec với tỷ lệ khung tùy chỉnh bằng Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/vietnamese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md b/barcode/vietnamese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md new file mode 100644 index 000000000..92ed7cbaa --- /dev/null +++ b/barcode/vietnamese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-09 +description: Cách đọc PDF417 trong C# bằng BarCodeReader. Tìm hiểu cách đọc các tệp + PNG chứa mã vạch, xử lý nhiều mã vạch và trích xuất siêu dữ liệu mở rộng. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- c# barcode reader +- read multiple barcodes +- read barcode png +- read barcode extended +language: vi +lastmod: 2026-08-09 +og_description: Cách đọc PDF417 trong C# với Aspose.BarCode. Hướng dẫn này cho bạn + biết cách đọc các tệp PNG chứa mã vạch, xử lý nhiều mã vạch trong một hình ảnh và + truy xuất siêu dữ liệu PDF417 mở rộng. +og_image_alt: Screenshot of C# BarCodeReader console output displaying PDF417 metadata +og_title: Cách đọc PDF417 trong C# – hướng dẫn đọc mã vạch +schemas: +- author: Aspose + dateModified: '2026-08-09' + description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + headline: How to read PDF417 in C# – complete barcode reader guide + type: TechArticle +- description: How to read PDF417 in C# using the BarCodeReader. Learn to read barcode + PNG files, handle multiple barcodes, and extract extended metadata. + name: How to read PDF417 in C# – complete barcode reader guide + steps: + - name: Verify the file exists before creating the reader. + text: Verify the file exists before creating the reader. + - name: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + text: Use `Image.FromFile` only when you need to pre‑process (rotate, crop). The + `BarCodeReader` can open the file directly, which avoids extra memory allocation. + - name: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + text: If the PNG contains transparency, the reader still works because the barcode + is rendered on opaque pixels. + type: HowTo +tags: +- barcode +- C# +- PDF417 +title: Cách đọc PDF417 trong C# – hướng dẫn đầy đủ về trình đọc mã vạch +url: /vi/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-barcode-reader-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách đọc PDF417 trong C# – hướng dẫn đọc mã vạch hoàn chỉnh + +Nếu bạn cần **cách đọc PDF417** trong một ứng dụng .NET, hướng dẫn này cung cấp cho bạn một giải pháp sẵn sàng chạy. Bạn sẽ thấy cách đọc một mã vạch PNG, xử lý nhiều mã vạch trong cùng một hình ảnh, và lấy các trường PDF417 mở rộng mà nhiều máy quét ẩn. + +Việc đọc mã vạch PDF417 là phổ biến trong logistics, bán vé và quản lý tài liệu. Đến cuối hướng dẫn này, bạn có thể giải mã một hình ảnh Macro PDF417, hiển thị mọi kết quả, và sử dụng thông tin bổ sung (ID tệp, số đoạn, dấu thời gian, v.v.) trong logic kinh doanh của mình. + +## Yêu cầu trước + +- .NET 6.0 hoặc mới hơn (mã cũng hoạt động với .NET Framework 4.7+) +- Visual Studio 2022 hoặc bất kỳ IDE C# nào +- **Aspose.BarCode for .NET** (bản dùng thử miễn phí hoặc gói NuGet có bản quyền) +- Một hình ảnh PNG chứa mã vạch Macro PDF417 (tệp mẫu có tên `ExtPDF417Meta.png`) + +> **Mẹo:** Cài đặt thư viện bằng console NuGet: +> `dotnet add package Aspose.BarCode` + +## Cách đọc PDF417 với BarCodeReader trong C# + +Lõi của giải pháp là lớp `BarCodeReader`. Nó nhận một đường dẫn hình ảnh và một enum `DecodeType` cho biết engine nên tìm kiếm ký hiệu nào. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.ReadEngine; + +class Pdf417Demo +{ + static void Main() + { + // Step 1: Create a BarCodeReader for a Macro PDF417 image + using (BarCodeReader reader = new BarCodeReader( + "YOUR_DIRECTORY/ExtPDF417Meta.png", + DecodeType.MacroPdf417)) + { + // Step 2: Read all barcodes from the image + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // Step 3: Output basic barcode information + Console.WriteLine($"CodeType: {result.CodeTypeName}"); + Console.WriteLine($"CodeText: {result.CodeText}"); + + // Step 4: Display Macro PDF417 extended metadata + Console.WriteLine($"Pdf417MacroFileID: {result.Extended.Pdf417.MacroPdf417FileID}"); + Console.WriteLine($"Pdf417MacroSegmentID: {result.Extended.Pdf417.MacroPdf417SegmentID}"); + Console.WriteLine($"Pdf417MacroSegmentsCount: {result.Extended.Pdf417.MacroPdf417SegmentsCount}"); + Console.WriteLine($"Pdf417MacroFileName: {result.Extended.Pdf417.MacroPdf417FileName}"); + Console.WriteLine($"Pdf417MacroChecksum: {result.Extended.Pdf417.MacroPdf417Checksum}"); + Console.WriteLine($"Pdf417MacroFileSize: {result.Extended.Pdf417.MacroPdf417FileSize}"); + Console.WriteLine($"Pdf417MacroTimeStamp: {result.Extended.Pdf417.MacroPdf417TimeStamp}"); + Console.WriteLine($"Pdf417MacroAddressee: {result.Extended.Pdf417.MacroPdf417Addressee}"); + Console.WriteLine($"Pdf417MacroSender: {result.Extended.Pdf417.MacroPdf417Sender}"); + Console.WriteLine($"MacroPdf417Terminator: {result.Extended.Pdf417.MacroPdf417Terminator}"); + Console.WriteLine(new string('-', 40)); + } + } + } +} +``` + +### Tại sao cách này hoạt động + +- **`DecodeType.MacroPdf417`** cho biết bộ đọc nên tìm kiếm biến thể Macro PDF417, vốn lưu trữ các trường bổ sung mà bạn thấy ở bước 4. +- Khối `using` sẽ tự động giải phóng bộ đọc, giải phóng các handle tệp. +- `ReadBarCodes()` trả về **tất cả** các mã vạch khớp với loại được yêu cầu, đáp ứng yêu cầu *đọc nhiều mã vạch* ngay cả khi hình ảnh chỉ chứa một mã. + +Chạy chương trình sẽ in ra đầu ra tương tự như: + +``` +CodeType: MacroPdf417 +CodeText: 1234567890 +Pdf417MacroFileID: 1 +Pdf417MacroSegmentID: 0 +Pdf417MacroSegmentsCount: 3 +Pdf417MacroFileName: invoice_2023.pdf +Pdf417MacroChecksum: 0x1A2B +Pdf417MacroFileSize: 254321 +Pdf417MacroTimeStamp: 2023-03-15T10:45:00Z +Pdf417MacroAddressee: ACME Corp. +Pdf417MacroSender: Warehouse 7 +MacroPdf417Terminator: True +---------------------------------------- +``` + +## Sử dụng bộ đọc mã vạch C# để đọc nhiều mã vạch + +Nếu một hình ảnh chứa nhiều ký hiệu Macro PDF417 (ví dụ, một trang quét với một loạt vé), vòng lặp `foreach` giống nhau sẽ xử lý từng ký hiệu. Không cần mã bổ sung; bộ đọc sẽ tổng hợp kết quả nội bộ. + +```csharp +// Example: processing a batch image +using (BarCodeReader batchReader = new BarCodeReader( + "batch.png", DecodeType.MacroPdf417)) +{ + int index = 0; + foreach (BarCodeResult item in batchReader.ReadBarCodes()) + { + Console.WriteLine($"--- Barcode #{++index} ---"); + Console.WriteLine($"Text: {item.CodeText}"); + // extended fields are accessed the same way + } +} +``` + +### Những cạm bẫy thường gặp + +- **Định dạng ảnh:** Bộ đọc hỗ trợ PNG, JPEG, BMP và TIFF. Nếu bạn thử một định dạng mà nó không thể giải mã, bạn sẽ nhận được một bộ sưu tập rỗng. Đó là lý do tại sao hướng dẫn nhấn mạnh *đọc mã vạch PNG*. +- **Độ phân giải:** Ảnh độ phân giải thấp (< 300 dpi) có thể gây mất các đoạn. Hãy tăng độ phân giải hoặc yêu cầu quét chất lượng cao hơn khi có thể. +- **Cờ Macro:** Quên `DecodeType.MacroPdf417` sẽ giới hạn engine chỉ đọc PDF417 thông thường và loại bỏ dữ liệu mở rộng. Luôn chỉ định loại macro khi bạn cần các trường *đọc mã vạch mở rộng*. + +## Đọc tệp PNG chứa mã vạch – các thực hành tốt nhất + +Làm việc với tệp PNG rất đơn giản vì định dạng này giữ nguyên dữ liệu pixel không mất mát. Dưới đây là danh sách kiểm tra nhanh: + +1. Xác minh tệp tồn tại trước khi tạo bộ đọc. + ```csharp + if (!File.Exists(path)) + throw new FileNotFoundException($"File not found: {path}"); + ``` +2. Sử dụng `Image.FromFile` chỉ khi bạn cần tiền xử lý (xoay, cắt). `BarCodeReader` có thể mở tệp trực tiếp, tránh việc cấp phát bộ nhớ thêm. +3. Nếu PNG có độ trong suốt, bộ đọc vẫn hoạt động vì mã vạch được hiển thị trên các pixel không trong suốt. + +## Truy cập siêu dữ liệu PDF417 mở rộng + +Đối tượng `Extended.Pdf417` cung cấp mọi trường tùy chọn được định nghĩa trong đặc tả PDF417. Bạn có thể ánh xạ các trường này vào mô hình miền, lưu chúng vào cơ sở dữ liệu, hoặc sử dụng để xác thực. + +```csharp +public class Pdf417Metadata +{ + public int FileID { get; set; } + public int SegmentID { get; set; } + public int SegmentsCount { get; set; } + public string FileName { get; set; } + public string Checksum { get; set; } + public long FileSize { get; set; } + public DateTime TimeStamp { get; set; } + public string Addressee { get; set; } + public string Sender { get; set; } + public bool Terminator { get; set; } +} +``` + +Điền dữ liệu vào mô hình: + + + +## Bạn nên học gì tiếp theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh với giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Cách đọc mã DataMatrix với Aspose.BarCode cho .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Cách tạo mã vạch – Compact PDF417 với Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Đọc mã DataMatrix C# – Tạo chế độ DataMatrix (Tự động)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-auto/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file