diff --git a/barcode/arabic/net/compact-pdf417-encoding/_index.md b/barcode/arabic/net/compact-pdf417-encoding/_index.md index 6b447ecb2..c09bd1cf4 100644 --- a/barcode/arabic/net/compact-pdf417-encoding/_index.md +++ b/barcode/arabic/net/compact-pdf417-encoding/_index.md @@ -84,6 +84,13 @@ PDF417 المدمج هو رمز ثنائي الأبعاد عالي السعة ي ## دروس ترميز PDF417 المدمج ### [إنشاء باركودات PDF417 المدمجة](./compact-pdf417-basic-configuration/) تعلم كيفية إنشاء باركودات PDF417 المدمجة باستخدام Aspose.BarCode for .NET. دليل شامل مع تعليمات خطوة بخطوة وأمثلة شفرة. +### [إنشاء بيانات تعريف الباركود PDF417 في C# – دليل خطوة بخطوة كامل](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +تعلم كيفية إنشاء بيانات تعريف الباركود PDF417 في C# عبر دليل شامل خطوة بخطوة. +### [إنشاء باركود PDF417 في C# – دليل كامل](./generate-pdf417-barcode-in-c-complete-guide/) +دليل شامل لإنشاء باركود PDF417 في C# خطوة بخطوة باستخدام Aspose.BarCode. +### [إنشاء باركود PDF417 في C# – دليل كامل خطوة بخطوة](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +دليل شامل يشرح خطوة بخطوة كيفية إنشاء باركود PDF417 في C# باستخدام Aspose.BarCode. +### [كيفية قراءة PDF417 في C# – دليل خطوة بخطوة كامل](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) ## الأسئلة المتكررة @@ -113,4 +120,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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/arabic/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..337513b09 --- /dev/null +++ b/barcode/arabic/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-07-15 +description: إنشاء بيانات تعريف الباركود PDF417 في C# باستخدام Aspose.BarCode. تعلم + إعدادات Macro PDF417، حفظه كملف PNG، ومعالجة النص Unicode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: ar +lastmod: 2026-07-15 +og_description: إنشاء بيانات تعريف شيفرة PDF417 في C# باستخدام Aspose.BarCode. يوضح + هذا الدليل جميع الإعدادات التي تحتاجها لتضمين معرف الملف، والطوابع الزمنية، وأكثر. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: إنشاء بيانات تعريف الباركود PDF417 في C# – دليل برمجي كامل +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: إنشاء بيانات تعريف باركود PDF417 في C# – دليل خطوة بخطوة كامل +url: /ar/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء بيانات تعريف شيفرة PDF417 في C# – دليل خطوة‑بخطوة كامل + +هل احتجت يوماً إلى **إنشاء بيانات تعريف شيفرة PDF417** في C# لكن لم تكن متأكدًا من الخصائص التي يجب تعديلها؟ لست وحدك—غالبًا ما يواجه المطورون صعوبة عندما يتطلب المعيار أشياء مثل معرفات الملفات، عدد القطع، أو طوابع زمنية مخصصة. + +الخبر السار هو أن Aspose.BarCode يجعل ذلك سهلًا للغاية. في هذا الدرس سننشئ كائن `BarcodeGenerator` لـ **Macro PDF417**، نضيف جميع البيانات التعريفية المهمة، ثم نحفظ النتيجة كصورة PNG. في النهاية ستحصل على شيفرة كاملة الميزات جاهزة لأي نظام سلاسل إمداد أو إدارة مستندات. + +## ما يغطيه هذا الدليل + +سنستعرض: + +1. إعداد حزمة NuGet الخاصة بـ Aspose.BarCode. +2. تهيئة `BarcodeGenerator` لـ **Macro PDF417**. +3. تعبئة كل **حقل بيانات تعريف الشيفرة** المفيد (معرف الملف، معرف القطعة، المجموع الاختباري، إلخ). +4. حفظ الشيفرة على القرص والتحقق من النتيجة. + +لا تحتاج إلى خبرة مسبقة في Macro PDF417—فقط معرفة أساسية بـ C# وبيئة .NET حديثة. + +لماذا يهمك ذلك؟ إدراج بيانات تعريف غنية مباشرة داخل الشيفرة يتيح للماسحات اللاحقة التحقق من نقل الملفات بالكامل، اكتشاف القطع المفقودة، أو حتى تشغيل سير عمل تلقائي. بعبارة أخرى، تحصل على **بيانات ذاتية الوصف قوية** دون الحاجة إلى قاعدة بيانات منفصلة. + +## المتطلبات المسبقة + +- .NET 6.0 أو أحدث (الكود يعمل أيضًا على .NET Framework 4.7+). +- Visual Studio 2022 (أو أي بيئة تطوير تفضلها). +- حزمة **Aspose.BarCode for .NET** من NuGet (يتوفر نسخة تجريبية مجانية). + +يمكنك تثبيت الحزمة بالأمر التالي: + +```bash +dotnet add package Aspose.BarCode +``` + +الآن بعد أن أعددنا الأساس، لننتقل إلى التنفيذ الفعلي. + +## الخطوة 1: تهيئة BarcodeGenerator لـ Macro PDF417 + +أول شيء نحتاجه هو كائن `BarcodeGenerator` مُعد لـ **Macro PDF417**. هذا يخبر Aspose.BarCode أي خوارزمية ترميز يستخدمه ويمنحنا مكانًا لإدخال النص القابل للقراءة البشرية. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **لماذا هذا مهم:** `EncodeTypes.MacroPdf417` يُفعِّل وضع PDF417 الموسع الذي يدعم بيانات تعريف مثل معرفات الملفات وأرقام القطع. يحتوي النص التجريبي على أحرف Unicode (`Å`, `ó`, `©`) لإثبات أن المُولِّد يتعامل مع الإدخال غير ASCII بسلاسة. + +## الخطوة 2: تعريف مظهر الشيفرة الأساسي + +قبل أن نضيف البيانات التعريفية، يجب ضبط بعض المعلمات البصرية حتى لا تكون الشيفرة نقطة دقيقة. يتحكم `XDimension` في عرض الوحدة، بينما يؤثر `Columns` على الشكل العام. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **نصيحة احترافية:** عرض بكسل قدره `2` يعمل جيدًا للعرض على الشاشة ومعظم الطابعات. إذا احتجت طباعة بدقة أعلى، زد القيمة إلى `3` أو `4`. + +## الخطوة 3: تعبئة حقول بيانات تعريف Macro PDF417 + +الآن يأتي جوهر الدرس—إضافة **حقول بيانات تعريف الشيفرة**. كل خاصية تُطابق مباشرةً جزءًا من مواصفات Macro PDF417. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### ما تقوم به كل خاصية + +| الخاصية | الغرض | القيمة النموذجية | +|----------|---------|---------------| +| **MacroPdf417FileID** | معرف فريد عالمي لمجموعة الملفات بالكامل. | `12345678` | +| **MacroPdf417SegmentID** | فهرس القطعة الحالية (يبدأ من `0`). | `12` | +| **MacroPdf417SegmentsCount** | إجمالي عدد القطع المتوقعة للملف. | `20` | +| **MacroPdf417FileName** | اسم قابل للقراءة البشرية، غالبًا اسم الملف الأصلي. | `"file01"` | +| **MacroPdf417Checksum** | مجموع اختباري 16‑بت CCITT لاكتشاف الأخطاء. | `1234` | +| **MacroPdf417FileSize** | حجم الملف الأصلي بالبايت. | `400000` | +| **MacroPdf417TimeStamp** | وقت إنشاء الملف. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | حقل اختياري يشير إلى الوجهة. | `"street"` | +| **MacroPdf417Sender** | حقل اختياري يشير إلى نظام المصدر. | `"aspose"` | +| **MacroPdf417Terminator** | علامة تخبر الماسح أن هذه هي القطعة النهائية. | `Pdf417MacroTerminator.Set` | + +> **لماذا تحتاج هذه الحقول:** الماسحات التي تدعم Macro PDF417 يمكنها إعادة تجميع ملف متعدد القطع، التحقق من سلامته باستخدام المجموع الاختباري، وحتى رفض البيانات القديمة بناءً على الطابع الزمني. هذا يلغي الحاجة إلى ملف دليل منفصل. + +## الخطوة 4: حفظ صورة الشيفرة + +بعد ضبط جميع المعلمات، نكتفي باستدعاء `Save`. المثال يكتب ملف PNG إلى المجلد الذي تحدده. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **حالة خاصة:** إذا كنت تخطط لإدراج الشيفرة في ملف PDF لاحقًا، قد تفضّل `BarCodeImageFormat.Jpeg` أو `Pdf`. PNG يحافظ على التفاصيل بدون فقد، وهو مفيد للتحقق. + +## مثال كامل يعمل + +بتجميع كل ما سبق، إليك البرنامج الكامل الذي يمكنك نسخه‑ولصقه في تطبيق Console: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### النتيجة المتوقعة + +عند تشغيل البرنامج يُنشئ ملفًا باسم **ExtPDF417Meta.png** في مجلد التنفيذ. افتحه بأي عارض صور وسترى شيفرة PDF417 كثيفة وعالية التباين. إذا قمت بمسحها باستخدام قارئ شيفرات يدعم Macro PDF417، سيُظهر القارئ قيم البيانات التعريفية التي ضبطناها—معرف الملف `12345678`، القطعة `12` من `20`، وما إلى ذلك. + +## أسئلة شائعة ومخاطر محتملة + +- **ماذا لو ظهرت الشيفرة غير واضحة؟** زد `XDimension.Pixels` أو استخدم صيغة صورة ذات دقة أعلى. +- **هل يجب ضبط كل حقل بيانات تعريف؟** لا. فقط الحقول المطلوبة من نظامك اللاحق هي الضرورية. يمكن ترك الحقول غير المستخدمة بقيمها الافتراضية. +- **هل يمكن توليد ملف متعدد القطع تلقائيًا؟** نعم—استخدم حلقة لتكرار البيانات، زد `MacroPdf417SegmentID`، وأنشئ شيفرة منفصلة لكل قطعة. تذكّر أن تحافظ على `MacroPdf417FileID` ثابتًا عبر جميع القطع. +- **هل يدعم Unicode؟** بالتأكيد. النص التجريبي يحتوي على `Å`، `ó`، و `©`، مما يوضح أن Aspose.BarCode يتعامل مع UTF‑8 مباشرة. + +## الخطوات التالية: ما بعد الأساسيات + +الآن بعد أن عرفت كيفية **إنشاء بيانات تعريف شيفرة PDF417**، قد ترغب في استكشاف: + +- **إدراج الشيفرات في ملفات PDF** باستخدام `Aspose.Pdf` لإنشاء مستندات شاملة من البداية إلى النهاية. +- **قراءة البيانات التعريفية** باستخدام `BarcodeReader` للتحقق من المسحات برمجيًا. +- **تخصيص الألوان** (الخلفية/المقدمة) لأغراض العلامة التجارية. +- **التكامل مع قاعدة بيانات** لتعبئة الحقول تلقائيًا مثل `FileID` أو `Timestamp`. + +جميع هذه المواضيع ترتبط بكلماتنا المفتاحية الثانوية—**macro pdf417**، **aspose barcode c#**، **barcode metadata fields**، و **c# barcode generation**—لذلك ستجد الكثير من المواد لتستمر في التعلم. + +## الخلاصة + +لقد استعرضنا مثالًا كاملاً وجاهزًا للإنتاج حول كيفية **إنشاء بيانات تعريف شيفرة PDF417** في C#. من تثبيت Aspose.BarCode، تهيئة `BarcodeGenerator`، ملء كل **حقل بيانات تعريف الشيفرة** ذي الصلة، إلى حفظ صورة PNG واضحة، العملية بسيطة بمجرد معرفة الخصائص الصحيحة. + +جرّبها، عدّل القيم، ولاحظ رد فعل الماسحات. مرونة Macro PDF417 تسمح لك بدمج كل ما يحتاجه النظام اللاحق—كل ذلك داخل صورة واحدة قابلة للمسح. برمجة سعيدة، ولتكون شيفراتك دائمًا خالية من الأخطاء! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة كود كاملة مع شروحات خطوة‑بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java barcode library – Add barcode to PDF using Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/arabic/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..430955986 --- /dev/null +++ b/barcode/arabic/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: قم بإنشاء رمز شريطي PDF417 بسرعة وتعلم كيفية ضبط الأعمدة للحصول على صورة + رمز PDF417 مضغوطة في C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: ar +lastmod: 2026-07-15 +og_description: إنشاء رمز شريطي PDF417 باستخدام Aspose.BarCode وتعلم كيفية ضبط الأعمدة + لإنشاء صورة رمز شريطي PDF417 مدمجة. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: إنشاء باركود PDF417 في C# – دليل خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: إنشاء رمز شريطي PDF417 في C# – دليل كامل +url: /ar/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء رمز شريطي PDF417 في C# – دليل كامل + +هل احتجت يوماً إلى **إنشاء رمز شريطي PDF417** في مشروع .NET لكنك لم تكن متأكدًا من أين تبدأ؟ أنت لست وحدك. في العديد من تطبيقات الشركات—مثل طابعات بطاقات الصعود، بطاقات المخزون، أو التذاكر المحمولة—PDF417 هو العامل الأساسي الذي يضع الكثير من البيانات في مساحة بصرية صغيرة. + +الأمر هو أن مكتبة Aspose.BarCode تجعل العملية بأكملها شبه خالية من المتاعب، ويمكنك حتى التحكم في **كيفية ضبط الأعمدة** بحيث يصبح الرمز الشريطي مضغوطًا قدر الإمكان. بنهاية هذا الدرس ستحصل على صورة PNG جاهزة للاستخدام ل**صورة رمز شريطي PDF417** يمكنك إدراجها في أي واجهة مستخدم، بريد إلكتروني، أو مهمة طباعة. + +## ما ستحصل عليه + +- تطبيق وحدة تحكم C# كامل الوظائف ينشئ رمز شريطي PDF417. +- فهم واضح لـ *X‑Dimension* (حجم الوحدة) ولماذا هو مهم. +- تعليمات خطوة بخطوة حول **كيفية ضبط الأعمدة** للحصول على رمز شريطي أكثر إحكامًا. +- ملف `PNG` محفوظ يمكنك فتحه فورًا للتحقق من النتيجة. +- نصائح لحل المشكلات الشائعة (مثل الرموز غير القابلة للقراءة، تنسيق الصورة الخاطئ). + +> **المتطلبات المسبقة** – .NET 6+ SDK، Visual Studio 2022 (أو أي محرر تفضله)، وإشارة NuGet إلى `Aspose.BarCode`. لا شيء آخر. + +--- + +## الخطوة 1: تثبيت حزمة Aspose.BarCode عبر NuGet + +قبل أن نتمكن من *إنشاء رمز شريطي PDF417*، يجب أن تكون المكتبة موجودة في المشروع. + +```bash +dotnet add package Aspose.BarCode +``` + +هذا السطر الواحد يجلب جميع الأنواع التي ستحتاجها، بما في ذلك `BarcodeGenerator`، `EncodeTypes`، و`BarCodeImageFormat` enum. + +> **نصيحة احترافية:** إذا كنت تستهدف .NET Framework بدلاً من .NET 6، استخدم الأمر الكلاسيكي `Install-Package Aspose.BarCode` في PowerShell داخل وحدة تحكم مدير الحزم. + +--- + +## الخطوة 2: إنشاء تطبيق وحدة تحكم بسيط + +لنقم بإنشاء برنامج صغير لا يفعل سوى إنتاج رمز شريطي. افتح مجلدًا جديدًا، شغّل `dotnet new console`، ثم استبدل ملف `Program.cs` الذي تم إنشاؤه تلقائيًا بالكود أدناه. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**لماذا هذا مهم:** +- `EncodeTypes.Pdf417` يخبر المكتبة أننا نريد رمز شريطي PDF417، وليس QR أو Code128. +- `XDimension.Pixels` يتحكم في دقة كل وحدة سوداء أو بيضاء صغيرة. +- كتلة **كيفية ضبط الأعمدة** تؤثر مباشرة على شكل **صورة رمز شريطي PDF417**. +- `Truncate = true` يزيل أي صفوف فارغة غير ضرورية، مما يمنحك المظهر “المضغوط” الذي تحبه العديد من القارئات. + +--- + +## الخطوة 3: الغوص أعمق – فهم الأعمدة والاقتطاع + +### كيفية ضبط الأعمدة + +PDF417 يرتب البيانات في مصفوفة من *الصفوف* × *الأعمدة*. المكتبة تستخدم افتراضيًا 5 أعمدة، وهو ما يناسب معظم الحالات. ومع ذلك، قد تحتاج إلى رمز شريطي أضيق ليتناسب مع ملصق أو أوسع لتحسين موثوقية القراءة. الخاصية: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +تقبل قيمًا من **1** إلى **30** (الحد الأقصى يعتمد على طول البيانات). إليك ورقة غش سريعة: + +| الأعمدة | العرض التقريبي (مم) | متى يستخدم | +|---------|-------------------|-------------| +| 1‑3 | ضيق جدًا | ملصق صغير، مساحة محدودة | +| 4‑6 | قياسي | معظم الإيصالات، التذاكر | +| 7‑10 | أوسع | بيانات عالية الكثافة، قراءة أفضل | + +### اقتطاع (الوضع المضغوط) + +ضبط `Truncate = true` يخبر المشفر بقطع أي صفوف فارغة غير ضرورية في الأسفل. النتيجة هي **صورة رمز شريطي PDF417 مضغوطة** تشغل أصغر مساحة ممكنة مع احتفاظها بجميع البيانات. إذا صادفت أخطاء “الرمز الشريطي كبير جدًا للملصق”، قم بتبديل هذه العلامة. + +--- + +## الخطوة 4: تشغيل التطبيق والتحقق من النتيجة + +Compile and execute: + +```bash +dotnet run +``` + +يجب أن ترى رسالة في وحدة التحكم تؤكد موقع الحفظ. انتقل إلى المجلد وافتح `CompactPdf417.png`. ستشبه الصورة ما يلي: + +![صورة رمز شريطي PDF417 تم إنشاؤها](./CompactPdf417.png "صورة رمز شريطي PDF417 – PNG مضغوط تم إنشاؤه بواسطة Aspose.BarCode") + +*نص بديل للصورة:* **صورة رمز شريطي PDF417 تم إنشاؤها** – ملف PNG مضغوط تم إنتاجه بواسطة كود الدرس. + +إذا كان الماسح الخاص بك يستطيع قراءتها، تهانينا—لقد نجحت في **إنشاء رمز شريطي PDF417** وتقنت **كيفية ضبط الأعمدة** للحصول على **صورة رمز شريطي PDF417** مرتبة. + +--- + +## الخطوة 5: المشكلات الشائعة وكيفية إصلاحها + +| العَرَض | السبب المحتمل | الحل السريع | +|---------|--------------|-----------| +| الرمز الشريطي يبدو ضبابيًا | `XDimension.Pixels` منخفض جدًا (مثلاً 1) | ارتقِ إلى 2‑3 بكسل للحصول على صورة أوضح. | +| الماسح لا يستطيع القراءة | عدد الأعمدة كبير جدًا بالنسبة للبيانات | قلل `Columns` أو فعّل `Truncate`. | +| تنسيق الملف غير صحيح | تم حفظه بـ `BarCodeImageFormat.Jpeg` عن طريق الخطأ | استخدم `BarCodeImageFormat.Png` للحصول على نتائج بلا فقد. | +| استثناء `ArgumentOutOfRangeException` | عدد الأعمدة يتجاوز النطاق المسموح | حافظ على الأعمدة بين 1‑30 وتأكد من أن البيانات تناسب. | + +--- + +## الخطوة 6: المضي قدمًا – تخصيص الألوان وإضافة نص + +إذا رغبت في جعل الرمز الشريطي يتطابق مع لوحة ألوان العلامة التجارية، يمكنك تعديل ألوان المقدمة والخلفية: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +أو إضافة نص قابل للقراءة البشرية أسفل الرمز الشريطي: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +هذه الإضافات اختيارية، لكنها توضح مدى مرونة سير عمل **إنشاء رمز شريطي PDF417**. + +--- + +## الخلاصة + +لقد استعرضنا مثالًا كاملاً من البداية إلى النهاية يوضح **إنشاء رمز شريطي PDF417** باستخدام Aspose.BarCode، وشرحنا **كيفية ضبط الأعمدة** للتحكم في أبعاد الرمز الشريطي، وحفظنا النتيجة كـ **صورة رمز شريطي PDF417** واضحة بصيغة PNG. الكود مستقل، يعمل مع .NET 6+، ويمكن إدراجه في أي مشروع موجود بأقل جهد. + +ما التالي؟ جرّب ترميز حمولات أكبر (مثل حمولات JSON)، جرب صيغ صور مختلفة، أو دمج المولد في واجهة ويب API تقدم الرموز الشريطية عند الطلب. السماء هي الحد، ولديك الآن أساس قوي للبناء عليه. + +برمجة سعيدة، ولتكن رموزك الشريطية دائمًا تُقرأ من المحاولة الأولى! + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مصدر يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية إنشاء رمز شريطي – PDF417 مضغوط باستخدام Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [كيفية إنشاء صورة رمز شريطي في Java باستخدام Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [إنشاء رمز شريطي Java – ضبط دقة الصورة باستخدام Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/arabic/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..a33bc58bd --- /dev/null +++ b/barcode/arabic/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,200 @@ +--- +category: general +date: 2026-07-15 +description: إنشاء رمز شريطي PDF417 بسرعة باستخدام C#. تعلّم كيفية إنشاء الرمز الشريطي + من النص، وضبط حجمه، وتحديد أبعاد مخصصة له في دقائق. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: ar +lastmod: 2026-07-15 +og_description: إنشاء رمز شريطي PDF417 في C# على الفور. يوضح هذا الدليل كيفية إنشاء + الرمز الشريطي من النص، وضبط حجم الرمز الشريطي، وتطبيق أبعاد مخصصة للرمز الشريطي. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: إنشاء رمز شريطي PDF417 في C# – دليل برمجي كامل +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: إنشاء باركود PDF417 في C# – دليل كامل خطوة بخطوة +url: /ar/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء شيفرة باركود PDF417 في C# – دليل كامل خطوة بخطوة + +هل احتجت يوماً إلى **إنشاء شيفرة باركود PDF417** لكن لم تكن متأكدًا من الإعدادات التي يجب تعديلها؟ لست وحدك—العديد من المطورين يواجهون نفس المشكلة عندما يتعاملون لأول مرة مع الباركود ثنائي الأبعاد. الخبر السار؟ ببضع أسطر من C# يمكنك تحويل أي سلسلة إلى صورة PDF417 قابلة للمسح، والتحكم في حجمها الدقيق، وحتى تعريف تخطيط مخصص للأعمدة والصفوف. + +في هذا الدرس سنستعرض كيفية **إنشاء شيفرة باركود من نص**، تعديل حجم الباركود، وتحديد أبعاد مخصصة للباركود — كل ذلك باستخدام مكتبة Aspose.BarCode الشهيرة. في النهاية ستحصل على مثال جاهز للتنفيذ يمكنك إدراجه في أي مشروع .NET. + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## ما ستقوم بإنشائه + +- شيفرة باركود PDF417 تشفر السلسلة `Åspóse.Barcóde©`. +- تحكم دقيق في البُعد X (عرض البكسل لكل وحدة). +- تخطيط مخصص من 4 أعمدة و9 صفوف. +- ملف PNG محفوظ على القرص. + +بدون خدمات خارجية، بدون حيل سحرية—فقط كود C# بسيط يمكنك تجميعه الآن. + +## المتطلبات المسبقة + +- .NET 6.0 أو أحدث (الكود يعمل أيضاً على .NET Framework 4.8). +- Visual Studio 2022 أو أي بيئة تطوير تدعم C#. +- Aspose.BarCode لـ .NET (نسخة تجريبية مجانية أو مرخصة). التثبيت عبر NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +هذا كل شيء—بمجرد الإشارة إلى الحزمة يمكنك المتابعة. + +## الخطوة 1 – إنشاء شيفرة باركود PDF417 ببيانات نصية + +أول شيء نحتاجه هو إنشاء كائن `BarcodeGenerator` يعرف أننا نتعامل مع رموز PDF417 والنص الدقيق الذي نريد تشفيره. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **لماذا هذا مهم:** +> `EncodeTypes.Pdf417` يخبر المكتبة باستخدام تنسيق PDF417 ثنائي الأبعاد، بينما الوسيط الثاني هو الحمولة الخاصة بـ **إنشاء شيفرة باركود من نص**. أي شيء تمرره هنا يصبح البيانات المخزنة في مصفوفة الباركود. + +## الخطوة 2 – تعديل حجم الباركود (البُعد X) + +إذا طُبعت شيفرة باركود صغيرة جدًا على إيصال، فأنت تعرف الإحباط عندما لا يلتقطها القارئ. خاصية `XDimension` تتحكم في عرض الوحدة الواحدة (أصغر مربع أسود أو أبيض) بالبكسل. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **نصيحة احترافية:** +> قيمة 2 px تعمل جيدًا لمعظم سيناريوهات العرض على الشاشة. للطباعة عالية الدقة قد ترفعها إلى 3 أو 4 px. فقط تذكر أن زيادة البُعد X يزيد من حجم الصورة الكلي. + +## الخطوة 3 – تحديد أبعاد مخصصة للباركود (الأعمدة والصفوف) + +PDF417 يسمح لك بتحديد عدد الأعمدة والصفوف التي سيشغلها الباركود. هنا يأتي دور **الأبعاد المخصصة للباركود**. تعديل هذه القيم يمكن أن يساعدك على ملاءمة الباركود في مساحة واجهة مستخدم ضيقة أو لتلبية حجم ملصق معين. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **ما الذي يحدث خلف الكواليس؟** +> المكتبة تعيد توزيع البيانات المشفرة عبر الشبكة المحددة. عدد أقل من الأعمدة يعني باركود أطول؛ عدد أكبر من الصفوف يجعلها أقصر. جرب الأرقام حتى تحصل على التوازن البصري المناسب لتطبيقك. + +## الخطوة 4 – حفظ صورة الباركود + +الآن بعد أن قمنا بإعداد كل شيء، نطلب من المولد كتابة ملف PNG. PNG غير مضغوط، لذا يبقى وضوح الوحدات محفوظًا. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +عند تشغيل البرنامج، يجب أن ترى ملفًا في `C:\Barcodes\CustomLayout.png` يشبه اللقطة أعلاه. مسحه بأي قارئ يدعم PDF417 سيعيد السلسلة الأصلية `Åspóse.Barcóde©`. + +## مثال كامل يعمل + +فيما يلي البرنامج الكامل الذي يمكنك نسخه ولصقه في تطبيق كونسول. يتضمن جميع توجيهات `using` ومعالجة الأخطاء التي تتوقعها في كود إنتاجي. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### النتيجة المتوقعة + +تشغيل الكود يطبع: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…وينشئ ملف PNG يمكن فتحه في أي عارض صور. إذا قمت بمسحه باستخدام تطبيق هاتف محمول (مثل “Barcode Scanner” على iOS/Android)، يجب أن يكون النص المفكك هو بالضبط **Åspóse.Barcóde©**. + +## أسئلة شائعة وحالات خاصة + +| السؤال | الجواب | +|----------|--------| +| **هل يمكنني استخدام تنسيق صورة مختلف؟** | نعم—`BarCodeImageFormat.Jpeg`، `Bmp`، `Gif` أو `Svg` كلها مدعومة. فقط غيّر الوسيط الثاني في `Save`. | +| **ماذا لو كان نصي يحتوي على أحرف Unicode؟** | Aspose.BarCode يدعم UTF‑8 بالكامل، لذا المثال مع `Å` و `©` يعمل مباشرةً. | +| **كيف يمكنني تغيير مستوى تصحيح الأخطاء؟** | استخدم `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (المستويات 0‑8). المستويات الأعلى تزيد من التكرار ولكنها تزيد أيضًا الحجم. | +| **أحتاج خلفية شفافة—هل يمكن ذلك؟** | قم بتعيين `generator.Parameters.Barcode.Image.TransparentBackground = true;` قبل الحفظ. | +| **هل هناك طريقة لإدراج الباركود مباشرةً في ملف PDF؟** | بالطبع. استبدل استدعاء `Save` بـ `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` وستحصل على ملف PDF من صفحة واحدة يحتوي على الباركود. | + +## الخلاصة + +أنت الآن تعرف كيفية **إنشاء شيفرة باركود PDF417** في C# من أي سلسلة، **تعديل حجم الباركود**، وتطبيق **أبعاد مخصصة للباركود** لتناسب احتياجات تخطيطك. تدفق الخطوات الأربع—التهيئة، الحجم، التخطيط، الحفظ—يغطي سير العمل الأساسي لمعظم سيناريوهات الباركود ثنائي الأبعاد. + +ما التالي؟ جرّب استبدال `EncodeTypes.Pdf417` بـ `EncodeTypes.QR` أو `EncodeTypes.Code128` لترى كيف يتكيف الـ API. جرب قيم `XDimension` مختلفة، العب بمصفوفة الأعمدة/الصفوف، أو أدخل الصورة في تقرير PDF. الاحتمالات لا حصر لها، والآن لديك أساس قوي للبناء عليه. + +هل لديك أسئلة أخرى، أو اكتشفت حيلة ذكية أثناء العمل مع PDF417؟ اترك تعليقًا أدناه—لنستمر في النقاش. برمجة سعيدة! + +## ماذا يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مصدر يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية إنشاء شيفرة باركود Aztec بنسبة أبعاد مخصصة باستخدام Aspose.BarCode لـ .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [كيفية إنشاء شيفرة باركود - أنواع الباركود أحادية الأبعاد](/barcode/english/net/one-dimensional-barcode-types/) +- [إنشاء شيفرة باركود DataMatrix – دليل احترافي مع Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/arabic/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..8115d36a3 --- /dev/null +++ b/barcode/arabic/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-07-15 +description: كيفية قراءة باركود PDF417 في C# وقراءة عدة باركودات من صورة. تعلم قراءة + صورة الباركود في C# مع كود مفصل ونصائح. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: ar +lastmod: 2026-07-15 +og_description: كيفية قراءة الباركود PDF417 في C# بسرعة. يوضح لك هذا الدليل كيفية + قراءة عدة باركودات من صورة واحدة وفك تشفير كل خاصية. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: كيفية قراءة PDF417 في C# – مثال كامل للشفرة وشرح +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: كيفية قراءة PDF417 في C# – دليل خطوة بخطوة كامل +url: /ar/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية قراءة PDF417 في C# – دليل خطوة بخطوة كامل + +هل تساءلت يومًا **كيفية قراءة PDF417** من صورة باستخدام C#؟ لست وحدك. يواجه معظم المطورين صعوبة عندما يحتاجون لاستخراج الحقول الموسعة Macro‑PDF417 من مستند ممسوح ضوئيًا. الخبر السار؟ ببضع أسطر من الشيفرة يمكنك فك تشفير PDF417، قراءة عدة باركودات في نفس الصورة، والحصول على كل خاصية مخفية يقدمها المعيار. + +في هذا الدرس سنستعرض مثالًا واقعيًا يوضح **كيفية قراءة PDF417**، وكيفية **قراءة عدة باركودات** من ملف واحد، ولماذا يبدو كود **read barcode image C#** كما هو. في النهاية ستحصل على تطبيق كونسول جاهز للتنفيذ يطبع كل معلومة قد تحتاجها—معرف الملف، معرف الجزء، المجموع الاختباري، الطوابع الزمنية، وما إلى ذلك. + +## المتطلبات المسبقة + +* .NET 6.0 SDK أو أحدث (الكود يعمل أيضًا مع .NET Core و .NET Framework). +* Visual Studio 2022 (أو أي محرر تفضله). +* حزمة **Aspose.BarCode for .NET** من NuGet – هذه هي المكتبة التي تقوم فعليًا بتحليل PDF417. +* صورة نموذجية تحتوي على باركود Macro‑PDF417 (مثال: `ExtPDF417Meta.png`). + +لا يلزم أي إعداد إضافي؛ المكتبة تأتي مع جميع المفككات التي تحتاجها. + +## الخطوة 1: تثبيت Aspose.BarCode + +افتح مجلد المشروع في الطرفية وشغّل: + +```bash +dotnet add package Aspose.BarCode +``` + +هذا الأمر يجلب أحدث نسخة مستقرة (حتى يوليو 2026 الإصدار هو 23.12). إذا كنت تفضّل وحدة التحكم Package Manager داخل Visual Studio، استخدم: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Pro tip:** احجز النسخة (`23.12.0`) في ملف `.csproj` لتجنب التغييرات المكسرة غير المتعمدة لاحقًا. + +## الخطوة 2: إنشاء هيكل تطبيق كونسول + +أنشئ مشروع كونسول جديد إذا لم يكن لديك واحد بالفعل: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +استبدل ملف `Program.cs` المُولد تلقائيًا بالكود أدناه. سنشرح كل جزء في الأقسام التالية. + +## الخطوة 3: كتابة الكود الكامل “كيفية قراءة PDF417” + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### لماذا يعمل هذا الكود + +* **`BarCodeReader`** هو الفئة الأساسية التي تقوم بقراءة الصورة، واكتشاف الباركودات، وإرجاع مجموعة من كائنات `BarCodeResult`. +* تمرير **`DecodeType.MacroPdf417`** يخبر المكتبة بمعالجة Macro‑PDF417 بشكل خاص؛ لا يزال يُعيد رموز PDF417 العادية، مما يلبي متطلبات **read multiple barcodes**. +* كائن **`Extended.Pdf417.MacroPdf417`** يحتوي على كل حقل اختياري معرف في معيار ISO/IEC 15438 – هنا تحصل على `FileID`، `SegmentID`، `Checksum`، إلخ. +* كتلة `using` تضمن تحرير الموارد الأصلية، مما يمنع تسرب الذاكرة في الخدمات طويلة التشغيل. + +## الخطوة 4: تشغيل التطبيق والتحقق من المخرجات + +من الطرفية: + +```bash +dotnet run +``` + +ستظهر لك نتيجة مشابهة لـ: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +إذا احتوت الصورة على أكثر من باركود واحد، سيطبع الحلقة سطر فاصل (`----------------------------------------`) ويستمر بالنتيجة التالية—وهو بالضبط ما يبدو عليه **read multiple barcodes** في الواقع. + +## الأسئلة الشائعة والحالات الخاصة + +### ماذا لو احتوت الصورة على كل من رموز Macro‑PDF417 و PDF417 العادية؟ + +ستُعيد نفس استدعاء `BarCodeReader` كلا النوعين. يمكنك التفريق بينهما بفحص `result.CodeType` (`MacroPdf417` مقابل `Pdf417`). ستكون الخصائص الموسعة `null` لباركود PDF417 العادي، لذا فإن شرط `if (macro != null)` يمنع حدوث `NullReferenceException`. + +### الباركود مائل أو مشوّه—هل سيستمر القارئ في العمل؟ + +تتضمن Aspose.BarCode تعويضًا مدمجًا للدوران والتشوه. طالما أن الباركود يغطي على الأقل 30 % من عرض الصورة، فإن المفكك عادةً ما ينجح. في الحالات القصوى يمكنك تمكين `reader.Options.AllowInvertedBarcodes = true;` قبل استدعاء `ReadBarCodes()`. + +### كيف أتعامل مع دفعات كبيرة من الصور؟ + +غلف منطق القراءة داخل حلقة `foreach (var file in Directory.GetFiles(folder, "*.png"))`. يضمن نمط `using` تحرير الموارد الأصلية لكل صورة قبل الانتقال إلى التالية، مما يحافظ على انخفاض استهلاك الذاكرة. + +## قائمة المصدر الكاملة (جاهزة للنسخ واللصق) + +فيما يلي البرنامج بالكامل في كتلة واحدة لسهولة النسخ واللصق. لا توجد تبعيات مخفية—فقط حزمة Aspose.BarCode من NuGet. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## ملخص – ما تم تغطيته + +* **كيفية قراءة PDF417** باستخدام Aspose.BarCode في C#. +* الخطوات الدقيقة لـ **read multiple barcodes** من صورة واحدة. +* كيفية **read barcode image C#** واستخراج كل حقل من Macro‑PDF417. +* نصائح حول الدوران، المعالجة الدفعية، والتعامل مع البيانات الموسعة المفقودة. + +## الخطوات التالية والمواضيع ذات الصلة + +* **Encode PDF417** – إنشاء باركودات Macro‑PDF417 الخاصة بك باستخدام `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR، DataMatrix، Aztec – باستخدام نفس فئة `BarCodeReader`. +* **Integrate with ASP.NET Core** – إنشاء نقطة نهاية ويب تستقبل صورة مرفوعة وتعيد JSON يحتوي على الحقول المفكوكة. + +لا تتردد في التجربة: غيّر مسار الصورة، ضع PDF417 عادي في نفس المجلد، أو عدّل أعلام `DecodeType` لترى سلوك المكتبة. كلما لعبت أكثر، كلما أصبحت أكثر ارتياحًا مع سيناريوهات **read barcode image C#**. + +هل لديك صورة صعبة ترفض الفك؟ اترك تعليقًا أدناه أو افتح قضية في مستودع GitHub الخاص بمشروع العينة. برمجة سعيدة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة شيفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف نهج تنفيذ بديلة في مشاريعك. + +- [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/arabic/net/one-dimensional-barcode-types/_index.md b/barcode/arabic/net/one-dimensional-barcode-types/_index.md index 704801638..dd1203d7c 100644 --- a/barcode/arabic/net/one-dimensional-barcode-types/_index.md +++ b/barcode/arabic/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ url: /ar/net/one-dimensional-barcode-types/ تعرف على كيفية التعامل مع الاستثناءات أثناء إنشاء رموز شريطية أحادية البعد باستخدام Aspose.BarCode لـ .NET. يضمن هذا الدليل التفصيلي حلول الباركود التي تتحمل الأخطاء. نبدأ الآن! ### [تكوين ذو نسبة واسعة وضيقة أحادية البعد](./one-dimensional-wide-narrow-ratio-configuration/) قم بإنشاء رموز شريطية مخصصة بسهولة باستخدام Aspose.BarCode لـ .NET. دليل خطوة بخطوة لتكوين نسبة واسعة وضيقة أحادية البعد. +### [إنشاء باركود من النص باستخدام Aspose.BarCode – دليل C#](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +تعلم كيفية إنشاء باركود من نص باستخدام Aspose.BarCode في C# خطوة بخطوة. ## خاتمة @@ -89,4 +91,4 @@ url: /ar/net/one-dimensional-barcode-types/ {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/arabic/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..566135975 --- /dev/null +++ b/barcode/arabic/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-07-15 +description: إنشاء رمز شريطي من النص باستخدام Aspose.BarCode في C#. تعلم كيفية تغيير + عدد الأعمدة، حفظ صورة الرمز الشريطي، وإنشاء حلول Aspose للرموز الشريطية بسرعة. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: ar +lastmod: 2026-07-15 +og_description: إنشاء رمز شريطي من النص باستخدام Aspose.BarCode. يوضح هذا الدليل كيفية + تغيير عدد الأعمدة، حفظ صورة الرمز الشريطي، وإنشاء رمز شريطي باستخدام Aspose في بضع + أسطر من الشيفرة. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: إنشاء رمز شريطي من النص باستخدام Aspose.BarCode – دليل سريع بلغة C# +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: إنشاء باركود من النص باستخدام Aspose.BarCode – دليل C# +url: /ar/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء باركود من نص باستخدام Aspose.BarCode – دليل C# + +إنشاء باركود من نص باستخدام Aspose.BarCode بسيط بشكل مدهش. في هذا الدليل سنستعرض **كيفية إنشاء الباركود**، ونضبط تخطيط الأعمدة، وأخيرًا **حفظ صورة الباركود** كملف PNG. سواءً كنت تبني نظام تذاكر، أو طابعة ملصقات للمستودعات، أو مجرد تجربة أكواد على نمط QR، فإن الخطوات أدناه ستوصلك إلى الهدف بسرعة. + +## ما ستتعلمه + +- إنشاء باركود من أي سلسلة Unicode (نعم، حتى “Åspóse.Barcóde©” تعمل). +- ضبط **عدد الأعمدة** لـ MicroPdf417 لتناسب الملصقات الضيقة أو العريضة. +- حفظ النتيجة على القرص بالتنسيق المناسب للصورة. +- نصائح للتعامل مع الأحرف الخاصة والمشكلات الشائعة عند **إنشاء باركود Aspose**. + +لا أدوات خارجية، ولا حيل سطر أوامر—فقط C# عادي ومكتبة Aspose.BarCode. + +## المتطلبات المسبقة + +قبل أن نغوص في التفاصيل، تأكد من وجود ما يلي: + +1. **.NET 6.0** أو أحدث مثبت (الكود يعمل أيضًا على .NET Framework 4.7+). +2. **رخصة** لـ Aspose.BarCode، أو يمكنك البدء بالإصدار التجريبي المجاني. +3. مجلد يمكنك الكتابة فيه – سنسميه `YOUR_DIRECTORY` في الأمثلة. + +إذا كان أيٌ من هذه مفقودًا، احصل على حزمة NuGet الآن: + +```bash +dotnet add package Aspose.BarCode +``` + +هذا كل شيء—لا حاجة لنسخ ملفات DLL إضافية يدويًا. + +## الخطوة 1 – إعداد المشروع والاستيرادات + +أولاً، أنشئ تطبيق console (أو ضع الكود في أي مشروع C#). الجزء المهم هو استيراد المساحات الاسمية الصحيحة: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +لماذا هذه عبارات using؟ `BarcodeGenerator` موجودة في `Aspose.BarCode.Generation`، بينما تعداد `BarCodeImageFormat` موجود في `Aspose.BarCode`. الحفاظ على الاستيرادات منظمة يجعل الكود اللاحق يُقرأ كإنجليزية بسيطة. + +## الخطوة 2 – إنشاء مولّد الباركود (كيفية إنشاء باركود) + +الآن سنقوم فعليًا **بإنشاء باركود من نص**. تعداد `EncodeTypes` يخبر Aspose أي رموزية (symbology) يجب استخدامها؛ هنا نختار `MicroPdf417` لأنه يتعامل مع سلاسل طويلة في شبكة مدمجة. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +لاحظ أن السلسلة تحتوي على أحرف مُشَكَّلة ورمز حقوق النشر. Aspose.BarCode يشفّر Unicode تلقائيًا، لذا لا تحتاج إلى معالجة النص مسبقًا. + +## الخطوة 3 – ضبط المظهر بدقة (كيفية تغيير عدد الأعمدة) + +يتيح لك MicroPdf417 التحكم في عدد الأعمدة، مما يؤثر مباشرةً على عرض الباركود. تخطيط أكثر ضيقًا مفيد للملصقات الضيقة؛ وتخطيط أوسع يحسن القابلية للقراءة على الطباعة الكبيرة. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +لماذا وحدات 2 بكسل؟ تعطي صورة واضحة دون زيادة حجم الملف. لا تتردد في التجربة—القيم بين 1 و4 عادةً تعمل جيدًا. إذا احتجت عدد أعمدة مختلف، فقط غيّر خاصية `Columns`؛ سيتولى Aspose إعادة حساب التخطيط تلقائيًا. + +## الخطوة 4 – حفظ صورة الباركود (حفظ صورة الباركود) + +بعد ضبط المولّد، نحن جاهزون **لحفظ صورة الباركود**. طريقة `Save` تقبل مسار ملف وتعداد تنسيق الصورة. PNG غير مضغوط، لذا يظل الباركود واضحًا حتى بعد التكبير. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +نصيحة سريعة: استخدم دائمًا مسارًا مطلقًا أو تأكد من أن دليل العمل هو ما تتوقع؛ وإلا قد ينتهي الملف إلى مجلد bin وستتساءل لماذا لا يمكنك العثور عليه. + +## مثال كامل يعمل + +بجمع كل ذلك، إليك برنامج مستقل يمكنك نسخه ولصقه في `Program.cs` وتشغيله: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**الناتج المتوقع** (الكونسول): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +وإذا فتحت `MicroPdf417.png`، سترى باركود MicroPdf417 واضحًا يشفر السلسلة الأصلية، بما في ذلك الأحرف الخاصة التي أدخلناها. + +## أسئلة شائعة وحالات خاصة + +### ماذا لو كان نصي أطول من السعة الافتراضية؟ + +يقوم MicroPdf417 تلقائيًا بالتحول إلى تخطيط متعدد الصفوف عندما تتجاوز البيانات الحد الأقصى لكل صف. لا يزال بإمكانك التحكم في عدد الأعمدة، لكن المكتبة قد تضيف صفوفًا إضافية خلف الكواليس. لا حاجة لكود إضافي—فقط راقب أبعاد الصورة الناتجة. + +### كيف أغيّر تنسيق الصورة إلى JPEG أو BMP؟ + +استبدل `BarCodeImageFormat.Png` بـ `BarCodeImageFormat.Jpeg` (أو `Bmp`). تذكر أن JPEG يضيف تشوهات ضغط قد تؤثر على موثوقية المسح. PNG هو الخيار الأكثر أمانًا افتراضيًا. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### أرى علامة مائية في الناتج—ما الخطأ؟ + +هذه نسخة التقييم من Aspose.BarCode. لإ **إنشاء باركود Aspose** بدون علامات مائية، حمّل ملف ترخيص صالح كما هو موضح في السطر المعلق في الخطوة 2. + +### هل يمكنني إنشاء رموزيات أخرى (QR، Code128، إلخ)؟ + +بالطبع. فقط استبدل `EncodeTypes.MicroPdf417` بأي قيمة أخرى من تعداد `EncodeTypes`، مثل `EncodeTypes.QR` أو `EncodeTypes.Code128`. باقي الكود يبقى كما هو، مما يجعل النهج قابلًا لإعادة الاستخدام بشكل كبير. + +## نصائح احترافية لتوليد باركود جاهز للإنتاج + +- **Cache the generator** إذا كنت تنشئ العديد من الباركود بنفس الإعدادات؛ يقلل من عبء إنشاء الكائنات. +- **Validate the input string** للتحقق من قيود الطول الخاصة بالرمزية المختارة (Aspose يرمي `ArgumentException` إذا كان النص طويلًا جدًا). +- **Use `using` statements** أو `Dispose` للمولد عند الانتهاء لتحرير الموارد الأصلية بسرعة. +- **Set DPI** عبر `generator.Parameters.ImageResolution.DpiX/DpiY` إذا كنت تحتاج إلى طباعة عالية الدقة للملصقات الكبيرة. + +## الخلاصة + +أنت الآن تعرف بالضبط **كيفية إنشاء باركود من نص** باستخدام Aspose.BarCode، وكيفية **تغيير عدد الأعمدة**، والطريقة الصحيحة **لحفظ صورة الباركود** كملف PNG. المثال الكامل القابل للتنفيذ أعلاه يوضح نهجًا نظيفًا وجاهزًا للإنتاج + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية إنشاء باركود – تكوين Code 39 مع Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [إنشاء صورة باركود – Code 93 مع Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [كيفية إنشاء باركود DataMatrix (ECC 200) مع Aspose.BarCode لـ .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/chinese/net/compact-pdf417-encoding/_index.md index 165dd64a9..02267ab33 100644 --- a/barcode/chinese/net/compact-pdf417-encoding/_index.md +++ b/barcode/chinese/net/compact-pdf417-encoding/_index.md @@ -85,7 +85,13 @@ Aspose.BarCode 允许您设置 `Pdf417ErrorCorrectionLevel` 属性(0‑8)。 ### [创建紧凑 PDF417 条形码](./compact-pdf417-basic-configuration/) -了解如何使用 Aspose.BarCode for .NET 生成紧凑 PDF417 条形码。提供完整的分步指南和代码示例。 +### [在 C# 中创建 PDF417 条码元数据 – 完整分步指南](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) + +### [在 C# 中生成 PDF417 条形码 – 完整指南](./generate-pdf417-barcode-in-c-complete-guide/) + +### [在 C# 中生成 PDF417 条码 – 完整分步指南](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) + +### [在 C# 中读取 PDF417 条码 – 完整分步指南](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) ## 常见问题 @@ -115,4 +121,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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/chinese/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..7600dc4f4 --- /dev/null +++ b/barcode/chinese/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-07-15 +description: 使用 Aspose.BarCode 在 C# 中创建 PDF417 条码元数据。了解宏 PDF417 设置,保存为 PNG,并处理 Unicode + 文本。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: zh +lastmod: 2026-07-15 +og_description: 使用 Aspose.BarCode 在 C# 中创建 PDF417 条形码元数据。本指南展示了嵌入文件 ID、时间戳等所需的所有设置。 +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: 在 C# 中创建 PDF417 条码元数据 – 完整编程教程 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: 在 C# 中创建 PDF417 条形码元数据 – 完整分步指南 +url: /zh/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中创建 PDF417 条形码元数据 – 完整分步指南 + +是否曾需要在 C# 中 **创建 PDF417 条形码元数据**,却不清楚该修改哪些属性?你并不孤单——开发者在规格要求文件 ID、段计数或自定义时间戳时常常卡住。 + +好消息是 Aspose.BarCode 能让这变得轻而易举。在本教程中,我们将为 **Macro PDF417** 创建一个 `BarcodeGenerator`,加入所有重要的元数据,并将结果保存为 PNG 图像。完成后,你将拥有一个功能完整的条形码,可用于任何供应链或文档管理系统。 + +## 本指南涵盖内容 + +我们将逐步演示: + +1. 安装 Aspose.BarCode NuGet 包。 +2. 为 **Macro PDF417** 初始化 `BarcodeGenerator`。 +3. 填充每个有用的 **条形码元数据字段**(文件 ID、段 ID、校验和等)。 +4. 将条形码保存到磁盘并验证输出。 + +不需要事先了解 Macro PDF417——只要具备基本的 C# 知识和最近的 .NET 运行时即可。 + +为什么值得关注?将丰富的元数据直接嵌入条形码,使下游扫描器能够验证完整文件传输、检测缺失段,甚至触发自动化工作流。换句话说,你可以获得 **健壮的自描述数据**,无需额外的数据库查找。 + +## 前置条件 + +- .NET 6.0 或更高(代码同样适用于 .NET Framework 4.7+)。 +- Visual Studio 2022(或任意你喜欢的 IDE)。 +- **Aspose.BarCode for .NET** NuGet 包(提供免费试用)。 + +使用以下命令安装包: + +```bash +dotnet add package Aspose.BarCode +``` + +有了这些基础,下面开始实际实现。 + +## 步骤 1:为 Macro PDF417 初始化 BarcodeGenerator + +首先需要一个配置为 **Macro PDF417** 的 `BarcodeGenerator` 实例。这告诉 Aspose.BarCode 使用哪种编码算法,并提供一个放置可读文本的地方。 + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **为什么重要:** `EncodeTypes.MacroPdf417` 启用支持文件 ID、段号等元数据的扩展 PDF417 模式。示例文本包含 Unicode 字符(`Å`、`ó`、`©`),以证明生成器能够优雅地处理非 ASCII 输入。 + +## 步骤 2:定义条形码基本外观 + +在添加元数据之前,先设置一些视觉参数,防止条形码过于微小。`XDimension` 控制模块宽度,`Columns` 影响整体形状。 + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **专业提示:** 像素宽度设为 `2` 在屏幕显示和大多数打印机上表现良好。如果需要更高分辨率的打印,可提升至 `3` 或 `4`。 + +## 步骤 3:填充 Macro PDF417 元数据字段 + +下面进入教程核心——添加 **条形码元数据字段**。每个属性直接映射到 Macro PDF417 规范的相应段。 + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### 各属性作用说明 + +| 属性 | 用途 | 典型值 | +|----------|---------|---------------| +| **MacroPdf417FileID** | 整个文件集的全局唯一标识符。 | `12345678` | +| **MacroPdf417SegmentID** | 当前段的索引(从 `0` 开始)。 | `12` | +| **MacroPdf417SegmentsCount** | 文件预期的总段数。 | `20` | +| **MacroPdf417FileName** | 人类可读的名称,通常为原始文件名。 | `"file01"` | +| **MacroPdf417Checksum** | 用于错误检测的 16 位 CCITT 校验和。 | `1234` | +| **MacroPdf417FileSize** | 原始文件的字节大小。 | `400000` | +| **MacroPdf417TimeStamp** | 文件生成的时间。 | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | 可选字段,指示目标地址。 | `"street"` | +| **MacroPdf417Sender** | 可选字段,指示源系统。 | `"aspose"` | +| **MacroPdf417Terminator** | 标记扫描器这是最后一个段。 | `Pdf417MacroTerminator.Set` | + +> **为什么需要这些:** 支持 Macro PDF417 的扫描器可以重新组装多段文件,使用校验和验证完整性,甚至根据时间戳拒绝过期数据。这消除了单独清单文件的需求。 + +## 步骤 4:保存条形码图像 + +所有参数设置完毕后,只需调用 `Save`。示例将 PNG 文件写入你指定的文件夹。 + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **边缘情况:** 如果后续计划将条形码嵌入 PDF,可能更倾向使用 `BarCodeImageFormat.Jpeg` 或 `Pdf`。PNG 保留无损细节,便于验证。 + +## 完整工作示例 + +将所有代码整合在一起,下面是可以直接复制到控制台应用的完整程序: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### 预期输出 + +运行程序后,会在可执行文件所在文件夹生成名为 **ExtPDF417Meta.png** 的文件。使用任意图像查看器打开,你会看到一个密集、高对比度的 PDF417 条形码。如果使用支持 Macro PDF417 的条形码阅读器扫描,它会返回我们设置的元数据值——文件 ID `12345678`、段 `12`(共 `20`)等。 + +## 常见问题与坑点 + +- **条形码模糊怎么办?** 增大 `XDimension.Pixels` 或切换到更高分辨率的图像格式。 +- **必须设置所有元数据字段吗?** 不必。只需满足下游系统要求的字段即可,未使用的字段保持默认即可。 +- **能自动生成多段文件吗?** 可以——遍历数据,递增 `MacroPdf417SegmentID`,为每段生成单独的条形码。记得在所有段中保持 `MacroPdf417FileID` 一致。 +- **支持 Unicode 吗?** 完全支持。示例文本中包含 `Å`、`ó`、`©`,展示了 Aspose.BarCode 对 UTF‑8 的原生处理。 + +## 后续步骤:深入进阶 + +了解了如何 **创建 PDF417 条形码元数据** 后,你可以进一步探索: + +- 使用 `Aspose.Pdf` 将条形码嵌入 PDF,实现端到端文档生成。 +- 使用 `BarcodeReader` 读取元数据,以编程方式验证扫描结果。 +- 自定义前景/背景颜色,实现品牌化。 +- 与数据库集成,自动填充 `FileID`、`Timestamp` 等字段。 + +这些主题都围绕我们的次要关键词——**macro pdf417**、**aspose barcode c#**、**barcode metadata fields**、**c# barcode generation**——提供了丰富的学习材料。 + +## 结论 + +我们已经完整演示了在 C# 中 **创建 PDF417 条形码元数据** 的全过程。从安装 Aspose.BarCode、初始化 `BarcodeGenerator`、填充所有相关 **条形码元数据字段**,到最终保存清晰的 PNG,整个过程在掌握正确属性后相当简洁。 + +动手尝试,调整数值,观察扫描器的响应。Macro PDF417 的灵活性让你能够在单个可扫描图像中嵌入下游系统所需的全部信息。祝编码愉快,愿你的条形码永远无误! + +## 接下来该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助你在项目中进一步运用 API 功能并探索替代实现方式。 + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java barcode library – Add barcode to PDF using Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/chinese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..f912e834e --- /dev/null +++ b/barcode/chinese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-07-15 +description: 快速生成 PDF417 条码,并学习如何在 C# 中设置列以生成紧凑的 PDF417 条码图像。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: zh +lastmod: 2026-07-15 +og_description: 使用 Aspose.BarCode 生成 PDF417 条码,并了解如何设置列以创建紧凑的 PDF417 条码图像。 +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: 使用 C# 生成 PDF417 条码 – 步骤指南 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: 在 C# 中生成 PDF417 条码 – 完整指南 +url: /zh/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中生成 PDF417 条形码 – 完整指南 + +是否曾经需要在 .NET 项目中**生成 PDF417 条形码**却不知从何入手?你并不孤单。在许多企业应用中——比如登机牌打印机、库存标签或移动票务——PDF417 是能够在小尺寸视觉空间内容纳大量数据的主力军。 + +关键在于:Aspose.BarCode 库让整个过程几乎毫不费力,而且你甚至可以**设置列数**,使条形码尽可能紧凑。完成本教程后,你将拥有一张可直接用于任何 UI、电子邮件或打印任务的 **PDF417 条形码 PNG 图像**。 + +## 你将收获的成果 + +- 一个完整的 C# 控制台应用程序,可生成 PDF417 条形码。 +- 对 *X‑Dimension*(模块尺寸)及其重要性的清晰理解。 +- **如何设置列数**的逐步说明,以获得更紧凑的条形码。 +- 一个已保存的 `PNG` 文件,可立即打开验证结果。 +- 常见问题的排查技巧(例如条码不可读、图像格式错误)。 + +> **先决条件** – .NET 6+ SDK、Visual Studio 2022(或任意你喜欢的编辑器),以及对 `Aspose.BarCode` 的 NuGet 引用。除此之外无需其他东西。 + +--- + +## 第一步:安装 Aspose.BarCode NuGet 包 + +在我们能够*生成 PDF417 条形码*之前,需要先在项目中引入该库。 + +```bash +dotnet add package Aspose.BarCode +``` + +这行代码会拉取所有必需的类型,包括 `BarcodeGenerator`、`EncodeTypes` 和 `BarCodeImageFormat` 枚举。 + +> **专业提示:** 如果你针对的是 .NET Framework 而非 .NET 6,请在包管理器控制台中使用经典的 `Install-Package Aspose.BarCode` PowerShell 命令。 + +--- + +## 第二步:创建最小化的控制台应用程序 + +让我们搭建一个只负责生成条形码的极简程序。新建一个文件夹,运行 `dotnet new console`,然后用下面的代码替换自动生成的 `Program.cs`。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**为什么重要:** +- `EncodeTypes.Pdf417` 告诉库我们需要的是 PDF417 条形码,而不是 QR 或 Code128。 +- `XDimension.Pixels` 控制每个黑白模块的分辨率。 +- **如何设置列数**的代码块直接影响 **PDF417 条形码图像** 的形状。 +- `Truncate = true` 会去除任何不必要的空行,呈现出许多扫描仪喜爱的“紧凑”外观。 + +--- + +## 第三步:深入了解列数和截断 + +### 如何设置列数 + +PDF417 将数据排列成 *行* × *列* 的矩阵。库默认使用 5 列,适用于大多数情况。但你可能需要更窄的条形码以适配标签,或更宽的条形码以提升扫描可靠性。属性: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +接受 **1** 到 **30** 的值(具体上限取决于数据长度)。下面是一张快速参考表: + +| 列数 | 近似宽度 (mm) | 适用场景 | +|------|--------------|----------| +| 1‑3 | 非常窄 | 小标签、空间受限 | +| 4‑6 | 标准 | 大多数收据、票据 | +| 7‑10 | 较宽 | 高密度数据、可读性更好 | + +### 截断(紧凑模式) + +将 `Truncate = true` 设置为 true,告诉编码器去掉底部所有不必要的空白行。结果是一个**紧凑的 PDF417 条形码图像**,在占用最小面积的同时仍然包含全部数据。如果遇到“条码太大无法贴标签”的错误,请切换此标志。 + +--- + +## 第四步:运行应用并验证输出 + +编译并执行: + +```bash +dotnet run +``` + +你应该会在控制台看到确认保存位置的消息。随后打开文件夹,查看 `CompactPdf417.png`。图像大致如下: + +![生成的 PDF417 条形码图像](./CompactPdf417.png "生成的 PDF417 条形码图像 – 由 Aspose.BarCode 创建的紧凑 PNG") + +*图像替代文字:* **生成的 PDF417 条形码图像** – 本教程代码生成的紧凑 PNG 文件。 + +如果你的扫描仪能够读取它,恭喜你——你已经成功**生成 PDF417 条形码**并掌握了**如何设置列数**以获得整洁的**PDF417 条形码图像**。 + +--- + +## 第五步:常见问题与解决方案 + +| 症状 | 可能原因 | 快速解决方案 | +|------|----------|--------------| +| 条码模糊 | `XDimension.Pixels` 设置过低(例如 1) | 提升至 2‑3 像素以获得更清晰的图像。 | +| 扫描仪无法读取 | 对给定数据列数过多 | 减少 `Columns` 或启用 `Truncate`。 | +| 文件格式错误 | 错误地使用 `BarCodeImageFormat.Jpeg` 保存 | 使用 `BarCodeImageFormat.Png` 以获得无损结果。 | +| 抛出 `ArgumentOutOfRangeException` | 列数超出允许范围 | 将列数保持在 1‑30 之间,并确保数据能够容纳。 | + +--- + +## 第六步:进一步——自定义颜色和添加文字 + +如果想让条形码匹配品牌配色,可以调整前景色和背景色: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +或者在条形码下方添加可读的文字说明: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +这些是可选的,但它们展示了**生成 PDF417 条形码**工作流的灵活性。 + +--- + +## 结论 + +我们已经完整演示了使用 Aspose.BarCode **生成 PDF417 条形码**的端到端示例,解释了**如何设置列数**以控制条形码尺寸,并将结果保存为清晰的 **PDF417 条形码 PNG 图像**。代码自包含,适用于 .NET 6+,可轻松嵌入任何现有项目。 + +接下来可以尝试编码更大的负载(例如 JSON),实验不同的图像格式,或将生成器集成到按需提供条形码的 Web API 中。前景无限,而你已经拥有了坚实的基础。 + +祝编码愉快,愿你的条形码总能一次成功扫描! + +## 接下来你应该学习什么? + +以下教程涵盖了与本指南技术紧密相关的主题,帮助你进一步掌握 API 功能并探索在项目中的替代实现方式。每个资源都提供完整的可运行代码示例和逐步解释。 + +- [如何使用 Aspose.BarCode 创建紧凑 PDF417 条形码](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [如何在 Java 中使用 Aspose.BarCode 生成条形码图像](/barcode/english/java/barcode-rendering-techniques/) +- [Java 生成条形码 – 使用 Aspose.BarCode 设置图像分辨率](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/chinese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..4c0d2fbff --- /dev/null +++ b/barcode/chinese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,199 @@ +--- +category: general +date: 2026-07-15 +description: 使用 C# 快速生成 PDF417 条码。了解如何从文本生成条码、调整条码大小,并在几分钟内设置自定义条码尺寸。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: zh +lastmod: 2026-07-15 +og_description: 在 C# 中即时生成 PDF417 条码。本指南展示了如何从文本生成条码、调整条码大小以及应用自定义条码尺寸。 +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: 在 C# 中生成 PDF417 条码 – 完整编程教程 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: 在 C# 中生成 PDF417 条码 – 完整的逐步指南 +url: /zh/net/compact-pdf417-encoding/generate-pdf417-barcode-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# 中生成 PDF417 条形码 – 完整分步指南 + +是否曾需要 **生成 PDF417 条形码** 却不确定该调整哪些设置?你并不孤单——许多开发者在首次接触 2‑D 条形码时都会遇到同样的难题。好消息是,只需几行 C# 代码,你就可以将任意字符串转换为可扫描的 PDF417 图像,精确控制其尺寸,甚至自定义列‑行布局。 + +在本教程中,我们将逐步演示如何 **从文本生成条形码**、调整条形码大小,以及设置自定义条形码尺寸 — 全部使用流行的 Aspose.BarCode 库。完成后,你将拥有一个可直接运行的示例,能够嵌入任何 .NET 项目。 + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## 你将构建的内容 + +- 一个编码字符串 `Åspóse.Barcóde©` 的 PDF417 条形码。 +- 对 X 维度(每个模块的像素宽度)的精确控制。 +- 一个 4 列 9 行的自定义布局。 +- 保存到磁盘的 PNG 文件。 + +无需外部服务,也不需要魔法棒——只需纯 C# 代码,立即即可编译运行。 + +## 前置条件 + +- .NET 6.0 或更高版本(代码同样适用于 .NET Framework 4.8)。 +- Visual Studio 2022 或任何支持 C# 的 IDE。 +- Aspose.BarCode for .NET(免费试用版或授权版)。通过 NuGet 安装: + +```bash +dotnet add package Aspose.BarCode +``` + +就这么简单——引用该包后即可开始。 + +## 第一步 – 使用文本数据生成 PDF417 条形码 + +首先需要创建一个 `BarcodeGenerator` 实例,告诉库我们使用 PDF417 符号并提供要编码的文本。 + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **为什么这很重要:** +> `EncodeTypes.Pdf417` 让库使用 PDF417 2‑D 格式,第二个参数则是 **generate barcode from text** 的负载。你在这里传入的任何内容都会成为条形码矩阵中存储的数据。 + +## 第二步 – 调整条形码大小(X‑Dimension) + +如果你曾打印过看起来太小的条形码,扫描器可能会漏扫。`XDimension` 属性控制单个模块(最小的黑白方块)的像素宽度。 + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **专业提示:** +> 2 px 的数值在大多数屏幕显示场景下表现良好。对于高分辨率打印,你可以将其提升到 3 或 4 px。只需记住,X‑Dimension 越大,整体图像尺寸也会随之增大。 + +## 第三步 – 设置自定义条形码尺寸(列数和行数) + +PDF417 允许你指定条形码应占用的列数和行数。这正是 **custom barcode dimensions** 发挥作用的地方。修改这些值可以帮助你将条形码适配到紧凑的 UI 空间或满足特定标签尺寸。 + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **底层原理是什么?** +> 库会在指定的网格中重新分配已编码的数据。列数少会使条形码更高;行数多则使其更矮。根据你的应用需求,反复尝试这些数字,直至视觉平衡满意为止。 + +## 第四步 – 保存条形码图像 + +配置完成后,只需让生成器写入 PNG 文件。PNG 为无损格式,模块的清晰度得以保持。 + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +运行程序后,你应当在 `C:\Barcodes\CustomLayout.png` 看到一张类似上方截图的文件。使用任何兼容 PDF417 的阅读器扫描,它会返回原始字符串 `Åspóse.Barcóde©`。 + +## 完整工作示例 + +下面是可以直接复制到控制台应用中的完整程序。它包含了所有 using 指令以及在生产代码中常见的错误处理。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### 预期输出 + +运行代码后会在控制台打印: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…并生成一张可在任意图像查看器中打开的 PNG。如果使用移动端应用(例如 iOS/Android 上的 “Barcode Scanner”)扫描,解码后的文本应正好是 **Åspóse.Barcóde©**。 + +## 常见问题与边缘情况 + +| Question | Answer | +|----------|--------| +| **Can I use a different image format?** | Yes—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, or `Svg` are all supported. Just change the second argument of `Save`. | +| **What if my text contains Unicode characters?** | Aspose.BarCode fully supports UTF‑8, so the example with `Å` and `©` works out‑of‑the‑box. | +| **How do I change the error‑correction level?** | Use `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (levels 0‑8). Higher levels increase redundancy but also size. | +| **I need a transparent background—can I do that?** | Set `generator.Parameters.Barcode.Image.TransparentBackground = true;` before saving. | +| **Is there a way to embed the barcode directly into a PDF?** | Absolutely. Replace the `Save` call with `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` and you’ll get a one‑page PDF containing the barcode. | + +## 结论 + +现在你已经掌握了如何在 C# 中 **generate PDF417 barcode**,以及 **adjust barcode size** 并应用 **custom barcode dimensions** 以满足布局需求。四步流程——初始化、尺寸、布局、保存——覆盖了大多数 2‑D 条形码场景的核心工作流。 + +接下来可以尝试将 `EncodeTypes.Pdf417` 替换为 `EncodeTypes.QR` 或 `EncodeTypes.Code128`,观察 API 如何适配。实验不同的 `XDimension` 值,玩转列/行矩阵,或将图像嵌入 PDF 报表。可能性几乎无限,而你已经拥有了坚实的基础。 + +还有其他问题,或在玩转 PDF417 时发现了巧妙技巧?欢迎在下方留言——让我们一起持续交流。祝编码愉快! + + +## 接下来该学习什么? + +以下教程涵盖了与本指南技术紧密相关的主题,帮助你在已有技巧之上进一步深化。每篇资源都提供完整可运行的代码示例以及逐步解释,助你掌握更多 API 功能并探索在项目中的不同实现方式。 + +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Generate DataMatrix Barcode – Pro Guide with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/chinese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..923ca4fe5 --- /dev/null +++ b/barcode/chinese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-07-15 +description: 如何在 C# 中读取 PDF417 条码并从图像中读取多个条码。学习使用 C# 读取条码图像,提供详细代码和技巧。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: zh +lastmod: 2026-07-15 +og_description: 如何在 C# 中快速读取 PDF417 条码。本指南展示了如何从单张图像中读取多个条码并解码每个属性。 +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: 如何在 C# 中读取 PDF417 – 完整代码示例与解释 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: 如何在 C# 中读取 PDF417 – 完整的逐步指南 +url: /zh/net/compact-pdf417-encoding/how-to-read-pdf417-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# 中读取 PDF417 – 完整分步指南 + +是否曾想过 **如何从图像中读取 PDF417**?你并不是唯一的遇到这个问题的开发者。大多数人在需要从扫描文档中提取扩展的 Macro‑PDF417 字段时都会卡住。好消息是,只需几行代码就能解码 PDF417,读取同一图片中的多个条码,并获取规范提供的所有隐藏属性。 + +在本教程中,我们将通过一个真实案例演示 **如何读取 PDF417**、如何 **从单个文件读取多个条码**,以及为什么 **read barcode image C#** 代码会是这样的。完成后,你将拥有一个可直接运行的控制台应用程序,能够打印出你可能需要的所有信息——文件 ID、段 ID、校验和、时间戳,等等。 + +## 前置条件 + +在开始之前,请确保你具备以下条件: + +* .NET 6.0 SDK 或更高版本(代码同样适用于 .NET Core 和 .NET Framework)。 +* Visual Studio 2022(或你喜欢的任何编辑器)。 +* **Aspose.BarCode for .NET** NuGet 包——这就是实际解析 PDF417 的库。 +* 包含 Macro‑PDF417 条码的示例图像(例如 `ExtPDF417Meta.png`)。 + +无需额外配置;库已自带所有所需的解码器。 + +## 第一步:安装 Aspose.BarCode + +在终端中打开项目文件夹并运行: + +```bash +dotnet add package Aspose.BarCode +``` + +该命令会拉取最新的稳定版本(截至 2026 年 7 月为 23.12)。如果你更喜欢在 Visual Studio 内的 Package Manager Console 中操作,请使用: + +```powershell +Install-Package Aspose.BarCode +``` + +> **小贴士:** 在 `.csproj` 中锁定版本号(`23.12.0`),以避免后期意外的破坏性更改。 + +## 第二步:创建控制台应用骨架 + +如果还没有控制台项目,请新建一个: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +用下面的代码替换自动生成的 `Program.cs`。我们将在后面的章节逐块解释。 + +## 第三步:编写完整的 “如何读取 PDF417” 代码 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### 为什么这段代码可行 + +* **`BarCodeReader`** 是核心类,用于流式读取图像、检测条码,并返回 `BarCodeResult` 对象集合。 +* 传入 **`DecodeType.MacroPdf417`** 告诉库特殊处理 Macro‑PDF417;它仍会返回普通 PDF417 符号,从而满足 **read multiple barcodes** 的需求。 +* **`Extended.Pdf417.MacroPdf417`** 对象包含 ISO/IEC 15438 标准定义的所有可选字段——这就是你获取 `FileID`、`SegmentID`、`Checksum` 等信息的地方。 +* `using` 块保证本机资源被释放,防止长时间运行的服务出现内存泄漏。 + +## 第四步:运行应用并验证输出 + +在终端中执行: + +```bash +dotnet run +``` + +你应该会看到类似如下的输出: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +如果图像中包含多个条码,循环会打印分隔线(`----------------------------------------`),并继续处理下一个结果——这正是 **read multiple barcodes** 在实际中的表现。 + +## 常见问题与边缘情况 + +### 如果图像同时包含 Macro‑PDF417 和普通 PDF417 符号怎么办? + +同一次 `BarCodeReader` 调用会返回两者。你可以通过检查 `result.CodeType`(`MacroPdf417` 与 `Pdf417`)来区分。对于普通 PDF417,扩展属性会为 `null`,因此 `if (macro != null)` 判断可以防止 `NullReferenceException`。 + +### 我的条码被旋转或倾斜——读取器还能工作吗? + +Aspose.BarCode 内置了旋转和畸变补偿。只要条码宽度至少占图像宽度的 30%,解码器通常能够成功。对于极端情况,你可以在调用 `ReadBarCodes()` 前启用 `reader.Options.AllowInvertedBarcodes = true;`。 + +### 如何处理大量图像批量读取? + +将读取逻辑包装在 `foreach (var file in Directory.GetFiles(folder, "*.png"))` 循环中。`using` 模式确保每张图像的本机资源在下一次迭代前被释放,从而保持低内存占用。 + +## 完整源码列表(可直接复制粘贴) + +下面是一整块的完整程序,方便快速复制粘贴。没有隐藏依赖——只需 Aspose.BarCode NuGet 包。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## 小结 – 本文覆盖内容 + +* 使用 Aspose.BarCode 在 C# 中 **读取 PDF417**。 +* 从单张图像 **读取多个条码** 的完整步骤。 +* 如何 **read barcode image C#** 并提取每个 Macro‑PDF417 字段。 +* 旋转、批处理以及缺失扩展数据的处理技巧。 + +## 后续步骤与相关主题 + +* **Encode PDF417** – 使用 `BarCodeBuilder` 生成自己的 Macro‑PDF417 条码。 +* **读取其他 2‑D 符号** – QR、DataMatrix、Aztec ——同样使用 `BarCodeReader` 类。 +* **与 ASP.NET Core 集成** – 暴露一个 Web 端点,接受上传的图像并返回包含解码字段的 JSON。 + +尽情实验吧:更改图像路径、在同一文件夹中放入普通 PDF417,或调节 `DecodeType` 标志观察库的行为。玩得越多,你对 **read barcode image C#** 场景的掌握就越熟练。 + +遇到难解的图像?在下方留言或在示例项目的 GitHub 仓库中提交 Issue。祝编码愉快! + +## 接下来你应该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助你在项目中进一步扩展 API 功能并探索替代实现方式,每篇都提供完整可运行的代码示例和逐步解释。 + +- [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/chinese/net/one-dimensional-barcode-types/_index.md b/barcode/chinese/net/one-dimensional-barcode-types/_index.md index 78607b4f1..e33db0245 100644 --- a/barcode/chinese/net/one-dimensional-barcode-types/_index.md +++ b/barcode/chinese/net/one-dimensional-barcode-types/_index.md @@ -55,7 +55,7 @@ url: /zh/net/one-dimensional-barcode-types/ 我们将探索一维条形码的宽窄比配置。在 Aspose.BarCode 的指导下轻松高效地定制您的条形码。 ## 一维条形码类型教程 ### [一维码128配置](./one-dimensional-code-128-configuration/) -了解如何使用 Aspose.BarCode 在 .NET 中生成一维 Code 128 条形码。请遵循我们的无缝条形码集成分步指南。 +了解如何使用 Aspose.BarCode 在 .NET 中生成一维 Code 128 条形码。请遵循我们的无缝条码集成分步指南。 ### [一维 Code 39 配置](./one-dimensional-code-39-configuration/) 了解如何使用 Aspose.BarCode 在 .NET 中生成一维 Code 39 条形码。开发人员的分步指南。 ### [一维代码 93 配置](./one-dimensional-code-93-configuration/) @@ -78,6 +78,8 @@ url: /zh/net/one-dimensional-barcode-types/ 了解如何使用 Aspose.BarCode for .NET 生成一维条形码时处理异常。本分步指南可确保条码解决方案具有容错性。现在就开始! ### [一维宽窄比配置](./one-dimensional-wide-narrow-ratio-configuration/) 使用 Aspose.BarCode for .NET 轻松生成自定义条形码。一维宽窄比配置的分步指南。 +### [使用 Aspose.BarCode 从文本生成条形码 – C# 指南](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +了解如何使用 Aspose.BarCode 在 .NET 中通过文本生成条形码的 C# 示例。请遵循我们的分步指南。 ## 结论 @@ -89,4 +91,4 @@ url: /zh/net/one-dimensional-barcode-types/ {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/chinese/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..afca04bc5 --- /dev/null +++ b/barcode/chinese/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-07-15 +description: 使用 Aspose.BarCode 在 C# 中从文本生成条形码。了解如何更改列数、保存条形码图像,并快速创建条形码 Aspose 解决方案。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: zh +lastmod: 2026-07-15 +og_description: 使用 Aspose.BarCode 从文本生成条形码。本指南展示了如何更改列数、保存条形码图像,以及在几行代码中创建 Aspose + 条形码。 +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: 使用 Aspose.BarCode 从文本生成条形码 – 快速 C# 演练 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: 使用 Aspose.BarCode 从文本生成条形码 – C# 指南 +url: /zh/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose.BarCode 从文本生成条形码 – C# 指南 + +使用 Aspose.BarCode 从文本生成条形码出奇地简单。在本教程中,我们将演示 **如何生成条形码**,调整列布局,最后 **将条形码图像** 保存为 PNG 文件。无论您是构建票务系统、仓库标签打印机,还是仅仅在尝试 QR 风格的码,下面的步骤都能让您快速实现。 + +## 您将学到的内容 + +- 从任意 Unicode 字符串创建条形码(是的,即使是 “Åspóse.Barcóde©” 也能工作)。 +- 为 MicroPdf417 调整 **列数** 以适应窄标签或宽标签。 +- 使用适当的图像格式将结果持久化到磁盘。 +- 处理特殊字符和常见陷阱的技巧,帮助您 **创建 Aspose 条形码** 解决方案。 + +无需外部工具,无需命令行技巧——只需纯 C# 和 Aspose.BarCode 库。 + +## 前提条件 + +在开始之前,请确保您拥有: + +1. 已安装 **.NET 6.0** 或更高版本(代码在 .NET Framework 4.7+ 上也可运行)。 +2. Aspose.BarCode 的 **许可证**,或者您可以使用免费评估版。 +3. 一个可写入的文件夹——我们在示例中称其为 `YOUR_DIRECTORY`。 + +如果缺少上述任意项,请立即获取 NuGet 包: + +```bash +dotnet add package Aspose.BarCode +``` + +就这样——无需手动复制额外的 DLL。 + +## 第一步 – 设置项目和导入 + +首先,创建一个控制台应用程序(或将代码放入任何 C# 项目中)。关键是引入正确的命名空间: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +为什么需要这些 using 语句?`BarcodeGenerator` 位于 `Aspose.BarCode.Generation`,而 `BarCodeImageFormat` 枚举位于 `Aspose.BarCode`。保持导入整洁可以让后续代码读起来像普通英语。 + +## 第二步 – 创建条形码生成器(如何生成条形码) + +现在我们实际 **从文本生成条形码**。`EncodeTypes` 枚举告诉 Aspose 使用哪种符号体系;这里我们选择 `MicroPdf417`,因为它能在紧凑的网格中处理长字符串。 + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +请注意,字符串中包含重音字符和版权符号。Aspose.BarCode 会自动对 Unicode 进行编码,无需预处理文本。 + +## 第三步 – 微调外观(如何更改列数) + +MicroPdf417 允许您控制列数,这直接影响条形码的宽度。更紧凑的布局适用于窄标签;更宽的布局提升大幅打印的可读性。 + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +为什么使用 2 像素模块?它在不显著增大文件大小的情况下提供清晰的图像。可以随意尝试——通常 1 到 4 之间的值效果良好。如果需要不同的列数,只需更改 `Columns` 属性;Aspose 会自动重新计算布局。 + +## 第四步 – 保存条形码图像(保存条形码图像) + +生成器配置完成后,我们即可 **保存条形码图像**。`Save` 方法接受文件路径和图像格式枚举。PNG 是无损的,因此即使放大,条形码仍保持清晰。 + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +小技巧:始终使用绝对路径或确保工作目录符合预期;否则文件可能会出现在 bin 文件夹中,您会找不到它而感到困惑。 + +## 完整可运行示例 + +将所有内容整合在一起,以下是一个可自行复制粘贴到 `Program.cs` 并运行的完整程序: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**预期输出**(控制台): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +如果打开 `MicroPdf417.png`,您会看到一个清晰的 MicroPdf417 条形码,编码了原始字符串,并包含我们提供的特殊字符。 + +## 常见问题与边缘情况 + +### 如果我的文本超过默认容量怎么办? + +当数据超过每行最大容量时,MicroPdf417 会自动切换为多行布局。您仍然可以控制列数,但库可能在后台添加额外的行。无需额外代码——只需关注生成图像的尺寸即可。 + +### 如何将图像格式改为 JPEG 或 BMP? + +将 `BarCodeImageFormat.Png` 替换为 `BarCodeImageFormat.Jpeg`(或 `Bmp`)。请记住,JPEG 会产生压缩伪影,可能影响扫描可靠性。PNG 是最安全的默认选项。 + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### 输出中出现水印——怎么回事? + +那是 Aspose.BarCode 的评估版。要 **创建 Aspose 条形码** 而不出现水印,请按照第 2 步注释行所示加载有效的许可证文件。 + +### 我可以生成其他符号体系吗(QR、Code128 等)? + +当然可以。只需将 `EncodeTypes.MicroPdf417` 替换为 `EncodeTypes` 枚举中的任意其他值,例如 `EncodeTypes.QR` 或 `EncodeTypes.Code128`。其余代码保持不变,使得此方法高度可复用。 + +## 生产就绪条形码生成的专业技巧 + +- 如果在相同设置下创建大量条形码,请 **缓存生成器**;这可以减少对象创建的开销。 +- 为所选符号体系的长度限制 **验证输入字符串**(如果过长,Aspose 会抛出 `ArgumentException`)。 +- 完成后使用 `using` 语句或调用 `Dispose` 来及时释放本机资源。 +- 如需大标签的高分辨率打印,可通过 `generator.Parameters.ImageResolution.DpiX/DpiY` **设置 DPI**。 + +## 结论 + +现在,您已经完全掌握了使用 Aspose.BarCode **从文本生成条形码** 的方法,了解了如何 **更改列数**,以及将条形码图像 **保存为 PNG** 的正确方式。上面的完整可运行示例展示了一个干净、可投入生产的实现。 + +## 接下来您应该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,构建在本指南演示的技巧之上。每个资源都包含完整的可运行代码示例和逐步说明,帮助您掌握更多 API 功能并在项目中探索替代实现方式。 + +- [如何使用 Aspose.BarCode 生成条形码 – Code 39 配置](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [生成条形码图像 – Code 93 使用 Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [如何使用 Aspose.BarCode for .NET 生成 DataMatrix 条码 (ECC 200)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/czech/net/compact-pdf417-encoding/_index.md index 29de108a1..4678968e0 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. +### [Vytvoření metadat čárového kódu PDF417 v C# – Kompletní průvodce krok za krokem](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +Naučte se, jak pomocí Aspose.BarCode pro .NET přidat a spravovat metadata v PDF417 čárových kódech v jazyce C#. + +### [Generování PDF417 čárového kódu v C# – Kompletní průvodce](./generate-pdf417-barcode-in-c-complete-guide/) +Naučte se, jak pomocí Aspose.BarCode pro .NET vygenerovat PDF417 čárový kód v jazyce C# krok za krokem. + +### [Generování PDF417 čárového kódu v C# – Kompletní průvodce krok za krokem](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +Podrobný návod, jak v C# vytvořit PDF417 čárový kód s Aspose.BarCode, včetně nastavení a optimalizace. + +### [Jak číst PDF417 v C# – Kompletní průvodce krok za krokem](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) +Naučte se, jak pomocí Aspose.BarCode pro .NET načíst a dekódovat PDF417 čárové kódy v C# krok za krokem. + ## Č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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/czech/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..062931fd7 --- /dev/null +++ b/barcode/czech/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-07-15 +description: Vytvořte metadata čárového kódu PDF417 v C# pomocí Aspose.BarCode. Naučte + se nastavení Macro PDF417, uložte jako PNG a pracujte s Unicode textem. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: cs +lastmod: 2026-07-15 +og_description: Vytvořte metadata čárového kódu PDF417 v C# pomocí Aspose.BarCode. + Tento průvodce ukazuje všechna nastavení, která potřebujete k vložení ID souboru, + časových razítek a dalších informací. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: Vytvořte metadata pro čárový kód PDF417 v C# – Kompletní programovací průvodce +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: Vytvořte metadata čárového kódu PDF417 v C# – kompletní průvodce krok po kroku +url: /cs/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření metadat čárového kódu PDF417 v C# – Kompletní průvodce krok za krokem + +Už jste někdy potřebovali **vytvořit metadata čárového kódu PDF417** v C#, ale nebyli jste si jisti, které vlastnosti upravit? Nejste v tom sami – vývojáři často narazí na problém, když specifikace vyžaduje například ID souboru, počet segmentů nebo vlastní časová razítka. + +Dobrou zprávou je, že Aspose.BarCode to dělá hračkou. V tomto tutoriálu vytvoříme `BarcodeGenerator` pro **Macro PDF417**, přidáme všechna důležitá metadata a výsledek uložíme jako PNG obrázek. Na konci budete mít plně vybavený čárový kód připravený pro jakýkoli systém řízení dodavatelského řetězce nebo správu dokumentů. + +## Co tento průvodce pokrývá + +Projdeme následující: + +1. Nastavení NuGet balíčku Aspose.BarCode. +2. Inicializaci `BarcodeGenerator` pro **Macro PDF417**. +3. Vyplnění každého užitečného **pole metadat čárového kódu** (ID souboru, ID segmentu, kontrolní součet atd.). +4. Uložení čárového kódu na disk a ověření výstupu. + +Předchozí zkušenost s Macro PDF417 není vyžadována – stačí základní znalost C# a aktuální .NET runtime. + +Proč by vás to mělo zajímat? Vkládání bohatých metadat přímo do čárového kódu umožňuje následným skenerům ověřovat celé přenosy souborů, detekovat chybějící segmenty nebo dokonce spouštět automatizované pracovní postupy. Jinými slovy získáte **robustní, samo‑popisná data** bez nutnosti samostatného databázového vyhledávání. + +## Požadavky + +- .NET 6.0 nebo novější (kód funguje také na .NET Framework 4.7+). +- Visual Studio 2022 (nebo jakékoli IDE dle vašeho výběru). +- NuGet balíček **Aspose.BarCode for .NET** (k dispozici bezplatná zkušební verze). + +Balíček můžete nainstalovat pomocí následujícího příkazu: + +```bash +dotnet add package Aspose.BarCode +``` + +Nyní, když máme základ, ponořme se do samotné implementace. + +## Krok 1: Inicializace BarcodeGenerator pro Macro PDF417 + +Prvním, co potřebujeme, je instance `BarcodeGenerator` nakonfigurovaná pro **Macro PDF417**. Tím říkáme Aspose.BarCode, který algoritmus kódování použít, a získáme místo pro zadání lidsky čitelného textu. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Proč je to důležité:** `EncodeTypes.MacroPdf417` aktivuje rozšířený režim PDF417, který podporuje metadata jako ID souboru a čísla segmentů. Vzorkový text obsahuje Unicode znaky (`Å`, `ó`, `©`), aby se ukázalo, že generátor zvládá vstup mimo ASCII bez problémů. + +## Krok 2: Definice základního vzhledu čárového kódu + +Než začneme přidávat metadata, měli bychom nastavit několik vizuálních parametrů, aby čárový kód nebyl mikroskopickou tečkou. `XDimension` řídí šířku modulu, zatímco `Columns` ovlivňuje celkový tvar. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Pro tip:** Šířka pixelu `2` funguje dobře pro zobrazení na obrazovce i většinu tiskáren. Pokud potřebujete vyšší rozlišení tisku, zvyšte ji na `3` nebo `4`. + +## Krok 3: Vyplnění polí metadat Macro PDF417 + +Nyní přichází jádro tutoriálu – přidání **polí metadat čárového kódu**. Každá vlastnost přímo odpovídá segmentu specifikace Macro PDF417. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Co každá vlastnost dělá + +| Property | Účel | Typická hodnota | +|----------|------|-----------------| +| **MacroPdf417FileID** | Globálně jedinečný identifikátor pro celý souborový set. | `12345678` | +| **MacroPdf417SegmentID** | Index aktuálního segmentu (začíná na `0`). | `12` | +| **MacroPdf417SegmentsCount** | Celkový počet segmentů očekávaných pro soubor. | `20` | +| **MacroPdf417FileName** | Lidsky čitelný název, často původní název souboru. | `"file01"` | +| **MacroPdf417Checksum** | 16‑bitový CCITT kontrolní součet pro detekci chyb. | `1234` | +| **MacroPdf417FileSize** | Velikost původního souboru v bajtech. | `400000` | +| **MacroPdf417TimeStamp** | Kdy byl soubor vygenerován. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Volitelné pole udávající destinaci. | `"street"` | +| **MacroPdf417Sender** | Volitelné pole udávající zdrojový systém. | `"aspose"` | +| **MacroPdf417Terminator** | Příznak, který říká skeneru, že se jedná o poslední segment. | `Pdf417MacroTerminator.Set` | + +> **Proč je potřebujete:** Skenery, které rozumí Macro PDF417, mohou znovu sestavit multi‑segmentní soubor, ověřit integritu pomocí kontrolního součtu a dokonce odmítnout zastaralá data na základě časového razítka. To eliminuje potřebu samostatného manifest souboru. + +## Krok 4: Uložení obrázku čárového kódu + +Jakmile jsou všechny parametry nastaveny, jednoduše zavoláme `Save`. Příklad zapíše PNG soubor do složky, kterou určíte. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Okrajový případ:** Pokud plánujete později vložit čárový kód do PDF, můžete upřednostnit `BarCodeImageFormat.Jpeg` nebo `Pdf`. PNG zachovává bezztrátové detaily, což je užitečné pro ověření. + +## Kompletní funkční příklad + +Spojením všeho dohromady získáte kompletní program, který můžete zkopírovat a vložit do konzolové aplikace: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Očekávaný výstup + +Spuštěním programu se vytvoří soubor s názvem **ExtPDF417Meta.png** ve složce spustitelného souboru. Otevřete jej libovolným prohlížečem obrázků a uvidíte hustý, vysoce kontrastní PDF417 čárový kód. Pokud jej naskenujete čtečkou čárových kódů, která podporuje Macro PDF417, skener vrátí nastavené hodnoty metadat – ID souboru `12345678`, segment `12` z `20` a tak dále. + +## Časté otázky a úskalí + +- **Co když čárový kód vypadá rozmazaně?** Zvyšte `XDimension.Pixels` nebo přepněte na formát obrázku s vyšším rozlišením. +- **Musím nastavit každé pole metadat?** Ne. Pouze pole požadovaná vaším následným systémem jsou povinná. Nepoužitá pole mohou zůstat v jejich výchozím nastavení. +- **Mohu automaticky generovat multi‑segmentní soubor?** Ano – projděte data v cyklu, inkrementujte `MacroPdf417SegmentID` a vygenerujte samostatný čárový kód pro každý segment. Nezapomeňte zachovat `MacroPdf417FileID` konzistentní napříč všemi segmenty. +- **Je podporováno Unicode?** Rozhodně. Vzorkový text obsahuje `Å`, `ó` a `©`, což ukazuje, že Aspose.BarCode zpracovává UTF‑8 přímo. + +## Další kroky: Přes základní použití + +Nyní, když víte, jak **vytvořit metadata čárového kódu PDF417**, můžete chtít prozkoumat: + +- **Vkládání čárových kódů do PDF** pomocí `Aspose.Pdf` pro end‑to‑end generování dokumentů. +- **Čtení zpětných metadat** pomocí `BarcodeReader` pro programové ověřování skenů. +- **Přizpůsobení barev** (popředí/pozadí) pro brandingové účely. +- **Integrace s databází** pro automatické vyplňování polí jako `FileID` nebo `Timestamp`. + +Všechny tyto témata se vztahují k našim sekundárním klíčovým slovům – **macro pdf417**, **aspose barcode c#**, **barcode metadata fields** a **c# barcode generation** – takže najdete spoustu materiálu pro další učení. + +## Závěr + +Právě jsme prošli kompletním, připraveným příkladem pro produkci, jak **vytvořit metadata čárového kódu PDF417** v C#. Od instalace Aspose.BarCode, inicializace `BarcodeGenerator`, vyplnění každého relevantního **pole metadat čárového kódu**, až po finální uložení ostrého PNG, je proces jednoduchý, jakmile znáte správné vlastnosti. + +Vyzkoušejte to, upravte hodnoty a podívejte se, jak skenery reagují. Flexibilita Macro PDF417 vám umožní vložit vše, co následný systém potřebuje – vše v jediném, skenovatelném obrázku. Šťastné kódování a ať jsou vaše čárové kódy vždy bez chyb! + +## 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/) +- [java knihovna čárových kódů – Přidat čárový kód do PDF pomocí Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [Jak vytvořit čárový kód – Kompaktní PDF417 s Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/czech/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..1cf87d3e3 --- /dev/null +++ b/barcode/czech/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: Rychle generujte čárový kód PDF417 a naučte se, jak nastavit sloupce + pro kompaktní obrázek čárového kódu PDF417 v C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: cs +lastmod: 2026-07-15 +og_description: Vytvořte čárový kód PDF417 pomocí Aspose.BarCode a zjistěte, jak nastavit + sloupce pro vytvoření kompaktního obrázku čárového kódu PDF417. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: Generování čárového kódu PDF417 v C# – průvodce krok za krokem +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: Generování čárového kódu PDF417 v C# – Kompletní průvodce +url: /cs/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření PDF417 čárového kódu v C# – Kompletní průvodce + +Už jste někdy potřebovali **vytvořit PDF417 čárový kód** v .NET projektu, ale nevedeli jste, kde začít? Nejste v tom sami. V mnoha podnikových aplikacích – například tiskárny palubních vstupenek, štítky zásob nebo mobilní ticketing – je PDF417 pracovním koněm, který vejde spoustu dat do malé vizuální plochy. + +Zde je pravda: knihovna Aspose.BarCode proces téměř zjednodušuje a můžete dokonce ovládat **jak nastavit sloupce**, aby byl čárový kód co nejkompaktnější. Na konci tohoto tutoriálu budete mít připravený PNG obrázek **PDF417 čárového kódu**, který můžete vložit do jakéhokoli UI, e‑mailu nebo tiskové úlohy. + +## Co si odnesete + +- Plně funkční C# konzolová aplikace, která vytváří PDF417 čárový kód. +- Jasné pochopení *X‑Dimension* (velikost modulu) a proč je důležitá. +- Krok‑za‑krokem instrukce, jak **nastavit sloupce** pro kompaktnější čárový kód. +- Uložený soubor `PNG`, který můžete okamžitě otevřít a ověřit výsledek. +- Tipy na řešení běžných problémů (např. nečitelné čárové kódy, špatný formát obrázku). + +> **Požadavky** – .NET 6+ SDK, Visual Studio 2022 (nebo jakýkoli editor dle vašeho výběru) a NuGet reference na `Aspose.BarCode`. Nic víc. + +--- + +## Krok 1: Instalace NuGet balíčku Aspose.BarCode + +Než budeme moci *vytvořit PDF417 čárový kód*, musí být knihovna v projektu. + +```bash +dotnet add package Aspose.BarCode +``` + +Tento jediný řádek načte všechny typy, které budete potřebovat, včetně `BarcodeGenerator`, `EncodeTypes` a výčtu `BarCodeImageFormat`. + +> **Pro tip:** Pokud cílíte na .NET Framework místo .NET 6, použijte klasický PowerShell příkaz `Install-Package Aspose.BarCode` v konzoli Package Manager Console. + +--- + +## Krok 2: Vytvoření minimální konzolové aplikace + +Vytvoříme malý program, který dělá jen jedno – generuje čárový kód. Otevřete nový adresář, spusťte `dotnet new console`, a poté nahraďte automaticky vygenerovaný `Program.cs` následujícím kódem. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Proč je to důležité:** +- `EncodeTypes.Pdf417` říká knihovně, že chceme PDF417 čárový kód, ne QR nebo Code128. +- `XDimension.Pixels` řídí rozlišení každého malého černého nebo bílého modulu. +- Blok **jak nastavit sloupce** přímo ovlivňuje tvar **obrázku PDF417 čárového kódu**. +- `Truncate = true` odstraňuje všechny zbytečné prázdné řádky, což vám dává ten „kompaktní“ vzhled, který mnoho skenerů miluje. + +--- + +## Krok 3: Hlubší ponor – Porozumění sloupcům a zkrácení + +### Jak nastavit sloupce + +PDF417 uspořádává data v matici *řádky* × *sloupce*. Knihovna ve výchozím nastavení používá 5 sloupců, což funguje ve většině případů. Nicméně můžete potřebovat užší čárový kód, aby se vešel na štítek, nebo širší pro lepší spolehlivost skenování. Vlastnost: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +přijímá hodnoty od **1** do **30** (přesný limit závisí na délce dat). Zde je rychlý přehled: + +| Sloupce | Přibližná šířka (mm) | Kdy použít | +|---------|----------------------|------------| +| 1‑3 | Velmi úzký | Malý štítek, omezený prostor | +| 4‑6 | Standardní | Většina účtenek, vstupenek | +| 7‑10 | Širší | Vysoká hustota dat, lepší čitelnost | + +### Truncate (Kompaktní režim) + +Nastavení `Truncate = true` říká enkodéru, aby ořízl všechny zbytečné prázdné řádky na konci. Výsledkem je **kompaktní PDF417 čárový kód**, který zabírá co nejmenší plochu a přitom obsahuje všechna data. Pokud někdy narazíte na chybu „čárový kód je příliš velký pro štítek“, přepněte tento příznak. + +--- + +## Krok 4: Spuštění aplikace a ověření výstupu + +Zkompilujte a spusťte: + +```bash +dotnet run +``` + +Měli byste vidět zprávu v konzoli potvrzující umístění souboru. Přejděte do složky a otevřete `CompactPdf417.png`. Obrázek bude vypadat zhruba takto: + +![Vygenerovaný obrázek PDF417 čárového kódu](./CompactPdf417.png "Vygenerovaný obrázek PDF417 čárového kódu – kompaktní PNG vytvořené pomocí Aspose.BarCode") + +*Text alternativy obrázku:* **Vygenerovaný obrázek PDF417 čárového kódu** – kompaktní PNG soubor vytvořený kódem v tutoriálu. + +Pokud váš skener dokáže kód přečíst, gratulujeme – úspěšně jste **vytvořili PDF417 čárový kód** a zvládli **nastavit sloupce** pro úhledný **obrázek PDF417 čárového kódu**. + +--- + +## Krok 5: Běžné problémy a jak je opravit + +| Příznak | Pravděpodobná příčina | Rychlé řešení | +|---------|-----------------------|---------------| +| Čárový kód je rozmazaný | `XDimension.Pixels` příliš nízké (např. 1) | Zvyšte na 2‑3 pixely pro ostřejší obrázek. | +| Skener nemůže číst | Příliš mnoho sloupců pro daná data | Snižte `Columns` nebo povolte `Truncate`. | +| Špatný formát souboru | Uloženo omylem s `BarCodeImageFormat.Jpeg` | Použijte `BarCodeImageFormat.Png` pro bezztrátové výsledky. | +| Výjimka `ArgumentOutOfRangeException` | Počet sloupců překračuje povolený rozsah | Udržujte sloupce mezi 1‑30 a zajistěte, aby data pasovala. | + +--- + +## Krok 6: Pokročilejší – Přizpůsobení barev a přidání textu + +Pokud chcete, aby čárový kód ladil s firemní paletou, můžete upravit barvy popředí a pozadí: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Nebo přidat pod čárový kód lidsky čitelný text: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Tyto doplňky jsou volitelné, ale ukazují, jak flexibilní může být workflow **vytvořit PDF417 čárový kód**. + +--- + +## Závěr + +Prošli jsme kompletním, end‑to‑end příkladem, který **vytvoří PDF417 čárový kód** pomocí Aspose.BarCode, vysvětlili **jak nastavit sloupce** pro kontrolu rozměrů čárového kódu a uložili výsledek jako ostrý **obrázek PDF417 čárového kódu** ve formátu PNG. Kód je samostatný, funguje s .NET 6+ a lze jej vložit do jakéhokoli existujícího projektu s minimální námahou. + +Co dál? Zkuste kódovat větší payloady (např. JSON), experimentujte s různými formáty obrázků nebo integrujte generátor do webového API, které poskytuje čárové kódy na vyžádání. Možnosti jsou neomezené a nyní máte pevný základ, na kterém můžete stavět. + +Šťastné programování a ať vaše čárové kódy vždy načte první pokus! + +## 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. + +- [Jak vytvořit čárový kód – Kompaktní PDF417 s Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Jak generovat obrázek čárového kódu v Javě s Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Generovat čárový kód v Javě – Nastavit rozlišení obrázku s Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/czech/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..097c21408 --- /dev/null +++ b/barcode/czech/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,201 @@ +--- +category: general +date: 2026-07-15 +description: Rychle generujte čárový kód PDF417 pomocí C#. Naučte se, jak vytvořit + čárový kód z textu, upravit jeho velikost a nastavit vlastní rozměry čárového kódu + během několika minut. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: cs +lastmod: 2026-07-15 +og_description: Okamžitě generujte PDF417 čárový kód v C#. Tento průvodce ukazuje, + jak generovat čárový kód z textu, upravit jeho velikost a použít vlastní rozměry. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Generovat čárový kód PDF417 v C# – Kompletní programovací tutoriál +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Vytvořte čárový kód PDF417 v C# – Kompletní průvodce krok za krokem +url: /cs/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-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# – Kompletní krok‑za‑krokem průvodce + +Už jste někdy potřebovali **vygenerovat PDF417 čárový kód**, ale nebyli jste si jisti, které nastavení upravit? Nejste v tom jediní — mnoho vývojářů narazí na stejný problém, když poprvé pracují s 2‑D čárovými kódy. Dobrá zpráva? Několika řádky C# můžete převést libovolný řetězec na skenovatelný PDF417 obrázek, ovládat jeho přesnou velikost a dokonce definovat vlastní rozložení sloupců a řádků. + +V tomto tutoriálu vás provedeme tím, jak **vygenerovat čárový kód z textu**, upravit velikost čárového kódu a nastavit vlastní rozměry čárového kódu — vše pomocí populární knihovny Aspose.BarCode. Na konci budete mít připravený ukázkový kód, který můžete vložit do libovolného .NET projektu. + +![Příklad generování PDF417 čárového kódu](https://example.com/og-image.png "Příklad generování PDF417 čárového kódu") + +## Co vytvoříte + +- PDF417 čárový kód, který kóduje řetězec `Åspóse.Barcóde©`. +- Přesnou kontrolu nad X‑dimenzí (šířka pixelu každého modulu). +- Vlastní rozložení se 4 sloupci a 9 řádky. +- PNG soubor uložený na disk. + +Žádné externí služby, žádné kouzelné hůlky — jen čistý C# kód, který můžete zkompilovat hned teď. + +## Požadavky + +- .NET 6.0 nebo novější (kód funguje také na .NET Framework 4.8). +- Visual Studio 2022 nebo jakékoli IDE podporující C#. +- Aspose.BarCode pro .NET (zdarma zkušební verze nebo licencovaná verze). Instalace přes NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +To je vše — jakmile je balíček přidán do projektu, můžete začít. + +## Krok 1 – Generování PDF417 čárového kódu s textovými daty + +První, co potřebujeme, je instance `BarcodeGenerator`, která ví, že pracujeme se symbologií PDF417 a s konkrétním textem, který chceme zakódovat. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Proč je to důležité:** +> `EncodeTypes.Pdf417` říká knihovně, aby použila 2‑D formát PDF417, zatímco druhý argument je **payload pro generování čárového kódu z textu**. Cokoliv sem předáte, se stane daty uloženými v matici čárového kódu. + +## Krok 2 – Úprava velikosti čárového kódu (X‑dimenze) + +Pokud jste někdy tiskli čárový kód, který na účtence vypadal příliš malý, znáte frustraci, když jej skener nezachytí. Vlastnost `XDimension` řídí šířku jednoho modulu (nejmenšího černého nebo bílého čtverečku) v pixelech. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Pro tip:** +> Hodnota 2 px funguje dobře pro většinu scénářů na obrazovce. Pro vysoce rozlišené tisky můžete zvýšit na 3 nebo 4 px. Pamatujte, že větší X‑dimenze zvětšují celkovou velikost obrázku. + +## Krok 3 – Nastavení vlastních rozměrů čárového kódu (sloupce a řádky) + +PDF417 vám umožňuje určit, kolik sloupců a řádků má čárový kód zabírat. Zde vstupují do hry **vlastní rozměry čárového kódu**. Změna těchto hodnot vám může pomoci veškerý kód vejít do úzkého UI prostoru nebo splnit konkrétní velikost štítku. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Co se děje pod kapotou?** +> Knihovna přerozdělí zakódovaná data po zadané mřížce. Méně sloupců znamená vyšší čárové kódy; více řádků je zkrátí. Pohrávejte si s čísly, dokud vizuální rovnováha nebude odpovídat vašim potřebám. + +## Krok 4 – Uložení obrázku čárového kódu + +Nyní, když máme vše nastavené, jednoduše požádáme generátor, aby zapsal PNG soubor. PNG je bezztrátový, takže ostrost modulů zůstane zachována. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Po spuštění programu byste měli vidět soubor na `C:\Barcodes\CustomLayout.png`, který vypadá podobně jako snímek výše. Naskenováním libovolným PDF417‑kompatibilním čtečkou získáte původní řetězec `Åspóse.Barcóde©`. + +## Kompletní funkční příklad + +Níže je kompletní program, který můžete zkopírovat a vložit do konzolové aplikace. Obsahuje všechny `using` direktivy a ošetření chyb, jaké byste očekávali v produkčním kódu. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Očekávaný výstup + +Spuštěním kódu se vypíše: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…a vytvoří se PNG, který lze otevřít v libovolném prohlížeči obrázků. Pokud jej naskenujete mobilní aplikací (např. „Barcode Scanner“ na iOS/Android), dekódovaný text bude přesně **Åspóse.Barcóde©**. + +## Časté otázky a okrajové případy + +| Otázka | Odpověď | +|----------|--------| +| **Mohu použít jiný formát obrázku?** | Ano — `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` nebo `Svg` jsou všechny podporovány. Stačí změnit druhý argument metody `Save`. | +| **Co když můj text obsahuje Unicode znaky?** | Aspose.BarCode plně podporuje UTF‑8, takže příklad s `Å` a `©` funguje bez úprav. | +| **Jak změním úroveň opravy chyb?** | Použijte `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (úrovně 0‑8). Vyšší úrovně zvyšují redundanci, ale i velikost. | +| **Potřebuji průhledné pozadí — je to možné?** | Nastavte `generator.Parameters.Barcode.Image.TransparentBackground = true;` před uložením. | +| **Existuje způsob, jak vložit čárový kód přímo do PDF?** | Rozhodně. Nahraďte volání `Save` tímto: `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` a získáte jednorázový PDF obsahující čárový kód. | + +## Závěr + +Nyní už víte, jak **vygenerovat PDF417 čárový kód** v C# z libovolného řetězce, **upravit velikost čárového kódu** a použít **vlastní rozměry čárového kódu**, aby vyhovoval vašim rozvrhovým potřebám. Čtyřkrokový postup — inicializace, velikost, rozložení, uložení — pokrývá základní workflow pro většinu 2‑D čárových kódů. + +Co dál? Zkuste vyměnit `EncodeTypes.Pdf417` za `EncodeTypes.QR` nebo `EncodeTypes.Code128` a podívejte se, jak se API přizpůsobí. Experimentujte s různými hodnotami `XDimension`, hrajte si s mřížkou sloupců/řádků nebo vložte obrázek do PDF reportu. Možnosti jsou prakticky neomezené a nyní máte pevný základ, na kterém můžete stavět. + +Máte další otázky nebo jste při práci s PDF417 objevili chytrý trik? Zanechte komentář níže — přispějme společně do diskuze. Šť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 podrobnými vysvětleními, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vašich projektech. + +- [Jak generovat Aztec čárový kód s vlastním poměrem stran pomocí Aspose.BarCode pro .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Jak generovat čárový kód – typy jednorozměrných čárových kódů](/barcode/english/net/one-dimensional-barcode-types/) +- [Generování DataMatrix čárového kódu – profesionální průvodce s Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/czech/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..878adf011 --- /dev/null +++ b/barcode/czech/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,314 @@ +--- +category: general +date: 2026-07-15 +description: Jak číst PDF417 čárový kód v C# a číst více čárových kódů z obrázku. + Naučte se číst čárový kód z obrázku v C# s podrobným kódem a tipy. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: cs +lastmod: 2026-07-15 +og_description: Jak rychle načíst čárový kód PDF417 v C#. Tento průvodce vám ukáže, + jak načíst více čárových kódů z jednoho obrázku a dekódovat každou vlastnost. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Jak číst PDF417 v C# – Kompletní ukázkový kód a vysvětlení +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Jak číst PDF417 v C# – Kompletní krok za krokem průvodce +url: /cs/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-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 krok za krokem + +Už jste se někdy ptali, **jak číst PDF417** z obrázku pomocí C#? Nejste v tom jediní. Většina vývojářů narazí na problém, když potřebují získat rozšířené pole Macro‑PDF417 ze skenovaného dokumentu. Dobrá zpráva? Pouhých několik řádků kódu vám umožní dekódovat PDF417, přečíst více čárových kódů na stejném obrázku a získat všechny skryté vlastnosti, které specifikace nabízí. + +V tomto tutoriálu projdeme reálný příklad, který ukazuje **jak číst PDF417**, jak **číst více čárových kódů** z jediného souboru, a proč kód **read barcode image C#** vypadá tak, jak vypadá. Na konci budete mít připravenou konzolovou aplikaci, která vytiskne každou informaci, kterou můžete potřebovat — ID souboru, ID segmentu, kontrolní součet, časová razítka, a tak dál. + +## Požadavky + +Než se pustíme do práce, ujistěte se, že máte: + +* .NET 6.0 SDK nebo novější (kód funguje také s .NET Core a .NET Framework). +* Visual Studio 2022 (nebo jakýkoli editor, který preferujete). +* Balíček NuGet **Aspose.BarCode for .NET** – to je knihovna, která skutečně parsuje PDF417. +* Ukázkový obrázek, který obsahuje čárový kód Macro‑PDF417 (například `ExtPDF417Meta.png`). + +Žádná další konfigurace není potřeba; knihovna obsahuje všechny dekodéry, které potřebujete. + +## Krok 1: Instalace Aspose.BarCode + +Otevřete složku projektu v terminálu a spusťte: + +```bash +dotnet add package Aspose.BarCode +``` + +Tento příkaz stáhne nejnovější stabilní verzi (k červenci 2026 je to 23.12). Pokud dáváte přednost Package Manager Console ve Visual Studiu, použijte: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Pro tip:** uzamkněte verzi (`23.12.0`) ve vašem `.csproj`, abyste se vyhnuli neúmyslným breaking changes později. + +## Krok 2: Vytvoření kostry konzolové aplikace + +Vytvořte nový konzolový projekt, pokud ještě žádný nemáte: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Nahraďte automaticky vygenerovaný `Program.cs` kódem níže. Každý blok vysvětlíme v následujících sekcích. + +## Krok 3: Napište kompletní kód „Jak číst PDF417“ + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Proč tento kód funguje + +* **`BarCodeReader`** je hlavní třída, která načítá obrázek, detekuje čárové kódy a vrací kolekci objektů `BarCodeResult`. +* Předáním **`DecodeType.MacroPdf417`** říkáte knihovně, aby zacházela s Macro‑PDF417 speciálně; stále vrací běžné PDF417 symboly, což splňuje požadavek na **read multiple barcodes**. +* Objekt **`Extended.Pdf417.MacroPdf417`** obsahuje všechna volitelná pole definovaná standardem ISO/IEC 15438 — zde získáte `FileID`, `SegmentID`, `Checksum` a další. +* `using` blok zajišťuje uvolnění nativních zdrojů, čímž zabraňuje únikům paměti v dlouho běžících službách. + +## Krok 4: Spusťte aplikaci a ověřte výstup + +Z terminálu: + +```bash +dotnet run +``` + +Měli byste vidět něco podobného: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Pokud obrázek obsahuje více než jeden čárový kód, smyčka vytiskne oddělovací řádek (`----------------------------------------`) a pokračuje dalším výsledkem — přesně to, co **read multiple barcodes** v praxi vypadá. + +## Časté otázky a okrajové případy + +### Co když obrázek obsahuje jak Macro‑PDF417, tak běžné PDF417 symboly? + +Stejný volání `BarCodeReader` vrátí oba. Můžete je odlišit kontrolou `result.CodeType` (`MacroPdf417` vs `Pdf417`). Rozšířené vlastnosti budou `null` pro běžný PDF417, takže podmínka `if (macro != null)` zabraňuje `NullReferenceException`. + +### Můj čárový kód je otočený nebo zkreslený — bude čtečka stále fungovat? + +Aspose.BarCode obsahuje vestavěnou kompenzaci rotace a zkreslení. Pokud je čárový kód alespoň 30 % šířky obrázku, dekodér obvykle uspěje. V extrémních případech můžete před voláním `ReadBarCodes()` povolit `reader.Options.AllowInvertedBarcodes = true;`. + +### Jak zvládnout velké dávky obrázků? + +Zabalte čtecí logiku do smyčky `foreach (var file in Directory.GetFiles(folder, "*.png"))`. Vzor `using` zajišťuje, že nativní zdroje každého obrázku jsou uvolněny před dalším průchodem, což udržuje nízkou spotřebu paměti. + +## Kompletní výpis zdrojového kódu (připravený ke kopírování) + +Níže je celý program v jednom bloku pro rychlé kopírování. Žádné skryté závislosti — pouze balíček NuGet Aspose.BarCode. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Shrnutí – Co jsme pokryli + +* **Jak číst PDF417** pomocí Aspose.BarCode v C#. +* Přesné kroky k **čtení více čárových kódů** z jednoho obrázku. +* Jak **číst obrázek čárového kódu C#** a extrahovat všechna pole Macro‑PDF417. +* Tipy pro rotaci, dávkové zpracování a řešení chybějících rozšířených dat. + +## Další kroky a související témata + +* **Encode PDF417** – vygenerujte vlastní Macro‑PDF417 čárové kódy pomocí `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – pomocí stejné třídy `BarCodeReader`. +* **Integrate with ASP.NET Core** – vystavte webový endpoint, který přijímá nahraný obrázek a vrací JSON s dekódovanými poli. + +Klidně experimentujte: změňte cestu k obrázku, přidejte běžný PDF417 do stejné složky nebo upravte příznaky `DecodeType`, abyste viděli, jak se knihovna chová. Čím více si budete hrát, tím jistější budete v scénářích **read barcode image C#**. + +Máte obtížný obrázek, který se nechce dekódovat? Zanechte komentář níže nebo otevřete issue v GitHub repozitáři ukázkového projektu. Šť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í implementační přístupy ve vašich projektech. + +- [Jak číst DataMatrix čárové kódy pomocí Aspose.BarCode pro .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Jak vytvořit čárový kód – Compact PDF417 s Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Číst DataMatrix čárový kód C# – Generovat DataMatrix režim (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/czech/net/one-dimensional-barcode-types/_index.md b/barcode/czech/net/one-dimensional-barcode-types/_index.md index 7d07268a4..7cd45e530 100644 --- a/barcode/czech/net/one-dimensional-barcode-types/_index.md +++ b/barcode/czech/net/one-dimensional-barcode-types/_index.md @@ -78,10 +78,12 @@ vydělávejte, jak generovat čárové kódy v .NET s Aspose.BarCode pro .NET. T Naučte se, jak zacházet s výjimkami při generování jednorozměrných čárových kódů pomocí Aspose.BarCode for .NET. Tento průvodce krok za krokem zajišťuje řešení čárových kódů odolné proti chybám. Začněte hned! ### [Konfigurace jednorozměrného širokoúhlého poměru](./one-dimensional-wide-narrow-ratio-configuration/) Snadno generujte přizpůsobené čárové kódy pomocí Aspose.BarCode pro .NET. Průvodce krok za krokem pro jednorozměrnou konfiguraci širokého a úzkého poměru. +### [Generování čárového kódu z textu pomocí Aspose.BarCode – C# průvodce](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Naučte se, jak pomocí Aspose.BarCode v C# vygenerovat čárový kód přímo z textu. Praktický průvodce krok za krokem. ## Závěr -V této sérii výukových programů jsme se ponořili do světa jednorozměrných typů čárových kódů a zaměřili jsme se na jejich konfiguraci a přizpůsobení. S Aspose.BarCode for .NET je tento proces jednoduchý a zajišťuje, že můžete vytvářet čárové kódy přizpůsobené vašim potřebám. Takže, ať už jste zkušený vývojář nebo teprve začínáte, tyto výukové programy vám umožní využít sílu jednorozměrných čárových kódů ve vašich projektech .NET. Začněte hned a uvolněte potenciál technologie čárových kódů! +V této sérii výukových programů jsme se ponořili do světa jednorozměrných typů čárových kódů a zaměřili se na jejich konfiguraci a přizpůsobení. S Aspose.BarCode for .NET je tento proces jednoduchý a zajišťuje, že můžete vytvářet čárové kódy přizpůsobené vašim potřebám. Takže, ať už jste zkušený vývojář nebo teprve začínáte, tyto výukové programy vám umožní využít sílu jednorozměrných čárových kódů ve vašich projektech .NET. Začněte hned a uvolněte potenciál technologie čárových kódů! tímto článkem získáte nejen znalosti o různých typech jednorozměrných čárových kódů, ale také sebevědomí je implementovat do svých projektů. Šťastné kódování! {{< /blocks/products/pf/tutorial-page-section >}} @@ -89,4 +91,4 @@ tímto článkem získáte nejen znalosti o různých typech jednorozměrných {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/czech/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..2be8a63f8 --- /dev/null +++ b/barcode/czech/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-07-15 +description: Generujte čárový kód z textu pomocí Aspose.BarCode v C#. Naučte se, jak + změnit počet sloupců, uložit obrázek čárového kódu a rychle vytvářet řešení čárových + kódů s Aspose. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: cs +lastmod: 2026-07-15 +og_description: Generujte čárový kód z textu pomocí Aspose.BarCode. Tento průvodce + ukazuje, jak změnit počet sloupců, uložit obrázek čárového kódu a vytvořit čárový + kód pomocí Aspose v několika řádcích kódu. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Vytvořte čárový kód z textu pomocí Aspose.BarCode – Rychlý průvodce C# +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Generovat čárový kód z textu pomocí Aspose.BarCode – C# průvodce +url: /cs/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generování čárového kódu z textu pomocí Aspose.BarCode – C# průvodce + +Generování čárového kódu z textu pomocí Aspose.BarCode je překvapivě jednoduché. V tomto tutoriálu si projdeme **jak generovat čárový kód**, upravíme rozložení sloupců a nakonec **uložíme obrázek čárového kódu** jako soubor PNG. Ať už budujete systém pro prodej vstupenek, tiskárnu štítků ve skladu, nebo jen experimentujete s kódy ve stylu QR, níže uvedené kroky vás rychle dostanou k cíli. + +## Co se naučíte + +- Vytvořit čárový kód z libovolného Unicode řetězce (ano, funguje i „Åspóse.Barcóde©“). +- Upravit **počet sloupců** pro MicroPdf417 tak, aby pasoval na úzké nebo široké štítky. +- Uložit výsledek na disk ve správném formátu obrázku. +- Tipy pro práci se speciálními znaky a běžné úskalí při **vytváření čárových kódů Aspose** řešení. + +Žádné externí nástroje, žádné hacky v příkazové řádce – jen čistý C# a knihovna Aspose.BarCode. + +## Požadavky + +Než se pustíme dál, ujistěte se, že máte: + +1. **.NET 6.0** nebo novější nainstalovaný (kód funguje také na .NET Framework 4.7+). +2. Licence **Aspose.BarCode**, nebo můžete začít s bezplatnou zkušební verzí. +3. Složku, do které můžete zapisovat – v příkladech ji budeme nazývat `YOUR_DIRECTORY`. + +Pokud vám něco chybí, stáhněte si nyní NuGet balíček: + +```bash +dotnet add package Aspose.BarCode +``` + +A to je vše – žádné další DLL soubory k ručnímu kopírování. + +## Krok 1 – Nastavení projektu a importů + +Nejprve vytvořte konzolovou aplikaci (nebo vložte kód do libovolného C# projektu). Důležitá část je načíst správné jmenné prostory: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Proč tyto using direktivy? `BarcodeGenerator` se nachází v `Aspose.BarCode.Generation`, zatímco výčtový typ `BarCodeImageFormat` je v `Aspose.BarCode`. Udržování importů v pořádku dělá pozdější kód čitelný jako běžná angličtina. + +## Krok 2 – Vytvoření generátoru čárového kódu (jak generovat čárový kód) + +Nyní skutečně **generujeme čárový kód z textu**. Výčtový typ `EncodeTypes` říká Aspose, jakou symbologii použít; zde volíme `MicroPdf417`, protože zvládá dlouhé řetězce v kompaktní mřížce. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Všimněte si, že řetězec obsahuje diakritické znaky a symbol copyrightu. Aspose.BarCode automaticky kóduje Unicode, takže není potřeba předzpracovávat text. + +## Krok 3 – Doladění vzhledu (jak změnit počet sloupců) + +MicroPdf417 vám umožňuje řídit počet sloupců, což přímo ovlivňuje šířku čárového kódu. Kompaktnější rozložení je skvělé pro úzké štítky; širší rozložení zlepšuje čitelnost na velkých výtiscích. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Proč 2‑pixelové moduly? Poskytují ostrý obrázek bez zvětšení velikosti souboru. Klidně experimentujte – hodnoty mezi 1 a 4 obvykle fungují dobře. Pokud budete potřebovat jiný počet sloupců, stačí změnit vlastnost `Columns`; Aspose automaticky přepočítá rozložení. + +## Krok 4 – Uložení obrázku čárového kódu (uložit obrázek čárového kódu) + +S nakonfigurovaným generátorem jsme připraveni **uložit obrázek čárového kódu**. Metoda `Save` přijímá cestu k souboru a výčtový typ formátu obrázku. PNG je bezztrátový, takže čárový kód zůstane ostrý i po zvětšení. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Rychlá rada: vždy používejte absolutní cestu nebo se ujistěte, že pracovní adresář je ten, který očekáváte; jinak může soubor skončit ve složce bin a budete se divit, proč ho nemůžete najít. + +## Kompletní funkční příklad + +Spojením všech částí získáte samostatný program, který můžete zkopírovat do `Program.cs` a spustit: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Očekávaný výstup** (konzole): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +A pokud otevřete `MicroPdf417.png`, uvidíte ostrý MicroPdf417 čárový kód, který kóduje původní řetězec, včetně speciálních znaků, které jsme mu předali. + +## Časté otázky a okrajové případy + +### Co když je můj text delší než výchozí kapacita? + +MicroPdf417 automaticky přepne na víceřádkové rozložení, když data překročí maximální počet na řádek. Počet sloupců stále můžete řídit, ale knihovna může za scénou přidat další řádky. Žádný další kód není potřeba – jen sledujte rozměry výsledného obrázku. + +### Jak změním formát obrázku na JPEG nebo BMP? + +Nahraďte `BarCodeImageFormat.Png` za `BarCodeImageFormat.Jpeg` (nebo `Bmp`). Pamatujte, že JPEG zavádí kompresní artefakty, které mohou ovlivnit spolehlivost skenování. PNG je nejbezpečnější výchozí volba. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Vidím ve výstupu vodoznak – co je špatně? + +Jedná se o zkušební verzi Aspose.BarCode. Pro **vytváření čárových kódů Aspose** bez vodoznaků načtěte platný licenční soubor, jak je ukázáno v zakomentované řádce kroku 2. + +### Můžu generovat jiné symbologie (QR, Code128, atd.)? + +Určitě. Stačí vyměnit `EncodeTypes.MicroPdf417` za libovolnou jinou hodnotu z výčtu `EncodeTypes`, např. `EncodeTypes.QR` nebo `EncodeTypes.Code128`. Zbytek kódu zůstane stejný, což činí přístup vysoce znovupoužitelný. + +## Profesionální tipy pro produkčně připravené generování čárových kódů + +- **Ukládejte generátor do cache** pokud vytváříte mnoho čárových kódů se stejným nastavením; snižuje to režii při vytváření objektů. +- **Ověřte vstupní řetězec** na omezení délky specifická pro zvolenou symbologii (Aspose vyhodí `ArgumentException`, pokud je příliš dlouhý). +- **Používejte `using` bloky** nebo `Dispose` generátor po dokončení, aby se rychle uvolnily nativní zdroje. +- **Nastavte DPI** pomocí `generator.Parameters.ImageResolution.DpiX/DpiY`, pokud potřebujete vysoce rozlišený tisk pro velké štítky. + +## Závěr + +Nyní přesně víte **jak generovat čárový kód z textu** pomocí Aspose.BarCode, jak **změnit počet sloupců** a správný způsob **uložení obrázku čárového kódu** jako PNG. Kompletní, spustitelný příklad výše ukazuje čistý, produkčně připravený + +## 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 generovat čárový kód – konfigurace Code 39 s Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Generování obrázku čárového kódu – Code 93 s Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [Jak generovat DataMatrix čárové kódy (ECC 200) s Aspose.BarCode pro .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/dutch/net/compact-pdf417-encoding/_index.md index 64f0fba6f..ab22ff292 100644 --- a/barcode/dutch/net/compact-pdf417-encoding/_index.md +++ b/barcode/dutch/net/compact-pdf417-encoding/_index.md @@ -82,7 +82,13 @@ Voorbij de basis, hier zijn enkele praktische tips om je workflow te stroomlijne ## Compact PDF417 Codering Tutorials ### [Compact PDF417 Barcodes Maken](./compact-pdf417-basic-configuration/) -Leer hoe je Compact PDF417 barcodes genereert met Aspose.BarCode voor .NET. Uitgebreide gids met stap‑voor‑stap instructies en code‑voorbeelden. +### [PDF417-barcode-metadata maken in C# – Complete stapsgewijze gids](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) + +### [PDF417-barcode genereren in C# – Complete gids](./generate-pdf417-barcode-in-c-complete-guide/) + +### [PDF417-barcode genereren in C# – Complete stapsgewijze gids](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) + +### [PDF417-barcode lezen in C# – Complete stapsgewijze gids](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) ## Veelgestelde Vragen @@ -112,4 +118,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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/dutch/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..e7323da4f --- /dev/null +++ b/barcode/dutch/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-07-15 +description: Maak PDF417‑barcode‑metadata in C# met Aspose.BarCode. Leer Macro PDF417‑instellingen, + sla op als PNG, en verwerk Unicode‑tekst. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: nl +lastmod: 2026-07-15 +og_description: Maak PDF417 barcode‑metadata in C# met Aspose.BarCode. Deze gids toont + alle instellingen die u nodig heeft om bestands‑ID, tijdstempels en meer in te sluiten. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: PDF417-barcodemetadata maken in C# – Volledige programmeerhandleiding +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: PDF417‑barcode‑metadata maken in C# – Complete stap‑voor‑stap gids +url: /nl/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maak PDF417-barcode-metadata in C# – Complete stapsgewijze gids + +Heb je ooit **PDF417 barcode metadata** moeten maken in C# maar wist je niet welke eigenschappen je moet aanpassen? Je bent niet de enige—ontwikkelaars lopen vaak tegen een muur aan wanneer de specificatie dingen vereist zoals bestands‑ID's, segmentaantallen of aangepaste tijdstempels. + +Het goede nieuws is dat Aspose.BarCode dit kinderspel maakt. In deze tutorial zetten we een `BarcodeGenerator` op voor **Macro PDF417**, voegen we alle belangrijke metadata toe, en slaan we het resultaat op als een PNG‑afbeelding. Aan het einde heb je een volledig uitgeruste barcode klaar voor elke supply‑chain of document‑managementsysteem. + +## Wat deze gids behandelt + +We lopen door: + +1. Het installeren van het Aspose.BarCode NuGet‑pakket. +2. Het initialiseren van een `BarcodeGenerator` voor **Macro PDF417**. +3. Het vullen van elk bruikbaar **barcode‑metadata‑veld** (bestand‑ID, segment‑ID, checksum, enz.). +4. Het opslaan van de barcode op schijf en het verifiëren van de output. + +Ervaring met Macro PDF417 is niet vereist—alleen basiskennis van C# en een recente .NET‑runtime. + +Waarom zou je dit willen? Het embedden van rijke metadata direct in een barcode laat downstream‑scanners volledige bestandsoverdrachten valideren, ontbrekende segmenten detecteren, of zelfs geautomatiseerde workflows activeren. Met andere woorden, je krijgt **robuste, zelfbeschrijvende data** zonder een aparte database‑lookup. + +## Vereisten + +- .NET 6.0 of later (de code werkt ook op .NET Framework 4.7+). +- Visual Studio 2022 (of een IDE naar keuze). +- Het **Aspose.BarCode for .NET** NuGet‑pakket (gratis proefversie beschikbaar). + +Je kunt het pakket installeren met het volgende commando: + +```bash +dotnet add package Aspose.BarCode +``` + +Nu we de basis hebben, laten we duiken in de daadwerkelijke implementatie. + +## Stap 1: Initialiseer de BarcodeGenerator voor Macro PDF417 + +Het eerste dat we nodig hebben is een `BarcodeGenerator`‑instantie geconfigureerd voor **Macro PDF417**. Dit vertelt Aspose.BarCode welk coderingsalgoritme te gebruiken en geeft ons een plek om de mens‑leesbare tekst in te voeren. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Waarom dit belangrijk is:** `EncodeTypes.MacroPdf417` activeert de uitgebreide PDF417‑modus die metadata ondersteunt zoals bestands‑ID's en segmentnummers. De voorbeeldtekst bevat Unicode‑karakters (`Å`, `ó`, `©`) om te bewijzen dat de generator niet‑ASCII‑invoer soepel verwerkt. + +## Stap 2: Definieer de basisuiterlijk van de barcode + +Voordat we metadata toevoegen, moeten we een paar visuele parameters instellen zodat de barcode geen microscopisch stipje wordt. De `XDimension` bepaalt de module‑breedte, terwijl `Columns` de algehele vorm beïnvloedt. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Pro tip:** Een pixelbreedte van `2` werkt goed voor schermweergave en de meeste printers. Als je een hogere resolutie‑print nodig hebt, verhoog dit naar `3` of `4`. + +## Stap 3: Vul de Macro PDF417‑metadata‑velden in + +Nu volgt het hart van de tutorial—het toevoegen van **barcode‑metadata‑velden**. Elke eigenschap mappt direct naar een segment van de Macro PDF417‑specificatie. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Wat elke eigenschap doet + +| Property | Doel | Typische Waarde | +|----------|------|-----------------| +| **MacroPdf417FileID** | Globaal unieke identifier voor de volledige bestandset. | `12345678` | +| **MacroPdf417SegmentID** | Index van het huidige segment (begint bij `0`). | `12` | +| **MacroPdf417SegmentsCount** | Totaal aantal verwachte segmenten voor het bestand. | `20` | +| **MacroPdf417FileName** | Mens‑leesbare naam, vaak de oorspronkelijke bestandsnaam. | `"file01"` | +| **MacroPdf417Checksum** | 16‑bit CCITT‑checksum voor foutdetectie. | `1234` | +| **MacroPdf417FileSize** | Grootte van het oorspronkelijke bestand in bytes. | `400000` | +| **MacroPdf417TimeStamp** | Wanneer het bestand werd gegenereerd. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Optioneel veld dat de bestemming aangeeft. | `"street"` | +| **MacroPdf417Sender** | Optioneel veld dat het bronsysteem aangeeft. | `"aspose"` | +| **MacroPdf417Terminator** | Vlag die de scanner vertelt dat dit het laatste segment is. | `Pdf417MacroTerminator.Set` | + +> **Waarom je deze nodig hebt:** Scanners die Macro PDF417 begrijpen kunnen een multi‑segment bestand opnieuw samenstellen, integriteit verifiëren met de checksum, en zelfs verouderde data afwijzen op basis van de tijdstempel. Dit elimineert de noodzaak van een apart manifest‑bestand. + +## Stap 4: Sla de barcode‑afbeelding op + +Zodra alle parameters zijn ingesteld, roepen we simpelweg `Save` aan. Het voorbeeld schrijft een PNG‑bestand naar een map die je opgeeft. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Randgeval:** Als je van plan bent de barcode later in een PDF te embedden, kun je `BarCodeImageFormat.Jpeg` of `Pdf` verkiezen. PNG behoudt verliesvrije details, wat handig is voor verificatie. + +## Volledig werkend voorbeeld + +Door alles samen te voegen, hier is het volledige programma dat je kunt kopiëren‑plakken in een console‑applicatie: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Verwachte output + +Het uitvoeren van het programma maakt een bestand genaamd **ExtPDF417Meta.png** aan in de map van het uitvoerbare bestand. Open het met een willekeurige afbeeldingsviewer en je ziet een dichte, hoog‑contrast PDF417‑barcode. Als je het scant met een barcode‑lezer die Macro PDF417 ondersteunt, zal de scanner de metadata‑waarden teruggeven die we hebben ingesteld—bestand‑ID `12345678`, segment `12` van `20`, enzovoort. + +## Veelgestelde vragen & valkuilen + +- **Wat als de barcode er wazig uitziet?** Verhoog `XDimension.Pixels` of schakel over naar een hoger‑resolutie‑afbeeldingsformaat. +- **Moet ik elk metadata‑veld instellen?** Nee. Alleen de velden die door je downstream‑systeem vereist zijn, zijn verplicht. Niet‑gebruikte velden kunnen op hun standaardwaarden blijven. +- **Kan ik automatisch een multi‑segment bestand genereren?** Ja—loop over de data, verhoog `MacroPdf417SegmentID`, en genereer een aparte barcode voor elk segment. Zorg ervoor dat `MacroPdf417FileID` consistent blijft over alle segmenten. +- **Wordt Unicode ondersteund?** Absoluut. De voorbeeldtekst bevat `Å`, `ó` en `©`, wat laat zien dat Aspose.BarCode UTF‑8 direct ondersteunt. + +## Volgende stappen: verder gaan dan de basis + +Nu je weet hoe je **PDF417 barcode metadata** kunt maken, wil je misschien verkennen: + +- **Barcodes embedden in PDF's** met `Aspose.Pdf` voor end‑to‑end documentgeneratie. +- **Metadata teruglezen** met `BarcodeReader` om scans programmatisch te valideren. +- **Kleuren aanpassen** (voor‑/achtergrond) voor brandingdoeleinden. +- **Integreren met een database** om velden zoals `FileID` of `Timestamp` automatisch te vullen. + +Al deze onderwerpen hangen samen met onze secundaire zoekwoorden—**macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, en **c# barcode generation**—dus je zult genoeg materiaal vinden om verder te leren. + +## Conclusie + +We hebben zojuist een volledig, productie‑klaar voorbeeld doorlopen van hoe je **PDF417 barcode metadata** in C# kunt **maken**. Van het installeren van Aspose.BarCode, het initialiseren van een `BarcodeGenerator`, het invullen van elk relevant **barcode‑metadata‑veld**, tot het uiteindelijk opslaan van een scherpe PNG, het proces is eenvoudig zodra je de juiste eigenschappen kent. + +Probeer het, pas de waarden aan, en zie hoe scanners reageren. De flexibiliteit van Macro PDF417 betekent dat je alles kunt embedden wat een downstream‑systeem nodig heeft—alles in één enkele, scanbare afbeelding. Veel programmeerplezier, en moge je barcodes altijd fout‑vrij zijn! + +## 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 stapsgewijze uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe maak je een barcode – Compact PDF417 met Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java barcode library – Barcode toevoegen aan PDF met Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [Zo maakt u een barcode – Compacte PDF417 met Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/dutch/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..c3fd0aa1e --- /dev/null +++ b/barcode/dutch/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,201 @@ +--- +category: general +date: 2026-07-15 +description: Genereer PDF417‑barcode snel en leer hoe je kolommen instelt voor een + compacte PDF417‑barcode‑afbeelding in C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: nl +lastmod: 2026-07-15 +og_description: Genereer PDF417‑barcode met Aspose.BarCode en leer hoe je kolommen + instelt om een compacte PDF417‑barcode‑afbeelding te maken. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: PDF417-barcode genereren in C# – Stapsgewijze handleiding +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: PDF417-barcode genereren in C# – Complete gids +url: /nl/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Genereer PDF417‑barcode in C# – Complete gids + +Heb je ooit een **PDF417‑barcode moeten genereren** in een .NET‑project, maar wist je niet waar te beginnen? Je bent niet de enige. In veel bedrijfsapplicaties—denk aan boarding‑pass printers, voorraadlabels of mobiel‑ticketing—is PDF417 de werkpaard die veel data in een klein visueel oppervlak verpakt. + +Het punt is: de Aspose.BarCode‑bibliotheek maakt het hele proces bijna pijnloos, en je kunt zelfs **hoe je kolommen instelt** regelen zodat de barcode zo compact mogelijk wordt. Aan het einde van deze tutorial heb je een kant‑klaar PNG‑beeld van een **PDF417‑barcode‑afbeelding** die je in elke UI, e‑mail of afdruktaak kunt plaatsen. + +## Wat je zult meenemen + +- Een volledig functionele C# console‑app die een PDF417‑barcode maakt. +- Duidelijk begrip van de *X‑Dimension* (module‑grootte) en waarom die belangrijk is. +- Stapsgewijze instructies over **hoe je kolommen instelt** voor een compactere barcode. +- Een opgeslagen `PNG`‑bestand dat je direct kunt openen om het resultaat te verifiëren. +- Tips voor het oplossen van veelvoorkomende valkuilen (bijv. onleesbare barcodes, verkeerd bestandsformaat). + +> **Voorvereisten** – .NET 6+ SDK, Visual Studio 2022 (of een andere editor naar keuze), en een NuGet‑referentie naar `Aspose.BarCode`. Niets anders. + +## Stap 1: Installeer het Aspose.BarCode NuGet‑pakket + +Voordat we een *PDF417‑barcode kunnen genereren*, moet de bibliotheek aanwezig zijn in het project. + +```bash +dotnet add package Aspose.BarCode +``` + +Die enkele regel haalt alle types op die je nodig hebt, inclusief `BarcodeGenerator`, `EncodeTypes` en de `BarCodeImageFormat`‑enum. + +> **Pro‑tip:** Als je .NET Framework target in plaats van .NET 6, gebruik dan de klassieke PowerShell‑opdracht `Install-Package Aspose.BarCode` in de Package Manager Console. + +## Stap 2: Maak een minimale console‑applicatie + +Laten we een klein programma opzetten dat niets anders doet dan een barcode produceren. Open een nieuwe map, voer `dotnet new console` uit, en vervang vervolgens de automatisch gegenereerde `Program.cs` door de onderstaande code. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Waarom dit belangrijk is:** +- `EncodeTypes.Pdf417` vertelt de bibliotheek dat we een PDF417‑barcode willen, niet QR of Code128. +- `XDimension.Pixels` bepaalt de resolutie van elk klein zwart of wit module. +- Het **hoe je kolommen instelt**‑blok beïnvloedt direct de vorm van de **PDF417‑barcode‑afbeelding**. +- `Truncate = true` verwijdert onnodige lege rijen, waardoor je die ‘compacte’ uitstraling krijgt die veel scanners waarderen. + +## Stap 3: Dieper duiken – Begrijpen van kolommen en truncatie + +### Hoe kolommen in te stellen + +PDF417 rangschikt data in een matrix van *rijen* × *kolommen*. De bibliotheek gebruikt standaard 5 kolommen, wat voor de meeste gevallen werkt. Je hebt echter een smallere barcode nodig om op een label te passen of een bredere om de scanbetrouwbaarheid te verbeteren. De eigenschap: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +accepteert waarden van **1** tot **30** (de exacte limiet hangt af van de datalengte). Hier is een snel overzicht: + +| Kolommen | Approx. breedte (mm) | Wanneer te gebruiken | +|----------|----------------------|-----------------------| +| 1‑3 | Zeer smal | Klein label, beperkte ruimte | +| 4‑6 | Standaard | De meeste bonnen, tickets | +| 7‑10 | Breder | Hoge‑dichtheidsdata, betere leesbaarheid | + +### Truncate (Compacte modus) + +Het instellen van `Truncate = true` vertelt de encoder om onnodige lege rijen onderaan af te knippen. Het resultaat is een **compacte PDF417‑barcode‑afbeelding** die zo klein mogelijk is, terwijl alle data behouden blijft. Als je ooit een fout krijgt zoals “barcode te groot voor label”, schakel dan deze vlag. + +## Stap 4: Voer de app uit en controleer de output + +Compile and execute: + +```bash +dotnet run +``` + +Je zou het console‑bericht moeten zien dat de opslaglocatie bevestigt. Navigeer naar de map en open `CompactPdf417.png`. De afbeelding ziet er ongeveer zo uit: + +![Gegenereerde PDF417 barcode afbeelding](./CompactPdf417.png "Gegenereerde PDF417 barcode afbeelding – compacte PNG gemaakt door Aspose.BarCode") + +*Afbeeldings‑alt‑tekst:* **Gegenereerde PDF417 barcode afbeelding** – een compacte PNG‑file geproduceerd door de tutorialcode. + +Als je scanner het kan lezen, gefeliciteerd—je hebt met succes een **PDF417‑barcode gegenereerd** en beheerst **hoe je kolommen instelt** voor een nette **PDF417‑barcode‑afbeelding**. + +## Stap 5: Veelvoorkomende valkuilen & hoe ze op te lossen + +| Symptom | Likely Cause | Quick Fix | +|---------|--------------|-----------| +| Barcode ziet er wazig uit | `XDimension.Pixels` te laag (bijv. 1) | Verhoog naar 2‑3 pixels voor een duidelijkere afbeelding. | +| Scanner kan niet lezen | Te veel kolommen voor de gegeven data | Verminder `Columns` of schakel `Truncate` in. | +| Verkeerd bestandsformaat | Per ongeluk opgeslagen met `BarCodeImageFormat.Jpeg` | Gebruik `BarCodeImageFormat.Png` voor verliesvrije resultaten. | +| Uitzondering `ArgumentOutOfRangeException` | Kolomtelling overschrijdt toegestane bereik | Houd kolommen tussen 1‑30 en zorg dat de data past. | + +## Stap 6: Verder gaan – Kleuren aanpassen en tekst toevoegen + +Als je de barcode wilt laten overeenkomen met een merkpalet, kun je de voor‑ en achtergrondkleuren aanpassen: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Of plaats leesbare tekst onder de barcode: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Deze toevoegingen zijn optioneel, maar ze laten zien hoe flexibel de **PDF417‑barcode genereren** workflow kan zijn. + +## Conclusie + +We hebben een volledig end‑to‑end‑voorbeeld doorlopen dat een **PDF417‑barcode genereert** met Aspose.BarCode, hebben uitgelegd **hoe je kolommen instelt** om de afmetingen van de barcode te beheersen, en het resultaat opgeslagen als een scherpe **PDF417‑barcode‑afbeelding** in PNG‑formaat. De code is zelfstandig, werkt met .NET 6+, en kan met minimale moeite in elk bestaand project worden geïntegreerd. + +Wat is de volgende stap? Probeer grotere payloads te coderen (bijv. JSON‑payloads), experimenteer met verschillende bestandsformaten, of integreer de generator in een web‑API die barcodes op aanvraag levert. De mogelijkheden zijn eindeloos, en je hebt nu een solide basis om op voort te bouwen. + +Veel plezier met coderen, en moge je barcodes altijd bij de eerste poging 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 stapsgewijze 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 – Compacte PDF417 met Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Hoe een barcode‑afbeelding te genereren in Java met Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Barcode genereren Java – Afbeeldingsresolutie instellen met Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/dutch/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..18b5f606e --- /dev/null +++ b/barcode/dutch/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,200 @@ +--- +category: general +date: 2026-07-15 +description: Genereer PDF417-barcode snel met C#. Leer hoe je een barcode uit tekst + genereert, de barcodegrootte aanpast en aangepaste barcode-afmetingen instelt in + enkele minuten. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: nl +lastmod: 2026-07-15 +og_description: Genereer PDF417‑barcode in C# direct. Deze gids laat zien hoe je een + barcode uit tekst genereert, de barcodegrootte aanpast en aangepaste barcode‑afmetingen + toepast. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Genereer PDF417-barcode in C# – Volledige programmeertutorial +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Genereer PDF417‑barcode in C# – Complete stap‑voor‑stap gids +url: /nl/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-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# – Complete Staps‑voor‑Stap Gids + +Heb je ooit **een PDF417 barcode moeten genereren** maar wist je niet welke instellingen je moest aanpassen? Je bent niet de enige—veel ontwikkelaars lopen tegen dezelfde muur aan wanneer ze voor het eerst met 2‑D barcodes werken. Het goede nieuws? Met een paar regels C# kun je elke string omzetten in een scanbare PDF417‑afbeelding, de exacte grootte regelen en zelfs een aangepaste kolom‑rij‑indeling definiëren. + +In deze tutorial lopen we stap voor stap uit hoe je **een barcode uit tekst genereert**, de barcodegrootte aanpast, en aangepaste barcode‑dimensies instelt — alles met de populaire Aspose.BarCode‑bibliotheek. Aan het einde heb je een kant‑klaar voorbeeld dat je in elk .NET‑project kunt gebruiken. + +![Voorbeeld van PDF417 barcode genereren](https://example.com/og-image.png "Voorbeeld van PDF417 barcode genereren") + +## Wat je gaat bouwen + +- Een PDF417 barcode die de string `Åspóse.Barcóde©` codeert. +- Nauwkeurige controle over de X‑dimensie (pixelbreedte van elke module). +- Een aangepaste indeling van 4 kolommen en 9 rijen. +- Een PNG‑bestand dat op schijf wordt opgeslagen. + +Geen externe services, geen toverstaf‑trucs—gewoon platte C#‑code die je direct kunt compileren. + +## Vereisten + +- .NET 6.0 of hoger (de code werkt ook op .NET Framework 4.8). +- Visual Studio 2022 of een IDE die C# ondersteunt. +- Aspose.BarCode voor .NET (gratis proefversie of gelicentieerde versie). Installeer via NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +Dat is alles—zodra het pakket is toegevoegd, ben je klaar om te gaan. + +## Stap 1 – PDF417 Barcode genereren met tekstgegevens + +Het eerste wat we nodig hebben is een instantie van `BarcodeGenerator` die weet dat we met PDF417‑symbologie werken en de exacte tekst die we willen coderen. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Waarom dit belangrijk is:** +> `EncodeTypes.Pdf417` vertelt de bibliotheek om het PDF417 2‑D‑formaat te gebruiken, terwijl het tweede argument de **barcode uit tekst genereren** payload is. Alles wat je hier opgeeft, wordt de data die in de barcode‑matrix wordt opgeslagen. + +## Stap 2 – Barcodegrootte aanpassen (X‑dimensie) + +Als je ooit een barcode hebt afgedrukt die te klein op een bon stond, ken je de frustratie dat de scanner hem mist. De eigenschap `XDimension` bepaalt de breedte van één module (het kleinste zwarte of witte vierkant) in pixels. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Pro tip:** +> Een waarde van 2 px werkt goed voor de meeste scherm‑weergaves. Voor hoge‑resolutie‑afdrukken kun je dit verhogen naar 3 of 4 px. Houd er rekening mee dat grotere X‑dimensies de totale afbeeldingsgrootte vergroten. + +## Stap 3 – Aangepaste barcode‑dimensies instellen (Kolommen & Rijen) + +PDF417 laat je bepalen hoeveel kolommen en rijen de barcode moet innemen. Hier komen de **aangepaste barcode‑dimensies** om de hoek kijken. Het aanpassen van deze waarden kan je helpen de barcode in een krappe UI‑ruimte te passen of te voldoen aan een specifiek labelformaat. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Wat gebeurt er onder de motorkap?** +> De bibliotheek verdeelt de gecodeerde data opnieuw over het opgegeven raster. Minder kolommen betekent hogere barcodes; meer rijen maken ze korter. Speel met de getallen totdat de visuele balans goed voelt voor jouw toepassing. + +## Stap 4 – Barcode‑afbeelding opslaan + +Nu we alles hebben geconfigureerd, vragen we de generator simpelweg om een PNG‑bestand te schrijven. PNG is verliesloos, dus de scherpte van de modules blijft behouden. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Wanneer je het programma uitvoert, zou je een bestand moeten zien op `C:\Barcodes\CustomLayout.png` dat lijkt op de screenshot hierboven. Het scannen ervan met een PDF417‑compatibele lezer geeft de oorspronkelijke string `Åspóse.Barcóde©` terug. + +## Volledig Werkend Voorbeeld + +Hieronder staat het volledige programma dat je kunt kopiëren‑en‑plakken in een console‑applicatie. Het bevat alle using‑directives en foutafhandeling die je in productiecodel verwacht. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Verwachte Output + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…en maakt een PNG die in elke afbeeldingsviewer kan worden geopend. Als je het scant met een mobiele app (bijv. “Barcode Scanner” op iOS/Android), moet de gedecodeerde tekst exact **Åspóse.Barcóde©** zijn. + +## Veelgestelde Vragen & Randgevallen + +| Vraag | Antwoord | +|----------|--------| +| **Kan ik een ander afbeeldingsformaat gebruiken?** | Ja—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, of `Svg` worden allemaal ondersteund. Verander gewoon het tweede argument van `Save`. | +| **Wat als mijn tekst Unicode‑tekens bevat?** | Aspose.BarCode ondersteunt volledig UTF‑8, dus het voorbeeld met `Å` en `©` werkt direct. | +| **Hoe wijzig ik het fout‑corrigatieniveau?** | Gebruik `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (niveaus 0‑8). Hogere niveaus verhogen de redundantie maar ook de grootte. | +| **Ik heb een transparante achtergrond nodig—kan ik dat doen?** | Stel `generator.Parameters.Barcode.Image.TransparentBackground = true;` in vóór het opslaan. | +| **Is er een manier om de barcode direct in een PDF in te sluiten?** | Absoluut. Vervang de `Save`‑aanroep door `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` en je krijgt een één‑pagina PDF met de barcode. | + +## Conclusie + +Je weet nu hoe je **een PDF417 barcode kunt genereren** in C# vanuit elke string, **de barcodegrootte kunt aanpassen**, en **aangepaste barcode‑dimensies** kunt toepassen om aan je lay-outbehoeften te voldoen. De vier‑stappen‑stroom—initialiseren, grootte, lay-out, opslaan—dekt de kernworkflow voor de meeste 2‑D barcode‑scenario's. + +Wat is het volgende? Probeer `EncodeTypes.Pdf417` te vervangen door `EncodeTypes.QR` of `EncodeTypes.Code128` om te zien hoe de API zich aanpast. Experimenteer met verschillende `XDimension`‑waarden, speel met de kolom/rij‑matrix, of voeg de afbeelding in een PDF‑rapport in. De mogelijkheden zijn praktisch eindeloos, en nu heb je een solide basis om op voort te bouwen. + +Heb je meer vragen, of een slimme truc ontdekt tijdens het werken met PDF417? Laat een reactie achter—laten we het gesprek gaande houden. Veel plezier met coderen! + +## 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 een Aztec barcode te genereren met aangepaste beeldverhouding met Aspose.BarCode voor .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Hoe een barcode te genereren – Eén‑dimensionale barcode‑typen](/barcode/english/net/one-dimensional-barcode-types/) +- [DataMatrix barcode genereren – Pro‑gids met Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/dutch/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..1788a1e6e --- /dev/null +++ b/barcode/dutch/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-07-15 +description: Hoe PDF417‑barcode te lezen in C# en meerdere barcodes uit een afbeelding + te lezen. Leer barcode‑afbeelding lezen in C# met gedetailleerde code en tips. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: nl +lastmod: 2026-07-15 +og_description: Hoe lees je snel PDF417‑barcode in C#. Deze gids laat zien hoe je + meerdere barcodes uit één afbeelding kunt lezen en elke eigenschap kunt decoderen. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Hoe PDF417 te lezen in C# – Volledig codevoorbeeld en uitleg +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Hoe PDF417 lezen in C# – Complete stap‑voor‑stap gids +url: /nl/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe PDF417 lezen in C# – Complete stap‑voor‑stap gids + +Heb je je ooit afgevraagd **hoe je PDF417** uit een afbeelding kunt lezen met C#? Je bent niet de enige. De meeste ontwikkelaars lopen tegen een muur aan wanneer ze de uitgebreide Macro‑PDF417‑velden uit een gescand document moeten halen. Het goede nieuws? Met slechts een paar regels code kun je een PDF417 decoderen, meerdere barcodes in dezelfde afbeelding lezen, en elke verborgen eigenschap die de specificatie biedt ophalen. + +In deze tutorial lopen we een praktijkvoorbeeld door dat laat zien **hoe je PDF417 leest**, hoe je **meerdere barcodes** uit één bestand kunt **lezen**, en waarom de **read barcode image C#**‑code er zo uitziet. Aan het einde heb je een kant‑klaar console‑applicatie die elke informatie die je nodig zou kunnen hebben afdrukt – bestands‑ID, segment‑ID, controlesom, tijdstempels, noem maar op. + +## Vereisten + +* .NET 6.0 SDK of later (de code werkt ook met .NET Core en .NET Framework). +* Visual Studio 2022 (of een andere editor naar keuze). +* Het **Aspose.BarCode for .NET** NuGet‑pakket – dit is de bibliotheek die daadwerkelijk PDF417 parseert. +* Een voorbeeldafbeelding die een Macro‑PDF417‑barcode bevat (bijvoorbeeld `ExtPDF417Meta.png`). + +Er is geen extra configuratie nodig; de bibliotheek wordt geleverd met alle decoders die je nodig hebt. + +## Stap 1: Installeer Aspose.BarCode + +Open je projectmap in een terminal en voer uit: + +```bash +dotnet add package Aspose.BarCode +``` + +Dat commando haalt de nieuwste stabiele versie op (vanaf juli 2026 is het 23.12). Als je de Package Manager Console binnen Visual Studio verkiest, gebruik dan: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Pro tip:** vergrendel de versie (`23.12.0`) in je `.csproj` om later per ongeluk brekende wijzigingen te voorkomen. + +## Stap 2: Maak een console‑app‑skelet + +Maak een nieuw console‑project aan als je er nog geen hebt: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Vervang de automatisch gegenereerde `Program.cs` door de onderstaande code. We zullen elk blok in de volgende secties uitleggen. + +## Stap 3: Schrijf de volledige “Hoe PDF417 lezen” code + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Waarom deze code werkt + +* **`BarCodeReader`** is de kernklasse die de afbeelding streamt, barcodes detecteert en een collectie van `BarCodeResult`‑objecten retourneert. +* Het doorgeven van **`DecodeType.MacroPdf417`** vertelt de bibliotheek om Macro‑PDF417 speciaal te behandelen; hij retourneert nog steeds gewone PDF417‑symbolen, wat voldoet aan de **read multiple barcodes**‑vereiste. +* Het **`Extended.Pdf417.MacroPdf417`**‑object bevat elk optioneel veld gedefinieerd door de ISO/IEC 15438‑standaard – daar krijg je `FileID`, `SegmentID`, `Checksum`, enz. +* Het `using`‑blok garandeert dat de native resources worden vrijgegeven, waardoor geheugenlekken in langdurige services worden voorkomen. + +## Stap 4: Voer de applicatie uit en controleer de output + +Vanuit de terminal: + +```bash +dotnet run +``` + +Je zou iets moeten zien zoals: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Als de afbeelding meer dan één barcode bevat, zal de lus een scheidingslijn (`----------------------------------------`) afdrukken en doorgaan met het volgende resultaat – precies wat **read multiple barcodes** in de praktijk betekent. + +## Veelgestelde vragen & randgevallen + +### Wat als de afbeelding zowel Macro‑PDF417 als gewone PDF417‑symbolen bevat? + +Dezelfde `BarCodeReader`‑aanroep zal beide retourneren. Je kunt ze onderscheiden door `result.CodeType` te controleren (`MacroPdf417` vs `Pdf417`). De uitgebreide eigenschappen zullen `null` zijn voor een gewone PDF417, dus de `if (macro != null)`‑guard voorkomt een `NullReferenceException`. + +### Mijn barcode is gedraaid of scheef—zal de lezer nog steeds werken? + +Aspose.BarCode bevat ingebouwde rotatie‑ en vervormingscompensatie. Zolang de barcode minstens 30 % van de afbeeldingsbreedte beslaat, zal de decoder meestal slagen. Voor extreme gevallen kun je `reader.Options.AllowInvertedBarcodes = true;` inschakelen voordat je `ReadBarCodes()` aanroept. + +### Hoe verwerk ik grote batches van afbeeldingen? + +Omhul de leeslogica in een `foreach (var file in Directory.GetFiles(folder, "*.png"))`‑lus. Het `using`‑patroon zorgt ervoor dat de native resources van elke afbeelding worden vrijgegeven vóór de volgende iteratie, waardoor het geheugenverbruik laag blijft. + +## Volledige broncode (klaar om te kopiëren‑plakken) + +Hieronder staat het volledige programma in één blok voor snelle copy‑paste. Geen verborgen afhankelijkheden – alleen het Aspose.BarCode NuGet‑pakket. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Samenvatting – Wat we hebben behandeld + +* **Hoe PDF417 lezen** met Aspose.BarCode in C#. +* De exacte stappen om **meerdere barcodes** uit één afbeelding te **lezen**. +* Hoe **read barcode image C#** uit te voeren en elk Macro‑PDF417‑veld te extraheren. +* Tips voor rotatie, batchverwerking en het omgaan met ontbrekende uitgebreide gegevens. + +## Volgende stappen & gerelateerde onderwerpen + +* **Encode PDF417** – genereer je eigen Macro‑PDF417‑barcodes met `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – met dezelfde `BarCodeReader`‑klasse. +* **Integrate with ASP.NET Core** – exposeer een web‑endpoint dat een geüploade afbeelding accepteert en JSON retourneert met de gedecodeerde velden. + +Voel je vrij om te experimenteren: wijzig het afbeeldingspad, plaats een gewone PDF417 in dezelfde map, of pas de `DecodeType`‑vlaggen aan om te zien hoe de bibliotheek zich gedraagt. Hoe meer je speelt, hoe comfortabeler je wordt met **read barcode image C#**‑scenario's. + +Heb je een lastig beeld dat niet wil decoderen? Laat een reactie achter of open een issue in de GitHub‑repo van het voorbeeldproject. Veel plezier met coderen! + +## 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 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/dutch/net/one-dimensional-barcode-types/_index.md b/barcode/dutch/net/one-dimensional-barcode-types/_index.md index cd103f02d..1f792dce3 100644 --- a/barcode/dutch/net/one-dimensional-barcode-types/_index.md +++ b/barcode/dutch/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ leer hoe u streepjescodes kunt genereren in .NET met Aspose.BarCode voor .NET. D Leer hoe u met uitzonderingen omgaat terwijl u eendimensionale streepjescodes genereert met Aspose.BarCode voor .NET. Deze stapsgewijze handleiding zorgt voor fouttolerante barcodeoplossingen. Begin nu! ### [Eendimensionale configuratie met brede en smalle verhoudingen](./one-dimensional-wide-narrow-ratio-configuration/) Genereer eenvoudig aangepaste barcodes met Aspose.BarCode voor .NET. Stapsgewijze handleiding voor eendimensionale configuratie van breed-nauw verhoudingen. +### [Barcode genereren vanuit tekst met Aspose.BarCode – C#-gids](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Leer hoe u met Aspose.BarCode in C# barcodes maakt vanuit tekst, stap voor stap. ## Conclusie @@ -89,4 +91,4 @@ Met dit artikel verkrijgt u niet alleen kennis over verschillende eendimensional {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/dutch/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..a07899556 --- /dev/null +++ b/barcode/dutch/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-07-15 +description: Genereer een barcode vanuit tekst met Aspose.BarCode in C#. Leer hoe + je het aantal kolommen kunt wijzigen, de barcode‑afbeelding kunt opslaan en snel + barcode‑oplossingen met Aspose kunt maken. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: nl +lastmod: 2026-07-15 +og_description: Genereer een barcode vanuit tekst met Aspose.BarCode. Deze gids laat + zien hoe je het aantal kolommen wijzigt, de barcode-afbeelding opslaat en een barcode + maakt met Aspose in een paar regels code. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Barcode genereren vanuit tekst met Aspose.BarCode – Snelle C# walkthrough +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Barcode genereren vanuit tekst met Aspose.BarCode – C#‑gids +url: /nl/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode genereren vanuit tekst met Aspose.BarCode – C# Gids + +Barcode genereren vanuit tekst met Aspose.BarCode is verrassend eenvoudig. In deze tutorial lopen we door **hoe je een barcode genereert**, passen we de kolomlay-out aan, en slaan we uiteindelijk de **barcode‑afbeelding op** als een PNG‑bestand op. Of je nu een ticketingsysteem bouwt, een magazijnlabelprinter, of gewoon experimenteert met QR‑achtige codes, de onderstaande stappen brengen je er snel. + +## Wat je zult leren + +- Maak een barcode van elke Unicode‑string (ja, zelfs “Åspóse.Barcóde©” werkt). +- Pas het **aantal kolommen** voor MicroPdf417 aan om smalle of brede labels te passen. +- Sla het resultaat op schijf op met het juiste afbeeldingsformaat. +- Tips voor het omgaan met speciale tekens en veelvoorkomende valkuilen wanneer je **barcode Aspose**‑oplossingen maakt. + +Geen externe tools, geen command‑line hacks—alleen plain C# en de Aspose.BarCode bibliotheek. + +## Vereisten + +Before we dive in, make sure you have: + +1. **.NET 6.0** of later geïnstalleerd (de code werkt ook op .NET Framework 4.7+). +2. Een **licentie** voor Aspose.BarCode, of je kunt beginnen met de gratis evaluatieversie. +3. Een map waar je naar kunt schrijven – we noemen deze `YOUR_DIRECTORY` in de voorbeelden. + +Als je een van deze mist, haal dan nu het NuGet‑pakket: + +```bash +dotnet add package Aspose.BarCode +``` + +Dat is alles—geen extra DLL’s die je handmatig moet kopiëren. + +## Stap 1 – Het project en imports instellen + +Eerst, maak een console‑app (of plaats de code in elk C#‑project). Het belangrijke is de juiste namespaces te importeren: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Waarom deze using‑statements? `BarcodeGenerator` bevindt zich in `Aspose.BarCode.Generation`, terwijl de `BarCodeImageFormat`‑enum zich in `Aspose.BarCode` bevindt. Het netjes houden van de imports maakt de latere code leesbaar als gewoon Engels. + +## Stap 2 – De Barcode‑generator maken (hoe barcode te genereren) + +Nu genereren we daadwerkelijk **barcode vanuit tekst**. De `EncodeTypes`‑enum vertelt Aspose welke symbologie te gebruiken; hier kiezen we `MicroPdf417` omdat het lange strings in een compact raster verwerkt. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Merk op dat de string accenten en een copyright‑symbool bevat. Aspose.BarCode codeert Unicode automatisch, dus je hoeft de tekst niet vooraf te verwerken. + +## Stap 3 – Het uiterlijk verfijnen (hoe kolomaantal te wijzigen) + +MicroPdf417 laat je het aantal kolommen bepalen, wat direct de breedte van de barcode beïnvloedt. Een strakkere lay-out is ideaal voor smalle labels; een bredere lay-out verbetert de leesbaarheid op grote afdrukken. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Waarom 2‑pixel modules? Het levert een scherp beeld zonder de bestandsgrootte op te blazen. Voel je vrij om te experimenteren—waarden tussen 1 en 4 werken meestal goed. Als je ooit een ander kolomaantal nodig hebt, wijzig dan simpelweg de `Columns`‑eigenschap; Aspose rekent de lay-out automatisch opnieuw uit. + +## Stap 4 – De barcode‑afbeelding opslaan (barcode‑afbeelding opslaan) + +Met de generator geconfigureerd, zijn we klaar om de **barcode‑afbeelding op te slaan**. De `Save`‑methode accepteert een bestandspad en een afbeeldingsformaat‑enum. PNG is verliesvrij, dus de barcode blijft scherp zelfs na schalen. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Een snelle tip: gebruik altijd een absoluut pad of zorg dat de werkmap is wat je verwacht; anders kan het bestand in de bin‑map terechtkomen en vraag je je af waarom je het niet kunt vinden. + +## Volledig werkend voorbeeld + +Alles bij elkaar, hier is een zelfstandige programma dat je kunt copy‑pasten in `Program.cs` en uitvoeren: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Verwachte output** (console): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +En als je `MicroPdf417.png` opent, zie je een scherpe MicroPdf417‑barcode die de oorspronkelijke string codeert, inclusief de speciale tekens die we hebben ingevoerd. + +## Veelgestelde vragen & randgevallen + +### Wat als mijn tekst langer is dan de standaardcapaciteit? + +MicroPdf417 schakelt automatisch over naar een multi‑row‑lay-out wanneer de data de maximum per rij overschrijdt. Je kunt nog steeds het kolomaantal bepalen, maar de bibliotheek kan extra rijen achter de schermen toevoegen. Geen extra code nodig—houd alleen de afmetingen van de resulterende afbeelding in de gaten. + +### Hoe wijzig ik het afbeeldingsformaat naar JPEG of BMP? + +Vervang `BarCodeImageFormat.Png` door `BarCodeImageFormat.Jpeg` (of `Bmp`). Houd er rekening mee dat JPEG compressie‑artefacten introduceert, wat de scanbetrouwbaarheid kan beïnvloeden. PNG is de veiligste standaard. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Ik zie een watermerk in de output—wat is er mis? + +Dat is de evaluatieversie van Aspose.BarCode. Om **barcode Aspose** zonder watermerken te maken, laad een geldig licentiebestand zoals getoond in de gecommentarieerde regel van Stap 2. + +### Kan ik andere symbologieën genereren (QR, Code128, etc.)? + +Zeker. Vervang gewoon `EncodeTypes.MicroPdf417` door een andere waarde uit de `EncodeTypes`‑enum, bijv. `EncodeTypes.QR` of `EncodeTypes.Code128`. De rest van de code blijft gelijk, waardoor de aanpak zeer herbruikbaar is. + +## Pro‑tips voor productie‑klare barcode‑generatie + +- **Cache de generator** als je veel barcodes met dezelfde instellingen maakt; dit vermindert de overhead van objectcreatie. +- **Valideer de invoerstring** op lengtebeperkingen die specifiek zijn voor de gekozen symbologie (Aspose gooit `ArgumentException` als deze te lang is). +- **Gebruik `using`‑statements** of `Dispose` de generator wanneer je klaar bent om native resources snel vrij te geven. +- **Stel DPI in** via `generator.Parameters.ImageResolution.DpiX/DpiY` als je hoge‑resolutie‑afdrukken nodig hebt voor grote labels. + +## Conclusie + +Je weet nu precies **hoe je barcode vanuit tekst genereert** met Aspose.BarCode, hoe je het **kolomaantal wijzigt**, en de juiste manier om de **barcode‑afbeelding op te slaan** als PNG. Het volledige, uitvoerbare voorbeeld hierboven toont een schone, productie‑klare + +## 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 genereren – Code 39‑configuratie met Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Barcode‑afbeelding genereren – Code 93 met Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [Hoe DataMatrix‑barcodes (ECC 200) te genereren met Aspose.BarCode voor .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/english/net/compact-pdf417-encoding/_index.md index 1762ea2a8..78ee4c066 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. +### [Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +Learn how to embed and manage metadata in PDF417 barcodes using C# with Aspose.BarCode, featuring clear step‑by‑step instructions. +### [Generate PDF417 Barcode in C# – Complete Guide](./generate-pdf417-barcode-in-c-complete-guide/) +Learn how to generate PDF417 barcodes in C# with Aspose.BarCode, featuring step‑by‑step instructions and code samples. +### [Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +Learn how to generate PDF417 barcodes in C# using Aspose.BarCode, with detailed step‑by‑step instructions and code examples. +### [How to Read PDF417 in C# – Complete Step‑by‑Step Guide](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) +Learn how to read PDF417 barcodes in C# using Aspose.BarCode, with clear step‑by‑step instructions and code examples. ## 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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/english/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..38dcaeba8 --- /dev/null +++ b/barcode/english/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-15 +description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: en +lastmod: 2026-07-15 +og_description: Create PDF417 barcode metadata in C# with Aspose.BarCode. This guide + shows every setting you need to embed file‑ID, timestamps, and more. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: Create PDF417 Barcode Metadata in C# – Full Programming Walkthrough +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide +url: /net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + +Ever needed to **create PDF417 barcode metadata** in C# but weren't sure which properties to tweak? You're not the only one—developers often hit a wall when the spec demands things like file IDs, segment counts, or custom timestamps. + +The good news is that Aspose.BarCode makes this a piece of cake. In this tutorial we'll spin up a `BarcodeGenerator` for **Macro PDF417**, sprinkle in all the important metadata, and save the result as a PNG image. By the end you’ll have a fully‑featured barcode ready for any supply‑chain or document‑management system. + +## What This Guide Covers + +We'll walk through: + +1. Setting up the Aspose.BarCode NuGet package. +2. Initializing a `BarcodeGenerator` for **Macro PDF417**. +3. Populating every useful **barcode metadata field** (file ID, segment ID, checksum, etc.). +4. Saving the barcode to disk and verifying the output. + +No prior experience with Macro PDF417 is required—just basic C# knowledge and a recent .NET runtime. + +Why should you care? Embedding rich metadata directly into a barcode lets downstream scanners validate whole file transfers, detect missing segments, or even trigger automated workflows. In other words, you get **robust, self‑describing data** without a separate database lookup. + +## Prerequisites + +- .NET 6.0 or later (the code works on .NET Framework 4.7+ as well). +- Visual Studio 2022 (or any IDE you prefer). +- The **Aspose.BarCode for .NET** NuGet package (free trial available). + +You can install the package with the following command: + +```bash +dotnet add package Aspose.BarCode +``` + +Now that we have the groundwork, let’s dive into the actual implementation. + +## Step 1: Initialize the BarcodeGenerator for Macro PDF417 + +The first thing we need is a `BarcodeGenerator` instance configured for **Macro PDF417**. This tells Aspose.BarCode which encoding algorithm to use and gives us a place to feed the human‑readable text. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Why this matters:** `EncodeTypes.MacroPdf417` activates the extended PDF417 mode that supports metadata like file IDs and segment numbers. The sample text contains Unicode characters (`Å`, `ó`, `©`) to prove that the generator handles non‑ASCII input gracefully. + +## Step 2: Define Basic Barcode Appearance + +Before we start sprinkling metadata, we should set a few visual parameters so the barcode isn’t a microscopic speck. The `XDimension` controls module width, while `Columns` influences the overall shape. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Pro tip:** A pixel width of `2` works well for screen‑display and most printers. If you need a higher‑resolution print, bump it up to `3` or `4`. + +## Step 3: Populate Macro PDF417 Metadata Fields + +Now comes the heart of the tutorial—adding **barcode metadata fields**. Each property maps directly to a segment of the Macro PDF417 specification. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### What Each Property Does + +| Property | Purpose | Typical Value | +|----------|---------|---------------| +| **MacroPdf417FileID** | Globally unique identifier for the whole file set. | `12345678` | +| **MacroPdf417SegmentID** | Index of the current segment (starts at `0`). | `12` | +| **MacroPdf417SegmentsCount** | Total segments expected for the file. | `20` | +| **MacroPdf417FileName** | Human‑readable name, often the original filename. | `"file01"` | +| **MacroPdf417Checksum** | 16‑bit CCITT checksum for error detection. | `1234` | +| **MacroPdf417FileSize** | Size of the original file in bytes. | `400000` | +| **MacroPdf417TimeStamp** | When the file was generated. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Optional field indicating the destination. | `"street"` | +| **MacroPdf417Sender** | Optional field indicating the source system. | `"aspose"` | +| **MacroPdf417Terminator** | Flag that tells the scanner this is the final segment. | `Pdf417MacroTerminator.Set` | + +> **Why you need these:** Scanners that understand Macro PDF417 can reassemble a multi‑segment file, verify integrity with the checksum, and even reject outdated data based on the timestamp. This eliminates the need for a separate manifest file. + +## Step 4: Save the Barcode Image + +Once all parameters are set, we simply call `Save`. The example writes a PNG file to a folder you specify. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Edge case:** If you plan to embed the barcode in a PDF later, you might prefer `BarCodeImageFormat.Jpeg` or `Pdf`. PNG preserves lossless detail, which is handy for verification. + +## Full Working Example + +Putting everything together, here’s the complete program you can copy‑paste into a console app: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Expected Output + +Running the program creates a file named **ExtPDF417Meta.png** in the executable's folder. Open it with any image viewer and you’ll see a dense, high‑contrast PDF417 barcode. If you scan it with a barcode reader that supports Macro PDF417, the scanner will return the metadata values we set—file ID `12345678`, segment `12` of `20`, and so on. + +## Common Questions & Pitfalls + +- **What if the barcode looks blurry?** Increase `XDimension.Pixels` or switch to a higher‑resolution image format. +- **Do I need to set every metadata field?** No. Only the fields required by your downstream system are mandatory. Unused fields can stay at their defaults. +- **Can I generate a multi‑segment file automatically?** Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent across all segments. +- **Is Unicode supported?** Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode handles UTF‑8 out of the box. + +## Next Steps: Going Beyond the Basics + +Now that you know how to **create PDF417 barcode metadata**, you might want to explore: + +- **Embedding barcodes in PDFs** using `Aspose.Pdf` for end‑to‑end document generation. +- **Reading back metadata** with `BarcodeReader` to validate scans programmatically. +- **Customizing colors** (foreground/background) for branding purposes. +- **Integrating with a database** to auto‑populate fields like `FileID` or `Timestamp`. + +All of these topics tie back to our secondary keywords—**macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, and **c# barcode generation**—so you’ll find plenty of material to keep learning. + +## Conclusion + +We’ve just walked through a complete, production‑ready example of how to **create PDF417 barcode metadata** in C#. From installing Aspose.BarCode, initializing a `BarcodeGenerator`, filling every relevant **barcode metadata field**, to finally saving a crisp PNG, the process is straightforward once you know the right properties. + +Give it a try, tweak the values, and see how scanners react. The flexibility of Macro PDF417 means you can embed everything a downstream system needs—all inside a single, scannable image. Happy coding, and may your barcodes always be error‑free! + + +## 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/) +- [java barcode library – Add barcode to PDF using Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/og-image.png b/barcode/english/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/og-image.png new file mode 100644 index 000000000..9ddb2253a Binary files /dev/null and b/barcode/english/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/og-image.png differ diff --git a/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..732a56f96 --- /dev/null +++ b/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-07-15 +description: Generate PDF417 barcode quickly and learn how to set columns for a compact + PDF417 barcode image in C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: en +lastmod: 2026-07-15 +og_description: Generate PDF417 barcode with Aspose.BarCode and learn how to set columns + to create a compact PDF417 barcode image. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: Generate PDF417 Barcode in C# – Step‑by‑Step Guide +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: Generate PDF417 Barcode in C# – Complete Guide +url: /net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generate PDF417 Barcode in C# – Complete Guide + +Ever needed to **generate PDF417 barcode** in a .NET project but weren’t sure where to start? You’re not alone. In many enterprise apps—think boarding‑pass printers, inventory tags, or mobile‑ticketing—PDF417 is the workhorse that packs a lot of data into a small visual footprint. + +Here’s the thing: the Aspose.BarCode library makes the whole process almost painless, and you can even control **how to set columns** so the barcode becomes as compact as possible. By the end of this tutorial you’ll have a ready‑to‑use PNG image of a **PDF417 barcode image** that you can drop into any UI, email, or print job. + +## What You’ll Walk Away With + +- A fully functional C# console app that creates a PDF417 barcode. +- Clear understanding of the *X‑Dimension* (module size) and why it matters. +- Step‑by‑step instructions on **how to set columns** for a tighter barcode. +- A saved `PNG` file you can open instantly to verify the result. +- Tips on troubleshooting common pitfalls (e.g., unreadable barcodes, wrong image format). + +> **Prerequisites** – .NET 6+ SDK, Visual Studio 2022 (or any editor you like), and a NuGet reference to `Aspose.BarCode`. Nothing else. + +--- + +## Step 1: Install the Aspose.BarCode NuGet Package + +Before we can *generate PDF417 barcode*, the library has to be present in the project. + +```bash +dotnet add package Aspose.BarCode +``` + +That single line pulls in all the types you’ll need, including `BarcodeGenerator`, `EncodeTypes`, and the `BarCodeImageFormat` enum. + +> **Pro tip:** If you target .NET Framework instead of .NET 6, use the classic `Install-Package Aspose.BarCode` PowerShell command inside the Package Manager Console. + +--- + +## Step 2: Create a Minimal Console Application + +Let’s scaffold a tiny program that does nothing but produce a barcode. Open a new folder, run `dotnet new console`, then replace the auto‑generated `Program.cs` with the code below. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Why this matters:** +- `EncodeTypes.Pdf417` tells the library we want a PDF417 barcode, not QR or Code128. +- `XDimension.Pixels` controls the resolution of each tiny black or white module. +- The **how to set columns** block directly influences the shape of the **PDF417 barcode image**. +- `Truncate = true` drops any unnecessary empty rows, giving you that “compact” look many scanners love. + +--- + +## Step 3: Dive Deeper – Understanding Columns and Truncation + +### How to Set Columns + +PDF417 arranges data in a matrix of *rows* × *columns*. The library defaults to 5 columns, which works for most cases. However, you might need a narrower barcode to fit a label or a wider one to improve scan reliability. The property: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +accepts values from **1** up to **30** (the exact limit depends on the data length). Here’s a quick cheat sheet: + +| Columns | Approx. Width (mm) | When to Use | +|---------|-------------------|-------------| +| 1‑3 | Very narrow | Small label, limited space | +| 4‑6 | Standard | Most receipts, tickets | +| 7‑10 | Wider | High‑density data, better readability | + +### Truncate (Compact Mode) + +Setting `Truncate = true` tells the encoder to cut off any unnecessary blank rows at the bottom. The result is a **compact PDF417 barcode image** that occupies the smallest possible area while still containing all the data. If you ever get “barcode too big for label” errors, toggle this flag. + +--- + +## Step 4: Run the App and Verify the Output + +Compile and execute: + +```bash +dotnet run +``` + +You should see the console message confirming the save location. Navigate to the folder and open `CompactPdf417.png`. The image will look something like this: + +![Generated PDF417 barcode image](./CompactPdf417.png "Generated PDF417 barcode image – compact PNG created by Aspose.BarCode") + +*Image alt text:* **Generated PDF417 barcode image** – a compact PNG file produced by the tutorial code. + +If your scanner can read it, congratulations—you’ve successfully **generate PDF417 barcode** and mastered **how to set columns** for a tidy **PDF417 barcode image**. + +--- + +## Step 5: Common Pitfalls & How to Fix Them + +| Symptom | Likely Cause | Quick Fix | +|---------|--------------|-----------| +| Barcode appears blurry | `XDimension.Pixels` too low (e.g., 1) | Raise to 2‑3 pixels for a clearer image. | +| Scanner can’t read | Too many columns for the given data | Reduce `Columns` or enable `Truncate`. | +| Wrong file format | Saved with `BarCodeImageFormat.Jpeg` by mistake | Use `BarCodeImageFormat.Png` for lossless results. | +| Exception `ArgumentOutOfRangeException` | Column count exceeds allowed range | Keep columns between 1‑30 and ensure data fits. | + +--- + +## Step 6: Going Further – Customizing Colors and Adding Text + +If you want to make the barcode match a brand palette, you can tweak foreground and background colors: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Or overlay human‑readable text under the barcode: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +These additions are optional, but they illustrate how flexible the **generate PDF417 barcode** workflow can be. + +--- + +## Conclusion + +We’ve walked through a complete, end‑to‑end example that **generate PDF417 barcode** using Aspose.BarCode, explained **how to set columns** to control the barcode’s dimensions, and saved the result as a crisp **PDF417 barcode image** in PNG format. The code is self‑contained, works with .NET 6+, and can be dropped into any existing project with minimal fuss. + +What’s next? Try encoding larger payloads (e.g., JSON payloads), experiment with different image formats, or integrate the generator into a web API that serves barcodes on demand. The sky’s the limit, and you now have a solid foundation to build on. + +Happy coding, and may your barcodes always scan on the first try! + + +## 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 Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-guide/og-image.png b/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/og-image.png new file mode 100644 index 000000000..a2d002d73 Binary files /dev/null and b/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/og-image.png differ diff --git a/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md b/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..2e7879f90 --- /dev/null +++ b/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-07-15 +description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: en +lastmod: 2026-07-15 +og_description: Generate PDF417 barcode in C# instantly. This guide shows how to generate + barcode from text, adjust barcode size, and apply custom barcode dimensions. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Generate PDF417 Barcode in C# – Full Programming Tutorial +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide +url: /net/compact-pdf417-encoding/generate-pdf417-barcode-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 PDF417 Barcode in C# – Complete Step‑by‑Step Guide + +Ever needed to **generate PDF417 barcode** but weren’t sure which settings to tweak? You’re not the only one—many developers hit the same wall when they first play with 2‑D barcodes. The good news? With a few lines of C# you can turn any string into a scannable PDF417 image, control its exact size, and even define a custom column‑row layout. + +In this tutorial we’ll walk through how to **generate barcode from text**, adjust the barcode size, and set custom barcode dimensions — all using the popular Aspose.BarCode library. By the end you’ll have a ready‑to‑run sample you can drop into any .NET project. + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## What You’ll Build + +- A PDF417 barcode that encodes the string `Åspóse.Barcóde©`. +- Precise control over the X‑dimension (pixel width of each module). +- A custom layout of 4 columns and 9 rows. +- A PNG file saved to disk. + +No external services, no magic‑wand tricks—just plain C# code you can compile right now. + +## Prerequisites + +- .NET 6.0 or later (the code works on .NET Framework 4.8 as well). +- Visual Studio 2022 or any IDE that supports C#. +- Aspose.BarCode for .NET (free trial or licensed version). Install via NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +That’s it—once the package is referenced you’re good to go. + +## Step 1 – Generate PDF417 Barcode with Text Data + +The first thing we need is an instance of `BarcodeGenerator` that knows we’re dealing with PDF417 symbology and the exact text we want to encode. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Why this matters:** +> `EncodeTypes.Pdf417` tells the library to use the PDF417 2‑D format, while the second argument is the **generate barcode from text** payload. Anything you pass here becomes the data stored in the barcode matrix. + +## Step 2 – Adjust Barcode Size (X‑Dimension) + +If you’ve ever printed a barcode that looked too tiny on a receipt, you know the frustration of the scanner missing it. The `XDimension` property controls the width of a single module (the smallest black or white square) in pixels. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Pro tip:** +> A value of 2 px works well for most screen‑display scenarios. For high‑resolution prints you might bump this up to 3 or 4 px. Just remember that larger X‑dimensions increase the overall image size. + +## Step 3 – Set Custom Barcode Dimensions (Columns & Rows) + +PDF417 lets you dictate how many columns and rows the barcode should occupy. This is where the **custom barcode dimensions** come into play. Changing these values can help you fit the barcode into a tight UI space or meet a specific label size. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **What’s happening under the hood?** +> The library redistributes the encoded data across the specified grid. Fewer columns mean taller barcodes; more rows make them shorter. Play with the numbers until the visual balance feels right for your application. + +## Step 4 – Save the Barcode Image + +Now that we’ve configured everything, we simply ask the generator to write a PNG file. PNG is lossless, so the crispness of the modules stays intact. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +When you run the program, you should see a file at `C:\Barcodes\CustomLayout.png` that looks similar to the screenshot above. Scanning it with any PDF417‑compatible reader will return the original string `Åspóse.Barcóde©`. + +## Full Working Example + +Below is the complete program you can copy‑paste into a console app. It includes all the using directives and error handling you’d expect in production code. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Expected Output + +Running the code prints: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…and creates a PNG that can be opened in any image viewer. If you scan it with a mobile app (e.g., “Barcode Scanner” on iOS/Android), the decoded text should be exactly **Åspóse.Barcóde©**. + +## Common Questions & Edge Cases + +| Question | Answer | +|----------|--------| +| **Can I use a different image format?** | Yes—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, or `Svg` are all supported. Just change the second argument of `Save`. | +| **What if my text contains Unicode characters?** | Aspose.BarCode fully supports UTF‑8, so the example with `Å` and `©` works out‑of‑the‑box. | +| **How do I change the error‑correction level?** | Use `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (levels 0‑8). Higher levels increase redundancy but also size. | +| **I need a transparent background—can I do that?** | Set `generator.Parameters.Barcode.Image.TransparentBackground = true;` before saving. | +| **Is there a way to embed the barcode directly into a PDF?** | Absolutely. Replace the `Save` call with `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` and you’ll get a one‑page PDF containing the barcode. | + +## Conclusion + +You now know how to **generate PDF417 barcode** in C# from any string, **adjust barcode size**, and apply **custom barcode dimensions** to fit your layout needs. The four‑step flow—initialize, size, layout, save—covers the core workflow for most 2‑D barcode scenarios. + +What’s next? Try swapping `EncodeTypes.Pdf417` for `EncodeTypes.QR` or `EncodeTypes.Code128` to see how the API adapts. Experiment with different `XDimension` values, play with the column/row matrix, or embed the image into a PDF report. The possibilities are practically endless, and now you have a solid foundation to build on. + +Got more questions, or discovered a clever trick while playing with PDF417? Drop a comment below—let’s keep the conversation rolling. 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 Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Generate DataMatrix Barcode – Pro Guide with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/generate-pdf417-barcode-in-c-complete-step-by-step-guide/og-image.png b/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/og-image.png new file mode 100644 index 000000000..90ad652fe Binary files /dev/null and b/barcode/english/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/og-image.png differ diff --git a/barcode/english/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/english/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..08ef34a80 --- /dev/null +++ b/barcode/english/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,316 @@ +--- +category: general +date: 2026-07-15 +description: How to read PDF417 barcode in C# and read multiple barcodes from an image. + Learn to read barcode image C# with detailed code and tips. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: en +lastmod: 2026-07-15 +og_description: How to read PDF417 barcode in C# quickly. This guide shows you how + to read multiple barcodes from a single image and decode each property. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: How to Read PDF417 in C# – Full Code Sample & Explanation +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: How to Read PDF417 in C# – Complete Step‑by‑Step Guide +url: /net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-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 Step‑by‑Step Guide + +Ever wondered **how to read PDF417** from an image using C#? You're not the only one. Most devs hit a wall when they need to pull out the extended Macro‑PDF417 fields from a scanned document. The good news? With just a few lines of code you can decode a PDF417, read multiple barcodes in the same picture, and grab every hidden property the spec offers. + +In this tutorial we’ll walk through a real‑world example that shows **how to read PDF417**, how to **read multiple barcodes** from a single file, and why **read barcode image C#** code looks the way it does. By the end you’ll have a ready‑to‑run console app that prints every piece of information you might need—file ID, segment ID, checksum, timestamps, you name it. + +## Prerequisites + +Before we dive in, make sure you have: + +* .NET 6.0 SDK or later (the code works with .NET Core and .NET Framework as well). +* Visual Studio 2022 (or any editor you prefer). +* The **Aspose.BarCode for .NET** NuGet package – this is the library that actually parses PDF417. +* A sample image that contains a Macro‑PDF417 barcode (for example `ExtPDF417Meta.png`). + +No extra configuration is required; the library ships with all the decoders you need. + +## Step 1: Install Aspose.BarCode + +Open your project folder in a terminal and run: + +```bash +dotnet add package Aspose.BarCode +``` + +That command pulls the latest stable version (as of July 2026 it’s 23.12). If you prefer the Package Manager Console inside Visual Studio, use: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Pro tip:** lock the version (`23.12.0`) in your `.csproj` to avoid accidental breaking changes later. + +## Step 2: Create a Console App Skeleton + +Create a new console project if you don’t already have one: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Replace the autogenerated `Program.cs` with the code below. We’ll explain each block in the next sections. + +## Step 3: Write the Full “How to Read PDF417” Code + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Why This Code Works + +* **`BarCodeReader`** is the core class that streams the image, detects barcodes, and returns a collection of `BarCodeResult` objects. +* Passing **`DecodeType.MacroPdf417`** tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 symbols, which satisfies the **read multiple barcodes** requirement. +* The **`Extended.Pdf417.MacroPdf417`** object holds every optional field defined by the ISO/IEC 15438 standard – that’s where you get `FileID`, `SegmentID`, `Checksum`, etc. +* The `using` block guarantees the native resources are released, preventing memory leaks in long‑running services. + +## Step 4: Run the Application and Verify Output + +From the terminal: + +```bash +dotnet run +``` + +You should see something like: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +If the image contains more than one barcode, the loop will print a separator line (`----------------------------------------`) and continue with the next result—exactly what **read multiple barcodes** looks like in practice. + +## Common Questions & Edge Cases + +### What if the image has both Macro‑PDF417 and regular PDF417 symbols? + +The same `BarCodeReader` call will return both. You can differentiate them by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents a `NullReferenceException`. + +### My barcode is rotated or skewed—will the reader still work? + +Aspose.BarCode includes built‑in rotation and distortion compensation. As long as the barcode is at least 30 % of the image width, the decoder will usually succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes = true;` before calling `ReadBarCodes()`. + +### How do I handle large batches of images? + +Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, "*.png"))` loop. The `using` pattern ensures each image’s native resources are freed before the next iteration, keeping memory usage low. + +## Full Source Listing (Copy‑Paste Ready) + +Below is the entire program in one block for quick copy‑paste. No hidden dependencies—just the Aspose.BarCode NuGet package. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Recap – What We Covered + +* **How to read PDF417** using Aspose.BarCode in C#. +* The exact steps to **read multiple barcodes** from a single image. +* How to **read barcode image C#** and extract every Macro‑PDF417 field. +* Tips for rotation, batch processing, and handling missing extended data. + +## Next Steps & Related Topics + +* **Encode PDF417** – generate your own Macro‑PDF417 barcodes with `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – using the same `BarCodeReader` class. +* **Integrate with ASP.NET Core** – expose a web endpoint that accepts an uploaded image and returns JSON with the decoded fields. + +Feel free to experiment: change the image path, drop a plain PDF417 into the same folder, or tweak the `DecodeType` flags to see how the library behaves. The more you play, the more comfortable you’ll become with **read barcode image C#** scenarios. + +Got a tricky image that refuses to decode? Drop a comment below or open an issue on the GitHub repo of the sample project. 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 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-step-by-step-guide/og-image.png b/barcode/english/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/og-image.png new file mode 100644 index 000000000..9a74ab382 Binary files /dev/null and b/barcode/english/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/og-image.png differ diff --git a/barcode/english/net/one-dimensional-barcode-types/_index.md b/barcode/english/net/one-dimensional-barcode-types/_index.md index 6c53014d9..83092907e 100644 --- a/barcode/english/net/one-dimensional-barcode-types/_index.md +++ b/barcode/english/net/one-dimensional-barcode-types/_index.md @@ -98,6 +98,8 @@ earn how to generate barcodes in .NET with Aspose.BarCode for .NET. This compreh Learn how to handle exceptions while generating one-dimensional barcodes using Aspose.BarCode for .NET. This step-by-step guide ensures error-tolerant barcode solutions. Get started now! ### [One-Dimensional Wide-Narrow Ratio Configuration](./one-dimensional-wide-narrow-ratio-configuration/) Generate customized barcodes easily with Aspose.BarCode for .NET. Step-by-step guide for one-dimensional wide-narrow ratio configuration. +### [Generate barcode from text using Aspose.BarCode – C# Guide](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Learn how to generate a barcode from text in C# using Aspose.BarCode. Follow our step‑by‑step guide for quick implementation. ## Frequently Asked Questions @@ -133,4 +135,4 @@ With this article, you'll not only gain knowledge about various one‑dimensiona {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/english/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..d787e2e24 --- /dev/null +++ b/barcode/english/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-07-15 +description: Generate barcode from text using Aspose.BarCode in C#. Learn how to change + column count, save barcode image, and create barcode Aspose solutions fast. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: en +lastmod: 2026-07-15 +og_description: Generate barcode from text using Aspose.BarCode. This guide shows + how to change column count, save barcode image, and create barcode Aspose in a few + lines of code. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Generate barcode from text with Aspose.BarCode – Quick C# Walkthrough +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Generate barcode from text using Aspose.BarCode – C# Guide +url: /net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generate barcode from text using Aspose.BarCode – C# Guide + +Generate barcode from text using Aspose.BarCode is surprisingly simple. In this tutorial we’ll walk through **how to generate barcode**, tweak the column layout, and finally **save barcode image** as a PNG file. Whether you’re building a ticketing system, a warehouse label printer, or just experimenting with QR‑style codes, the steps below will get you there quickly. + +## What You’ll Learn + +- Create a barcode from any Unicode string (yes, even “Åspóse.Barcóde©” works). +- Adjust the **column count** for MicroPdf417 to fit narrow or wide labels. +- Persist the result to disk with the proper image format. +- Tips for handling special characters and common pitfalls when you **create barcode Aspose** solutions. + +No external tools, no command‑line hacks—just plain C# and the Aspose.BarCode library. + +## Prerequisites + +Before we dive in, make sure you have: + +1. **.NET 6.0** or later installed (the code works on .NET Framework 4.7+ as well). +2. A **license** for Aspose.BarCode, or you can start with the free evaluation version. +3. A folder you can write to – we’ll call it `YOUR_DIRECTORY` in the examples. + +If you’re missing any of these, grab the NuGet package now: + +```bash +dotnet add package Aspose.BarCode +``` + +That’s it—no extra DLLs to copy manually. + +## Step 1 – Set Up the Project and Imports + +First, spin up a console app (or drop the code into any C# project). The important part is pulling in the right namespaces: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Why these using statements? `BarcodeGenerator` lives in `Aspose.BarCode.Generation`, while the `BarCodeImageFormat` enum lives in `Aspose.BarCode`. Keeping the imports tidy makes the later code read like plain English. + +## Step 2 – Create the Barcode Generator (how to generate barcode) + +Now we actually **generate barcode from text**. The `EncodeTypes` enum tells Aspose which symbology to use; here we pick `MicroPdf417` because it handles long strings in a compact grid. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Notice the string contains accented characters and a copyright symbol. Aspose.BarCode automatically encodes Unicode, so you don’t need to pre‑process the text. + +## Step 3 – Fine‑Tune the Appearance (how to change column count) + +MicroPdf417 lets you control the number of columns, which directly influences the barcode’s width. A tighter layout is great for narrow labels; a wider layout improves readability on large prints. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Why 2‑pixel modules? It gives a crisp image without blowing up the file size. Feel free to experiment—values between 1 and 4 usually work well. If you ever need a different column count, just change the `Columns` property; Aspose will recalculate the layout automatically. + +## Step 4 – Save the Barcode Image (save barcode image) + +With the generator configured, we’re ready to **save barcode image**. The `Save` method accepts a file path and an image format enum. PNG is loss‑less, so the barcode stays sharp even after scaling. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +A quick tip: always use an absolute path or ensure the working directory is what you expect; otherwise the file may end up in the bin folder and you’ll wonder why you can’t find it. + +## Full Working Example + +Putting it all together, here’s a self‑contained program you can copy‑paste into `Program.cs` and run: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Expected output** (console): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +And if you open `MicroPdf417.png`, you’ll see a crisp MicroPdf417 barcode that encodes the original string, complete with the special characters we fed it. + +## Common Questions & Edge Cases + +### What if my text is longer than the default capacity? + +MicroPdf417 automatically switches to a multi‑row layout when the data exceeds the maximum per row. You can still control the column count, but the library may add extra rows behind the scenes. No extra code needed—just keep an eye on the resulting image dimensions. + +### How do I change the image format to JPEG or BMP? + +Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). Remember that JPEG introduces compression artifacts, which can affect scanning reliability. PNG is the safest default. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### I’m seeing a watermark in the output—what’s wrong? + +That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** without watermarks, load a valid license file as shown in the commented line of Step 2. + +### Can I generate other symbologies (QR, Code128, etc.)? + +Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The rest of the code stays the same, which makes the approach highly reusable. + +## Pro Tips for Production‑Ready Barcode Generation + +- **Cache the generator** if you’re creating many barcodes with the same settings; it reduces object‑creation overhead. +- **Validate the input string** for length constraints specific to the chosen symbology (Aspose throws `ArgumentException` if it’s too long). +- **Use `using` statements** or `Dispose` the generator when done to free native resources promptly. +- **Set DPI** via `generator.Parameters.ImageResolution.DpiX/DpiY` if you need high‑resolution prints for large labels. + +## Conclusion + +You now know exactly **how to generate barcode from text** with Aspose.BarCode, how to **change column count**, and the proper way to **save barcode image** as PNG. The complete, runnable example above demonstrates a clean, production‑ready + + +## 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 Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Generate barcode image – Code 93 with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/og-image.png b/barcode/english/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/og-image.png new file mode 100644 index 000000000..e18bee40d Binary files /dev/null and b/barcode/english/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-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..a5f140cda 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. +### [Créer des métadonnées de code-barres PDF417 en C# – Guide complet étape par étape](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +Apprenez à ajouter et gérer des métadonnées dans les codes-barres PDF417 avec C#, grâce à un guide complet pas à pas. + +### [Générer un code-barres PDF417 en C# – Guide complet](./generate-pdf417-barcode-in-c-complete-guide/) +Apprenez à créer un code-barres PDF417 en C# avec Aspose.BarCode, étape par étape, incluant la configuration et les meilleures pratiques. + +### [Générer un code-barres PDF417 en C# – Guide complet étape par étape](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +Apprenez à créer un code-barres PDF417 en C# avec Aspose.BarCode, en suivant chaque étape du processus, de la configuration à la génération. + +### [Comment lire le PDF417 en C# – Guide complet étape par étape](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) +Apprenez à décoder les codes-barres PDF417 en C# avec Aspose.BarCode, étape par étape, incluant la configuration et les meilleures pratiques. + ## 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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/french/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..c8bd64c18 --- /dev/null +++ b/barcode/french/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-07-15 +description: Créer des métadonnées de code‑barres PDF417 en C# avec Aspose.BarCode. + Apprendre les paramètres Macro PDF417, enregistrer au format PNG et gérer le texte + Unicode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: fr +lastmod: 2026-07-15 +og_description: Créez des métadonnées de code‑barres PDF417 en C# avec Aspose.BarCode. + Ce guide montre chaque paramètre nécessaire pour intégrer l’ID du fichier, les horodatages + et plus encore. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: Créer des métadonnées de code-barres PDF417 en C# – Guide complet de programmation +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: Créer des métadonnées de code‑barres PDF417 en C# – Guide complet étape par + étape +url: /fr/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer des métadonnées de code‑barres PDF417 en C# – Guide complet étape par étape + +Vous avez déjà eu besoin de **créer des métadonnées de code‑barres PDF417** en C# sans savoir quelles propriétés ajuster ? Vous n’êtes pas seul — les développeurs se heurtent souvent à un mur lorsque la spécification exige des éléments comme des ID de fichier, le nombre de segments ou des horodatages personnalisés. + +La bonne nouvelle, c’est qu’Aspose.BarCode rend cela très simple. Dans ce tutoriel, nous allons créer un `BarcodeGenerator` pour **Macro PDF417**, ajouter toutes les métadonnées importantes, puis enregistrer le résultat sous forme d’image PNG. À la fin, vous disposerez d’un code‑barres complet, prêt pour tout système de chaîne d’approvisionnement ou de gestion de documents. + +## Ce que couvre ce guide + +Nous allons parcourir : + +1. L’installation du package NuGet Aspose.BarCode. +2. L’initialisation d’un `BarcodeGenerator` pour **Macro PDF417**. +3. Le remplissage de chaque **champ de métadonnées du code‑barres** (file ID, segment ID, checksum, etc.). +4. L’enregistrement du code‑barres sur le disque et la vérification du résultat. + +Aucune expérience préalable avec Macro PDF417 n’est requise — il vous suffit de connaissances de base en C# et d’un runtime .NET récent. + +Pourquoi cela vous intéresse ? Intégrer des métadonnées riches directement dans un code‑barres permet aux scanners en aval de valider des transferts de fichiers complets, de détecter des segments manquants ou même de déclencher des flux de travail automatisés. En d’autres termes, vous obtenez des **données robustes et auto‑descriptives** sans avoir besoin d’une base de données séparée. + +## Prérequis + +- .NET 6.0 ou supérieur (le code fonctionne également avec .NET Framework 4.7+). +- Visual Studio 2022 (ou tout autre IDE de votre choix). +- Le package NuGet **Aspose.BarCode for .NET** (essai gratuit disponible). + +Vous pouvez installer le package avec la commande suivante : + +```bash +dotnet add package Aspose.BarCode +``` + +Maintenant que les bases sont en place, plongeons dans l’implémentation réelle. + +## Étape 1 : Initialiser le BarcodeGenerator pour Macro PDF417 + +La première chose dont nous avons besoin est une instance `BarcodeGenerator` configurée pour **Macro PDF417**. Cela indique à Aspose.BarCode quel algorithme d’encodage utiliser et nous fournit un endroit où injecter le texte lisible par l’homme. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Pourquoi c’est important :** `EncodeTypes.MacroPdf417` active le mode PDF417 étendu qui prend en charge les métadonnées telles que les ID de fichier et les numéros de segment. Le texte d’exemple contient des caractères Unicode (`Å`, `ó`, `©`) pour prouver que le générateur gère correctement les entrées non‑ASCII. + +## Étape 2 : Définir l’apparence de base du code‑barres + +Avant d’ajouter les métadonnées, nous devons définir quelques paramètres visuels afin que le code‑barres ne soit pas une tache microscopique. `XDimension` contrôle la largeur du module, tandis que `Columns` influence la forme globale. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Astuce :** Une largeur de pixel de `2` fonctionne bien pour l’affichage à l’écran et la plupart des imprimantes. Si vous avez besoin d’une impression à plus haute résolution, augmentez-la à `3` ou `4`. + +## Étape 3 : Remplir les champs de métadonnées Macro PDF417 + +Voici le cœur du tutoriel — l’ajout des **champs de métadonnées du code‑barres**. Chaque propriété correspond directement à un segment de la spécification Macro PDF417. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Fonction de chaque propriété + +| Propriété | Objectif | Valeur typique | +|-----------|----------|----------------| +| **MacroPdf417FileID** | Identifiant unique global pour l’ensemble du fichier. | `12345678` | +| **MacroPdf417SegmentID** | Index du segment actuel (commence à `0`). | `12` | +| **MacroPdf417SegmentsCount** | Nombre total de segments attendus pour le fichier. | `20` | +| **MacroPdf417FileName** | Nom lisible par l’homme, souvent le nom de fichier d’origine. | `"file01"` | +| **MacroPdf417Checksum** | Checksum CCITT 16 bits pour la détection d’erreurs. | `1234` | +| **MacroPdf417FileSize** | Taille du fichier original en octets. | `400000` | +| **MacroPdf417TimeStamp** | Date de génération du fichier. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Champ optionnel indiquant la destination. | `"street"` | +| **MacroPdf417Sender** | Champ optionnel indiquant le système source. | `"aspose"` | +| **MacroPdf417Terminator** | Indicateur qui informe le scanner qu’il s’agit du segment final. | `Pdf417MacroTerminator.Set` | + +> **Pourquoi vous en avez besoin :** Les scanners qui comprennent Macro PDF417 peuvent reconstituer un fichier multi‑segments, vérifier l’intégrité avec le checksum, et même rejeter des données périmées en fonction de l’horodatage. Cela élimine le besoin d’un fichier manifeste séparé. + +## Étape 4 : Enregistrer l’image du code‑barres + +Une fois tous les paramètres définis, il suffit d’appeler `Save`. L’exemple écrit un fichier PNG dans le dossier que vous spécifiez. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Cas particulier :** Si vous prévoyez d’intégrer le code‑barres dans un PDF ultérieurement, vous pourriez préférer `BarCodeImageFormat.Jpeg` ou `Pdf`. PNG conserve les détails sans perte, ce qui est pratique pour la vérification. + +## Exemple complet fonctionnel + +En rassemblant le tout, voici le programme complet que vous pouvez copier‑coller dans une application console : + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Résultat attendu + +L’exécution du programme crée un fichier nommé **ExtPDF417Meta.png** dans le répertoire de l’exécutable. Ouvrez‑le avec n’importe quel visualiseur d’images et vous verrez un code‑barres PDF417 dense et à fort contraste. Si vous le scannez avec un lecteur de code‑barres compatible Macro PDF417, le scanner renverra les valeurs de métadonnées que nous avons définies — ID de fichier `12345678`, segment `12` sur `20`, etc. + +## Questions fréquentes & pièges courants + +- **Et si le code‑barres apparaît flou ?** Augmentez `XDimension.Pixels` ou passez à un format d’image à plus haute résolution. +- **Dois‑je définir chaque champ de métadonnées ?** Non. Seuls les champs requis par votre système en aval sont obligatoires. Les champs inutilisés peuvent rester à leurs valeurs par défaut. +- **Puis‑je générer automatiquement un fichier multi‑segments ?** Oui — bouclez sur les données, incrémentez `MacroPdf417SegmentID` et générez un code‑barres distinct pour chaque segment. Veillez à ce que `MacroPdf417FileID` reste identique pour tous les segments. +- **L’Unicode est‑il supporté ?** Absolument. Le texte d’exemple contient `Å`, `ó` et `©`, montrant qu’Aspose.BarCode gère le UTF‑8 dès le départ. + +## Prochaines étapes : Aller au‑delà des bases + +Maintenant que vous savez **créer des métadonnées de code‑barres PDF417**, vous pourriez explorer : + +- **Intégrer des codes‑barres dans des PDF** avec `Aspose.Pdf` pour une génération de documents de bout en bout. +- **Lire les métadonnées** avec `BarcodeReader` afin de valider les scans de façon programmatique. +- **Personnaliser les couleurs** (avant‑plan/arrière‑plan) pour des besoins de branding. +- **Intégrer à une base de données** pour auto‑remplir des champs comme `FileID` ou `Timestamp`. + +Tous ces sujets renvoient à nos mots‑clés secondaires — **macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, et **c# barcode generation**—vous trouverez donc de nombreuses ressources pour continuer à apprendre. + +## Conclusion + +Nous venons de parcourir un exemple complet, prêt pour la production, montrant comment **créer des métadonnées de code‑barres PDF417** en C#. De l’installation d’Aspose.BarCode, à l’initialisation d’un `BarcodeGenerator`, en passant par le remplissage de chaque **champ de métadonnées du code‑barres**, jusqu’à l’enregistrement d’un PNG net, le processus est simple une fois que vous connaissez les bonnes propriétés. + +Essayez, modifiez les valeurs et observez la réaction des scanners. La flexibilité de Macro PDF417 vous permet d’embedder tout ce dont un système en aval a besoin—dans une seule image scannable. Bon codage, et que vos codes‑barres soient toujours sans erreur ! + +## Que devez‑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 avec des explications pas à pas pour vous aider à maîtriser d’autres fonctionnalités 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/) +- [java barcode library – Add barcode to PDF using Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/french/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..3f478b2c7 --- /dev/null +++ b/barcode/french/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: Générez rapidement un code‑barres PDF417 et apprenez comment définir + les colonnes pour une image de code‑barres PDF417 compacte en C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: fr +lastmod: 2026-07-15 +og_description: Générez un code‑barres PDF417 avec Aspose.BarCode et apprenez comment + définir les colonnes pour créer une image de code‑barres PDF417 compacte. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: Générer un code‑barres PDF417 en C# – Guide étape par étape +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: Générer un code‑barres PDF417 en C# – Guide complet +url: /fr/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-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 complet + +Vous avez déjà eu besoin de **générer un code-barres PDF417** dans un projet .NET mais vous ne saviez pas par où commencer ? Vous n'êtes pas seul. Dans de nombreuses applications d'entreprise — pensez aux imprimantes de cartes d'embarquement, aux étiquettes d'inventaire ou à la billetterie mobile — le PDF417 est le cheval de bataille qui emporte beaucoup de données dans un petit espace visuel. + +Voici le point clé : la bibliothèque Aspose.BarCode rend le processus presque indolore, et vous pouvez même contrôler **comment définir les colonnes** afin que le code-barres soit aussi compact que possible. À la fin de ce tutoriel, vous disposerez d’une image PNG prête à l’emploi d’un **code-barres PDF417** que vous pourrez insérer dans n’importe quelle interface, e‑mail ou tâche d’impression. + +## Ce que vous retirerez de ce tutoriel + +- Une application console C# entièrement fonctionnelle qui crée un code-barres PDF417. +- Une compréhension claire de la *X‑Dimension* (taille du module) et de son importance. +- Des instructions étape par étape sur **comment définir les colonnes** pour un code-barres plus compact. +- Un fichier `PNG` enregistré que vous pouvez ouvrir immédiatement pour vérifier le résultat. +- Des astuces pour résoudre les problèmes courants (par ex., codes-barres illisibles, mauvais format d’image). + +> **Prérequis** – SDK .NET 6+, Visual Studio 2022 (ou tout éditeur de votre choix), et une référence NuGet à `Aspose.BarCode`. Rien d’autre. + +--- + +## Étape 1 : Installer le package NuGet Aspose.BarCode + +Avant de pouvoir *générer un code-barres PDF417*, la bibliothèque doit être présente dans le projet. + +```bash +dotnet add package Aspose.BarCode +``` + +Cette seule ligne importe tous les types dont vous aurez besoin, y compris `BarcodeGenerator`, `EncodeTypes` et l’énumération `BarCodeImageFormat`. + +> **Astuce :** Si vous ciblez le .NET Framework au lieu de .NET 6, utilisez la commande PowerShell classique `Install-Package Aspose.BarCode` dans la console du gestionnaire de packages. + +--- + +## Étape 2 : Créer une application console minimale + +Créons une petite application qui ne fait rien d’autre que produire un code-barres. Ouvrez un nouveau dossier, exécutez `dotnet new console`, puis remplacez le fichier `Program.cs` généré automatiquement par le code ci‑dessous. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Pourquoi c’est important :** +- `EncodeTypes.Pdf417` indique à la bibliothèque que nous voulons un code-barres PDF417, pas un QR ou un Code128. +- `XDimension.Pixels` contrôle la résolution de chaque petit module noir ou blanc. +- Le bloc **comment définir les colonnes** influence directement la forme de l’**image du code-barres PDF417**. +- `Truncate = true` supprime toutes les lignes vides inutiles, vous offrant cet aspect « compact » apprécié par de nombreux scanners. + +--- + +## Étape 3 : Approfondir – Comprendre les colonnes et la troncature + +### Comment définir les colonnes + +PDF417 organise les données dans une matrice de *lignes* × *colonnes*. La bibliothèque utilise par défaut 5 colonnes, ce qui convient à la plupart des cas. Cependant, il peut être nécessaire d’avoir un code-barres plus étroit pour s’adapter à une étiquette ou plus large pour améliorer la fiabilité de la lecture. La propriété : + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +accepte des valeurs de **1** à **30** (la limite exacte dépend de la longueur des données). Voici une petite feuille de triche : + +| Colonnes | Largeur approximative (mm) | Quand l’utiliser | +|----------|----------------------------|-------------------| +| 1‑3 | Très étroite | Petite étiquette, espace limité | +| 4‑6 | Standard | La plupart des reçus, tickets | +| 7‑10 | Plus large | Données à haute densité, meilleure lisibilité | + +### Troncature (Mode compact) + +Définir `Truncate = true` indique à l’encodeur de couper toutes les lignes vides inutiles en bas. Le résultat est une **image de code-barres PDF417 compacte** qui occupe la plus petite surface possible tout en contenant toutes les données. Si vous obtenez un jour des erreurs « code-barres trop grand pour l’étiquette », basculez ce drapeau. + +--- + +## Étape 4 : Exécuter l’application et vérifier la sortie + +Compile and execute: + +```bash +dotnet run +``` + +Vous devriez voir le message de la console confirmant l’emplacement d’enregistrement. Accédez au dossier et ouvrez `CompactPdf417.png`. L’image ressemblera à ceci : + +![Image du code-barres PDF417 généré](./CompactPdf417.png "Image du code-barres PDF417 généré – PNG compact créé par Aspose.BarCode") + +*Texte alternatif de l’image :* **Image du code-barres PDF417 généré** – un fichier PNG compact produit par le code du tutoriel. + +Si votre scanner peut le lire, félicitations — vous avez réussi à **générer un code-barres PDF417** et maîtrisé **comment définir les colonnes** pour une **image de code-barres PDF417** soignée. + +--- + +## Étape 5 : Problèmes courants et comment les résoudre + +| Symptôme | Cause probable | Solution rapide | +|----------|----------------|-----------------| +| Le code-barres apparaît flou | `XDimension.Pixels` trop faible (ex., 1) | Augmentez à 2‑3 pixels pour une image plus nette. | +| Le scanner ne peut pas lire | Trop de colonnes pour les données fournies | Réduisez `Columns` ou activez `Truncate`. | +| Mauvais format de fichier | Enregistré avec `BarCodeImageFormat.Jpeg` par erreur | Utilisez `BarCodeImageFormat.Png` pour des résultats sans perte. | +| Exception `ArgumentOutOfRangeException` | Le nombre de colonnes dépasse la plage autorisée | Gardez les colonnes entre 1‑30 et assurez-vous que les données tiennent. | + +--- + +## Étape 6 : Aller plus loin – Personnaliser les couleurs et ajouter du texte + +Si vous souhaitez que le code-barres corresponde à la palette d’une marque, vous pouvez ajuster les couleurs de premier plan et d’arrière‑plan : + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Ou superposer du texte lisible par l’homme sous le code-barres : + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Ces ajouts sont optionnels, mais ils illustrent la flexibilité du flux de travail **générer un code-barres PDF417**. + +--- + +## Conclusion + +Nous avons parcouru un exemple complet, de bout en bout, qui **génère un code-barres PDF417** à l’aide d’Aspose.BarCode, expliqué **comment définir les colonnes** pour contrôler les dimensions du code-barres, et enregistré le résultat sous forme d’une image **PDF417 nette** au format PNG. Le code est autonome, fonctionne avec .NET 6+, et peut être intégré à n’importe quel projet existant avec un minimum d’effort. + +Et ensuite ? Essayez d’encoder des charges utiles plus importantes (par ex., des charges JSON), expérimentez différents formats d’image, ou intégrez le générateur dans une API web qui fournit des codes-barres à la demande. Le ciel est la limite, et vous disposez maintenant d’une base solide pour construire. + +Bon codage, et que vos codes-barres soient toujours lus du premier coup ! + +## 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 supplémentaires de l’API et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [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 une image de code-barres en Java avec Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Générer un code-barres Java – Définir la résolution d’image avec Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/french/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..0d0716440 --- /dev/null +++ b/barcode/french/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-07-15 +description: Générez rapidement un code‑barres PDF417 avec C#. Apprenez à créer un + code‑barres à partir de texte, à ajuster sa taille et à définir des dimensions personnalisées + en quelques minutes. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: fr +lastmod: 2026-07-15 +og_description: Générez un code‑barres PDF417 en C# instantanément. Ce guide montre + comment créer un code‑barres à partir du texte, ajuster sa taille et appliquer des + dimensions personnalisées. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Générer un code-barres PDF417 en C# – Tutoriel complet de programmation +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Générer un code‑barres PDF417 en C# – Guide complet étape par étape +url: /fr/net/compact-pdf417-encoding/generate-pdf417-barcode-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 PDF417 en C# – Guide complet étape par étape + +Vous avez déjà eu besoin de **générer un code‑barres PDF417** mais vous ne saviez pas quels paramètres ajuster ? Vous n'êtes pas le seul—de nombreux développeurs rencontrent le même problème lorsqu'ils manipulent pour la première fois des codes‑barres 2‑D. La bonne nouvelle ? En quelques lignes de C#, vous pouvez transformer n'importe quelle chaîne en une image PDF417 scannable, contrôler sa taille exacte, et même définir une disposition personnalisée de colonnes et de lignes. + +Dans ce tutoriel, nous allons parcourir comment **générer un code‑barres à partir de texte**, ajuster la taille du code‑barres, et définir des dimensions personnalisées du code‑barres — le tout en utilisant la populaire bibliothèque Aspose.BarCode. À la fin, vous disposerez d'un exemple prêt à l'exécution que vous pourrez intégrer dans n'importe quel projet .NET. + +![Exemple de génération de code‑barres PDF417](https://example.com/og-image.png "Exemple de génération de code‑barres PDF417") + +## Ce que vous allez créer + +- Un code‑barres PDF417 qui encode la chaîne `Åspóse.Barcóde©`. +- Un contrôle précis de la X‑dimension (largeur en pixels de chaque module). +- Une disposition personnalisée de 4 colonnes et 9 lignes. +- Un fichier PNG enregistré sur le disque. + +Pas de services externes, pas de tours de magie—juste du code C# pur que vous pouvez compiler dès maintenant. + +## Prérequis + +- .NET 6.0 ou ultérieur (le code fonctionne également sur .NET Framework 4.8). +- Visual Studio 2022 ou tout IDE supportant C#. +- Aspose.BarCode pour .NET (version d'essai gratuite ou version sous licence). Installez via NuGet : + +```bash +dotnet add package Aspose.BarCode +``` + +C’est tout—une fois le package référencé, vous êtes prêt à partir. + +## Étape 1 – Générer un code‑barres PDF417 avec des données texte + +La première chose dont nous avons besoin est une instance de `BarcodeGenerator` qui sait que nous travaillons avec la symbologie PDF417 et le texte exact que nous voulons encoder. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Pourquoi c'est important :** +> `EncodeTypes.Pdf417` indique à la bibliothèque d'utiliser le format PDF417 2‑D, tandis que le deuxième argument est la charge utile **générer un code‑barres à partir de texte**. Tout ce que vous passez ici devient les données stockées dans la matrice du code‑barres. + +## Étape 2 – Ajuster la taille du code‑barres (X‑Dimension) + +Si vous avez déjà imprimé un code‑barres qui semblait trop petit sur un reçu, vous connaissez la frustration du scanner qui ne le détecte pas. La propriété `XDimension` contrôle la largeur d'un seul module (le plus petit carré noir ou blanc) en pixels. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Astuce pro :** +> Une valeur de 2 px fonctionne bien pour la plupart des scénarios d'affichage à l'écran. Pour les impressions haute résolution, vous pouvez l'augmenter à 3 ou 4 px. N'oubliez pas que des X‑dimensions plus grandes augmentent la taille globale de l'image. + +## Étape 3 – Définir des dimensions personnalisées du code‑barres (Colonnes & Lignes) + +PDF417 vous permet de définir le nombre de colonnes et de lignes que le code‑barres doit occuper. C'est ici que les **dimensions personnalisées du code‑barres** entrent en jeu. Modifier ces valeurs peut vous aider à adapter le code‑barres à un espace UI restreint ou à répondre à une taille d'étiquette spécifique. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Que se passe-t-il en coulisses ?** +> La bibliothèque redistribue les données encodées sur la grille spécifiée. Moins de colonnes signifie des codes‑barres plus hauts ; plus de lignes les rendent plus courts. Expérimentez avec les nombres jusqu'à ce que l'équilibre visuel vous convienne pour votre application. + +## Étape 4 – Enregistrer l'image du code‑barres + +Maintenant que nous avons tout configuré, nous demandons simplement au générateur d'écrire un fichier PNG. Le PNG est sans perte, donc la netteté des modules reste intacte. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Lorsque vous exécutez le programme, vous devriez voir un fichier à `C:\Barcodes\CustomLayout.png` qui ressemble à la capture d'écran ci‑dessus. Le scanner avec n'importe quel lecteur compatible PDF417 renverra la chaîne originale `Åspóse.Barcóde©`. + +## Exemple complet fonctionnel + +Voici le programme complet que vous pouvez copier‑coller dans une application console. Il inclut toutes les directives using et la gestion des erreurs que l’on attend d’un code de production. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Sortie attendue + +L'exécution du code affiche : + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…et crée un PNG qui peut être ouvert dans n'importe quel visualiseur d'images. Si vous le scannez avec une application mobile (par ex., “Barcode Scanner” sur iOS/Android), le texte décodé devrait être exactement **Åspóse.Barcóde©**. + +## Questions fréquentes & cas particuliers + +| Question | Réponse | +|----------|--------| +| **Puis-je utiliser un autre format d'image ?** | Oui—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` ou `Svg` sont tous pris en charge. Il suffit de changer le deuxième argument de `Save`. | +| **Et si mon texte contient des caractères Unicode ?** | Aspose.BarCode prend en charge pleinement UTF‑8, donc l'exemple avec `Å` et `©` fonctionne immédiatement. | +| **Comment modifier le niveau de correction d'erreur ?** | Utilisez `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (niveaux 0‑8). Des niveaux plus élevés augmentent la redondance mais aussi la taille. | +| **J'ai besoin d'un arrière-plan transparent—est‑ce possible ?** | Définissez `generator.Parameters.Barcode.Image.TransparentBackground = true;` avant d'enregistrer. | +| **Existe‑t‑il un moyen d'intégrer le code‑barres directement dans un PDF ?** | Absolument. Remplacez l'appel `Save` par `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` et vous obtiendrez un PDF d'une page contenant le code‑barres. | + +## Conclusion + +Vous savez maintenant comment **générer un code‑barres PDF417** en C# à partir de n'importe quelle chaîne, **ajuster la taille du code‑barres**, et appliquer des **dimensions personnalisées du code‑barres** pour répondre à vos besoins de mise en page. Le flux en quatre étapes—initialisation, taille, disposition, enregistrement—couvre le processus principal pour la plupart des scénarios de codes‑barres 2‑D. + +Et ensuite ? Essayez de remplacer `EncodeTypes.Pdf417` par `EncodeTypes.QR` ou `EncodeTypes.Code128` pour voir comment l'API s'adapte. Expérimentez avec différentes valeurs de `XDimension`, jouez avec la matrice colonnes/lignes, ou intégrez l'image dans un rapport PDF. Les possibilités sont pratiquement infinies, et vous disposez maintenant d'une base solide pour construire. + +Vous avez d'autres questions, ou avez découvert une astuce ingénieuse en manipulant PDF417 ? Laissez un commentaire ci‑dessous—continuons la discussion. 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 un code‑barres Aztec avec un ratio d'aspect personnalisé en utilisant Aspose.BarCode pour .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Comment générer des codes‑barres - Types de codes‑barres unidimensionnels](/barcode/english/net/one-dimensional-barcode-types/) +- [Générer un code‑barres DataMatrix – Guide pro avec Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/french/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..689342e11 --- /dev/null +++ b/barcode/french/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,314 @@ +--- +category: general +date: 2026-07-15 +description: Comment lire un code‑barres PDF417 en C# et lire plusieurs codes‑barres + à partir d’une image. Apprenez à lire une image de code‑barres en C# avec du code + détaillé et des astuces. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: fr +lastmod: 2026-07-15 +og_description: Comment lire rapidement un code‑barres PDF417 en C#. Ce guide vous + montre comment lire plusieurs codes‑barres à partir d’une seule image et décoder + chaque propriété. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Comment lire le PDF417 en C# – Exemple complet de code et explication +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Comment lire le PDF417 en C# – Guide complet étape par étape +url: /fr/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-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 étape par étape + +Vous vous êtes déjà demandé **comment lire PDF417** à partir d'une image en utilisant C# ? Vous n'êtes pas le seul. La plupart des développeurs se heurtent à un mur lorsqu'ils doivent extraire les champs étendus Macro‑PDF417 d'un document numérisé. La bonne nouvelle ? En quelques lignes de code, vous pouvez décoder un PDF417, lire plusieurs codes-barres dans la même image, et récupérer chaque propriété cachée offerte par la spécification. + +Dans ce tutoriel, nous parcourrons un exemple concret qui montre **comment lire PDF417**, comment **lire plusieurs codes-barres** à partir d'un seul fichier, et pourquoi le code **read barcode image C#** a cette apparence. À la fin, vous disposerez d'une application console prête à l'emploi qui affiche chaque information dont vous pourriez avoir besoin — ID de fichier, ID de segment, somme de contrôle, horodatages, etc. + +## Prérequis + +* .NET 6.0 SDK ou version ultérieure (le code fonctionne également avec .NET Core et .NET Framework). +* Visual Studio 2022 (ou tout éditeur de votre choix). +* Le package NuGet **Aspose.BarCode for .NET** – c’est la bibliothèque qui analyse réellement le PDF417. +* Une image d'exemple contenant un code-barres Macro‑PDF417 (par exemple `ExtPDF417Meta.png`). + +Aucune configuration supplémentaire n'est requise ; la bibliothèque est fournie avec tous les décodeurs dont vous avez besoin. + +## Étape 1 : Installer Aspose.BarCode + +Ouvrez le dossier de votre projet dans un terminal et exécutez : + +```bash +dotnet add package Aspose.BarCode +``` + +Cette commande récupère la dernière version stable (en juillet 2026, c’est la 23.12). Si vous préférez la console du gestionnaire de packages dans Visual Studio, utilisez : + +```powershell +Install-Package Aspose.BarCode +``` + +> **Astuce :** verrouillez la version (`23.12.0`) dans votre `.csproj` pour éviter des changements incompatibles accidentels plus tard. + +## Étape 2 : Créer la structure d’une application console + +Créez un nouveau projet console si vous n’en avez pas déjà un : + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Remplacez le `Program.cs` généré automatiquement par le code ci‑dessous. Nous expliquerons chaque bloc dans les sections suivantes. + +## Étape 3 : Écrire le code complet « How to Read PDF417 » + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Pourquoi ce code fonctionne + +* **`BarCodeReader`** est la classe principale qui charge l'image, détecte les codes‑barres et renvoie une collection d'objets `BarCodeResult`. +* Passer **`DecodeType.MacroPdf417`** indique à la bibliothèque de traiter spécialement le Macro‑PDF417 ; elle renvoie toujours des symboles PDF417 simples, ce qui satisfait le besoin de **read multiple barcodes**. +* L'objet **`Extended.Pdf417.MacroPdf417`** contient chaque champ optionnel défini par la norme ISO/IEC 15438 – c’est là que vous obtenez `FileID`, `SegmentID`, `Checksum`, etc. +* Le bloc `using` garantit la libération des ressources natives, évitant les fuites de mémoire dans les services de longue durée. + +## Étape 4 : Exécuter l’application et vérifier la sortie + +Depuis le terminal : + +```bash +dotnet run +``` + +Vous devriez voir quelque chose comme : + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Si l'image contient plus d'un code‑barres, la boucle affichera une ligne de séparation (`----------------------------------------`) et continuera avec le résultat suivant — exactement ce à quoi ressemble **read multiple barcodes** en pratique. + +## Questions fréquentes & cas particuliers + +### Et si l'image contient à la fois des symboles Macro‑PDF417 et PDF417 classiques ? + +Le même appel `BarCodeReader` renverra les deux. Vous pouvez les différencier en vérifiant `result.CodeType` (`MacroPdf417` vs `Pdf417`). Les propriétés étendues seront `null` pour un PDF417 simple, ainsi la condition `if (macro != null)` empêche une `NullReferenceException`. + +### Mon code‑barres est tourné ou déformé — le lecteur fonctionnera‑t‑il toujours ? + +Aspose.BarCode inclut une compensation intégrée de rotation et de distorsion. Tant que le code‑barres occupe au moins 30 % de la largeur de l'image, le décodeur réussira généralement. Dans les cas extrêmes, vous pouvez activer `reader.Options.AllowInvertedBarcodes = true;` avant d’appeler `ReadBarCodes()`. + +### Comment gérer de gros lots d'images ? + +Enveloppez la logique de lecture dans une boucle `foreach (var file in Directory.GetFiles(folder, "*.png"))`. Le modèle `using` garantit que les ressources natives de chaque image sont libérées avant l’itération suivante, maintenant ainsi une faible consommation de mémoire. + +## Listing complet du code source (prêt à copier-coller) + +Ci‑dessous se trouve le programme complet en un seul bloc pour un copier-coller rapide. Aucune dépendance cachée — uniquement le package NuGet Aspose.BarCode. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Récapitulatif – Ce que nous avons couvert + +* **Comment lire PDF417** avec Aspose.BarCode en C#. +* Les étapes exactes pour **read multiple barcodes** à partir d’une seule image. +* Comment **read barcode image C#** et extraire chaque champ Macro‑PDF417. +* Astuces pour la rotation, le traitement par lots et la gestion des données étendues manquantes. + +## Prochaines étapes & sujets associés + +* **Encode PDF417** – générez vos propres codes‑barres Macro‑PDF417 avec `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – en utilisant la même classe `BarCodeReader`. +* **Integrate with ASP.NET Core** – exposez un point de terminaison web qui accepte une image téléchargée et renvoie du JSON avec les champs décodés. + +N’hésitez pas à expérimenter : modifiez le chemin de l’image, déposez un PDF417 simple dans le même dossier, ou ajustez les indicateurs `DecodeType` pour voir comment la bibliothèque se comporte. Plus vous jouez, plus vous serez à l’aise avec les scénarios **read barcode image C#**. + +Vous avez une image difficile qui refuse de se décoder ? Laissez un commentaire ci‑dessous ou ouvrez une issue sur le dépôt GitHub du projet d’exemple. 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 d’API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [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/french/net/one-dimensional-barcode-types/_index.md b/barcode/french/net/one-dimensional-barcode-types/_index.md index 9f7bfd64d..036bcfa35 100644 --- a/barcode/french/net/one-dimensional-barcode-types/_index.md +++ b/barcode/french/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ Découvrez comment générer des codes-barres dans .NET avec Aspose.BarCode pour Découvrez comment gérer les exceptions lors de la génération de codes-barres unidimensionnels à l'aide d'Aspose.BarCode for .NET. Ce guide étape par étape garantit des solutions de codes-barres tolérantes aux erreurs. Commencez maintenant! ### [Configuration unidimensionnelle à rapport large-étroit](./one-dimensional-wide-narrow-ratio-configuration/) Générez facilement des codes-barres personnalisés avec Aspose.BarCode pour .NET. Guide étape par étape pour la configuration unidimensionnelle du rapport large-étroit. +### [Générer un code-barres à partir du texte avec Aspose.BarCode – Guide C#](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Apprenez à créer un code-barres à partir de texte en C# avec Aspose.BarCode. Guide étape par étape pour une intégration facile. ## Conclusion @@ -89,4 +91,4 @@ Avec cet article, vous acquerrez non seulement des connaissances sur les différ {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/french/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..939d37710 --- /dev/null +++ b/barcode/french/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-07-15 +description: Générez un code‑barres à partir de texte avec Aspose.BarCode en C#. Apprenez + à modifier le nombre de colonnes, à enregistrer l’image du code‑barres et à créer + rapidement des solutions de code‑barres Aspose. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: fr +lastmod: 2026-07-15 +og_description: Générez un code‑barres à partir du texte en utilisant Aspose.BarCode. + Ce guide montre comment modifier le nombre de colonnes, enregistrer l’image du code‑barres + et créer un code‑barres Aspose en quelques lignes de code. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Générer un code-barres à partir de texte avec Aspose.BarCode – Guide rapide + C# +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Générer un code‑barres à partir du texte avec Aspose.BarCode – Guide C# +url: /fr/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-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 avec Aspose.BarCode – Guide C# + +Générer un code-barres à partir de texte avec Aspose.BarCode est étonnamment simple. Dans ce tutoriel, nous allons parcourir **comment générer un code-barres**, ajuster la disposition des colonnes, et enfin **enregistrer l’image du code-barres** au format PNG. Que vous construisiez un système de billetterie, une imprimante d’étiquettes d’entrepôt, ou que vous expérimentiez simplement avec des codes de type QR, les étapes ci‑dessous vous y mèneront rapidement. + +## Ce que vous allez apprendre + +- Créer un code-barres à partir de n’importe quelle chaîne Unicode (oui, même “Åspóse.Barcóde©” fonctionne). +- Ajuster le **nombre de colonnes** pour MicroPdf417 afin de s’adapter aux étiquettes étroites ou larges. +- Persister le résultat sur le disque avec le format d’image approprié. +- Astuces pour gérer les caractères spéciaux et les pièges courants lors de la **création d’un code-barres Aspose**. + +Aucun outil externe, aucune astuce en ligne de commande — juste du C# pur et la bibliothèque Aspose.BarCode. + +## Prérequis + +Avant de commencer, assurez‑vous d’avoir : + +1. **.NET 6.0** ou une version ultérieure installée (le code fonctionne également avec .NET Framework 4.7+). +2. Une **licence** pour Aspose.BarCode, ou vous pouvez commencer avec la version d’évaluation gratuite. +3. Un dossier dans lequel vous pouvez écrire – nous l’appellerons `YOUR_DIRECTORY` dans les exemples. + +Si l’un de ces éléments vous manque, récupérez le package NuGet maintenant : + +```bash +dotnet add package Aspose.BarCode +``` + +C’est tout — aucune DLL supplémentaire à copier manuellement. + +## Étape 1 – Configurer le projet et les imports + +Tout d’abord, créez une application console (ou insérez le code dans n’importe quel projet C#). L’important est d’inclure les bons espaces de noms : + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Pourquoi ces instructions using ? `BarcodeGenerator` se trouve dans `Aspose.BarCode.Generation`, tandis que l’énumération `BarCodeImageFormat` se trouve dans `Aspose.BarCode`. Garder les imports propres rend le code ultérieur lisible comme de l’anglais simple. + +## Étape 2 – Créer le générateur de code-barres (comment générer un code-barres) + +Nous allons maintenant réellement **générer un code-barres à partir de texte**. L’énumération `EncodeTypes` indique à Aspose quelle symbologie utiliser ; ici nous choisissons `MicroPdf417` car elle gère les longues chaînes dans une grille compacte. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Remarquez que la chaîne contient des caractères accentués et le symbole de copyright. Aspose.BarCode encode automatiquement l’Unicode, vous n’avez donc pas besoin de pré‑traiter le texte. + +## Étape 3 – Affiner l’apparence (comment modifier le nombre de colonnes) + +MicroPdf417 vous permet de contrôler le nombre de colonnes, ce qui influence directement la largeur du code-barres. Une disposition plus compacte est idéale pour les étiquettes étroites ; une disposition plus large améliore la lisibilité sur les impressions de grande taille. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Pourquoi des modules de 2 pixels ? Cela donne une image nette sans gonfler la taille du fichier. N’hésitez pas à expérimenter — les valeurs entre 1 et 4 fonctionnent généralement bien. Si vous avez besoin d’un nombre de colonnes différent, modifiez simplement la propriété `Columns` ; Aspose recalculera automatiquement la disposition. + +## Étape 4 – Enregistrer l’image du code-barres (save barcode image) + +Avec le générateur configuré, nous sommes prêts à **enregistrer l’image du code-barres**. La méthode `Save` accepte un chemin de fichier et une énumération de format d’image. PNG est sans perte, donc le code-barres reste net même après mise à l’échelle. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Astuce rapide : utilisez toujours un chemin absolu ou assurez‑vous que le répertoire de travail est celui attendu ; sinon le fichier peut se retrouver dans le dossier bin et vous vous demanderez pourquoi vous ne le trouvez pas. + +## Exemple complet fonctionnel + +En assemblant le tout, voici un programme autonome que vous pouvez copier‑coller dans `Program.cs` et exécuter : + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Sortie attendue** (console) : + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +Et si vous ouvrez `MicroPdf417.png`, vous verrez un code‑barres MicroPdf417 net qui encode la chaîne originale, avec les caractères spéciaux que nous lui avons fournis. + +## Questions fréquentes et cas limites + +### Que faire si mon texte dépasse la capacité par défaut ? + +MicroPdf417 passe automatiquement à une disposition multi‑lignes lorsque les données dépassent le maximum par ligne. Vous pouvez toujours contrôler le nombre de colonnes, mais la bibliothèque peut ajouter des lignes supplémentaires en arrière‑plan. Aucun code supplémentaire n’est nécessaire — surveillez simplement les dimensions de l’image résultante. + +### Comment changer le format d’image en JPEG ou BMP ? + +Remplacez `BarCodeImageFormat.Png` par `BarCodeImageFormat.Jpeg` (ou `Bmp`). Gardez à l’esprit que le JPEG introduit des artefacts de compression, ce qui peut affecter la fiabilité du scan. PNG reste le choix le plus sûr par défaut. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### J’obtiens un filigrane dans le résultat — qu’est‑ce qui ne va pas ? + +C’est la version d’évaluation d’Aspose.BarCode. Pour **créer un code‑barres Aspose** sans filigrane, chargez un fichier de licence valide comme indiqué dans la ligne commentée de l’Étape 2. + +### Puis‑je générer d’autres symbologies (QR, Code128, etc.) ? + +Absolument. Remplacez simplement `EncodeTypes.MicroPdf417` par n’importe quelle autre valeur de l’énumération `EncodeTypes`, par ex. `EncodeTypes.QR` ou `EncodeTypes.Code128`. Le reste du code reste identique, ce qui rend l’approche très réutilisable. + +## Astuces pro pour la génération de code‑barres prête pour la production + +- **Mettre en cache le générateur** si vous créez de nombreux codes‑barres avec les mêmes paramètres ; cela réduit la surcharge de création d’objets. +- **Valider la chaîne d’entrée** pour les contraintes de longueur spécifiques à la symbologie choisie (Aspose lève une `ArgumentException` si elle est trop longue). +- **Utiliser des instructions `using`** ou appeler `Dispose` sur le générateur une fois terminé pour libérer rapidement les ressources natives. +- **Définir le DPI** via `generator.Parameters.ImageResolution.DpiX/DpiY` si vous avez besoin d’impressions haute résolution pour de grandes étiquettes. + +## Conclusion + +Vous savez maintenant exactement **comment générer un code‑barres à partir de texte** avec Aspose.BarCode, comment **modifier le nombre de colonnes**, et la bonne façon **d’enregistrer l’image du code‑barres** au format PNG. L’exemple complet et exécutable ci‑dessus montre une implémentation propre, prête pour la production + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques présenté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 supplémentaires de l’API et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Generate barcode image – Code 93 with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/german/net/compact-pdf417-encoding/_index.md index 201fcffef..8a4a85f65 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 @@ -84,6 +84,14 @@ Nachfolgend eine knappe Beschreibung eines typischen Barcode‑Erstellungsszenar ## Compact PDF417 Codierungs‑Tutorials ### [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. +### [PDF417‑Barcode‑Metadaten in C# erstellen – vollständige Schritt‑für‑Schritt‑Anleitung](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +Erfahren Sie, wie Sie PDF417‑Barcode‑Metadaten in C# hinzufügen, inklusive Code‑Beispielen und Best Practices. +### [PDF417-Barcode in C# generieren – Vollständiger Leitfaden](./generate-pdf417-barcode-in-c-complete-guide/) +Erfahren Sie, wie Sie PDF417‑Barcodes in C# erstellen, mit vollständigen Code‑Beispielen und Schritt‑für‑Schritt‑Anleitung. +### [PDF417-Barcode in C# generieren – vollständige Schritt‑für‑Schritt‑Anleitung](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +Erfahren Sie, wie Sie PDF417‑Barcodes in C# komplett Schritt für Schritt erstellen, inkl. Code‑Beispielen und Best Practices. +### [PDF417 in C# lesen – vollständige Schritt‑für‑Schritt‑Anleitung](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) +Erfahren Sie, wie Sie PDF417‑Barcodes in C# auslesen, mit vollständigen Code‑Beispielen und Schritt‑für‑Schritt‑Anleitung. ## Häufig gestellte Fragen @@ -113,4 +121,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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/german/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..2a3fbd310 --- /dev/null +++ b/barcode/german/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-07-15 +description: Erstellen Sie PDF417-Barcode-Metadaten in C# mit Aspose.BarCode. Lernen + Sie die Macro‑PDF417‑Einstellungen kennen, speichern Sie als PNG und verarbeiten + Sie Unicode‑Text. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: de +lastmod: 2026-07-15 +og_description: Erstellen Sie PDF417‑Barcode‑Metadaten in C# mit Aspose.BarCode. Dieser + Leitfaden zeigt alle Einstellungen, die Sie benötigen, um Datei‑ID, Zeitstempel + und mehr einzubetten. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: PDF417-Barcode-Metadaten in C# erstellen – Vollständige Programmieranleitung +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: PDF417-Barcode-Metadaten in C# erstellen – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF417‑Barcode‑Metadaten in C# erstellen – Vollständige Schritt‑für‑Schritt‑Anleitung + +Haben Sie jemals **PDF417‑Barcode‑Metadaten** in C# erstellen müssen, waren sich aber nicht sicher, welche Eigenschaften Sie anpassen müssen? Sie sind nicht allein – Entwickler stoßen häufig auf Probleme, wenn die Spezifikation Dinge wie Datei‑IDs, Segment‑Anzahlen oder benutzerdefinierte Zeitstempel verlangt. + +Die gute Nachricht: Aspose.BarCode macht das zu einem Kinderspiel. In diesem Tutorial erzeugen wir einen `BarcodeGenerator` für **Macro PDF417**, fügen alle wichtigen Metadaten hinzu und speichern das Ergebnis als PNG‑Bild. Am Ende haben Sie einen voll ausgestatteten Barcode, bereit für jedes Supply‑Chain‑ oder Dokumenten‑Management‑System. + +## Was diese Anleitung abdeckt + +Wir gehen durch: + +1. Installation des Aspose.BarCode‑NuGet‑Pakets. +2. Initialisierung eines `BarcodeGenerator` für **Macro PDF417**. +3. Befüllung aller nützlichen **Barcode‑Metadatenfelder** (File ID, Segment ID, Checksum usw.). +4. Speicherung des Barcodes auf dem Datenträger und Überprüfung der Ausgabe. + +Vorkenntnisse zu Macro PDF417 sind nicht nötig – nur Grundwissen in C# und eine aktuelle .NET‑Runtime. + +Warum ist das wichtig? Durch das Einbetten reichhaltiger Metadaten direkt in einen Barcode können nachgelagerte Scanner komplette Dateitransfers validieren, fehlende Segmente erkennen oder sogar automatisierte Workflows auslösen. Mit anderen Worten: Sie erhalten **robuste, selbsterklärende Daten**, ohne dass eine separate Datenbankabfrage nötig ist. + +## Voraussetzungen + +- .NET 6.0 oder höher (der Code funktioniert auch mit .NET Framework 4.7+). +- Visual Studio 2022 (oder jede andere IDE Ihrer Wahl). +- Das **Aspose.BarCode for .NET** NuGet‑Paket (kostenlose Testversion verfügbar). + +Sie können das Paket mit folgendem Befehl installieren: + +```bash +dotnet add package Aspose.BarCode +``` + +Jetzt, wo die Grundlagen stehen, tauchen wir in die eigentliche Implementierung ein. + +## Schritt 1: Initialisieren des BarcodeGenerator für Macro PDF417 + +Als erstes benötigen wir eine `BarcodeGenerator`‑Instanz, die für **Macro PDF417** konfiguriert ist. Damit teilt Aspose.BarCode mit, welchen Kodierungsalgorithmus es verwenden soll, und wir erhalten einen Ort, an dem wir den menschenlesbaren Text einfügen können. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Warum das wichtig ist:** `EncodeTypes.MacroPdf417` aktiviert den erweiterten PDF417‑Modus, der Metadaten wie Datei‑IDs und Segment‑Nummern unterstützt. Der Beispieltext enthält Unicode‑Zeichen (`Å`, `ó`, `©`), um zu zeigen, dass der Generator nicht‑ASCII‑Eingaben problemlos verarbeitet. + +## Schritt 2: Grundlegendes Aussehen des Barcodes festlegen + +Bevor wir Metadaten hinzufügen, sollten wir ein paar visuelle Parameter setzen, damit der Barcode nicht zu klein wird. `XDimension` steuert die Modulbreite, während `Columns` die Gesamtform beeinflusst. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Pro‑Tipp:** Eine Pixel‑Breite von `2` funktioniert gut für Bildschirme und die meisten Drucker. Wenn Sie einen hochauflösenden Druck benötigen, erhöhen Sie den Wert auf `3` oder `4`. + +## Schritt 3: Macro PDF417‑Metadatenfelder befüllen + +Jetzt kommt der Kern des Tutorials – das Hinzufügen von **Barcode‑Metadatenfeldern**. Jede Eigenschaft entspricht einem Segment der Macro PDF417‑Spezifikation. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Was jede Eigenschaft bewirkt + +| Eigenschaft | Zweck | Typischer Wert | +|-------------|-------|----------------| +| **MacroPdf417FileID** | Global eindeutiger Bezeichner für das gesamte Dateiset. | `12345678` | +| **MacroPdf417SegmentID** | Index des aktuellen Segments (beginnend bei `0`). | `12` | +| **MacroPdf417SegmentsCount** | Gesamtzahl der erwarteten Segmente für die Datei. | `20` | +| **MacroPdf417FileName** | Menschlich lesbarer Name, häufig der ursprüngliche Dateiname. | `"file01"` | +| **MacroPdf417Checksum** | 16‑Bit‑CCITT‑Prüfsumme zur Fehlererkennung. | `1234` | +| **MacroPdf417FileSize** | Größe der Originaldatei in Bytes. | `400000` | +| **MacroPdf417TimeStamp** | Zeitpunkt der Dateierstellung. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Optionales Feld, das den Empfänger angibt. | `"street"` | +| **MacroPdf417Sender** | Optionales Feld, das das Quellsystem angibt. | `"aspose"` | +| **MacroPdf417Terminator** | Flag, das dem Scanner signalisiert, dass dies das letzte Segment ist. | `Pdf417MacroTerminator.Set` | + +> **Warum Sie das benötigen:** Scanner, die Macro PDF417 verstehen, können eine mehrsegmentige Datei wieder zusammensetzen, die Integrität mit der Prüfsumme prüfen und sogar veraltete Daten anhand des Zeitstempels ablehnen. Das eliminiert die Notwendigkeit einer separaten Manifest‑Datei. + +## Schritt 4: Barcode‑Bild speichern + +Sobald alle Parameter gesetzt sind, rufen wir einfach `Save` auf. Das Beispiel schreibt eine PNG‑Datei in einen von Ihnen angegebenen Ordner. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Randfall:** Wenn Sie den Barcode später in ein PDF einbetten wollen, können Sie `BarCodeImageFormat.Jpeg` oder `Pdf` bevorzugen. PNG bewahrt verlustfreie Details, was für die Überprüfung praktisch ist. + +## Vollständiges funktionierendes Beispiel + +Alles zusammengeführt, hier das komplette Programm, das Sie in eine Konsolen‑App kopieren‑und‑einfügen können: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Erwartete Ausgabe + +Beim Ausführen des Programms wird im Ordner der ausführbaren Datei eine Datei namens **ExtPDF417Meta.png** erstellt. Öffnen Sie sie mit einem Bildbetrachter – Sie sehen einen dichten, hochkontrastierten PDF417‑Barcode. Wenn Sie ihn mit einem Barcode‑Reader scannen, der Macro PDF417 unterstützt, liefert der Scanner die von uns gesetzten Metadaten – Datei‑ID `12345678`, Segment `12` von `20` usw. + +## Häufige Fragen & Stolperfallen + +- **Was tun, wenn der Barcode unscharf aussieht?** Erhöhen Sie `XDimension.Pixels` oder wechseln Sie zu einem hochauflösenderen Bildformat. +- **Muss ich jedes Metadatenfeld setzen?** Nein. Nur die Felder, die Ihr nachgelagertes System benötigt, sind verpflichtend. Unbenutzte Felder können auf ihren Standardwerten bleiben. +- **Kann ich automatisch eine mehrsegmentige Datei erzeugen?** Ja – iterieren Sie über die Daten, erhöhen Sie `MacroPdf417SegmentID` und erzeugen Sie für jedes Segment einen eigenen Barcode. Achten Sie darauf, dass `MacroPdf417FileID` über alle Segmente hinweg gleich bleibt. +- **Wird Unicode unterstützt?** Absolut. Der Beispieltext enthält `Å`, `ó` und `©` und zeigt, dass Aspose.BarCode UTF‑8 von Haus aus verarbeitet. + +## Nächste Schritte: Über die Grundlagen hinaus + +Jetzt, wo Sie wissen, wie man **PDF417‑Barcode‑Metadaten** erstellt, können Sie Folgendes erkunden: + +- **Barcodes in PDFs einbetten** mit `Aspose.Pdf` für eine End‑zu‑End‑Dokumentengenerierung. +- **Metadaten auslesen** mit `BarcodeReader`, um Scans programmgesteuert zu validieren. +- **Farben anpassen** (Vorder‑/Hintergrund) für Branding‑Zwecke. +- **Integration in eine Datenbank**, um Felder wie `FileID` oder `Timestamp` automatisch zu befüllen. + +All diese Themen knüpfen an unsere sekundären Schlüsselwörter – **macro pdf417**, **aspose barcode c#**, **barcode metadata fields** und **c# barcode generation** – an, sodass Sie reichlich Material zum Weiterlernen finden. + +## Fazit + +Wir haben ein komplettes, produktionsreifes Beispiel durchgearbeitet, wie man **PDF417‑Barcode‑Metadaten** in C# erstellt. Von der Installation von Aspose.BarCode, über die Initialisierung eines `BarcodeGenerator`, das Befüllen aller relevanten **Barcode‑Metadatenfelder** bis hin zum Speichern eines scharfen PNGs – der Prozess ist unkompliziert, sobald Sie die richtigen Eigenschaften kennen. + +Probieren Sie es aus, passen Sie die Werte an und beobachten Sie, wie Scanner reagieren. Die Flexibilität von Macro PDF417 ermöglicht es Ihnen, alles, was ein nachgelagertes System benötigt, in einem einzigen, scannbaren Bild zu verankern. Viel Spaß beim Coden und mögen Ihre Barcodes immer fehlerfrei sein! + +## 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 meistern und alternative Implementierungsansätze in Ihren eigenen Projekten erkunden können. + +- [Wie man Barcode erstellt – Kompaktes PDF417 mit Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java barcode library – Barcode zu PDF hinzufügen mit Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/german/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..27ce915e4 --- /dev/null +++ b/barcode/german/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: Erzeugen Sie PDF417‑Barcodes schnell und lernen Sie, wie Sie Spalten + für ein kompaktes PDF417‑Barcode‑Bild in C# festlegen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: de +lastmod: 2026-07-15 +og_description: Erzeugen Sie PDF417‑Barcodes mit Aspose.BarCode und erfahren Sie, + wie Sie Spalten festlegen, um ein kompaktes PDF417‑Barcode‑Bild zu erstellen. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: PDF417-Barcode in C# generieren – Schritt‑für‑Schritt‑Anleitung +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: PDF417-Barcode in C# generieren – Vollständige Anleitung +url: /de/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF417-Barcode in C# generieren – Vollständige Anleitung + +Haben Sie jemals **PDF417-Barcode** in einem .NET‑Projekt erzeugen müssen, wussten aber nicht, wo Sie anfangen sollen? Sie sind nicht allein. In vielen Unternehmens‑Apps – denken Sie an Boarding‑Pass‑Drucker, Inventur‑Etiketten oder Mobile‑Ticketing – ist PDF417 das Arbeitspferd, das viele Daten in einem kleinen visuellen Fußabdruck unterbringt. + +Die Sache ist die: Die Aspose.BarCode‑Bibliothek macht den gesamten Prozess fast schmerzfrei, und Sie können sogar **wie man Spalten festlegt** steuern, sodass der Barcode so kompakt wie möglich wird. Am Ende dieses Tutorials haben Sie ein einsatzbereites PNG‑Bild eines **PDF417‑Barcode‑Bildes**, das Sie in jede UI, E‑Mail oder Druckauftrag einbinden können. + +## Was Sie am Ende erhalten + +- Eine voll funktionsfähige C#‑Konsolen‑App, die einen PDF417‑Barcode erstellt. +- Klares Verständnis der *X‑Dimension* (Modulgröße) und warum sie wichtig ist. +- Schritt‑für‑Schritt‑Anleitungen, wie **man Spalten festlegt** für einen kompakteren Barcode. +- Eine gespeicherte `PNG`‑Datei, die Sie sofort öffnen können, um das Ergebnis zu prüfen. +- Tipps zur Fehlersuche bei häufigen Stolperfallen (z. B. unlesbare Barcodes, falsches Bildformat). + +> **Voraussetzungen** – .NET 6+ SDK, Visual Studio 2022 (oder ein beliebiger Editor), und ein NuGet‑Verweis auf `Aspose.BarCode`. Mehr nicht. + +--- + +## Schritt 1: Installieren Sie das Aspose.BarCode NuGet‑Paket + +Bevor wir **PDF417‑Barcode** erzeugen können, muss die Bibliothek im Projekt vorhanden sein. + +```bash +dotnet add package Aspose.BarCode +``` + +Diese eine Zeile zieht alle Typen, die Sie benötigen, inklusive `BarcodeGenerator`, `EncodeTypes` und dem Enum `BarCodeImageFormat`. + +> **Pro Tipp:** Wenn Sie .NET Framework statt .NET 6 anvisieren, verwenden Sie den klassischen PowerShell‑Befehl `Install-Package Aspose.BarCode` in der Package‑Manager‑Konsole. + +--- + +## Schritt 2: Erstellen Sie eine minimale Konsolenanwendung + +Wir legen ein winziges Programm an, das nichts anderes tut, als einen Barcode zu erzeugen. Öffnen Sie einen neuen Ordner, führen Sie `dotnet new console` aus und ersetzen Sie die automatisch erzeugte `Program.cs` durch den Code unten. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Warum das wichtig ist:** +- `EncodeTypes.Pdf417` teilt der Bibliothek mit, dass wir einen PDF417‑Barcode wollen, nicht QR oder Code128. +- `XDimension.Pixels` steuert die Auflösung jedes kleinen schwarzen oder weißen Moduls. +- Der Block **wie man Spalten festlegt** beeinflusst direkt die Form des **PDF417‑Barcode‑Bildes**. +- `Truncate = true` entfernt unnötige leere Zeilen und gibt Ihnen das „kompakte“ Aussehen, das viele Scanner lieben. + +--- + +## Schritt 3: Tiefer einsteigen – Verständnis von Spalten und Trunkierung + +### Wie man Spalten festlegt + +PDF417 ordnet Daten in einer Matrix aus *Zeilen* × *Spalten*. Die Bibliothek verwendet standardmäßig 5 Spalten, was für die meisten Fälle funktioniert. Möglicherweise benötigen Sie jedoch einen schmaleren Barcode, um auf ein Etikett zu passen, oder einen breiteren, um die Scan‑Zuverlässigkeit zu erhöhen. Die Eigenschaft: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +akzeptiert Werte von **1** bis **30** (die genaue Grenze hängt von der Datenlänge ab). Hier ein kurzer Spickzettel: + +| Spalten | Ungef. Breite (mm) | Wann zu verwenden | +|---------|-------------------|--------------------| +| 1‑3 | Sehr schmal | Kleines Etikett, begrenzter Platz | +| 4‑6 | Standard | Die meisten Quittungen, Tickets | +| 7‑10 | Breiter | Hochdichte Daten, bessere Lesbarkeit | + +### Truncate (Kompaktmodus) + +Durch Setzen von `Truncate = true` wird dem Encoder mitgeteilt, unnötige leere Zeilen am unteren Rand abzuschneiden. Das Ergebnis ist ein **kompaktes PDF417‑Barcode‑Bild**, das den kleinstmöglichen Raum einnimmt und dennoch alle Daten enthält. Wenn Sie jemals den Fehler „Barcode zu groß für Etikett“ erhalten, schalten Sie dieses Flag um. + +--- + +## Schritt 4: Führen Sie die Anwendung aus und überprüfen Sie die Ausgabe + +Kompilieren und ausführen: + +```bash +dotnet run +``` + +Sie sollten die Konsolennachricht sehen, die den Speicherort bestätigt. Navigieren Sie zum Ordner und öffnen Sie `CompactPdf417.png`. Das Bild sieht etwa so aus: + +![Generiertes PDF417-Barcode-Bild](./CompactPdf417.png "Generiertes PDF417-Barcode-Bild – kompaktes PNG erstellt von Aspose.BarCode") + +*Bild-Alt-Text:* **Generiertes PDF417-Barcode-Bild** – eine kompakte PNG-Datei, die durch den Tutorialcode erzeugt wurde. + +Wenn Ihr Scanner es lesen kann, herzlichen Glückwunsch – Sie haben erfolgreich **PDF417‑Barcode generiert** und **wie man Spalten festlegt** für ein ordentliches **PDF417‑Barcode‑Bild** gemeistert. + +--- + +## Schritt 5: Häufige Fallstricke & wie man sie behebt + +| Symptom | Wahrscheinliche Ursache | Schnelle Lösung | +|---------|--------------------------|-----------------| +| Barcode erscheint unscharf | `XDimension.Pixels` zu niedrig (z. B. 1) | Auf 2‑3 Pixel erhöhen für ein klareres Bild. | +| Scanner kann nicht lesen | Zu viele Spalten für die gegebenen Daten | `Columns` reduzieren oder `Truncate` aktivieren. | +| Falsches Dateiformat | Versehentlich mit `BarCodeImageFormat.Jpeg` gespeichert | `BarCodeImageFormat.Png` für verlustfreie Ergebnisse verwenden. | +| Ausnahme `ArgumentOutOfRangeException` | Spaltenanzahl überschreitet den zulässigen Bereich | Spalten zwischen 1‑30 halten und sicherstellen, dass die Daten passen. | + +--- + +## Schritt 6: Weiterführend – Farben anpassen und Text hinzufügen + +Wenn Sie den Barcode an eine Marken‑Palette anpassen möchten, können Sie Vorder‑ und Hintergrundfarben ändern: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Oder lesbaren Text unter dem Barcode einblenden: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Diese Ergänzungen sind optional, zeigen aber, wie flexibel der **PDF417‑Barcode‑Erzeugungs‑Workflow** sein kann. + +--- + +## Fazit + +Wir haben ein vollständiges End‑zu‑End‑Beispiel durchgearbeitet, das **PDF417‑Barcode** mit Aspose.BarCode erzeugt, erklärt **wie man Spalten festlegt**, um die Abmessungen des Barcodes zu steuern, und das Ergebnis als gestochen scharfes **PDF417‑Barcode‑Bild** im PNG‑Format gespeichert. Der Code ist eigenständig, funktioniert mit .NET 6+ und lässt sich mit minimalem Aufwand in jedes bestehende Projekt einbinden. + +Was kommt als Nächstes? Versuchen Sie, größere Payloads (z. B. JSON‑Payloads) zu kodieren, experimentieren Sie mit verschiedenen Bildformaten oder integrieren Sie den Generator in eine Web‑API, die Barcodes auf Abruf bereitstellt. Der Himmel ist die Grenze, und Sie haben jetzt ein solides Fundament, auf dem Sie aufbauen können. + +Viel Spaß beim Coden, und möge Ihr Barcode immer beim ersten Versuch gescannt werden! + +## 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, 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‑Bild in Java mit Aspose.BarCode generiert](/barcode/english/java/barcode-rendering-techniques/) +- [Barcode in Java generieren – Bildauflösung mit Aspose.BarCode festlegen](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/german/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..5887cceff --- /dev/null +++ b/barcode/german/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-07-15 +description: Erstellen Sie PDF417‑Barcodes schnell mit C#. Erfahren Sie, wie Sie Barcodes + aus Text generieren, die Barcode‑Größe anpassen und benutzerdefinierte Barcode‑Abmessungen + in wenigen Minuten festlegen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: de +lastmod: 2026-07-15 +og_description: Erstelle PDF417-Barcode in C# sofort. Dieser Leitfaden zeigt, wie + man einen Barcode aus Text generiert, die Barcode‑Größe anpasst und benutzerdefinierte + Barcode‑Abmessungen anwendet. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: PDF417-Barcode in C# generieren – Vollständiges Programmier‑Tutorial +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: PDF417-Barcode in C# generieren – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-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# – Vollständige Schritt‑für‑Schritt‑Anleitung + +Haben Sie jemals **PDF417-Barcode generieren** müssen, waren sich aber nicht sicher, welche Einstellungen Sie anpassen sollten? Sie sind nicht der Einzige – viele Entwickler stoßen beim ersten Umgang mit 2‑D‑Barcodes auf dieselbe Hürde. Die gute Nachricht? Mit ein paar Zeilen C# können Sie jede Zeichenkette in ein scannbares PDF417‑Bild verwandeln, die genaue Größe steuern und sogar ein benutzerdefiniertes Spalten‑Zeilen‑Layout festlegen. + +In diesem Tutorial führen wir Sie Schritt für Schritt durch das **Generieren eines Barcodes aus Text**, das Anpassen der Barcode‑Größe und das Festlegen benutzerdefinierter Barcode‑Abmessungen — alles mit der beliebten Aspose.BarCode‑Bibliothek. Am Ende haben Sie ein einsatzbereites Beispiel, das Sie in jedes .NET‑Projekt einbinden können. + +![Beispiel für PDF417-Barcode-Generierung](https://example.com/og-image.png "Beispiel für PDF417-Barcode-Generierung") + +## Was Sie erstellen werden + +- Einen PDF417-Barcode, der die Zeichenkette `Åspóse.Barcóde©` kodiert. +- Präzise Kontrolle über die X‑Dimension (Pixelbreite jedes Moduls). +- Ein benutzerdefiniertes Layout mit 4 Spalten und 9 Zeilen. +- Eine PNG‑Datei, die auf die Festplatte gespeichert wird. + +Keine externen Dienste, keine Zauberstab‑Tricks – nur reiner C#‑Code, den Sie sofort kompilieren können. + +## Voraussetzungen + +- .NET 6.0 oder höher (der Code funktioniert auch mit .NET Framework 4.8). +- Visual Studio 2022 oder jede IDE, die C# unterstützt. +- Aspose.BarCode für .NET (Kostenlose Testversion oder lizenziert). Installation über NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +Das war’s – sobald das Paket referenziert ist, können Sie loslegen. + +## Schritt 1 – PDF417-Barcode mit Textdaten generieren + +Das Erste, was wir benötigen, ist eine Instanz von `BarcodeGenerator`, die weiß, dass wir die PDF417‑Symbologie verwenden und den genauen Text, den wir kodieren wollen. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Warum das wichtig ist:** +> `EncodeTypes.Pdf417` weist die Bibliothek an, das PDF417‑2‑D‑Format zu verwenden, während das zweite Argument die **Barcode‑Generierung aus Text**‑Nutzlast ist. Alles, was Sie hier übergeben, wird zu den im Barcode‑Matrix gespeicherten Daten. + +## Schritt 2 – Barcode‑Größe anpassen (X‑Dimension) + +Wenn Sie jemals einen Barcode gedruckt haben, der auf einem Kassenbon zu klein wirkte, kennen Sie die Frustration, wenn der Scanner ihn nicht erkennt. Die Eigenschaft `XDimension` steuert die Breite eines einzelnen Moduls (das kleinste schwarze oder weiße Quadrat) in Pixeln. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Profi‑Tipp:** +> Ein Wert von 2 px funktioniert gut für die meisten Bildschirm‑Darstellungen. Für hochauflösende Drucke können Sie diesen auf 3 oder 4 px erhöhen. Denken Sie daran, dass größere X‑Dimensionen die Gesamtbildgröße vergrößern. + +## Schritt 3 – Benutzerdefinierte Barcode‑Abmessungen festlegen (Spalten & Zeilen) + +PDF417 ermöglicht es Ihnen, festzulegen, wie viele Spalten und Zeilen der Barcode einnehmen soll. Hier kommen die **benutzerdefinierten Barcode‑Abmessungen** ins Spiel. Das Ändern dieser Werte kann Ihnen helfen, den Barcode in einen engen UI‑Bereich zu passen oder eine bestimmte Etikettengröße zu erreichen. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Was passiert im Hintergrund?** +> Die Bibliothek verteilt die kodierten Daten über das angegebene Raster neu. Weniger Spalten bedeuten höhere Barcodes; mehr Zeilen machen sie kürzer. Spielen Sie mit den Zahlen, bis das visuelle Gleichgewicht für Ihre Anwendung passend erscheint. + +## Schritt 4 – Barcode‑Bild speichern + +Jetzt, wo wir alles konfiguriert haben, lassen wir den Generator einfach eine PNG‑Datei schreiben. PNG ist verlustfrei, sodass die Schärfe der Module erhalten bleibt. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Wenn Sie das Programm ausführen, sollten Sie eine Datei unter `C:\Barcodes\CustomLayout.png` sehen, die dem obigen Screenshot ähnelt. Das Scannen mit einem beliebigen PDF417‑kompatiblen Leser gibt die ursprüngliche Zeichenkette `Åspóse.Barcóde©` zurück. + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie das komplette Programm, das Sie in eine Konsolen‑App kopieren können. Es enthält alle using‑Direktiven und die Fehlerbehandlung, die Sie in Produktionscode erwarten würden. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Erwartete Ausgabe + +Beim Ausführen des Codes wird ausgegeben: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…und erstellt ein PNG, das in jedem Bildbetrachter geöffnet werden kann. Wenn Sie es mit einer mobilen App (z. B. „Barcode Scanner“ auf iOS/Android) scannen, sollte der dekodierte Text exakt **Åspóse.Barcóde©** sein. + +## Häufige Fragen & Sonderfälle + +| Frage | Antwort | +|----------|--------| +| **Kann ich ein anderes Bildformat verwenden?** | Ja—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` oder `Svg` werden alle unterstützt. Ändern Sie einfach das zweite Argument von `Save`. | +| **Was ist, wenn mein Text Unicode‑Zeichen enthält?** | Aspose.BarCode unterstützt UTF‑8 vollständig, sodass das Beispiel mit `Å` und `©` sofort funktioniert. | +| **Wie ändere ich das Fehlerkorrektur‑Level?** | Verwenden Sie `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (Level 0‑8). Höhere Level erhöhen die Redundanz, vergrößern aber auch die Größe. | +| **Ich benötige einen transparenten Hintergrund – ist das möglich?** | Setzen Sie `generator.Parameters.Barcode.Image.TransparentBackground = true;` vor dem Speichern. | +| **Gibt es eine Möglichkeit, den Barcode direkt in ein PDF einzubetten?** | Auf jeden Fall. Ersetzen Sie den Aufruf `Save` durch `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` und Sie erhalten ein einseitiges PDF, das den Barcode enthält. | + +## Fazit + +Sie wissen jetzt, wie man in C# aus jeder Zeichenkette **PDF417‑Barcode generiert**, **die Barcode‑Größe anpasst** und **benutzerdefinierte Barcode‑Abmessungen** anwendet, um Ihren Layout‑Bedürfnissen gerecht zu werden. Der vier‑schrittige Ablauf – Initialisieren, Größe, Layout, Speichern – deckt den Kern‑Workflow für die meisten 2‑D‑Barcode‑Szenarien ab. + +Was kommt als Nächstes? Versuchen Sie, `EncodeTypes.Pdf417` durch `EncodeTypes.QR` oder `EncodeTypes.Code128` zu ersetzen, um zu sehen, wie sich die API anpasst. Experimentieren Sie mit verschiedenen `XDimension`‑Werten, spielen Sie mit dem Spalten‑/Zeilen‑Matrix oder betten Sie das Bild in einen PDF‑Bericht ein. Die Möglichkeiten sind praktisch unbegrenzt, und Sie haben nun ein solides Fundament, auf dem Sie aufbauen können. + +Haben Sie weitere Fragen oder einen cleveren Trick entdeckt, während Sie mit PDF417 experimentiert haben? Hinterlassen Sie unten einen Kommentar – lassen Sie die Unterhaltung weiterlaufen. 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, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Wie man Aztec‑Barcode mit benutzerdefiniertem Seitenverhältnis mit Aspose.BarCode für .NET generiert](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Wie man Barcodes generiert – Ein‑dimensionalen Barcode‑Typen](/barcode/english/net/one-dimensional-barcode-types/) +- [DataMatrix‑Barcode generieren – Pro‑Leitfaden mit Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/german/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..757ae1d57 --- /dev/null +++ b/barcode/german/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,314 @@ +--- +category: general +date: 2026-07-15 +description: Wie man PDF417‑Barcodes in C# liest und mehrere Barcodes aus einem Bild + ausliest. Lernen Sie, Barcode‑Bilder in C# mit detailliertem Code und Tipps zu lesen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: de +lastmod: 2026-07-15 +og_description: Wie man PDF417‑Barcodes in C# schnell liest. Dieser Leitfaden zeigt, + wie man mehrere Barcodes aus einem einzigen Bild liest und jede Eigenschaft dekodiert. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Wie man PDF417 in C# liest – Vollständiges Codebeispiel & Erklärung +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Wie man PDF417 in C# liest – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-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ändige Schritt‑für‑Schritt‑Anleitung + +Haben Sie sich jemals gefragt, **wie man PDF417** aus einem Bild mit C# liest? Sie sind nicht der Einzige. Die meisten Entwickler stoßen an ihre Grenzen, wenn sie die erweiterten Macro‑PDF417‑Felder aus einem gescannten Dokument extrahieren müssen. Die gute Nachricht? Mit nur wenigen Codezeilen können Sie ein PDF417 dekodieren, mehrere Barcodes im selben Bild lesen und jede versteckte Eigenschaft, die die Spezifikation bietet, abrufen. + +In diesem Tutorial gehen wir ein praxisnahes Beispiel durch, das **zeigt, wie man PDF417 liest**, wie man **mehrere Barcodes** aus einer einzigen Datei liest und warum der **read barcode image C#**‑Code so aussieht, wie er aussieht. Am Ende haben Sie eine sofort ausführbare Konsolen‑App, die jede Information ausgibt, die Sie benötigen könnten – Datei‑ID, Segment‑ID, Prüfsumme, Zeitstempel, und vieles mehr. + +## Voraussetzungen + +Bevor wir beginnen, stellen Sie sicher, dass Sie folgendes haben: + +* .NET 6.0 SDK oder neuer (der Code funktioniert auch mit .NET Core und .NET Framework). +* Visual Studio 2022 (oder ein beliebiger anderer Editor). +* Das **Aspose.BarCode for .NET** NuGet‑Paket – das ist die Bibliothek, die PDF417 tatsächlich analysiert. +* Ein Beispielbild, das einen Macro‑PDF417‑Barcode enthält (z. B. `ExtPDF417Meta.png`). + +Es ist keine zusätzliche Konfiguration erforderlich; die Bibliothek liefert alle Decoder, die Sie benötigen. + +## Schritt 1: Aspose.BarCode installieren + +Öffnen Sie Ihren Projektordner in einem Terminal und führen Sie aus: + +```bash +dotnet add package Aspose.BarCode +``` + +Dieser Befehl holt die neueste stabile Version (Stand Juli 2026 ist das 23.12). Wenn Sie die Package Manager Console in Visual Studio bevorzugen, verwenden Sie: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Pro‑Tipp:** Sperren Sie die Version (`23.12.0`) in Ihrer `.csproj`, um versehentliche Breaking Changes später zu vermeiden. + +## Schritt 2: Konsolen‑App‑Gerüst erstellen + +Erstellen Sie ein neues Konsolenprojekt, falls Sie noch keines haben: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Ersetzen Sie die automatisch erzeugte `Program.cs` durch den untenstehenden Code. Wir erklären jeden Block in den nächsten Abschnitten. + +## Schritt 3: Den vollständigen „Wie man PDF417 liest“‑Code schreiben + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Warum dieser Code funktioniert + +* **`BarCodeReader`** ist die Kernklasse, die das Bild streamt, Barcodes erkennt und eine Sammlung von `BarCodeResult`‑Objekten zurückgibt. +* Das Übergeben von **`DecodeType.MacroPdf417`** weist die Bibliothek an, Macro‑PDF417 speziell zu behandeln; sie liefert weiterhin einfache PDF417‑Symbole, was die Anforderung **read multiple barcodes** erfüllt. +* Das **`Extended.Pdf417.MacroPdf417`**‑Objekt enthält jedes optionale Feld, das im ISO/IEC 15438‑Standard definiert ist – dort erhalten Sie `FileID`, `SegmentID`, `Checksum` usw. +* Der `using`‑Block stellt sicher, dass native Ressourcen freigegeben werden und verhindert Speicherlecks in langfristig laufenden Diensten. + +## Schritt 4: Anwendung ausführen und Ausgabe überprüfen + +Aus dem Terminal: + +```bash +dotnet run +``` + +Sie sollten etwas Ähnliches sehen: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Enthält das Bild mehr als einen Barcode, gibt die Schleife eine Trennlinie (`----------------------------------------`) aus und fährt mit dem nächsten Ergebnis fort – genau das, was **read multiple barcodes** in der Praxis bedeutet. + +## Häufige Fragen & Sonderfälle + +### Was ist, wenn das Bild sowohl Macro‑PDF417‑ als auch reguläre PDF417‑Symbole enthält? + +Der gleiche `BarCodeReader`‑Aufruf liefert beide. Sie können sie unterscheiden, indem Sie `result.CodeType` prüfen (`MacroPdf417` vs `Pdf417`). Die erweiterten Eigenschaften sind bei einem einfachen PDF417 `null`, sodass die Prüfung `if (macro != null)` eine `NullReferenceException` verhindert. + +### Mein Barcode ist gedreht oder verzerrt – funktioniert der Reader trotzdem? + +Aspose.BarCode enthält eingebaute Dreh‑ und Verzerrungskompensation. Solange der Barcode mindestens 30 % der Bildbreite einnimmt, gelingt die Dekodierung in der Regel. Für extreme Fälle können Sie vor dem Aufruf von `ReadBarCodes()` `reader.Options.AllowInvertedBarcodes = true;` aktivieren. + +### Wie gehe ich mit großen Bildmengen um? + +Wickeln Sie die Leselogik in eine Schleife wie `foreach (var file in Directory.GetFiles(folder, "*.png"))`. Das `using`‑Muster stellt sicher, dass die nativen Ressourcen jedes Bildes freigegeben werden, bevor die nächste Iteration beginnt, wodurch der Speicherverbrauch niedrig bleibt. + +## Vollständige Quellcode‑Auflistung (zum Kopieren‑und‑Einfügen bereit) + +Unten finden Sie das gesamte Programm in einem Block für schnelles Kopieren‑und‑Einfügen. Keine versteckten Abhängigkeiten – nur das Aspose.BarCode NuGet‑Paket. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Zusammenfassung – Was wir behandelt haben + +* **How to read PDF417** mit Aspose.BarCode in C#. +* Die genauen Schritte, um **read multiple barcodes** aus einem einzigen Bild zu lesen. +* Wie man **read barcode image C#** verwendet und jedes Macro‑PDF417‑Feld extrahiert. +* Tipps zu Drehungen, Batch‑Verarbeitung und dem Umgang mit fehlenden erweiterten Daten. + +## Nächste Schritte & verwandte Themen + +* **Encode PDF417** – erzeugen Sie eigene Macro‑PDF417‑Barcodes mit `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – mit derselben `BarCodeReader`‑Klasse. +* **Integrate with ASP.NET Core** – stellen Sie einen Web‑Endpoint bereit, der ein hochgeladenes Bild akzeptiert und JSON mit den dekodierten Feldern zurückgibt. + +Fühlen Sie sich frei zu experimentieren: ändern Sie den Bildpfad, legen Sie ein einfaches PDF417 in denselben Ordner, oder passen Sie die `DecodeType`‑Flags an, um zu sehen, wie sich die Bibliothek verhält. Je mehr Sie spielen, desto sicherer werden Sie im Umgang mit **read barcode image C#**‑Szenarien. + +Haben Sie ein kniffliges Bild, das sich nicht dekodieren lässt? Hinterlassen Sie einen Kommentar unten oder öffnen Sie ein Issue im GitHub‑Repo des Beispielprojekts. 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 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. + +- [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/german/net/one-dimensional-barcode-types/_index.md b/barcode/german/net/one-dimensional-barcode-types/_index.md index b2fd5ba30..42fd56e36 100644 --- a/barcode/german/net/one-dimensional-barcode-types/_index.md +++ b/barcode/german/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ Erfahren Sie, wie Sie mit Aspose.BarCode für .NET Barcodes in .NET generieren. Erfahren Sie, wie Sie Ausnahmen beim Generieren eindimensionaler Barcodes mit Aspose.BarCode für .NET behandeln. Diese Schritt-für-Schritt-Anleitung sorgt für fehlertolerante Barcode-Lösungen. Jetzt loslegen! ### [Eindimensionale Breit-Schmal-Verhältnis-Konfiguration](./one-dimensional-wide-narrow-ratio-configuration/) Generieren Sie ganz einfach individuelle Barcodes mit Aspose.BarCode für .NET. Schritt-für-Schritt-Anleitung für die eindimensionale Breit-Schmal-Verhältniskonfiguration. +### [Barcode aus Text generieren mit Aspose.BarCode – C#-Leitfaden](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Erfahren Sie, wie Sie mit Aspose.BarCode in C# Barcodes aus Text generieren. Schritt-für-Schritt-Anleitung für .NET-Entwickler. ## Abschluss @@ -89,4 +91,4 @@ Mit diesem Artikel erwerben Sie nicht nur Kenntnisse über verschiedene eindimen {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/german/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..b01f338b7 --- /dev/null +++ b/barcode/german/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-07-15 +description: Erzeugen Sie Barcodes aus Text mit Aspose.BarCode in C#. Erfahren Sie, + wie Sie die Spaltenanzahl ändern, das Barcode‑Bild speichern und schnell Barcode‑Lösungen + mit Aspose erstellen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: de +lastmod: 2026-07-15 +og_description: Erzeugen Sie einen Barcode aus Text mit Aspose.BarCode. Dieser Leitfaden + zeigt, wie Sie die Spaltenanzahl ändern, das Barcode‑Bild speichern und einen Barcode + mit Aspose in wenigen Codezeilen erstellen. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Barcode aus Text mit Aspose.BarCode generieren – Schnelle C#‑Anleitung +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Barcode aus Text mit Aspose.BarCode generieren – C#‑Leitfaden +url: /de/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode aus Text mit Aspose.BarCode generieren – C#‑Leitfaden + +Barcode aus Text mit Aspose.BarCode zu generieren ist überraschend einfach. In diesem Tutorial führen wir Sie durch **wie man einen Barcode generiert**, passen das Spaltenlayout an und schließlich **speichern das barcode image** als PNG‑Datei. Egal, ob Sie ein Ticket‑System, einen Lageretikettendrucker bauen oder einfach mit QR‑ähnlichen Codes experimentieren, die folgenden Schritte bringen Sie schnell ans Ziel. + +## Was Sie lernen werden + +- Erstellen Sie einen Barcode aus einer beliebigen Unicode‑Zeichenkette (ja, sogar „Åspóse.Barcóde©“ funktioniert). +- Passen Sie die **column count** für MicroPdf417 an, um schmale oder breite Etiketten zu passen. +- Speichern Sie das Ergebnis auf der Festplatte im richtigen Bildformat. +- Tipps zum Umgang mit Sonderzeichen und häufigen Fallstricken, wenn Sie **create barcode Aspose**‑Lösungen erstellen. + +Keine externen Werkzeuge, keine Befehlszeilen‑Tricks – nur reines C# und die Aspose.BarCode‑Bibliothek. + +## Voraussetzungen + +Bevor wir loslegen, stellen Sie sicher, dass Sie folgendes haben: + +1. **.NET 6.0** oder höher installiert (der Code funktioniert auch mit .NET Framework 4.7+). +2. Eine **license** für Aspose.BarCode, oder Sie können mit der kostenlosen Evaluierungs‑Version beginnen. +3. Einen Ordner, in den Sie schreiben können – wir nennen ihn `YOUR_DIRECTORY` in den Beispielen. + +Falls Ihnen etwas fehlt, holen Sie sich jetzt das NuGet‑Paket: + +```bash +dotnet add package Aspose.BarCode +``` + +Das war’s – keine zusätzlichen DLLs, die Sie manuell kopieren müssen. + +## Schritt 1 – Projekt einrichten und Imports + +Zuerst erstellen Sie eine Konsolen‑App (oder fügen den Code in ein beliebiges C#‑Projekt ein). Der wichtige Teil ist, die richtigen Namespaces zu importieren: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Warum diese using‑Anweisungen? `BarcodeGenerator` befindet sich in `Aspose.BarCode.Generation`, während das `BarCodeImageFormat`‑Enum in `Aspose.BarCode` liegt. Saubere Imports lassen den späteren Code wie lesbares Englisch wirken. + +## Schritt 2 – Barcode‑Generator erstellen (wie man einen Barcode generiert) + +Jetzt **generieren wir einen barcode from text**. Das `EncodeTypes`‑Enum teilt Aspose mit, welche Symbolik verwendet werden soll; hier wählen wir `MicroPdf417`, weil es lange Zeichenketten in einem kompakten Raster verarbeitet. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Beachten Sie, dass die Zeichenkette akzentuierte Zeichen und ein Copyright‑Symbol enthält. Aspose.BarCode kodiert Unicode automatisch, sodass Sie den Text nicht vorverarbeiten müssen. + +## Schritt 3 – Aussehen feinjustieren (wie man die column count ändert) + +MicroPdf417 ermöglicht die Steuerung der Spaltenanzahl, was die Breite des Barcodes direkt beeinflusst. Ein kompakteres Layout ist ideal für schmale Etiketten; ein breiteres Layout verbessert die Lesbarkeit bei großen Drucken. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Warum 2‑Pixel‑Module? Sie erzeugen ein scharfes Bild, ohne die Dateigröße zu vergrößern. Experimentieren Sie gern – Werte zwischen 1 und 4 funktionieren meist gut. Wenn Sie eine andere column count benötigen, ändern Sie einfach die `Columns`‑Eigenschaft; Aspose berechnet das Layout automatisch neu. + +## Schritt 4 – barcode image speichern (save barcode image) + +Mit dem konfigurierten Generator sind wir bereit, das **barcode image** zu **speichern**. Die Methode `Save` akzeptiert einen Dateipfad und ein Bildformat‑Enum. PNG ist verlustfrei, sodass der Barcode auch nach Skalierung scharf bleibt. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Ein schneller Hinweis: Verwenden Sie immer einen absoluten Pfad oder stellen Sie sicher, dass das Arbeitsverzeichnis dem erwarteten entspricht; sonst kann die Datei im bin‑Ordner landen und Sie fragen sich, warum Sie sie nicht finden können. + +## Vollständiges funktionierendes Beispiel + +Alles zusammengefügt, hier ein eigenständiges Programm, das Sie in `Program.cs` kopieren und ausführen können: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Erwartete Ausgabe** (Konsole): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +Und wenn Sie `MicroPdf417.png` öffnen, sehen Sie einen scharfen MicroPdf417‑Barcode, der die ursprüngliche Zeichenkette inklusive der speziellen Zeichen, die wir ihm übergeben haben, kodiert. + +## Häufige Fragen & Sonderfälle + +### Was, wenn mein Text länger ist als die Standardkapazität? + +MicroPdf417 wechselt automatisch zu einem mehrzeiligen Layout, wenn die Daten die maximale Zeichenanzahl pro Zeile überschreiten. Sie können weiterhin die column count steuern, aber die Bibliothek kann im Hintergrund zusätzliche Zeilen hinzufügen. Kein zusätzlicher Code nötig – achten Sie nur auf die resultierenden Bildabmessungen. + +### Wie ändere ich das Bildformat zu JPEG oder BMP? + +Ersetzen Sie `BarCodeImageFormat.Png` durch `BarCodeImageFormat.Jpeg` (oder `Bmp`). Denken Sie daran, dass JPEG Kompressionsartefakte einführt, die die Scan‑Zuverlässigkeit beeinträchtigen können. PNG ist die sicherste Vorgabe. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Ich sehe ein Wasserzeichen in der Ausgabe – was ist das Problem? + +Das ist die Evaluierungs‑Version von Aspose.BarCode. Um **create barcode Aspose** ohne Wasserzeichen zu verwenden, laden Sie eine gültige Lizenzdatei, wie in der kommentierten Zeile von Schritt 2 gezeigt. + +### Kann ich andere Symboliken (QR, Code128, etc.) generieren? + +Natürlich. Ersetzen Sie einfach `EncodeTypes.MicroPdf417` durch einen anderen Wert aus dem `EncodeTypes`‑Enum, z. B. `EncodeTypes.QR` oder `EncodeTypes.Code128`. Der restliche Code bleibt unverändert, was den Ansatz sehr wiederverwendbar macht. + +## Profi‑Tipps für produktionsreife Barcode‑Generierung + +- **Cache the generator** wenn Sie viele Barcodes mit denselben Einstellungen erzeugen; das reduziert den Overhead bei der Objekterstellung. +- **Validate the input string** hinsichtlich Längenbeschränkungen, die für die gewählte Symbolik gelten (Aspose wirft `ArgumentException`, wenn sie zu lang ist). +- **Use `using` statements** oder `Dispose` den Generator nach Gebrauch, um native Ressourcen sofort freizugeben. +- **Set DPI** über `generator.Parameters.ImageResolution.DpiX/DpiY`, wenn Sie hochauflösende Drucke für große Etiketten benötigen. + +## Fazit + +Sie wissen jetzt genau **how to generate barcode from text** mit Aspose.BarCode, wie man **change column count** ändert und wie man **save barcode image** korrekt als PNG speichert. Das vollständige, ausführbare Beispiel oben demonstriert einen sauberen, produktionsreifen + +## 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 Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Generate barcode image – Code 93 with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/greek/net/compact-pdf417-encoding/_index.md index 06b8d9294..12c5f8af8 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 @@ -84,7 +84,10 @@ weight: 29 ## Συμμετοχικά Σεμινάρια Συμπαγούς PDF417 ### [Δημιουργία Συμπαγών PDF417 Κωδικών](./compact-pdf417-basic-configuration/) -Μάθετε πώς να δημιουργείτε Συμπαγείς PDF417 κωδικούς χρησιμοποιώντας το Aspose.BarCode for .NET. Αναλυτικός οδηγός με βήμα‑βήμα οδηγίες και παραδείγματα κώδικα. +### [Δημιουργία Μεταδεδομένων PDF417 Barcode σε C# – Πλήρης Οδηγός Βήμα‑βήμα](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +### [Δημιουργία PDF417 Barcode σε C# – Πλήρης Οδηγός](./generate-pdf417-barcode-in-c-complete-guide/) +### [Δημιουργία PDF417 Barcode σε C# – Πλήρης Οδηγός Βήμα‑βήμα](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +### [Πώς να Διαβάσετε PDF417 σε C# – Πλήρης Οδηγός Βήμα‑βήμα](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) ## Συχνές Ερωτήσεις @@ -98,7 +101,7 @@ weight: 29 Α: Ναι. Το Aspose.BarCode for .NET υποστηρίζει πλήρως το .NET Core 3.1 και μεταγενέστερες εκδόσεις. **Ε: Είναι δυνατόν να προσαρμόσω τα χρώματα προσκηνίου και φόντου του κώδικα;** -Α: Απολύτως. Χρησιμοποιήστε τις ιδιότητες `ForeColor` και `BackColor` του γεννήτρια για να ταιριάξετε το θέμα της διεπαφής σας. +Α: Απόλυτα. Χρησιμοποιήστε τις ιδιότητες `ForeColor` και `BackColor` του γεννήτρια για να ταιριάξετε το θέμα της διεπαφής σας. **Ε: Πρέπει να εγκαταστήσω επιπλέον γραμματοσειρές ή πόρους;** Α: Δεν απαιτούνται εξωτερικές γραμματοσειρές· η βιβλιοθήκη διαχειρίζεται όλη την απόδοση εσωτερικά. @@ -114,4 +117,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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/greek/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..8f9d09d79 --- /dev/null +++ b/barcode/greek/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-07-15 +description: Δημιουργήστε μεταδεδομένα barcode PDF417 σε C# χρησιμοποιώντας το Aspose.BarCode. + Μάθετε τις ρυθμίσεις Macro PDF417, αποθηκεύστε ως PNG και διαχειριστείτε κείμενο + Unicode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: el +lastmod: 2026-07-15 +og_description: Δημιουργήστε μεταδεδομένα barcode PDF417 σε C# με το Aspose.BarCode. + Αυτός ο οδηγός δείχνει κάθε ρύθμιση που χρειάζεστε για την ενσωμάτωση του file‑ID, + χρονικών σημάνσεων και περισσότερων. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: Δημιουργία μεταδεδομένων barcode PDF417 σε C# – Πλήρης οδηγός προγραμματισμού +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: Δημιουργία μεταδεδομένων barcode PDF417 σε C# – Πλήρης οδηγός βήμα‑βήμα +url: /el/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία Μεταδεδομένων Barcode PDF417 σε C# – Πλήρης Οδηγός Βήμα‑βήμα + +Κάποτε χρειάστηκε να **δημιουργήσετε μεταδεδομένα barcode PDF417** σε C# αλλά δεν ήσασταν σίγουροι ποιες ιδιότητες πρέπει να ρυθμίσετε; Δεν είστε μόνοι—οι προγραμματιστές συχνά συναντούν δυσκολίες όταν η προδιαγραφή απαιτεί στοιχεία όπως IDs αρχείων, αριθμούς τμημάτων ή προσαρμοσμένες χρονικές σφραγίδες. + +Το καλό νέο είναι ότι το Aspose.BarCode το κάνει παιχνιδάκι. Σε αυτό το tutorial θα δημιουργήσουμε ένα `BarcodeGenerator` για **Macro PDF417**, θα προσθέσουμε όλα τα σημαντικά μεταδεδομένα και θα αποθηκεύσουμε το αποτέλεσμα ως εικόνα PNG. Στο τέλος θα έχετε ένα πλήρως εξοπλισμένο barcode έτοιμο για οποιοδήποτε σύστημα εφοδιαστικής αλυσίδας ή διαχείρισης εγγράφων. + +## Τι Καλύπτει Αυτός ο Οδηγός + +Θα περάσουμε από: + +1. Εγκατάσταση του πακέτου NuGet Aspose.BarCode. +2. Αρχικοποίηση ενός `BarcodeGenerator` για **Macro PDF417**. +3. Συμπλήρωση κάθε χρήσιμης **πεδίου μεταδεδομένων barcode** (file ID, segment ID, checksum κ.λπ.). +4. Αποθήκευση του barcode στο δίσκο και επαλήθευση του αποτελέσματος. + +Δεν απαιτείται προηγούμενη εμπειρία με Macro PDF417—απλώς βασικές γνώσεις C# και ένα πρόσφατο .NET runtime. + +Γιατί να σας ενδιαφέρει; Η ενσωμάτωση πλούσιων μεταδεδομένων απευθείας σε ένα barcode επιτρέπει στους επόμενους σαρωτές να επικυρώνουν ολόκληρες μεταφορές αρχείων, να εντοπίζουν ελλιπή τμήματα ή ακόμη και να ενεργοποιούν αυτοματοποιημένες ροές εργασίας. Με άλλα λόγια, έχετε **αξιόπιστα, αυτό-περιγραφικά δεδομένα** χωρίς ξεχωριστή βάση δεδομένων. + +## Προαπαιτούμενα + +- .NET 6.0 ή νεότερο (ο κώδικας λειτουργεί επίσης σε .NET Framework 4.7+). +- Visual Studio 2022 (ή οποιοδήποτε IDE προτιμάτε). +- Το **Aspose.BarCode for .NET** πακέτο NuGet (διατίθεται δωρεάν δοκιμή). + +Μπορείτε να εγκαταστήσετε το πακέτο με την ακόλουθη εντολή: + +```bash +dotnet add package Aspose.BarCode +``` + +Τώρα που έχουμε τη βάση, ας βουτήξουμε στην υλοποίηση. + +## Βήμα 1: Αρχικοποίηση του BarcodeGenerator για Macro PDF417 + +Το πρώτο που χρειαζόμαστε είναι μια παρουσία `BarcodeGenerator` ρυθμισμένη για **Macro PDF417**. Αυτό ενημερώνει το Aspose.BarCode ποιος αλγόριθμος κωδικοποίησης θα χρησιμοποιηθεί και μας δίνει χώρο για το κείμενο που διαβάζεται από άνθρωπο. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Γιατί είναι σημαντικό:** `EncodeTypes.MacroPdf417` ενεργοποιεί τη διευρυμένη λειτουργία PDF417 που υποστηρίζει μεταδεδομένα όπως IDs αρχείων και αριθμούς τμημάτων. Το δείγμα κειμένου περιέχει χαρακτήρες Unicode (`Å`, `ó`, `©`) για να αποδείξει ότι ο γεννήτορας διαχειρίζεται σωστά μη‑ASCII είσοδο. + +## Βήμα 2: Ορισμός Βασικής Εμφάνισης του Barcode + +Πριν αρχίσουμε να προσθέτουμε μεταδεδομένα, πρέπει να ορίσουμε μερικές οπτικές παραμέτρους ώστε το barcode να μην είναι μικροσκοπικό. Η `XDimension` ελέγχει το πλάτος του μονάδας, ενώ η `Columns` επηρεάζει το συνολικό σχήμα. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Pro tip:** Ένα πλάτος pixel `2` λειτουργεί καλά για οθόνες και τους περισσότερους εκτυπωτές. Αν χρειάζεστε εκτύπωση υψηλότερης ανάλυσης, αυξήστε το σε `3` ή `4`. + +## Βήμα 3: Συμπλήρωση Πεδίων Μεταδεδομένων Macro PDF417 + +Τώρα έρχεται η καρδιά του tutorial—η προσθήκη **πεδίων μεταδεδομένων barcode**. Κάθε ιδιότητα αντιστοιχεί άμεσα σε ένα τμήμα της προδιαγραφής Macro PDF417. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Τι Κάνει Κάθε Ιδιότητα + +| Ιδιότητα | Σκοπός | Τυπική Τιμή | +|----------|--------|------------| +| **MacroPdf417FileID** | Παγκοσμίως μοναδικό αναγνωριστικό για ολόκληρο το σύνολο αρχείων. | `12345678` | +| **MacroPdf417SegmentID** | Δείκτης του τρέχοντος τμήματος (ξεκινά από `0`). | `12` | +| **MacroPdf417SegmentsCount** | Συνολικός αριθμός τμημάτων που αναμένονται για το αρχείο. | `20` | +| **MacroPdf417FileName** | Ανθρώπινα αναγνώσιμο όνομα, συχνά το αρχικό όνομα αρχείου. | `"file01"` | +| **MacroPdf417Checksum** | 16‑bit CCITT checksum για ανίχνευση σφαλμάτων. | `1234` | +| **MacroPdf417FileSize** | Μέγεθος του αρχικού αρχείου σε bytes. | `400000` | +| **MacroPdf417TimeStamp** | Ημερομηνία δημιουργίας του αρχείου. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Προαιρετικό πεδίο που υποδεικνύει τον προορισμό. | `"street"` | +| **MacroPdf417Sender** | Προαιρετικό πεδίο που υποδεικνύει το σύστημα προέλευσης. | `"aspose"` | +| **MacroPdf417Terminator** | Σημαία που λέει στον σαρωτή ότι αυτό είναι το τελικό τμήμα. | `Pdf417MacroTerminator.Set` | + +> **Γιατί τα χρειάζεστε:** Οι σαρωτές που καταλαβαίνουν Macro PDF417 μπορούν να επανασυνθέσουν ένα πολυ‑τμηματικό αρχείο, να επαληθεύσουν την ακεραιότητα με το checksum και ακόμη να απορρίψουν παλαιά δεδομένα βάσει της χρονικής σφραγίδας. Αυτό εξαλείφει την ανάγκη ξεχωριστού αρχείου manifest. + +## Βήμα 4: Αποθήκευση της Εικόνας Barcode + +Μόλις οριστούν όλες οι παράμετροι, απλώς καλούμε το `Save`. Το παράδειγμα γράφει ένα αρχείο PNG σε φάκελο που θα ορίσετε. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Edge case:** Αν σκοπεύετε να ενσωματώσετε το barcode σε PDF αργότερα, ίσως προτιμήσετε `BarCodeImageFormat.Jpeg` ή `Pdf`. Το PNG διατηρεί τις λεπτομέρειες χωρίς απώλειες, κάτι χρήσιμο για επαλήθευση. + +## Πλήρες Παράδειγμα Εργασίας + +Συνδυάζοντας τα παραπάνω, εδώ είναι το πλήρες πρόγραμμα που μπορείτε να αντιγράψετε‑επικολλήσετε σε μια εφαρμογή console: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Αναμενόμενο Αποτέλεσμα + +Η εκτέλεση του προγράμματος δημιουργεί ένα αρχείο με όνομα **ExtPDF417Meta.png** στον φάκελο της εκτελέσιμης εφαρμογής. Ανοίξτε το με οποιονδήποτε προβολέα εικόνων και θα δείτε ένα πυκνό, υψηλής αντίθεσης barcode PDF417. Αν το σαρώσετε με έναν αναγνώστη που υποστηρίζει Macro PDF417, ο σαρωτής θα επιστρέψει τις τιμές μεταδεδομένων που ορίσαμε—file ID `12345678`, segment `12` από `20`, κ.λπ. + +## Συχνές Ερωτήσεις & Πιθανά Προβλήματα + +- **Τι γίνεται αν το barcode είναι θολό;** Αυξήστε το `XDimension.Pixels` ή αλλάξτε σε μορφή εικόνας υψηλότερης ανάλυσης. +- **Πρέπει να ορίσω κάθε πεδίο μεταδεδομένων;** Όχι. Μόνο τα πεδία που απαιτούνται από το σύστημα προορισμού είναι υποχρεωτικά. Τα μη χρησιμοποιημένα πεδία μπορούν να μείνουν στις προεπιλογές τους. +- **Μπορώ να δημιουργήσω αυτόματα ένα πολυ‑τμηματικό αρχείο;** Ναι—επαναλάβετε τη διαδικασία, αυξήστε το `MacroPdf417SegmentID` και δημιουργήστε ξεχωριστό barcode για κάθε τμήμα. Φροντίστε το `MacroPdf417FileID` να παραμένει ίδιο σε όλα τα τμήματα. +- **Υποστηρίζεται το Unicode;** Απόλυτα. Το δείγμα κειμένου περιέχει `Å`, `ó` και `©`, δείχνοντας ότι το Aspose.BarCode διαχειρίζεται UTF‑8 εξ ορισμού. + +## Επόμενα Βήματα: Πέρα από τα Βασικά + +Τώρα που ξέρετε πώς να **δημιουργήσετε μεταδεδομένα barcode PDF417**, μπορείτε να εξερευνήσετε: + +- **Ενσωμάτωση barcode σε PDF** χρησιμοποιώντας `Aspose.Pdf` για ολοκληρωμένη δημιουργία εγγράφων. +- **Ανάγνωση μεταδεδομένων** με `BarcodeReader` για προγραμματιστική επαλήθευση σκαναρισμάτων. +- **Προσαρμογή χρωμάτων** (προσκηνίου/προσκηνίου) για σκοπούς branding. +- **Σύνδεση με βάση δεδομένων** για αυτόματη συμπλήρωση πεδίων όπως `FileID` ή `Timestamp`. + +Όλα αυτά τα θέματα συνδέονται με τις δευτερεύουσες λέξεις‑κλειδιά—**macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, και **c# barcode generation**—οπότε θα βρείτε άφθονο υλικό για να συνεχίσετε την εκμάθηση. + +## Συμπέρασμα + +Διασχίσαμε ένα πλήρες, έτοιμο για παραγωγή παράδειγμα για το πώς να **δημιουργήσετε μεταδεδομένα barcode PDF417** σε C#. Από την εγκατάσταση του Aspose.BarCode, την αρχικοποίηση ενός `BarcodeGenerator`, τη συμπλήρωση κάθε σχετικού **πεδίου μεταδεδομένων barcode**, μέχρι την αποθήκευση μιας καθαρής PNG, η διαδικασία είναι απλή μόλις γνωρίζετε τις σωστές ιδιότητες. + +Δοκιμάστε το, τροποποιήστε τις τιμές και δείτε πώς αντιδρούν οι σαρωτές. Η ευελιξία του Macro PDF417 σημαίνει ότι μπορείτε να ενσωματώσετε όλα όσα χρειάζεται ένα downstream σύστημα—μέσα σε μια μόνο, σκαναρίσιμη εικόνα. Καλό coding και εύχομαι τα barcodes σας να είναι πάντα χωρίς σφάλματα! + +## Τι Θα Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να κυριαρχήσετε επιπλέον δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στα δικά σας έργα. + +- [Πώς να Δημιουργήσετε Barcode – Compact PDF417 με Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java barcode library – Προσθήκη barcode σε PDF χρησιμοποιώντας Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/greek/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..e449bf8cf --- /dev/null +++ b/barcode/greek/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: Δημιουργήστε γρήγορα γραμμωτό κώδικα PDF417 και μάθετε πώς να ορίσετε + στήλες για μια συμπαγή εικόνα γραμμωτού κώδικα PDF417 σε C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: el +lastmod: 2026-07-15 +og_description: Δημιουργήστε γραμμωτό κώδικα PDF417 με το Aspose.BarCode και μάθετε + πώς να ορίζετε στήλες για να δημιουργήσετε μια συμπαγή εικόνα γραμμωτού κώδικα PDF417. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: Δημιουργία Barcode PDF417 σε C# – Οδηγός βήμα‑προς‑βήμα +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: Δημιουργία γραμμωτού κώδικα PDF417 σε C# – Πλήρης οδηγός +url: /el/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία PDF417 Barcode σε C# – Πλήρης Οδηγός + +Έχετε ποτέ χρειαστεί να **δημιουργήσετε PDF417 barcode** σε ένα .NET project αλλά δεν ήξερες από πού να ξεκινήσεις; Δεν είστε μόνοι. Σε πολλές επιχειρησιακές εφαρμογές—σκεφτείτε εκτυπωτές boarding‑pass, ετικέτες αποθέματος ή mobile‑ticketing—το PDF417 είναι ο βασικός μηχανισμός που συμπιέζει πολλά δεδομένα σε μικρό οπτικό αποτύπωμα. + +Το θέμα είναι: η βιβλιοθήκη Aspose.BarCode κάνει όλη τη διαδικασία σχεδόν αβλαβή, και μπορείτε ακόμη να ελέγξετε **πώς να ορίσετε στήλες** ώστε το barcode να γίνει όσο το δυνατόν πιο συμπαγές. Στο τέλος αυτού του οδηγού θα έχετε μια έτοιμη για χρήση εικόνα PNG ενός **PDF417 barcode image** που μπορείτε να ενσωματώσετε σε οποιοδήποτε UI, email ή εργασία εκτύπωσης. + +## Τι Θα Κερδίσετε + +- Μια πλήρως λειτουργική εφαρμογή C# console που δημιουργεί ένα PDF417 barcode. +- Καθαρή κατανόηση του *X‑Dimension* (μέγεθος μονάδας) και γιατί είναι σημαντικό. +- Οδηγίες βήμα‑βήμα για **πώς να ορίσετε στήλες** για ένα πιο συμπαγές barcode. +- Ένα αποθηκευμένο αρχείο `PNG` που μπορείτε να ανοίξετε αμέσως για να επαληθεύσετε το αποτέλεσμα. +- Συμβουλές για την αντιμετώπιση κοινών προβλημάτων (π.χ., μη αναγνώσιμα barcodes, λάθος μορφή εικόνας). + +> **Προαπαιτούμενα** – .NET 6+ SDK, Visual Studio 2022 (ή οποιονδήποτε επεξεργαστή προτιμάτε), και μια αναφορά NuGet στο `Aspose.BarCode`. Τίποτα άλλο. + +--- + +## Βήμα 1: Εγκατάσταση του πακέτου NuGet Aspose.BarCode + +Πριν μπορέσουμε να *δημιουργήσουμε PDF417 barcode*, η βιβλιοθήκη πρέπει να είναι παρούσα στο project. + +```bash +dotnet add package Aspose.BarCode +``` + +Αυτή η εντολή φέρνει όλα τα τύπους που θα χρειαστείτε, συμπεριλαμβανομένων των `BarcodeGenerator`, `EncodeTypes` και του enum `BarCodeImageFormat`. + +> **Συμβουλή επαγγελματία:** Αν στοχεύετε .NET Framework αντί για .NET 6, χρησιμοποιήστε την κλασική εντολή PowerShell `Install-Package Aspose.BarCode` μέσα στην Package Manager Console. + +--- + +## Βήμα 2: Δημιουργία μιας Ελάχιστης Εφαρμογής Console + +Ας δημιουργήσουμε ένα μικρό πρόγραμμα που δεν κάνει τίποτα εκτός από την παραγωγή ενός barcode. Ανοίξτε ένα νέο φάκελο, εκτελέστε `dotnet new console`, και στη συνέχεια αντικαταστήστε το αυτόματα παραγόμενο `Program.cs` με τον κώδικα παρακάτω. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Why this matters:** +- `EncodeTypes.Pdf417` λέει στη βιβλιοθήκη ότι θέλουμε ένα PDF417 barcode, όχι QR ή Code128. +- `XDimension.Pixels` ελέγχει την ανάλυση κάθε μικρής μαύρης ή λευκής μονάδας. +- Το τμήμα **πώς να ορίσετε στήλες** επηρεάζει άμεσα το σχήμα του **PDF417 barcode image**. +- `Truncate = true` αφαιρεί τυχόν περιττές κενές γραμμές, δίνοντάς σας την «συμπαγή» εμφάνιση που αγαπούν πολλοί σαρωτές. + +--- + +## Βήμα 3: Βυθιστείτε Πιο Βαθιά – Κατανόηση Στηλών και Truncation + +### Πώς να Ορίσετε Στήλες + +Το PDF417 οργανώνει τα δεδομένα σε έναν πίνακα *γραμμών* × *στηλών*. Η βιβλιοθήκη προεπιλογή είναι 5 στήλες, που λειτουργεί στις περισσότερες περιπτώσεις. Ωστόσο, μπορεί να χρειαστείτε ένα πιο στενό barcode για να χωρέσει σε ετικέτα ή ένα πιο φαρδύ για να βελτιώσετε την αξιοπιστία σάρωσης. Η ιδιότητα: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +δέχεται τιμές από **1** έως **30** (το ακριβές όριο εξαρτάται από το μήκος των δεδομένων). Εδώ είναι ένας γρήγορος οδηγός: + +| Στήλες | Προσεγγ. Πλάτος (mm) | Πότε να Χρησιμοποιηθεί | +|--------|----------------------|--------------------------| +| 1‑3 | Πολύ στενό | Μικρή ετικέτα, περιορισμένος χώρος | +| 4‑6 | Κανονικό | Τα περισσότερα αποδείξεις, εισιτήρια | +| 7‑10 | Πιο φαρδύ | Δεδομένα υψηλής πυκνότητας, καλύτερη αναγνωσιμότητα | + +### Truncate (Λειτουργία Συμπαγούς) + +Ορίζοντας `Truncate = true` λέει στον κωδικοποιητή να κόψει τυχόν περιττές κενές γραμμές στο κάτω μέρος. Το αποτέλεσμα είναι μια **συμπαγής PDF417 barcode image** που καταλαμβάνει το μικρότερο δυνατό χώρο ενώ εξακολουθεί να περιέχει όλα τα δεδομένα. Αν ποτέ λάβετε σφάλματα «barcode πολύ μεγάλο για την ετικέτα», αλλάξτε αυτή τη σημαία. + +--- + +## Βήμα 4: Εκτέλεση της Εφαρμογής και Επαλήθευση του Αποτελέσματος + +Compile and execute: + +```bash +dotnet run +``` + +Θα πρέπει να δείτε το μήνυμα της κονσόλας που επιβεβαιώνει τη θέση αποθήκευσης. Μεταβείτε στο φάκελο και ανοίξτε το `CompactPdf417.png`. Η εικόνα θα μοιάζει κάπως έτσι: + +![Δημιουργημένη εικόνα PDF417 barcode](./CompactPdf417.png "Δημιουργημένη εικόνα PDF417 barcode – συμπαγής PNG δημιουργημένος από το Aspose.BarCode") + +*Κείμενο alt εικόνας:* **Δημιουργημένη εικόνα PDF417 barcode** – ένα συμπαγές αρχείο PNG που δημιουργήθηκε από τον κώδικα του tutorial. + +Αν ο σαρωτής σας μπορεί να το διαβάσει, συγχαρητήρια—έχετε δημιουργήσει επιτυχώς **PDF417 barcode** και έχετε κατακτήσει **πώς να ορίσετε στήλες** για μια τακτοποιημένη **PDF417 barcode image**. + +--- + +## Βήμα 5: Συνηθισμένα Προβλήματα & Πώς να τα Διορθώσετε + +| Συμπτωμα | Πιθανή Αιτία | Γρήγορη Διόρθωση | +|----------|--------------|-------------------| +| Το barcode εμφανίζεται θολό | `XDimension.Pixels` πολύ χαμηλό (π.χ., 1) | Αυξήστε σε 2‑3 pixels για πιο καθαρή εικόνα. | +| Ο σαρωτής δεν μπορεί να διαβάσει | Πάρα πολλές στήλες για τα δεδομένα | Μειώστε τις `Columns` ή ενεργοποιήστε το `Truncate`. | +| Λάθος μορφή αρχείου | Αποθηκεύτηκε κατά λάθος με `BarCodeImageFormat.Jpeg` | Χρησιμοποιήστε `BarCodeImageFormat.Png` για αποτελέσματα χωρίς απώλειες. | +| Εξαίρεση `ArgumentOutOfRangeException` | Ο αριθμός στηλών υπερβαίνει το επιτρεπόμενο εύρος | Κρατήστε τις στήλες μεταξύ 1‑30 και βεβαιωθείτε ότι τα δεδομένα χωρούν. | + +--- + +## Βήμα 6: Προχωρώντας Περαιτέρω – Προσαρμογή Χρωμάτων και Προσθήκη Κειμένου + +Αν θέλετε το barcode να ταιριάζει με την παλέτα της μάρκας, μπορείτε να ρυθμίσετε τα χρώματα προσκηνίου και φόντου: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Ή να προσθέσετε κείμενο αναγνώσιμο από άνθρωπο κάτω από το barcode: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Αυτές οι προσθήκες είναι προαιρετικές, αλλά δείχνουν πόσο ευέλικτη μπορεί να είναι η ροή εργασίας **δημιουργίας PDF417 barcode**. + +--- + +## Συμπέρασμα + +Διασχίσαμε ένα πλήρες, από‑αρχή‑μέχρι‑τέλος παράδειγμα που **δημιουργεί PDF417 barcode** χρησιμοποιώντας το Aspose.BarCode, εξηγήσαμε **πώς να ορίσετε στήλες** για να ελέγξετε τις διαστάσεις του barcode, και αποθηκεύσαμε το αποτέλεσμα ως καθαρή **PDF417 barcode image** σε μορφή PNG. Ο κώδικας είναι αυτόνομος, λειτουργεί με .NET 6+, και μπορεί να ενσωματωθεί σε οποιοδήποτε υπάρχον project με ελάχιστη προσπάθεια. + +Τι ακολουθεί; Δοκιμάστε την κωδικοποίηση μεγαλύτερων φορτίων (π.χ., JSON payloads), πειραματιστείτε με διαφορετικές μορφές εικόνας, ή ενσωματώστε τον δημιουργό σε ένα web API που παρέχει barcodes κατ' απαίτηση. Ο ουρανός είναι το όριο, και τώρα έχετε μια σταθερή βάση για να χτίσετε. + +Καλό προγραμματισμό, και εύχομαι τα barcodes σας πάντα να σαρώνουν με την πρώτη προσπάθεια! + +## Τι Θα Πρέπει Να Μάθετε Στη Σύντομη Μελλοντική + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας projects. + +- [Πώς να Δημιουργήσετε Barcode – Compact PDF417 με Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Πώς να Δημιουργήσετε Εικόνα Barcode σε Java με Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Δημιουργία Barcode Java – Ορισμός Ανάλυσης Εικόνας με Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/greek/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..92ff412b1 --- /dev/null +++ b/barcode/greek/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,200 @@ +--- +category: general +date: 2026-07-15 +description: Δημιουργήστε γρήγορα γραμμωτό κώδικα PDF417 με C#. Μάθετε πώς να δημιουργείτε + γραμμωτό κώδικα από κείμενο, να ρυθμίζετε το μέγεθός του και να ορίζετε προσαρμοσμένες + διαστάσεις του γραμμωτού κώδικα σε λίγα λεπτά. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: el +lastmod: 2026-07-15 +og_description: Δημιουργήστε αμέσως barcode PDF417 σε C#. Αυτός ο οδηγός δείχνει πώς + να δημιουργήσετε barcode από κείμενο, να προσαρμόσετε το μέγεθος του barcode και + να εφαρμόσετε προσαρμοσμένες διαστάσεις barcode. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Δημιουργία γραμμωτού κώδικα PDF417 σε C# – Πλήρης οδηγός προγραμματισμού +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Δημιουργία γραμμικού κώδικα PDF417 σε C# – Πλήρης οδηγός βήμα‑βήμα +url: /el/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-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** αλλά δεν ήσασταν σίγουροι ποιες ρυθμίσεις να προσαρμόσετε; Δεν είστε μόνοι—πολλοί προγραμματιστές αντιμετωπίζουν το ίδιο πρόβλημα όταν αρχίζουν να δουλεύουν με 2‑D barcodes. Τα καλά νέα; Με λίγες γραμμές C# μπορείτε να μετατρέψετε οποιαδήποτε συμβολοσειρά σε μια σαρωτή PDF417 εικόνα, να ελέγξετε το ακριβές της μέγεθος και ακόμη να ορίσετε μια προσαρμοσμένη διάταξη στήλης‑γραμμής. + +Σε αυτό το tutorial θα δούμε πώς να **δημιουργήσετε barcode από κείμενο**, να προσαρμόσετε το μέγεθος του barcode και να ορίσετε προσαρμοσμένες διαστάσεις barcode — όλα χρησιμοποιώντας τη δημοφιλή βιβλιοθήκη Aspose.BarCode. Στο τέλος θα έχετε ένα έτοιμο δείγμα που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο .NET. + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## Τι Θα Δημιουργήσετε + +- Ένα PDF417 barcode που κωδικοποιεί τη συμβολοσειρά `Åspóse.Barcóde©`. +- Ακριβή έλεγχο της X‑διάστασης (πλάτος σε pixel κάθε μονάδας). +- Προσαρμοσμένη διάταξη 4 στηλών και 9 γραμμών. +- Ένα αρχείο PNG αποθηκευμένο στο δίσκο. + +Χωρίς εξωτερικές υπηρεσίες, χωρίς μαγικά κόλπα—απλώς καθαρός κώδικας C# που μπορείτε να μεταγλωττίσετε αμέσως. + +## Προαπαιτούμενα + +- .NET 6.0 ή νεότερο (ο κώδικας λειτουργεί επίσης σε .NET Framework 4.8). +- Visual Studio 2022 ή οποιοδήποτε IDE που υποστηρίζει C#. +- Aspose.BarCode για .NET (δωρεάν δοκιμή ή έκδοση με άδεια). Εγκατάσταση μέσω NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +Αυτό είναι—μόλις γίνει η αναφορά στο πακέτο, είστε έτοιμοι να ξεκινήσετε. + +## Βήμα 1 – Δημιουργία PDF417 Barcode με Δεδομένα Κειμένου + +Το πρώτο που χρειαζόμαστε είναι μια παρουσία του `BarcodeGenerator` που γνωρίζει ότι δουλεύουμε με τη συμβολική PDF417 και το ακριβές κείμενο που θέλουμε να κωδικοποιήσουμε. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Γιατί είναι σημαντικό:** +> `EncodeTypes.Pdf417` λέει στη βιβλιοθήκη να χρησιμοποιήσει τη μορφή PDF417 2‑D, ενώ το δεύτερο όρισμα είναι το payload **generate barcode from text**. Οτιδήποτε περάσετε εδώ γίνεται τα δεδομένα που αποθηκεύονται στο matrix του barcode. + +## Βήμα 2 – Προσαρμογή Μεγέθους Barcode (X‑Διάσταση) + +Αν έχετε ποτέ εκτυπώσει ένα barcode που φαινόταν πολύ μικρό στην απόδειξη, ξέρετε την απογοήτευση όταν ο σαρωτής το παραλείπει. Η ιδιότητα `XDimension` ελέγχει το πλάτος μιας μονάδας (το μικρότερο μαύρο ή λευκό τετράγωνο) σε pixel. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Συμβουλή:** +> Μια τιμή 2 px λειτουργεί καλά για τις περισσότερες περιπτώσεις εμφάνισης στην οθόνη. Για εκτυπώσεις υψηλής ανάλυσης μπορείτε να την αυξήσετε σε 3 ή 4 px. Θυμηθείτε ότι μεγαλύτερες X‑διαστάσεις αυξάνουν το συνολικό μέγεθος της εικόνας. + +## Βήμα 3 – Ορισμός Προσαρμοσμένων Διαστάσεων Barcode (Στήλες & Γραμμές) + +Το PDF417 σας επιτρέπει να καθορίσετε πόσες στήλες και γραμμές θα καταλάβει το barcode. Εδώ έρχονται σε δράση οι **custom barcode dimensions**. Η αλλαγή αυτών των τιμών μπορεί να σας βοηθήσει να τοποθετήσετε το barcode σε περιορισμένο χώρο UI ή να ταιριάξετε ένα συγκεκριμένο μέγεθος ετικέτας. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Τι συμβαίνει στο παρασκήνιο;** +> Η βιβλιοθήκη αναδιανέμει τα κωδικοποιημένα δεδομένα στο καθορισμένο πλέγμα. Λιγότερες στήλες σημαίνουν ψηλότερα barcodes· περισσότερες γραμμές τα κάνουν πιο κοντά. Πειραματιστείτε με τους αριθμούς μέχρι η οπτική ισορροπία να φαίνεται σωστή για την εφαρμογή σας. + +## Βήμα 4 – Αποθήκευση Εικόνας Barcode + +Τώρα που έχουμε ρυθμίσει τα πάντα, απλώς ζητάμε από το generator να γράψει ένα αρχείο PNG. Το PNG είναι lossless, έτσι η ευκρίνεια των μονάδων παραμένει αμετάβλητη. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Όταν εκτελέσετε το πρόγραμμα, θα πρέπει να δείτε ένα αρχείο στο `C:\Barcodes\CustomLayout.png` που μοιάζει με το screenshot παραπάνω. Σαρώνοντάς το με οποιονδήποτε αναγνώστη συμβατό με PDF417 θα επιστρέψει την αρχική συμβολοσειρά `Åspóse.Barcóde©`. + +## Πλήρες Παράδειγμα Εργασίας + +Παρακάτω είναι το πλήρες πρόγραμμα που μπορείτε να αντιγράψετε‑επικολλήσετε σε μια εφαρμογή console. Περιλαμβάνει όλες τις οδηγίες using και τη διαχείριση σφαλμάτων που θα περιμένατε σε κώδικα παραγωγής. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Αναμενόμενη Έξοδος + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…και δημιουργεί ένα PNG που μπορεί να ανοιχτεί σε οποιονδήποτε προβολέα εικόνων. Αν το σαρώσετε με μια εφαρμογή κινητού (π.χ., “Barcode Scanner” σε iOS/Android), το αποκωδικοποιημένο κείμενο πρέπει να είναι ακριβώς **Åspóse.Barcóde©**. + +## Συχνές Ερωτήσεις & Ακραίες Περιπτώσεις + +| Question | Answer | +|----------|--------| +| **Μπορώ να χρησιμοποιήσω διαφορετική μορφή εικόνας;** | Ναι—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, ή `Svg` υποστηρίζονται όλα. Απλώς αλλάξτε το δεύτερο όρισμα της `Save`. | +| **Τι γίνεται αν το κείμενό μου περιέχει χαρακτήρες Unicode;** | Το Aspose.BarCode υποστηρίζει πλήρως UTF‑8, έτσι το παράδειγμα με `Å` και `©` λειτουργεί αμέσως. | +| **Πώς αλλάζω το επίπεδο διόρθωσης σφαλμάτων;** | Χρησιμοποιήστε `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (επίπεδα 0‑8). Τα υψηλότερα επίπεδα αυξάνουν την πλεοναστικότητα αλλά και το μέγεθος. | +| **Χρειάζομαι διαφανές φόντο—μπορώ να το κάνω;** | Ορίστε `generator.Parameters.Barcode.Image.TransparentBackground = true;` πριν από την αποθήκευση. | +| **Υπάρχει τρόπος να ενσωματώσω το barcode απευθείας σε PDF;** | Απολύτως. Αντικαταστήστε την κλήση `Save` με `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` και θα έχετε ένα PDF μιας σελίδας που περιέχει το barcode. | + +## Συμπέρασμα + +Τώρα ξέρετε πώς να **generate PDF417 barcode** σε C# από οποιαδήποτε συμβολοσειρά, **adjust barcode size**, και να εφαρμόσετε **custom barcode dimensions** για να ταιριάζουν στις ανάγκες διάταξής σας. Η ροή τεσσάρων βημάτων—αρχικοποίηση, μέγεθος, διάταξη, αποθήκευση—καλύπτει τη βασική ροή εργασίας για τις περισσότερες περιπτώσεις 2‑D barcode. + +Τι ακολουθεί; Δοκιμάστε να αντικαταστήσετε το `EncodeTypes.Pdf417` με `EncodeTypes.QR` ή `EncodeTypes.Code128` για να δείτε πώς προσαρμόζεται το API. Πειραματιστείτε με διαφορετικές τιμές `XDimension`, παίξτε με το πλέγμα στήλης/γραμμής, ή ενσωματώστε την εικόνα σε μια αναφορά PDF. Οι δυνατότητες είναι πρακτικά ατελείωτες, και τώρα έχετε μια ισχυρή βάση για να χτίσετε. + +Έχετε περισσότερες ερωτήσεις ή ανακαλύψατε ένα έξυπνο κόλπο ενώ παίζατε με το PDF417; Αφήστε ένα σχόλιο παρακάτω—ας συνεχίσουμε τη συζήτηση. Καλό κώδικα! + +## Τι Θα Μάθετε Στη Σύντομη Μελλοντική Περίοδο; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να δημιουργήσετε Aztec barcode με προσαρμοσμένη αναλογία διαστάσεων χρησιμοποιώντας Aspose.BarCode για .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Πώς να Δημιουργήσετε Barcode - Τύποι Μονοδιάστατου Barcode](/barcode/english/net/one-dimensional-barcode-types/) +- [Δημιουργία DataMatrix Barcode – Επαγγελματικός Οδηγός με Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/greek/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..9b7a4e745 --- /dev/null +++ b/barcode/greek/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,314 @@ +--- +category: general +date: 2026-07-15 +description: Πώς να διαβάσετε το barcode PDF417 σε C# και να διαβάσετε πολλαπλά barcodes + από μια εικόνα. Μάθετε πώς να διαβάζετε εικόνα barcode σε C# με λεπτομερή κώδικα + και συμβουλές. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: el +lastmod: 2026-07-15 +og_description: Πώς να διαβάσετε τον κώδικα PDF417 σε C# γρήγορα. Αυτός ο οδηγός σας + δείχνει πώς να διαβάσετε πολλαπλούς κώδικες από μία εικόνα και να αποκωδικοποιήσετε + κάθε ιδιότητα. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Πώς να διαβάσετε PDF417 σε C# – Πλήρες παράδειγμα κώδικα & Εξήγηση +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Πώς να διαβάσετε PDF417 σε C# – Πλήρης οδηγός βήμα‑βήμα +url: /el/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να Διαβάσετε PDF417 σε C# – Πλήρης Οδηγός Βήμα‑Βήμα + +Έχετε αναρωτηθεί ποτέ **πώς να διαβάσετε PDF417** από μια εικόνα χρησιμοποιώντας C#; Δεν είστε οι μόνοι. Οι περισσότεροι προγραμματιστές συναντούν δυσκολίες όταν πρέπει να εξάγουν τα επεκταμένα πεδία Macro‑PDF417 από ένα σαρωμένο έγγραφο. Τα καλά νέα; Με λίγες μόνο γραμμές κώδικα μπορείτε να αποκωδικοποιήσετε ένα PDF417, να διαβάσετε πολλαπλά barcode στην ίδια εικόνα και να πάρετε κάθε κρυφή ιδιότητα που προσφέρει η προδιαγραφή. + +Σε αυτό το tutorial θα περάσουμε από ένα πραγματικό παράδειγμα που δείχνει **πώς να διαβάσετε PDF417**, πώς να **διαβάσετε πολλαπλά barcode** από ένα μόνο αρχείο, και γιατί ο κώδικας **read barcode image C#** φαίνεται όπως είναι. Στο τέλος θα έχετε μια έτοιμη για εκτέλεση εφαρμογή console που εκτυπώνει κάθε πληροφορία που μπορεί να χρειαστείτε — ID αρχείου, ID τμήματος, checksum, χρονικές σφραγίδες, ό,τι θέλετε. + +## Προαπαιτούμενα + +* .NET 6.0 SDK ή νεότερο (ο κώδικας λειτουργεί επίσης με .NET Core και .NET Framework). +* Visual Studio 2022 (ή οποιονδήποτε επεξεργαστή προτιμάτε). +* Το πακέτο NuGet **Aspose.BarCode for .NET** – αυτή είναι η βιβλιοθήκη που πραγματικά αναλύει PDF417. +* Μια δείγμα εικόνας που περιέχει ένα Macro‑PDF417 barcode (π.χ. `ExtPDF417Meta.png`). + +Δεν απαιτείται πρόσθετη διαμόρφωση· η βιβλιοθήκη περιλαμβάνει όλους τους αποκωδικοποιητές που χρειάζεστε. + +## Βήμα 1: Εγκατάσταση Aspose.BarCode + +Ανοίξτε το φάκελο του έργου σας σε ένα τερματικό και εκτελέστε: + +```bash +dotnet add package Aspose.BarCode +``` + +Αυτή η εντολή κατεβάζει την πιο πρόσφατη σταθερή έκδοση (ως Ιούλιο 2026 είναι η 23.12). Αν προτιμάτε την Package Manager Console μέσα στο Visual Studio, χρησιμοποιήστε: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Συμβουλή:** κλειδώστε την έκδοση (`23.12.0`) στο `.csproj` σας για να αποφύγετε τυχαίες αλλαγές που θα σπάσουν τη λειτουργία αργότερα. + +## Βήμα 2: Δημιουργία Σκελετού Εφαρμογής Console + +Δημιουργήστε ένα νέο έργο console αν δεν έχετε ήδη ένα: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Αντικαταστήστε το αυτόματα δημιουργημένο `Program.cs` με τον κώδικα παρακάτω. Θα εξηγήσουμε κάθε τμήμα στις επόμενες ενότητες. + +## Βήμα 3: Γράψτε τον Πλήρη Κώδικα “Πώς να Διαβάσετε PDF417” + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Γιατί Λειτουργεί Αυτός ο Κώδικας + +* **`BarCodeReader`** είναι η κεντρική κλάση που διαβάζει την εικόνα, ανιχνεύει barcode και επιστρέφει μια συλλογή αντικειμένων `BarCodeResult`. +* Η μεταβίβαση του **`DecodeType.MacroPdf417`** λέει στη βιβλιοθήκη να αντιμετωπίζει ειδικά το Macro‑PDF417· εξακολουθεί να επιστρέφει απλά σύμβολα PDF417, το οποίο ικανοποιεί την απαίτηση **read multiple barcodes**. +* Το αντικείμενο **`Extended.Pdf417.MacroPdf417`** περιέχει κάθε προαιρετικό πεδίο που ορίζεται από το πρότυπο ISO/IEC 15438 – εκεί παίρνετε `FileID`, `SegmentID`, `Checksum`, κλπ. +* Το μπλοκ `using` εγγυάται ότι οι εγγενείς πόροι απελευθερώνονται, αποτρέποντας διαρροές μνήμης σε υπηρεσίες που τρέχουν για μεγάλο χρονικό διάστημα. + +## Βήμα 4: Εκτέλεση της Εφαρμογής και Επαλήθευση του Αποτελέσματος + +Από το τερματικό: + +```bash +dotnet run +``` + +Θα πρέπει να δείτε κάτι όπως: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Αν η εικόνα περιέχει περισσότερα από ένα barcode, ο βρόχος θα εκτυπώσει μια γραμμή διαχωριστή (`----------------------------------------`) και θα συνεχίσει με το επόμενο αποτέλεσμα — ακριβώς όπως φαίνεται η λειτουργία **read multiple barcodes** στην πράξη. + +## Συχνές Ερωτήσεις & Ακραίες Περιπτώσεις + +### Τι γίνεται αν η εικόνα έχει τόσο Macro‑PDF417 όσο και κανονικά σύμβολα PDF417; + +Η ίδια κλήση `BarCodeReader` θα επιστρέψει και τα δύο. Μπορείτε να τα διακρίνετε ελέγχοντας το `result.CodeType` (`MacroPdf417` vs `Pdf417`). Οι επεκταμένες ιδιότητες θα είναι `null` για ένα απλό PDF417, έτσι ο έλεγχος `if (macro != null)` αποτρέπει ένα `NullReferenceException`. + +### Το barcode μου είναι περιστραμμένο ή παραμορφωμένο — θα λειτουργήσει ακόμα ο αναγνώστης; + +Το Aspose.BarCode περιλαμβάνει ενσωματωμένη αντιστάθμιση περιστροφής και παραμόρφωσης. Όσο το barcode είναι τουλάχιστον 30 % του πλάτους της εικόνας, ο αποκωδικοποιητής συνήθως θα πετύχει. Για ακραίες περιπτώσεις μπορείτε να ενεργοποιήσετε `reader.Options.AllowInvertedBarcodes = true;` πριν καλέσετε το `ReadBarCodes()`. + +### Πώς να διαχειριστώ μεγάλες παρτίδες εικόνων; + +Τυλίξτε τη λογική ανάγνωσης σε έναν βρόχο `foreach (var file in Directory.GetFiles(folder, "*.png"))`. Το πρότυπο `using` εξασφαλίζει ότι οι εγγενείς πόροι κάθε εικόνας απελευθερώνονται πριν την επόμενη επανάληψη, διατηρώντας τη χρήση μνήμης χαμηλή. + +## Πλήρης Λίστα Πηγαίου Κώδικα (Έτοιμη για Αντιγραφή‑Επικόλληση) + +Παρακάτω βρίσκεται ολόκληρο το πρόγραμμα σε ένα μπλοκ για γρήγορη αντιγραφή‑επικόλληση. Δεν υπάρχουν κρυφές εξαρτήσεις — μόνο το πακέτο NuGet Aspose.BarCode. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Ανακεφαλαίωση – Τι Καλύψαμε + +* **How to read PDF417** χρησιμοποιώντας Aspose.BarCode σε C#. +* Τα ακριβή βήματα για **read multiple barcodes** από μια μόνο εικόνα. +* Πώς να **read barcode image C#** και να εξάγετε κάθε πεδίο Macro‑PDF417. +* Συμβουλές για περιστροφή, επεξεργασία παρτίδων και διαχείριση ελλιπών επεκταμένων δεδομένων. + +## Επόμενα Βήματα & Σχετικά Θέματα + +* **Encode PDF417** – δημιουργήστε τα δικά σας Macro‑PDF417 barcode με το `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – χρησιμοποιώντας την ίδια κλάση `BarCodeReader`. +* **Integrate with ASP.NET Core** – εκθέστε ένα web endpoint που δέχεται μια ανεβασμένη εικόνα και επιστρέφει JSON με τα αποκωδικοποιημένα πεδία. + +Μη διστάσετε να πειραματιστείτε: αλλάξτε τη διαδρομή της εικόνας, τοποθετήστε ένα απλό PDF417 στον ίδιο φάκελο, ή τροποποιήστε τις σημαίες `DecodeType` για να δείτε πώς συμπεριφέρεται η βιβλιοθήκη. Όσο περισσότερο παίζετε, τόσο πιο άνετοι θα γίνετε με σενάρια **read barcode image C#**. + +Έχετε μια δύσκολη εικόνα που δεν αποκωδικοποιείται; Αφήστε ένα σχόλιο παρακάτω ή ανοίξτε ένα ζήτημα στο αποθετήριο GitHub του δείγματος έργου. Καλή προγραμματιστική! + +## Τι Πρέπει Να Μάθετε Στη Σύντομη Μελλοντική; + +Τα παρακάτω 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 (Αυτόματο)](/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/one-dimensional-barcode-types/_index.md b/barcode/greek/net/one-dimensional-barcode-types/_index.md index 42905c3b2..e7749d83e 100644 --- a/barcode/greek/net/one-dimensional-barcode-types/_index.md +++ b/barcode/greek/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ url: /el/net/one-dimensional-barcode-types/ Μάθετε πώς να χειρίζεστε τις εξαιρέσεις κατά τη δημιουργία μονοδιάστατων γραμμωτών κωδίκων χρησιμοποιώντας το Aspose.BarCode για .NET. Αυτός ο οδηγός βήμα προς βήμα διασφαλίζει λύσεις γραμμωτού κώδικα ανεκτικές σε σφάλματα. Ξεκινήστε τώρα! ### [Μονοδιάστατη διαμόρφωση ευρείας-στενής αναλογίας](./one-dimensional-wide-narrow-ratio-configuration/) Δημιουργήστε εύκολα προσαρμοσμένους γραμμικούς κώδικες με το Aspose.BarCode για .NET. Οδηγός βήμα προς βήμα για μονοδιάστατη διαμόρφωση ευρείας-στενής αναλογίας. +### [Δημιουργία barcode από κείμενο με Aspose.BarCode – Οδηγός C#](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Μάθετε πώς να δημιουργείτε barcode από κείμενο σε C# με το Aspose.BarCode, βήμα-βήμα οδηγός. ## συμπέρασμα @@ -89,4 +91,4 @@ url: /el/net/one-dimensional-barcode-types/ {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/greek/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..34397f33f --- /dev/null +++ b/barcode/greek/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-07-15 +description: Δημιουργήστε barcode από κείμενο χρησιμοποιώντας το Aspose.BarCode σε + C#. Μάθετε πώς να αλλάζετε τον αριθμό των στηλών, να αποθηκεύετε την εικόνα του + barcode και να δημιουργείτε γρήγορα λύσεις barcode με το Aspose. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: el +lastmod: 2026-07-15 +og_description: Δημιουργήστε barcode από κείμενο χρησιμοποιώντας το Aspose.BarCode. + Αυτός ο οδηγός δείχνει πώς να αλλάξετε τον αριθμό των στηλών, να αποθηκεύσετε την + εικόνα του barcode και να δημιουργήσετε barcode με το Aspose σε λίγες γραμμές κώδικα. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Δημιουργία γραμμωτού κώδικα από κείμενο με το Aspose.BarCode – Γρήγορη παρουσίαση + C# +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Δημιουργία γραμμωτού κώδικα από κείμενο με χρήση του Aspose.BarCode – Οδηγός + C# +url: /el/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία barcode από κείμενο χρησιμοποιώντας Aspose.BarCode – Οδηγός C# + +Η δημιουργία barcode από κείμενο χρησιμοποιώντας Aspose.BarCode είναι εκπληκτικά απλή. Σε αυτό το tutorial θα δούμε **πώς να δημιουργήσουμε barcode**, θα προσαρμόσουμε τη διάταξη των στηλών και τελικά θα **αποθηκεύσουμε την εικόνα barcode** ως αρχείο PNG. Είτε δημιουργείτε σύστημα έκδοσης εισιτηρίων, εκτυπωτή ετικετών αποθήκης, είτε απλώς πειραματίζεστε με κώδικες τύπου QR, τα παρακάτω βήματα θα σας οδηγήσουν γρήγορα. + +## Τι Θα Μάθετε + +- Δημιουργήστε ένα barcode από οποιαδήποτε Unicode συμβολοσειρά (ναι, ακόμη και το “Åspóse.Barcóde©” λειτουργεί). +- Ρυθμίστε τον **αριθμό στηλών** για MicroPdf417 ώστε να ταιριάζει σε στενές ή ευρείες ετικέτες. +- Αποθηκεύστε το αποτέλεσμα στο δίσκο με το κατάλληλο φορμά εικόνας. +- Συμβουλές για τη διαχείριση ειδικών χαρακτήρων και κοινών παγίδων όταν **δημιουργείτε barcode Aspose** λύσεις. + +Χωρίς εξωτερικά εργαλεία, χωρίς hacks γραμμής εντολών—μόνο απλό C# και τη βιβλιοθήκη Aspose.BarCode. + +## Προαπαιτούμενα + +1. **.NET 6.0** ή νεότερο εγκατεστημένο (ο κώδικας λειτουργεί επίσης σε .NET Framework 4.7+). +2. Μια **άδεια** για Aspose.BarCode, ή μπορείτε να ξεκινήσετε με τη δωρεάν έκδοση αξιολόγησης. +3. Ένας φάκελος στον οποίο μπορείτε να γράψετε – θα τον ονομάσουμε `YOUR_DIRECTORY` στα παραδείγματα. + +Αν λείπει κάποιο από αυτά, αποκτήστε το πακέτο NuGet τώρα: + +```bash +dotnet add package Aspose.BarCode +``` + +Αυτό είναι όλο—χωρίς επιπλέον DLLs για χειροκίνητη αντιγραφή. + +## Βήμα 1 – Ρύθμιση του Έργου και Εισαγωγών + +Πρώτα, δημιουργήστε μια εφαρμογή console (ή ενσωματώστε τον κώδικα σε οποιοδήποτε έργο C#). Το σημαντικό μέρος είναι η εισαγωγή των σωστών namespaces: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Γιατί αυτές οι δηλώσεις using; Το `BarcodeGenerator` βρίσκεται στο `Aspose.BarCode.Generation`, ενώ το enum `BarCodeImageFormat` βρίσκεται στο `Aspose.BarCode`. Η τακτική οργάνωση των εισαγωγών κάνει τον επόμενο κώδικα πιο κατανοητό, σαν απλά αγγλικά. + +## Βήμα 2 – Δημιουργία του Barcode Generator (πώς να δημιουργήσετε barcode) + +Τώρα πραγματικά **δημιουργούμε barcode από κείμενο**. Το enum `EncodeTypes` λέει στο Aspose ποια συμβολική γραφή να χρησιμοποιήσει· εδώ επιλέγουμε `MicroPdf417` επειδή διαχειρίζεται μεγάλες συμβολοσειρές σε ένα συμπαγές πλέγμα. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Παρατηρήστε ότι η συμβολοσειρά περιέχει τονισμένους χαρακτήρες και σύμβολο πνευματικών δικαιωμάτων. Το Aspose.BarCode κωδικοποιεί αυτόματα Unicode, οπότε δεν χρειάζεται να προεπεξεργαστείτε το κείμενο. + +## Βήμα 3 – Λεπτομερής Ρύθμιση της Εμφάνισης (πώς να αλλάξετε τον αριθμό στηλών) + +Το MicroPdf417 σας επιτρέπει να ελέγξετε τον αριθμό των στηλών, κάτι που επηρεάζει άμεσα το πλάτος του barcode. Μια πιο σφιχτή διάταξη είναι ιδανική για στενές ετικέτες· μια πιο ευρεία διάταξη βελτιώνει την αναγνωσιμότητα σε μεγάλες εκτυπώσεις. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Γιατί μονάδες 2‑pixel; Παρέχουν καθαρή εικόνα χωρίς να αυξάνουν το μέγεθος του αρχείου. Μη διστάσετε να πειραματιστείτε—τιμές μεταξύ 1 και 4 συνήθως λειτουργούν καλά. Αν χρειαστείτε διαφορετικό αριθμό στηλών, απλώς αλλάξτε την ιδιότητα `Columns`; το Aspose θα επαναϋπολογίσει αυτόματα τη διάταξη. + +## Βήμα 4 – Αποθήκευση της Εικόνας Barcode (αποθήκευση barcode εικόνας) + +Με τον γεννήτρια ρυθμισμένο, είμαστε έτοιμοι να **αποθηκεύσουμε την εικόνα barcode**. Η μέθοδος `Save` δέχεται διαδρομή αρχείου και enum μορφής εικόνας. Το PNG είναι χωρίς απώλειες, έτσι το barcode παραμένει καθαρό ακόμη και μετά την κλιμάκωση. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Συμβουλή: χρησιμοποιείτε πάντα απόλυτη διαδρομή ή βεβαιωθείτε ότι ο τρέχων φάκελος είναι αυτός που περιμένετε· διαφορετικά το αρχείο μπορεί να καταλήξει στον φάκελο bin και θα αναρωτηθείτε γιατί δεν το βρίσκετε. + +## Πλήρες Παράδειγμα Λειτουργίας + +Συνδυάζοντας όλα, εδώ είναι ένα αυτόνομο πρόγραμμα που μπορείτε να αντιγράψετε‑επικολλήσετε στο `Program.cs` και να εκτελέσετε: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Αναμενόμενη έξοδος** (console): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +Και αν ανοίξετε το `MicroPdf417.png`, θα δείτε ένα καθαρό barcode MicroPdf417 που κωδικοποιεί την αρχική συμβολοσειρά, συμπεριλαμβανομένων των ειδικών χαρακτήρων που του δώσαμε. + +## Συχνές Ερωτήσεις & Ακραίες Περιπτώσεις + +### Τι γίνεται αν το κείμενό μου είναι μεγαλύτερο από την προεπιλεγμένη χωρητικότητα; + +Το MicroPdf417 αλλάζει αυτόματα σε διάταξη πολλαπλών γραμμών όταν τα δεδομένα υπερβούν το μέγιστο ανά γραμμή. Μπορείτε ακόμη να ελέγξετε τον αριθμό των στηλών, αλλά η βιβλιοθήκη μπορεί να προσθέσει επιπλέον γραμμές στο παρασκήνιο. Δεν απαιτείται επιπλέον κώδικας—απλώς παρακολουθήστε τις διαστάσεις της παραγόμενης εικόνας. + +### Πώς αλλάζω τη μορφή εικόνας σε JPEG ή BMP; + +Αντικαταστήστε το `BarCodeImageFormat.Png` με `BarCodeImageFormat.Jpeg` (ή `Bmp`). Θυμηθείτε ότι το JPEG εισάγει συμπιεστικά artefacts, που μπορούν να επηρεάσουν την αξιοπιστία σάρωσης. Το PNG είναι η πιο ασφαλής προεπιλογή. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Βλέπω υδατογράφημα στην έξοδο—τι συμβαίνει; + +Αυτό είναι η έκδοση αξιολόγησης του Aspose.BarCode. Για να **δημιουργήσετε barcode Aspose** χωρίς υδατογράφημα, φορτώστε ένα έγκυρο αρχείο άδειας όπως φαίνεται στη σχολιασμένη γραμμή του Βήματος 2. + +### Μπορώ να δημιουργήσω άλλες συμβολικές γραφές (QR, Code128, κ.λπ.;) + +Απολύτως. Απλώς αντικαταστήστε το `EncodeTypes.MicroPdf417` με οποιαδήποτε άλλη τιμή του enum `EncodeTypes`, π.χ., `EncodeTypes.QR` ή `EncodeTypes.Code128`. Το υπόλοιπο του κώδικα παραμένει το ίδιο, καθιστώντας την προσέγγιση ιδιαίτερα επαναχρησιμοποιήσιμη. + +## Επαγγελματικές Συμβουλές για Παραγωγική Δημιουργία Barcode + +- **Κάντε cache τον generator** αν δημιουργείτε πολλά barcodes με τις ίδιες ρυθμίσεις· μειώνει το κόστος δημιουργίας αντικειμένων. +- **Επικυρώστε τη συμβολοσειρά εισόδου** για περιορισμούς μήκους ειδικούς για την επιλεγμένη συμβολική γραφή (το Aspose ρίχνει `ArgumentException` αν είναι πολύ μεγάλη). +- **Χρησιμοποιήστε δηλώσεις `using`** ή `Dispose` τον generator όταν τελειώσετε για να ελευθερώσετε άμεσα τους εγγενείς πόρους. +- **Ορίστε DPI** μέσω `generator.Parameters.ImageResolution.DpiX/DpiY` αν χρειάζεστε εκτυπώσεις υψηλής ανάλυσης για μεγάλες ετικέτες. + +## Συμπέρασμα + +Τώρα γνωρίζετε ακριβώς **πώς να δημιουργήσετε barcode από κείμενο** με Aspose.BarCode, πώς να **αλλάξετε τον αριθμό στηλών**, και τον σωστό τρόπο για **να αποθηκεύσετε την εικόνα barcode** ως PNG. Το πλήρες, εκτελέσιμο παράδειγμα παραπάνω δείχνει μια καθαρή, παραγωγική λύση + +## Τι Θα Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Generate barcode image – Code 93 with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/hindi/net/compact-pdf417-encoding/_index.md index 7df391155..e32b44936 100644 --- a/barcode/hindi/net/compact-pdf417-encoding/_index.md +++ b/barcode/hindi/net/compact-pdf417-encoding/_index.md @@ -84,7 +84,13 @@ Aspose.BarCode आपको `Pdf417ErrorCorrectionLevel` प्रॉपर् ## Compact PDF417 एन्कोडिंग ट्यूटोरियल्स ### [Compact PDF417 बारकोड बनाना](./compact-pdf417-basic-configuration/) -Aspose.BarCode for .NET का उपयोग करके Compact PDF417 बारकोड कैसे जनरेट करें सीखें। चरण‑दर‑चरण निर्देशों और कोड उदाहरणों के साथ व्यापक गाइड। +### [C# में PDF417 बारकोड मेटाडेटा बनाना – पूर्ण चरण‑दर‑चरण गाइड](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) + +### [C# में PDF417 बारकोड बनाना – पूर्ण गाइड](./generate-pdf417-barcode-in-c-complete-guide/) + +### [C# में PDF417 बारकोड बनाना – पूर्ण चरण‑दर‑चरण गाइड](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) + +### [C# में PDF417 पढ़ना – पूर्ण चरण‑दर‑चरण गाइड](./how-to-read-pdf417-in-c-complete-step-by-step-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/hindi/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/hindi/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..1d155a570 --- /dev/null +++ b/barcode/hindi/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-07-15 +description: Aspose.BarCode का उपयोग करके C# में PDF417 बारकोड मेटाडेटा बनाएं। मैक्रो + PDF417 सेटिंग्स सीखें, PNG के रूप में सहेजें, और यूनिकोड टेक्स्ट को संभालें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: hi +lastmod: 2026-07-15 +og_description: Aspose.BarCode के साथ C# में PDF417 बारकोड मेटाडेटा बनाएं। यह गाइड + दिखाता है कि फ़ाइल‑आईडी, टाइमस्टैम्प और अधिक एम्बेड करने के लिए आपको कौन‑सी सेटिंग्स + चाहिए। +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: C# में PDF417 बारकोड मेटाडेटा बनाएं – पूर्ण प्रोग्रामिंग मार्गदर्शन +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: C# में PDF417 बारकोड मेटाडाटा बनाएं – पूर्ण चरण‑दर‑चरण गाइड +url: /hi/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में PDF417 बारकोड मेटाडेटा बनाएं – पूर्ण चरण‑दर‑चरण गाइड + +क्या आपको **C# में PDF417 बारकोड मेटाडेटा** बनाना था लेकिन कौन‑सी प्रॉपर्टी बदलनी है, यह नहीं पता था? आप अकेले नहीं हैं—डेवलपर्स अक्सर फ़ाइल आईडी, सेगमेंट काउंट या कस्टम टाइमस्टैम्प जैसी चीज़ों की ज़रूरत पड़ने पर अटक जाते हैं। + +अच्छी खबर यह है कि Aspose.BarCode इसे बहुत आसान बना देता है। इस ट्यूटोरियल में हम **Macro PDF417** के लिए एक `BarcodeGenerator` बनाएँगे, सभी महत्वपूर्ण मेटाडेटा जोड़ेंगे, और परिणाम को PNG इमेज के रूप में सेव करेंगे। अंत में आपके पास कोई भी सप्लाई‑चेन या डॉक्यूमेंट‑मैनेजमेंट सिस्टम के लिये तैयार एक पूर्ण‑फ़ीचर वाला बारकोड होगा। + +## इस गाइड में क्या कवर किया गया है + +हम निम्नलिखित चरणों से गुजरेंगे: + +1. Aspose.BarCode NuGet पैकेज को सेट‑अप करना। +2. **Macro PDF417** के लिये `BarcodeGenerator` को इनिशियलाइज़ करना। +3. हर उपयोगी **बारकोड मेटाडेटा फ़ील्ड** (फ़ाइल आईडी, सेगमेंट आईडी, चेकसम आदि) को भरना। +4. बारकोड को डिस्क पर सेव करना और आउटपुट की पुष्टि करना। + +Macro PDF417 का कोई पूर्व अनुभव आवश्यक नहीं—सिर्फ बेसिक C# ज्ञान और एक हालिया .NET रनटाइम चाहिए। + +क्यों महत्वपूर्ण है? बारकोड में सीधे रिच मेटाडेटा एम्बेड करने से डाउनस्ट्रीम स्कैनर पूरे फ़ाइल ट्रांसफ़र को वैलिडेट कर सकते हैं, मिसिंग सेगमेंट का पता लगा सकते हैं, या ऑटोमेटेड वर्कफ़्लो ट्रिगर कर सकते हैं। दूसरे शब्दों में, आपको **मज़बूत, सेल्फ‑डिस्क्राइबिंग डेटा** मिलता है बिना किसी अलग डेटाबेस लुक‑अप के। + +## प्री‑रिक्विज़िट्स + +- .NET 6.0 या बाद का (कोड .NET Framework 4.7+ पर भी काम करता है)। +- Visual Studio 2022 (या आपका पसंदीदा IDE)। +- **Aspose.BarCode for .NET** NuGet पैकेज (फ़्री ट्रायल उपलब्ध)। + +पैकेज को नीचे दिए गए कमांड से इंस्टॉल कर सकते हैं: + +```bash +dotnet add package Aspose.BarCode +``` + +अब बुनियादी सेट‑अप हो गया, चलिए असली इम्प्लीमेंटेशन की ओर बढ़ते हैं। + +## चरण 1: Macro PDF417 के लिये BarcodeGenerator इनिशियलाइज़ करें + +सबसे पहले हमें **Macro PDF417** के लिये कॉन्फ़िगर किया गया `BarcodeGenerator` इंस्टेंस चाहिए। यह Aspose.BarCode को बताता है कि कौन‑सा एन्कोडिंग एल्गोरिद्म इस्तेमाल करना है और हमें ह्यूमन‑रीडेबल टेक्स्ट फीड करने की जगह देता है। + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **क्यों जरूरी है:** `EncodeTypes.MacroPdf417` विस्तारित PDF417 मोड को एक्टिवेट करता है जो फ़ाइल आईडी और सेगमेंट नंबर जैसी मेटाडेटा को सपोर्ट करता है। सैंपल टेक्स्ट में यूनिकोड कैरेक्टर (`Å`, `ó`, `©`) शामिल हैं ताकि यह दिखाया जा सके कि जेनरेटर नॉन‑ASCII इनपुट को सहजता से हैंडल करता है। + +## चरण 2: बेसिक बारकोड अपीयरेंस सेट करें + +मेटाडेटा जोड़ने से पहले हमें कुछ विज़ुअल पैरामीटर सेट करने चाहिए ताकि बारकोड माइक्रोस्कोपिक न लगे। `XDimension` मॉड्यूल की चौड़ाई नियंत्रित करता है, जबकि `Columns` समग्र आकार को प्रभावित करता है। + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **प्रो टिप:** `2` पिक्सेल की चौड़ाई स्क्रीन डिस्प्ले और अधिकांश प्रिंटरों के लिये उपयुक्त रहती है। अगर आपको हाई‑रेज़ोल्यूशन प्रिंट चाहिए तो इसे `3` या `4` कर दें। + +## चरण 3: Macro PDF417 मेटाडेटा फ़ील्ड्स भरें + +अब ट्यूटोरियल का मुख्य भाग—**बारकोड मेटाडेटा फ़ील्ड्स** जोड़ना। प्रत्येक प्रॉपर्टी सीधे Macro PDF417 स्पेसिफिकेशन के एक सेगमेंट से मैप होती है। + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### प्रत्येक प्रॉपर्टी क्या करती है + +| प्रॉपर्टी | उद्देश्य | सामान्य मान | +|----------|----------|-------------| +| **MacroPdf417FileID** | पूरी फ़ाइल सेट के लिये ग्लोबली यूनिक आइडेंटिफ़ायर। | `12345678` | +| **MacroPdf417SegmentID** | वर्तमान सेगमेंट का इंडेक्स (शुरू `0` से)। | `12` | +| **MacroPdf417SegmentsCount** | फ़ाइल के लिये अपेक्षित कुल सेगमेंट। | `20` | +| **MacroPdf417FileName** | ह्यूमन‑रीडेबल नाम, अक्सर मूल फ़ाइलनाम। | `"file01"` | +| **MacroPdf417Checksum** | एरर डिटेक्शन के लिये 16‑बिट CCITT चेकसम। | `1234` | +| **MacroPdf417FileSize** | मूल फ़ाइल का आकार बाइट्स में। | `400000` | +| **MacroPdf417TimeStamp** | फ़ाइल कब जेनरेट हुई। | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | वैकल्पिक फ़ील्ड जो डेस्टिनेशन दर्शाता है। | `"street"` | +| **MacroPdf417Sender** | वैकल्पिक फ़ील्ड जो सोर्स सिस्टम दर्शाता है। | `"aspose"` | +| **MacroPdf417Terminator** | फ़्लैग जो स्कैनर को बताता है कि यह अंतिम सेगमेंट है। | `Pdf417MacroTerminator.Set` | + +> **इनकी ज़रूरत क्यों है:** Macro PDF417 समझने वाले स्कैनर मल्टी‑सेगमेंट फ़ाइल को पुनः असेंबल कर सकते हैं, चेकसम से इंटीग्रिटी वेरिफ़ाई कर सकते हैं, और टाइमस्टैम्प के आधार पर पुराना डेटा रिजेक्ट कर सकते हैं। इससे अलग मैनिफेस्ट फ़ाइल की ज़रूरत नहीं रहती। + +## चरण 4: बारकोड इमेज को सेव करें + +सभी पैरामीटर सेट हो जाने के बाद, बस `Save` कॉल करें। उदाहरण में PNG फ़ाइल को आप द्वारा निर्दिष्ट फ़ोल्डर में लिखा जाता है। + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **एज केस:** अगर बाद में आप बारकोड को PDF में एम्बेड करना चाहते हैं, तो `BarCodeImageFormat.Jpeg` या `Pdf` चुन सकते हैं। PNG लॉसलेस डिटेल रखता है, जो वेरिफ़िकेशन के लिये उपयोगी है। + +## पूरा कार्यशील उदाहरण + +सब कुछ मिलाकर, यहाँ पूरा प्रोग्राम है जिसे आप कॉन्सोल ऐप में कॉपी‑पेस्ट कर सकते हैं: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### अपेक्षित आउटपुट + +प्रोग्राम चलाने पर **ExtPDF417Meta.png** नाम की फ़ाइल एक्सिक्यूटेबल फ़ोल्डर में बनती है। इसे किसी भी इमेज व्यूअर से खोलें और आपको एक घना, हाई‑कॉंट्रास्ट PDF417 बारकोड दिखेगा। अगर आप इसे Macro PDF417 सपोर्ट करने वाले बारकोड रीडर से स्कैन करेंगे, तो रीडर सेट किए गए मेटाडेटा वैल्यूज़ लौटाएगा—फ़ाइल आईडी `12345678`, सेगमेंट `12` ऑफ़ `20`, आदि। + +## सामान्य प्रश्न और पिटफ़ॉल्स + +- **बारकोड धुंधला दिख रहा है तो क्या करें?** `XDimension.Pixels` बढ़ाएँ या हाई‑रेज़ोल्यूशन इमेज फ़ॉर्मेट इस्तेमाल करें। +- **क्या सभी मेटाडेटा फ़ील्ड्स सेट करनी ज़रूरी हैं?** नहीं। केवल वही फ़ील्ड्स सेट करें जो आपके डाउनस्ट्रीम सिस्टम को चाहिए। अनयूज़्ड फ़ील्ड्स डिफ़ॉल्ट पर रह सकते हैं। +- **क्या मैं मल्टी‑सेगमेंट फ़ाइल ऑटोमैटिक जेनरेट कर सकता हूँ?** हाँ—डेटा पर लूप चलाएँ, `MacroPdf417SegmentID` को इन्क्रीमेंट करें, और प्रत्येक सेगमेंट के लिये अलग बारकोड बनाएँ। सभी सेगमेंट में `MacroPdf417FileID` समान रखें। +- **क्या यूनिकोड सपोर्टेड है?** बिलकुल। सैंपल टेक्स्ट में `Å`, `ó`, और `©` हैं, जो दिखाते हैं कि Aspose.BarCode आउट‑ऑफ़‑द‑बॉक्स UTF‑8 को हैंडल करता है। + +## अगले कदम: बेसिक से आगे + +अब जब आप **PDF417 बारकोड मेटाडेटा** बनाना जानते हैं, तो आप आगे देख सकते हैं: + +- `Aspose.Pdf` का उपयोग करके **PDF में बारकोड एम्बेड** करना, ताकि एंड‑टू‑एंड डॉक्यूमेंट जेनरेशन हो सके। +- `BarcodeReader` से **मेटाडेटा पढ़ना** और स्कैन वैलिडेशन प्रोग्रामेटिकली करना। +- ब्रांडिंग के लिये **कलर्स कस्टमाइज़** करना (फ़ोरग्राउंड/बैकग्राउंड)। +- डेटाबेस के साथ **इंटीग्रेशन** करके `FileID` या `Timestamp` जैसे फ़ील्ड्स ऑटो‑पॉप्युलेट करना। + +इन सभी टॉपिक्स हमारे सेकेंडरी कीवर्ड्स—**macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, और **c# barcode generation**—से जुड़े हैं, इसलिए सीखने के लिये पर्याप्त सामग्री उपलब्ध होगी। + +## निष्कर्ष + +हमने C# में **PDF417 बारकोड मेटाडेटा** बनाने का एक पूर्ण, प्रोडक्शन‑रेडी उदाहरण पूरा किया। Aspose.BarCode को इंस्टॉल करने, `BarcodeGenerator` इनिशियलाइज़ करने, सभी प्रासंगिक **बारकोड मेटाडेटा फ़ील्ड्स** भरने, और अंत में एक क्रिस्प PNG सेव करने की प्रक्रिया को समझ लिया। + +इसे आज़माएँ, वैल्यूज़ बदलें, और देखें स्कैनर कैसे प्रतिक्रिया देता है। Macro PDF417 की लचीलापन आपको एक ही स्कैन करने योग्य इमेज में सभी आवश्यक जानकारी एम्बेड करने की सुविधा देता है। कोडिंग का आनंद लें, और आपके बारकोड हमेशा एरर‑फ्री रहें! + +## आगे क्या सीखें? + +नीचे दिए गए ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक में पूरी कोड उदाहरण और चरण‑दर‑चरण व्याख्या है, जिससे आप अतिरिक्त API फीचर्स को मास्टर कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोचेज़ को एक्सप्लोर कर सकें। + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java barcode library – Add barcode to PDF using Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/hindi/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..1d35d12fd --- /dev/null +++ b/barcode/hindi/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-07-15 +description: PDF417 बारकोड जल्दी बनाएं और C# में कॉम्पैक्ट PDF417 बारकोड इमेज के लिए + कॉलम सेट करना सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: hi +lastmod: 2026-07-15 +og_description: Aspose.BarCode के साथ PDF417 बारकोड जेनरेट करें और कॉलम सेट करके एक + कॉम्पैक्ट PDF417 बारकोड इमेज बनाना सीखें। +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: C# में PDF417 बारकोड बनाएं – चरण-दर-चरण गाइड +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: C# में PDF417 बारकोड जनरेट करें – पूर्ण गाइड +url: /hi/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में PDF417 बारकोड जनरेट करें – पूर्ण गाइड + +क्या आपको कभी .NET प्रोजेक्ट में **PDF417 बारकोड जनरेट** करने की ज़रूरत पड़ी है लेकिन आप नहीं जानते थे कि कहाँ से शुरू करें? आप अकेले नहीं हैं। कई एंटरप्राइज़ ऐप्स—जैसे बोर्डिंग‑पास प्रिंटर, इन्वेंटरी टैग, या मोबाइल‑टिकटिंग—में PDF417 वह काम करने वाला है जो बहुत सारा डेटा छोटे विज़ुअल फुटप्रिंट में पैक करता है। + +बात यह है: Aspose.BarCode लाइब्रेरी पूरी प्रक्रिया को लगभग बिना किसी परेशानी के बना देती है, और आप **how to set columns** को भी नियंत्रित कर सकते हैं ताकि बारकोड यथासंभव कॉम्पैक्ट हो सके। इस ट्यूटोरियल के अंत तक आपके पास एक तैयार‑टू‑यूज़ PNG इमेज होगी **PDF417 barcode image** की, जिसे आप किसी भी UI, ईमेल, या प्रिंट जॉब में डाल सकते हैं। + +## आप क्या सीखेंगे + +- एक पूरी तरह कार्यात्मक C# कंसोल ऐप जो PDF417 बारकोड बनाता है। +- *X‑Dimension* (मॉड्यूल आकार) की स्पष्ट समझ और इसका महत्व। +- **how to set columns** के लिए चरण‑दर‑चरण निर्देश, जिससे बारकोड अधिक टाइट हो। +- एक सेव किया गया `PNG` फ़ाइल जिसे आप तुरंत खोल कर परिणाम की जाँच कर सकते हैं। +- सामान्य समस्याओं (जैसे, अपठनीय बारकोड, गलत इमेज फॉर्मेट) को हल करने के टिप्स। + +> **Prerequisites** – .NET 6+ SDK, Visual Studio 2022 (या कोई भी एडिटर जो आपको पसंद हो), और `Aspose.BarCode` का NuGet रेफ़रेंस। और कुछ नहीं। + +--- + +## चरण 1: Aspose.BarCode NuGet पैकेज इंस्टॉल करें + +PDF417 बारकोड *जनरेट* करने से पहले, लाइब्रेरी को प्रोजेक्ट में मौजूद होना चाहिए। + +```bash +dotnet add package Aspose.BarCode +``` + +यह एकल लाइन सभी आवश्यक टाइप्स को लाती है, जिसमें `BarcodeGenerator`, `EncodeTypes`, और `BarCodeImageFormat` एनम शामिल हैं। + +> **Pro tip:** यदि आप .NET 6 के बजाय .NET Framework को टार्गेट कर रहे हैं, तो पैकेज मैनेजर कंसोल के अंदर क्लासिक `Install-Package Aspose.BarCode` PowerShell कमांड का उपयोग करें। + +--- + +## चरण 2: एक न्यूनतम कंसोल एप्लिकेशन बनाएं + +आइए एक छोटा प्रोग्राम बनाते हैं जो केवल बारकोड उत्पन्न करता है। एक नया फ़ोल्डर खोलें, `dotnet new console` चलाएँ, फिर ऑटो‑जनरेटेड `Program.cs` को नीचे दिए गए कोड से बदल दें। + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**यह क्यों महत्वपूर्ण है:** +- `EncodeTypes.Pdf417` लाइब्रेरी को बताता है कि हमें PDF417 बारकोड चाहिए, न कि QR या Code128। +- `XDimension.Pixels` प्रत्येक छोटे काले या सफेद मॉड्यूल की रिज़ॉल्यूशन को नियंत्रित करता है। +- **how to set columns** ब्लॉक सीधे **PDF417 barcode image** के आकार को प्रभावित करता है। +- `Truncate = true` किसी भी अनावश्यक खाली पंक्तियों को हटा देता है, जिससे आपको वह “कॉम्पैक्ट” लुक मिलता है जिसे कई स्कैनर पसंद करते हैं। + +--- + +## चरण 3: गहराई से देखें – कॉलम्स और ट्रंकेशन को समझना + +### कॉलम्स कैसे सेट करें + +PDF417 डेटा को *rows* × *columns* की मैट्रिक्स में व्यवस्थित करता है। लाइब्रेरी डिफ़ॉल्ट रूप से 5 कॉलम उपयोग करती है, जो अधिकांश मामलों में काम करता है। हालांकि, आपको लेबल में फिट होने के लिए एक संकरी बारकोड या स्कैन विश्वसनीयता बढ़ाने के लिए एक चौड़ी बारकोड की आवश्यकता हो सकती है। यह प्रॉपर्टी: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +**1** से **30** तक मान स्वीकार करती है (सटीक सीमा डेटा की लंबाई पर निर्भर करती है)। यहाँ एक त्वरित चीट शीट है: + +| कॉलम्स | लगभग चौड़ाई (mm) | कब उपयोग करें | +|---------|-------------------|-----------------| +| 1‑3 | बहुत संकरी | छोटा लेबल, सीमित जगह | +| 4‑6 | मानक | अधिकांश रसीदें, टिकट | +| 7‑10 | चौड़ा | हाई‑डेंसिटी डेटा, बेहतर पठनीयता | + +### ट्रंकेट (कॉम्पैक्ट मोड) + +`Truncate = true` सेट करने से एन्कोडर को नीचे की किसी भी अनावश्यक खाली पंक्तियों को काटने के लिए कहा जाता है। परिणामस्वरूप एक **compact PDF417 barcode image** मिलता है जो सबसे छोटा संभव क्षेत्र घेरता है जबकि सभी डेटा को रखता है। यदि आपको “barcode too big for label” जैसी त्रुटियाँ मिलती हैं, तो इस फ़्लैग को टॉगल करें। + +--- + +## चरण 4: ऐप चलाएँ और आउटपुट सत्यापित करें + +```bash +dotnet run +``` + +आपको कंसोल में एक संदेश दिखना चाहिए जो सहेजने का स्थान पुष्टि करता है। फ़ोल्डर में जाएँ और `CompactPdf417.png` खोलें। इमेज कुछ इस प्रकार दिखेगी: + +![जनरेट किया गया PDF417 बारकोड इमेज](./CompactPdf417.png "जनरेट किया गया PDF417 बारकोड इमेज – Aspose.BarCode द्वारा निर्मित कॉम्पैक्ट PNG") + +*इमेज वैकल्पिक टेक्स्ट:* **जनरेट किया गया PDF417 बारकोड इमेज** – ट्यूटोरियल कोड द्वारा निर्मित एक कॉम्पैक्ट PNG फ़ाइल। + +यदि आपका स्कैनर इसे पढ़ सकता है, तो बधाई—आपने सफलतापूर्वक **PDF417 बारकोड जनरेट** किया है और एक साफ़ **PDF417 barcode image** के लिए **how to set columns** में महारत हासिल की है। + +--- + +## चरण 5: सामान्य समस्याएँ और उन्हें कैसे ठीक करें + +| लक्षण | संभावित कारण | त्वरित समाधान | +|---------|--------------|-----------| +| बारकोड धुंधला दिखता है | `XDimension.Pixels` बहुत कम (जैसे, 1) | स्पष्ट इमेज के लिए 2‑3 पिक्सेल बढ़ाएँ। | +| स्कैनर पढ़ नहीं सकता | दिए गए डेटा के लिए बहुत अधिक कॉलम | `Columns` कम करें या `Truncate` सक्षम करें। | +| गलत फ़ाइल फ़ॉर्मेट | `BarCodeImageFormat.Jpeg` से गलती से सेव किया गया | `BarCodeImageFormat.Png` का उपयोग करें ताकि लॉसलेस परिणाम मिलें। | +| Exception `ArgumentOutOfRangeException` | कॉलम संख्या अनुमत सीमा से अधिक है | कॉलम को 1‑30 के बीच रखें और सुनिश्चित करें कि डेटा फिट हो। | + +--- + +## चरण 6: आगे बढ़ना – रंगों को कस्टमाइज़ करना और टेक्स्ट जोड़ना + +यदि आप बारकोड को ब्रांड पैलेट से मिलाना चाहते हैं, तो आप फ़ोरग्राउंड और बैकग्राउंड रंगों को समायोजित कर सकते हैं: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +या बारकोड के नीचे मानव‑पठनीय टेक्स्ट ओवरले करें: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +ये जोड़ वैकल्पिक हैं, लेकिन वे दर्शाते हैं कि **PDF417 बारकोड जनरेट** वर्कफ़्लो कितना लचीला हो सकता है। + +--- + +## निष्कर्ष + +हमने एक पूर्ण, एंड‑टू‑एंड उदाहरण के माध्यम से चलकर दिखाया है कि Aspose.BarCode का उपयोग करके **PDF417 बारकोड जनरेट** किया जाए, **how to set columns** को समझाया गया है ताकि बारकोड के आयाम नियंत्रित हों, और परिणाम को PNG फ़ॉर्मेट में एक स्पष्ट **PDF417 बारकोड इमेज** के रूप में सहेजा गया है। कोड स्वयं‑समाहित है, .NET 6+ के साथ काम करता है, और न्यूनतम प्रयास के साथ किसी भी मौजूदा प्रोजेक्ट में डाला जा सकता है। + +आगे क्या? बड़े पेलोड (जैसे, JSON पेलोड) एन्कोड करने की कोशिश करें, विभिन्न इमेज फ़ॉर्मेट्स के साथ प्रयोग करें, या जेनरेटर को एक वेब API में इंटीग्रेट करें जो मांग पर बारकोड सर्व करता है। संभावनाएँ असीमित हैं, और आपके पास अब निर्माण के लिए एक ठोस आधार है। + +कोडिंग का आनंद लें, और आपके बारकोड हमेशा पहली कोशिश में ही स्कैन हों! + +## अगला आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन निकट-संबंधित विषयों को कवर करते हैं जो इस गाइड में प्रदर्शित तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोच को एक्सप्लोर करने में मदद करेंगे। + +- [कैसे बनाएं बारकोड – कॉम्पैक्ट PDF417 Aspose.BarCode के साथ](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [कैसे जनरेट करें बारकोड इमेज जावा में Aspose.BarCode के साथ](/barcode/english/java/barcode-rendering-techniques/) +- [बारकोड जावा जनरेट करें – इमेज रिज़ॉल्यूशन सेट करें Aspose.BarCode के साथ](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/hindi/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..e9511eb0b --- /dev/null +++ b/barcode/hindi/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,199 @@ +--- +category: general +date: 2026-07-15 +description: C# के साथ PDF417 बारकोड जल्दी बनाएं। टेक्स्ट से बारकोड बनाना, बारकोड + का आकार समायोजित करना, और मिनटों में कस्टम बारकोड आयाम सेट करना सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: hi +lastmod: 2026-07-15 +og_description: C# में तुरंत PDF417 बारकोड जेनरेट करें। यह गाइड दिखाता है कि टेक्स्ट + से बारकोड कैसे बनाएं, बारकोड का आकार कैसे समायोजित करें, और कस्टम बारकोड आयाम कैसे + लागू करें। +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: C# में PDF417 बारकोड जनरेट करें – पूर्ण प्रोग्रामिंग ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: C# में PDF417 बारकोड जनरेट करें – पूर्ण चरण‑दर‑चरण गाइड +url: /hi/net/compact-pdf417-encoding/generate-pdf417-barcode-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# में PDF417 बारकोड उत्पन्न करें – पूर्ण चरण‑दर‑चरण गाइड + +क्या आपको कभी **PDF417 बारकोड उत्पन्न** करने की ज़रूरत पड़ी है लेकिन सेटिंग्स को कैसे बदलें, यह नहीं पता था? आप अकेले नहीं हैं—कई डेवलपर्स को 2‑D बारकोड के साथ पहली बार काम करते समय यही समस्या आती है। अच्छी खबर? कुछ ही पंक्तियों के C# कोड से आप किसी भी स्ट्रिंग को स्कैन करने योग्य PDF417 इमेज में बदल सकते हैं, उसका सटीक आकार नियंत्रित कर सकते हैं, और यहाँ तक कि कस्टम कॉलम‑रो लेआउट भी निर्धारित कर सकते हैं। + +इस ट्यूटोरियल में हम **टेक्स्ट से बारकोड उत्पन्न** करने, बारकोड का आकार समायोजित करने, और कस्टम बारकोड आयाम सेट करने की प्रक्रिया को लोकप्रिय Aspose.BarCode लाइब्रेरी का उपयोग करके देखेंगे। अंत तक आपके पास एक तैयार‑से‑चलाने वाला सैंपल होगा जिसे आप किसी भी .NET प्रोजेक्ट में डाल सकते हैं। + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## आप क्या बनाएँगे + +- एक PDF417 बारकोड जो स्ट्रिंग `Åspóse.Barcóde©` को एन्कोड करता है। +- X‑डायमेंशन (प्रत्येक मॉड्यूल की पिक्सेल चौड़ाई) पर सटीक नियंत्रण। +- 4 कॉलम और 9 रो का कस्टम लेआउट। +- डिस्क पर सहेजी गई PNG फ़ाइल। + +कोई बाहरी सेवाएँ नहीं, कोई जादू‑छड़ी ट्रिक्स नहीं—सिर्फ साधारण C# कोड जिसे आप अभी कंपाइल कर सकते हैं। + +## आवश्यकताएँ + +- .NET 6.0 या बाद का (कोड .NET Framework 4.8 पर भी काम करता है)। +- Visual Studio 2022 या कोई भी IDE जो C# को सपोर्ट करता हो। +- Aspose.BarCode for .NET (फ्री ट्रायल या लाइसेंस्ड संस्करण)। NuGet के माध्यम से इंस्टॉल करें: + +```bash +dotnet add package Aspose.BarCode +``` + +बस इतना ही—एक बार पैकेज रेफ़रेंस हो जाने पर आप तैयार हैं। + +## चरण 1 – टेक्स्ट डेटा के साथ PDF417 बारकोड उत्पन्न करें + +सबसे पहले हमें `BarcodeGenerator` का एक इंस्टेंस चाहिए जो यह जानता हो कि हम PDF417 सिंबोलॉजी का उपयोग कर रहे हैं और वह ठीक वही टेक्स्ट जिसे हम एन्कोड करना चाहते हैं। + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Why this matters:** +> `EncodeTypes.Pdf417` लाइब्रेरी को PDF417 2‑D फ़ॉर्मेट उपयोग करने के लिए बताता है, जबकि दूसरा आर्ग्यूमेंट **generate barcode from text** पेलोड है। यहाँ पास किया गया कोई भी डेटा बारकोड मैट्रिक्स में संग्रहीत हो जाता है। + +## चरण 2 – बारकोड आकार समायोजित करें (X‑Dimension) + +यदि आपने कभी रसीद पर बहुत छोटा दिखने वाला बारकोड प्रिंट किया है, तो आप जानते हैं कि स्कैनर उसे मिस कर देता है। `XDimension` प्रॉपर्टी एकल मॉड्यूल (सबसे छोटा काला या सफ़ेद वर्ग) की चौड़ाई पिक्सेल में नियंत्रित करती है। + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Pro tip:** +> 2 px का मान अधिकांश स्क्रीन‑डिस्प्ले पर अच्छा काम करता है। हाई‑रिज़ॉल्यूशन प्रिंट्स के लिए आप इसे 3 या 4 px तक बढ़ा सकते हैं। बस याद रखें कि बड़े X‑डायमेंशन से इमेज का कुल आकार बढ़ जाता है। + +## चरण 3 – कस्टम बारकोड आयाम सेट करें (कॉलम और रो) + +PDF417 आपको यह निर्धारित करने की अनुमति देता है कि बारकोड कितने कॉलम और रो लेगा। यही वह जगह है जहाँ **custom barcode dimensions** काम आते हैं। इन मानों को बदलने से आप बारकोड को टाइट UI स्पेस में फिट कर सकते हैं या किसी विशेष लेबल साइज को पूरा कर सकते हैं। + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **What’s happening under the hood?** +> लाइब्रेरी निर्दिष्ट ग्रिड में एन्कोडेड डेटा को पुनः वितरित करती है। कम कॉलम का मतलब ऊँचा बारकोड, अधिक रो का मतलब छोटा बारकोड। अपने एप्लिकेशन के लिए विज़ुअल बैलेंस सही लगने तक संख्याओं के साथ प्रयोग करें। + +## चरण 4 – बारकोड इमेज सहेजें + +अब जब हमने सब कुछ कॉन्फ़िगर कर लिया है, तो हम बस जेनरेटर को PNG फ़ाइल लिखने के लिए कहते हैं। PNG लॉसलेस है, इसलिए मॉड्यूल की स्पष्टता बनी रहती है। + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +जब आप प्रोग्राम चलाएँगे, तो आपको `C:\Barcodes\CustomLayout.png` पर एक फ़ाइल दिखनी चाहिए जो ऊपर की स्क्रीनशॉट के समान होगी। इसे किसी भी PDF417‑कम्पैटिबल रीडर से स्कैन करने पर मूल स्ट्रिंग `Åspóse.Barcóde©` वापस मिलेगी। + +## पूर्ण कार्यशील उदाहरण + +नीचे पूरा प्रोग्राम दिया गया है जिसे आप कॉन्सोल ऐप में कॉपी‑पेस्ट कर सकते हैं। इसमें सभी `using` निर्देश और प्रोडक्शन कोड में अपेक्षित एरर हैंडलिंग शामिल है। + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### अपेक्षित आउटपुट + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…और एक PNG बनाता है जिसे कोई भी इमेज व्यूअर खोल सकता है। यदि आप इसे मोबाइल ऐप (जैसे iOS/Android पर “Barcode Scanner”) से स्कैन करते हैं, तो डिकोडेड टेक्स्ट बिल्कुल **Åspóse.Barcóde©** होना चाहिए। + +## सामान्य प्रश्न और किनारे के मामले + +| Question | Answer | +|----------|--------| +| **Can I use a different image format?** | Yes—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, or `Svg` are all supported. Just change the second argument of `Save`. | +| **What if my text contains Unicode characters?** | Aspose.BarCode fully supports UTF‑8, so the example with `Å` and `©` works out‑of‑the‑box. | +| **How do I change the error‑correction level?** | Use `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (levels 0‑8). Higher levels increase redundancy but also size. | +| **I need a transparent background—can I do that?** | Set `generator.Parameters.Barcode.Image.TransparentBackground = true;` before saving. | +| **Is there a way to embed the barcode directly into a PDF?** | Absolutely. Replace the `Save` call with `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` and you’ll get a one‑page PDF containing the barcode. | + +## निष्कर्ष + +अब आप जानते हैं कि **C# में PDF417 बारकोड कैसे उत्पन्न करें**, **बारकोड आकार कैसे समायोजित करें**, और **कस्टम बारकोड आयाम** को अपने लेआउट की जरूरतों के अनुसार कैसे लागू करें। चार‑चरणीय प्रक्रिया—इनीशियलाइज़, साइज, लेआउट, सेव—अधिकांश 2‑D बारकोड परिदृश्यों के लिए कोर वर्कफ़्लो को कवर करती है। + +अब आगे क्या? `EncodeTypes.Pdf417` को `EncodeTypes.QR` या `EncodeTypes.Code128` से बदलें और देखें कि API कैसे अनुकूलित होता है। विभिन्न `XDimension` मानों के साथ प्रयोग करें, कॉलम/रो मैट्रिक्स को ट्यून करें, या इमेज को PDF रिपोर्ट में एम्बेड करें। संभावनाएँ व्यावहारिक रूप से अनंत हैं, और अब आपके पास एक ठोस नींव है जिस पर आप निर्माण कर सकते हैं। + +क्या आपके पास और प्रश्न हैं, या PDF417 के साथ काम करते हुए कोई चतुर ट्रिक मिली? नीचे कमेंट करें—आइए बातचीत जारी रखें। Happy coding! + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में प्रदर्शित तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोच को एक्सप्लोर कर सकें। + +- [Aspose.BarCode for .NET का उपयोग करके कस्टम आस्पेक्ट रेशियो के साथ Aztec बारकोड कैसे जनरेट करें](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [बारकोड कैसे जनरेट करें - एक-आयामी बारकोड प्रकार](/barcode/english/net/one-dimensional-barcode-types/) +- [DataMatrix बारकोड जनरेट करें – Aspose.BarCode के साथ प्रो गाइड](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/hindi/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..1a75b74e3 --- /dev/null +++ b/barcode/hindi/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,314 @@ +--- +category: general +date: 2026-07-15 +description: C# में PDF417 बारकोड कैसे पढ़ें और एक छवि से कई बारकोड पढ़ें। विस्तृत + कोड और टिप्स के साथ C# में बारकोड छवि पढ़ना सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: hi +lastmod: 2026-07-15 +og_description: C# में PDF417 बारकोड को जल्दी से कैसे पढ़ें। यह गाइड आपको दिखाता है + कि एक ही छवि से कई बारकोड कैसे पढ़ें और प्रत्येक प्रॉपर्टी को डिकोड करें। +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: C# में PDF417 कैसे पढ़ें – पूर्ण कोड नमूना और व्याख्या +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: C# में PDF417 कैसे पढ़ें – पूर्ण चरण‑दर‑चरण गाइड +url: /hi/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-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 Step‑by‑Step Guide + +क्या आपने कभी **C#** का उपयोग करके इमेज से **PDF417 पढ़ने** के बारे में सोचा है? आप अकेले नहीं हैं। अधिकांश डेवलपर्स को स्कैन किए गए दस्तावेज़ से विस्तारित Macro‑PDF417 फ़ील्ड निकालते समय रुकावट आती है। अच्छी खबर? कुछ ही लाइनों के कोड से आप PDF417 डिकोड कर सकते हैं, एक ही तस्वीर में कई बारकोड पढ़ सकते हैं, और स्पेसिफिकेशन द्वारा प्रदान किए गए सभी छिपे हुए प्रॉपर्टी प्राप्त कर सकते हैं। + +इस ट्यूटोरियल में हम एक वास्तविक उदाहरण के माध्यम से दिखाएंगे कि **PDF417 कैसे पढ़ें**, एक फ़ाइल से **कई बारकोड कैसे पढ़ें**, और क्यों **read barcode image C#** कोड ऐसा दिखता है। अंत तक आपके पास एक तैयार‑चलाने‑योग्य कंसोल ऐप होगा जो सभी आवश्यक जानकारी प्रिंट करेगा—फ़ाइल ID, सेगमेंट ID, चेकसम, टाइमस्टैम्प, आदि। + +## Prerequisites + +शुरू करने से पहले सुनिश्चित करें कि आपके पास ये हैं: + +* .NET 6.0 SDK या बाद का संस्करण (कोड .NET Core और .NET Framework के साथ भी काम करता है)। +* Visual Studio 2022 (या आपका पसंदीदा कोई भी एडिटर)। +* **Aspose.BarCode for .NET** NuGet पैकेज – यही लाइब्रेरी PDF417 को पार्स करती है। +* एक सैंपल इमेज जिसमें Macro‑PDF417 बारकोड हो (उदाहरण के लिए `ExtPDF417Meta.png`)। + +कोई अतिरिक्त कॉन्फ़िगरेशन आवश्यक नहीं है; लाइब्रेरी में सभी आवश्यक डिकोडर शामिल हैं। + +## Step 1: Install Aspose.BarCode + +टर्मिनल में अपने प्रोजेक्ट फ़ोल्डर को खोलें और चलाएँ: + +```bash +dotnet add package Aspose.BarCode +``` + +यह कमांड नवीनतम स्थिर संस्करण (जुलाई 2026 तक यह 23.12 है) को डाउनलोड करता है। यदि आप Visual Studio के भीतर Package Manager Console का उपयोग करना पसंद करते हैं, तो यह चलाएँ: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Pro tip:** अपने `.csproj` में संस्करण (`23.12.0`) को लॉक कर रखें ताकि बाद में अनजाने में ब्रेकिंग बदलाव न आएँ। + +## Step 2: Create a Console App Skeleton + +यदि आपके पास अभी तक कोई कंसोल प्रोजेक्ट नहीं है, तो नया बनाएँ: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +ऑटो‑जनरेटेड `Program.cs` को नीचे दिए गए कोड से बदल दें। हम अगले सेक्शन में प्रत्येक ब्लॉक की व्याख्या करेंगे। + +## Step 3: Write the Full “How to Read PDF417” Code + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Why This Code Works + +* **`BarCodeReader`** कोर क्लास है जो इमेज को स्ट्रीम करता है, बारकोड डिटेक्ट करता है, और `BarCodeResult` ऑब्जेक्ट्स का कलेक्शन रिटर्न करता है। +* **`DecodeType.MacroPdf417`** पास करने से लाइब्रेरी Macro‑PDF417 को विशेष रूप से ट्रीट करती है; यह अभी भी साधारण PDF417 सिम्बॉल रिटर्न करती है, जिससे **read multiple barcodes** की आवश्यकता पूरी होती है। +* **`Extended.Pdf417.MacroPdf417`** ऑब्जेक्ट ISO/IEC 15438 मानक द्वारा परिभाषित सभी वैकल्पिक फ़ील्ड रखता है – यहीं से आपको `FileID`, `SegmentID`, `Checksum` आदि मिलते हैं। +* `using` ब्लॉक नेेटिव रिसोर्सेज़ को रिलीज़ करना सुनिश्चित करता है, जिससे लंबी‑चलाने वाली सर्विसेज़ में मेमोरी लीक्स नहीं होते। + +## Step 4: Run the Application and Verify Output + +टर्मिनल से चलाएँ: + +```bash +dotnet run +``` + +आपको कुछ इस तरह दिखना चाहिए: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +यदि इमेज में एक से अधिक बारकोड हैं, तो लूप एक सेपरेटर लाइन (`----------------------------------------`) प्रिंट करेगा और अगले रिज़ल्ट पर जारी रहेगा—बिल्कुल वही जो **read multiple barcodes** का व्यवहार है। + +## Common Questions & Edge Cases + +### What if the image has both Macro‑PDF417 and regular PDF417 symbols? + +उसी `BarCodeReader` कॉल से दोनों रिटर्न होंगे। आप `result.CodeType` (`MacroPdf417` बनाम `Pdf417`) चेक करके उन्हें अलग कर सकते हैं। साधारण PDF417 के लिए एक्स्टेंडेड प्रॉपर्टीज़ `null` होंगी, इसलिए `if (macro != null)` गार्ड `NullReferenceException` को रोकता है। + +### My barcode is rotated or skewed—will the reader still work? + +Aspose.BarCode में बिल्ट‑इन रोटेशन और डिस्टॉर्शन कम्पेंसेशन है। जब तक बारकोड इमेज की चौड़ाई का कम से कम 30 % हो, डिकोडर आमतौर पर सफल रहता है। अत्यधिक मामलों में आप `reader.Options.AllowInvertedBarcodes = true;` को `ReadBarCodes()` से पहले एनेबल कर सकते हैं। + +### How do I handle large batches of images? + +पढ़ने की लॉजिक को `foreach (var file in Directory.GetFiles(folder, "*.png"))` लूप में रखें। `using` पैटर्न प्रत्येक इमेज के नेेटिव रिसोर्सेज़ को अगले इटरेशन से पहले फ्री कर देता है, जिससे मेमोरी उपयोग कम रहता है। + +## Full Source Listing (Copy‑Paste Ready) + +नीचे पूरा प्रोग्राम एक ही ब्लॉक में दिया गया है, ताकि आप तुरंत कॉपी‑पेस्ट कर सकें। कोई छिपी डिपेंडेंसी नहीं—सिर्फ Aspose.BarCode NuGet पैकेज चाहिए। + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Recap – What We Covered + +* **How to read PDF417** using Aspose.BarCode in C#. +* एक ही इमेज से **multiple barcodes** पढ़ने के सटीक कदम। +* **read barcode image C#** कैसे करें और सभी Macro‑PDF417 फ़ील्ड निकालें। +* रोटेशन, बैच प्रोसेसिंग, और मिसिंग एक्स्टेंडेड डेटा को हैंडल करने के टिप्स। + +## Next Steps & Related Topics + +* **Encode PDF417** – `BarCodeBuilder` के साथ अपना खुद का Macro‑PDF417 बारकोड जेनरेट करें। +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – उसी `BarCodeReader` क्लास का उपयोग करके। +* **Integrate with ASP.NET Core** – एक वेब एंडपॉइंट बनाएं जो अपलोड की गई इमेज ले और डिकोडेड फ़ील्ड्स के साथ JSON रिटर्न करे। + +इसे आज़माएँ: इमेज पाथ बदलें, उसी फ़ोल्डर में साधारण PDF417 डालें, या `DecodeType` फ्लैग्स को टॉगल करके देखें कि लाइब्रेरी कैसे व्यवहार करती है। जितना अधिक आप प्रयोग करेंगे, उतना ही आप **read barcode image C#** परिदृश्यों में सहज महसूस करेंगे। + +कोई कठिन इमेज है जो डिकोड नहीं हो रही? नीचे कमेंट करें या सैंपल प्रोजेक्ट के GitHub रेपो में इश्यू खोलें। Happy coding! + +## What Should You Learn Next? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक रिसोर्स में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर कर सकें। + +- [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/hindi/net/one-dimensional-barcode-types/_index.md b/barcode/hindi/net/one-dimensional-barcode-types/_index.md index c02a2e3d8..9e552a7ce 100644 --- a/barcode/hindi/net/one-dimensional-barcode-types/_index.md +++ b/barcode/hindi/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ Aspose.BarCode का उपयोग करके .NET में डेटा .NET के लिए Aspose.BarCode का उपयोग करके एक-आयामी बारकोड उत्पन्न करते समय अपवादों को संभालना सीखें। यह चरण-दर-चरण मार्गदर्शिका त्रुटि-सहिष्णु बारकोड समाधान सुनिश्चित करती है। अब शुरू हो जाओ! ### [एक-आयामी चौड़ा-संकीर्ण अनुपात विन्यास](./one-dimensional-wide-narrow-ratio-configuration/) .NET के लिए Aspose.BarCode के साथ आसानी से अनुकूलित बारकोड जेनरेट करें। एक-आयामी चौड़े-संकीर्ण अनुपात कॉन्फ़िगरेशन के लिए चरण-दर-चरण मार्गदर्शिका। +### [Aspose.BarCode का उपयोग करके टेक्स्ट से बारकोड जनरेट करें – C# गाइड](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Aspose.BarCode का उपयोग करके .NET में C# के साथ टेक्स्ट से बारकोड कैसे बनाएं, चरण-दर-चरण मार्गदर्शिका। ## निष्कर्ष @@ -89,4 +91,4 @@ Aspose.BarCode का उपयोग करके .NET में डेटा {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/hindi/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..04c0b9bf4 --- /dev/null +++ b/barcode/hindi/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-07-15 +description: C# में Aspose.BarCode का उपयोग करके टेक्स्ट से बारकोड बनाएं। कॉलम काउंट + बदलना, बारकोड इमेज सहेजना और तेज़ी से बारकोड Aspose समाधान बनाना सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: hi +lastmod: 2026-07-15 +og_description: Aspose.BarCode का उपयोग करके टेक्स्ट से बारकोड जनरेट करें। यह गाइड + दिखाता है कि कॉलम काउंट कैसे बदलें, बारकोड इमेज को सहेजें, और कुछ लाइनों के कोड + में Aspose बारकोड बनाएं। +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Aspose.BarCode के साथ टेक्स्ट से बारकोड जनरेट करें – त्वरित C# वॉकथ्रू +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Aspose.BarCode का उपयोग करके टेक्स्ट से बारकोड जेनरेट करें – C# गाइड +url: /hi/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.BarCode का उपयोग करके टेक्स्ट से बारकोड जेनरेट करें – C# गाइड + +Aspose.BarCode का उपयोग करके टेक्स्ट से बारकोड जेनरेट करना आश्चर्यजनक रूप से सरल है। इस ट्यूटोरियल में हम **बारकोड कैसे जेनरेट करें** को समझेंगे, कॉलम लेआउट को समायोजित करेंगे, और अंत में **बारकोड इमेज को** PNG फ़ाइल के रूप में **सेव करेंगे**। चाहे आप टिकटिंग सिस्टम, वेयरहाउस लेबल प्रिंटर बना रहे हों, या सिर्फ QR‑स्टाइल कोड्स के साथ प्रयोग कर रहे हों, नीचे दिए गए चरण आपको जल्दी ही वहां पहुंचा देंगे। + +## आप क्या सीखेंगे + +- किसी भी Unicode स्ट्रिंग से बारकोड बनाएं (हाँ, यहाँ तक कि “Åspóse.Barcóde©” भी काम करता है)। +- **column count** को MicroPdf417 के लिए समायोजित करें ताकि संकरी या चौड़ी लेबल्स में फिट हो सके। +- उचित इमेज फ़ॉर्मेट के साथ परिणाम को डिस्क पर सहेजें। +- **create barcode Aspose** समाधान बनाते समय विशेष अक्षरों को संभालने और सामान्य समस्याओं के लिए टिप्स। + +कोई बाहरी टूल्स नहीं, कोई कमांड‑लाइन हैक्स नहीं—सिर्फ साधारण C# और Aspose.BarCode लाइब्रेरी। + +## पूर्वापेक्षाएँ + +Before we dive in, make sure you have: + +1. **.NET 6.0** या बाद का संस्करण स्थापित हो (कोड .NET Framework 4.7+ पर भी काम करता है)। +2. Aspose.BarCode के लिए **license** हो, या आप मुफ्त evaluation संस्करण से शुरू कर सकते हैं। +3. एक फ़ोल्डर जहाँ आप लिख सकें – हम इसे उदाहरणों में `YOUR_DIRECTORY` कहेंगे। + +यदि इनमें से कोई भी नहीं है, तो अभी NuGet पैकेज प्राप्त करें: + +```bash +dotnet add package Aspose.BarCode +``` + +बस इतना ही—कोई अतिरिक्त DLL मैन्युअली कॉपी करने की जरूरत नहीं। + +## चरण 1 – प्रोजेक्ट सेट अप करें और इम्पोर्ट्स + +सबसे पहले, एक कंसोल ऐप बनाएं (या कोड को किसी भी C# प्रोजेक्ट में डालें)। महत्वपूर्ण भाग सही नेमस्पेसेस को इम्पोर्ट करना है: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +इन using स्टेटमेंट्स की आवश्यकता क्यों है? `BarcodeGenerator` `Aspose.BarCode.Generation` में स्थित है, जबकि `BarCodeImageFormat` एनीम `Aspose.BarCode` में है। इम्पोर्ट्स को व्यवस्थित रखने से बाद का कोड साधारण अंग्रेज़ी की तरह पढ़ा जाता है। + +## चरण 2 – बारकोड जेनरेटर बनाएं (बारकोड कैसे जेनरेट करें) + +अब हम वास्तव में **टेक्स्ट से बारकोड जेनरेट** करते हैं। `EncodeTypes` एनीम Aspose को बताता है कि कौन सा सिम्बोलॉजी उपयोग करना है; यहाँ हम `MicroPdf417` चुनते हैं क्योंकि यह लंबी स्ट्रिंग्स को कॉम्पैक्ट ग्रिड में संभालता है। + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +ध्यान दें कि स्ट्रिंग में एक्सेंटेड कैरेक्टर्स और कॉपीराइट सिंबल है। Aspose.BarCode स्वचालित रूप से Unicode एन्कोड करता है, इसलिए आपको टेक्स्ट को पहले से प्रोसेस करने की जरूरत नहीं है। + +## चरण 3 – दिखावट को फ़ाइन‑ट्यून करें (column count कैसे बदलें) + +MicroPdf417 आपको कॉलम की संख्या नियंत्रित करने देता है, जो सीधे बारकोड की चौड़ाई को प्रभावित करता है। टाइट लेआउट संकरी लेबल्स के लिए उत्तम है; वाइड लेआउट बड़े प्रिंट्स पर पठनीयता बढ़ाता है। + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +2‑पिक्सेल मॉड्यूल क्यों? यह फ़ाइल आकार बढ़ाए बिना एक स्पष्ट इमेज देता है। प्रयोग करने में संकोच न करें—1 से 4 के बीच के मान आमतौर पर अच्छे काम करते हैं। यदि आपको कभी अलग column count चाहिए, तो बस `Columns` प्रॉपर्टी बदल दें; Aspose स्वचालित रूप से लेआउट को पुनः गणना करेगा। + +## चरण 4 – बारकोड इमेज को सेव करें (बारकोड इमेज को सेव करें) + +जेनरेटर कॉन्फ़िगर हो जाने के बाद, हम **बारकोड इमेज को सेव** करने के लिए तैयार हैं। `Save` मेथड एक फ़ाइल पाथ और इमेज फ़ॉर्मेट एनीम लेता है। PNG लॉस‑लेस है, इसलिए स्केल करने के बाद भी बारकोड तेज़ रहता है। + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +एक त्वरित टिप: हमेशा एब्सोल्यूट पाथ का उपयोग करें या सुनिश्चित करें कि कार्यशील डायरेक्टरी वही है जिसकी आप अपेक्षा करते हैं; अन्यथा फ़ाइल bin फ़ोल्डर में चली जा सकती है और आप सोचेंगे कि इसे क्यों नहीं ढूँढ़ पा रहे हैं। + +## पूर्ण कार्यशील उदाहरण + +सब कुछ मिलाकर, यहाँ एक स्व-निहित प्रोग्राम है जिसे आप `Program.cs` में कॉपी‑पेस्ट करके चला सकते हैं: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**अपेक्षित आउटपुट** (कंसोल): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +और यदि आप `MicroPdf417.png` खोलते हैं, तो आपको एक स्पष्ट MicroPdf417 बारकोड दिखेगा जो मूल स्ट्रिंग को एन्कोड करता है, जिसमें हमने जो विशेष कैरेक्टर्स डाले थे वे भी शामिल हैं। + +## सामान्य प्रश्न एवं किनारे के मामले + +### यदि मेरा टेक्स्ट डिफ़ॉल्ट क्षमता से लंबा हो तो क्या करें? + +जब डेटा प्रति पंक्ति अधिकतम से अधिक हो जाता है, तो MicroPdf417 स्वचालित रूप से मल्टी‑रो लेआउट में स्विच कर जाता है। आप अभी भी column count को नियंत्रित कर सकते हैं, लेकिन लाइब्रेरी बैकग्राउंड में अतिरिक्त पंक्तियाँ जोड़ सकती है। अतिरिक्त कोड की जरूरत नहीं—सिर्फ परिणामस्वरूप इमेज के आयामों पर नज़र रखें। + +### इमेज फ़ॉर्मेट को JPEG या BMP में कैसे बदलें? + +`BarCodeImageFormat.Png` को `BarCodeImageFormat.Jpeg` (या `Bmp`) से बदलें। याद रखें कि JPEG संपीड़न आर्टिफैक्ट्स लाता है, जो स्कैनिंग की विश्वसनीयता को प्रभावित कर सकता है। PNG सबसे सुरक्षित डिफ़ॉल्ट है। + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### आउटपुट में वॉटरमार्क दिख रहा है—क्या समस्या है? + +यह Aspose.BarCode का इवैल्यूएशन संस्करण है। वॉटरमार्क के बिना **create barcode Aspose** करने के लिए, Step 2 की टिप्पणी वाली लाइन में दिखाए अनुसार वैध लाइसेंस फ़ाइल लोड करें। + +### क्या मैं अन्य सिम्बोलॉजीज़ (QR, Code128, आदि) जेनरेट कर सकता हूँ? + +बिल्कुल। बस `EncodeTypes.MicroPdf417` को `EncodeTypes` एनीम के किसी अन्य मान से बदलें, जैसे `EncodeTypes.QR` या `EncodeTypes.Code128`। बाकी कोड वही रहता है, जिससे यह तरीका बहुत पुन: उपयोगी बन जाता है। + +## प्रोडक्शन‑रेडी बारकोड जेनरेशन के प्रो टिप्स + +- यदि आप समान सेटिंग्स के साथ कई बारकोड बना रहे हैं तो **जेनरेटर को कैश** करें; यह ऑब्जेक्ट‑क्रिएशन ओवरहेड को कम करता है। +- चुनी गई सिम्बोलॉजी के लिए लंबाई प्रतिबंधों के अनुसार **इनपुट स्ट्रिंग को वैलिडेट** करें (यदि बहुत लंबी हो तो Aspose `ArgumentException` फेंकता है)। +- पूरा होने पर **`using` स्टेटमेंट्स** का उपयोग करें या जेनरेटर को `Dispose` करें ताकि नेटिव रिसोर्सेज तुरंत मुक्त हो जाएँ। +- यदि बड़े लेबल्स के लिए हाई‑रेज़ोल्यूशन प्रिंट चाहिए तो `generator.Parameters.ImageResolution.DpiX/DpiY` के माध्यम से **DPI सेट** करें। + +## निष्कर्ष + +अब आप बिल्कुल जानते हैं कि Aspose.BarCode के साथ **टेक्स्ट से बारकोड कैसे जेनरेट करें**, **column count कैसे बदलें**, और PNG के रूप में **बारकोड इमेज को कैसे सेव करें**। ऊपर दिया गया पूर्ण, चलाने योग्य उदाहरण एक साफ़, प्रोडक्शन‑रेडी समाधान दर्शाता है + +## अब आपको आगे क्या सीखना चाहिए? + +निम्नलिखित ट्यूटोरियल्स इस गाइड में दिखाए गए तकनीकों पर आधारित निकट संबंधित विषयों को कवर करते हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ का अन्वेषण करने में मदद करेंगे। + +- [बारकोड कैसे जेनरेट करें – Aspose.BarCode के साथ Code 39 कॉन्फ़िगरेशन](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [बारकोड इमेज जेनरेट करें – Aspose.BarCode के साथ Code 93](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [Aspose.BarCode for .NET के साथ DataMatrix बारकोड (ECC 200) कैसे जेनरेट करें](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/hongkong/net/compact-pdf417-encoding/_index.md index 9254eb3ec..1f856fac5 100644 --- a/barcode/hongkong/net/compact-pdf417-encoding/_index.md +++ b/barcode/hongkong/net/compact-pdf417-encoding/_index.md @@ -82,7 +82,10 @@ Aspose.BarCode 讓你設定 `Pdf417ErrorCorrectionLevel` 屬性 (0‑8)。較高 ## 緊湊式 PDF417 編碼教學 ### [建立緊湊式 PDF417 條碼](./compact-pdf417-basic-configuration/) -了解如何使用 Aspose.BarCode for .NET 產生緊湊式 PDF417 條碼。完整指南包含一步一步說明與程式碼範例。 +### [使用 C# 建立 PDF417 條碼中繼資料 – 完整步驟指南](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +### [在 C# 中產生 PDF417 條碼 – 完整指南](./generate-pdf417-barcode-in-c-complete-guide/) +### [在 C# 中產生 PDF417 條碼 – 完整步驟指南](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +### [在 C# 中讀取 PDF417 – 完整步驟指南](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) ## 常見問題 @@ -112,4 +115,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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/hongkong/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..9089af119 --- /dev/null +++ b/barcode/hongkong/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-07-15 +description: 使用 Aspose.BarCode 在 C# 中建立 PDF417 條碼的中繼資料。了解 Macro PDF417 設定,儲存為 PNG,並處理 + Unicode 文字。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: zh-hant +lastmod: 2026-07-15 +og_description: 使用 Aspose.BarCode 在 C# 中建立 PDF417 條碼的中繼資料。本指南展示了嵌入檔案 ID、時間戳記等所有設定。 +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: 在 C# 中建立 PDF417 條碼元資料 – 完整程式教學 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: 在 C# 中建立 PDF417 條碼元資料 – 完整逐步指南 +url: /zh-hant/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中建立 PDF417 條碼 Metadata – 完整逐步指南 + +曾經需要在 C# 中 **建立 PDF417 條碼 metadata**,卻不確定要調整哪些屬性嗎?你並非唯一遇到這種情況的人——開發者常在規格要求檔案 ID、段落數量或自訂時間戳記時卡住。 + +好消息是 Aspose.BarCode 讓這件事變得輕而易舉。在本教學中,我們會建立一個用於 **Macro PDF417** 的 `BarcodeGenerator`,加入所有重要的 metadata,並將結果儲存為 PNG 圖片。完成後,你將擁有一個功能完整的條碼,適用於任何供應鏈或文件管理系統。 + +## 本指南涵蓋內容 + +我們將逐步說明: + +1. 設定 Aspose.BarCode NuGet 套件。 +2. 初始化用於 **Macro PDF417** 的 `BarcodeGenerator`。 +3. 填入每個有用的 **條碼 metadata 欄位**(檔案 ID、段落 ID、檢查碼等)。 +4. 將條碼儲存至磁碟並驗證輸出。 + +不需要事先了解 Macro PDF417——只要具備基本的 C# 知識與最近的 .NET 執行環境即可。 +為什麼這很重要?將豐富的 metadata 直接嵌入條碼,使下游掃描器能驗證整個檔案傳輸、偵測遺失的段落,甚至觸發自動化工作流程。換句話說,你可以在不需要額外資料庫查詢的情況下,取得 **健全、自我描述的資料**。 + +## 前置條件 + +- .NET 6.0 或更新版本(程式碼亦可在 .NET Framework 4.7+ 上執行)。 +- Visual Studio 2022(或任何你偏好的 IDE)。 +- **Aspose.BarCode for .NET** NuGet 套件(提供免費試用)。 + +你可以使用以下指令安裝套件: + +```bash +dotnet add package Aspose.BarCode +``` + +既然基礎已備妥,讓我們深入實作細節。 + +## 步驟 1:為 Macro PDF417 初始化 BarcodeGenerator + +我們首先需要一個已設定為 **Macro PDF417** 的 `BarcodeGenerator` 實例。這會告訴 Aspose.BarCode 使用哪種編碼演算法,並提供一個輸入可讀文字的地方。 + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **為什麼重要:** `EncodeTypes.MacroPdf417` 會啟用支援檔案 ID 與段落編號等 metadata 的擴充 PDF417 模式。範例文字包含 Unicode 字元(`Å`, `ó`, `©`),以證明產生器能順利處理非 ASCII 輸入。 + +## 步驟 2:定義條碼基本外觀 + +在加入 metadata 之前,我們應先設定一些視覺參數,避免條碼變成微小的斑點。`XDimension` 控制模組寬度,而 `Columns` 影響整體形狀。 + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **專業提示:** 像素寬度設定為 `2` 在螢幕顯示與大多數印表機上表現良好。若需更高解析度的列印,可提升至 `3` 或 `4`。 + +## 步驟 3:填入 Macro PDF417 Metadata 欄位 + +現在進入本教學的核心——加入 **條碼 metadata 欄位**。每個屬性皆直接對應到 Macro PDF417 規格中的一段。 + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### 各屬性說明 + +| 屬性 | 用途 | 典型值 | +|----------|---------|---------------| +| **MacroPdf417FileID** | Globally unique identifier for the whole file set. | `12345678` | +| **MacroPdf417SegmentID** | Index of the current segment (starts at `0`). | `12` | +| **MacroPdf417SegmentsCount** | Total segments expected for the file. | `20` | +| **MacroPdf417FileName** | Human‑readable name, often the original filename. | `"file01"` | +| **MacroPdf417Checksum** | 16‑bit CCITT checksum for error detection. | `1234` | +| **MacroPdf417FileSize** | Size of the original file in bytes. | `400000` | +| **MacroPdf417TimeStamp** | When the file was generated. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Optional field indicating the destination. | `"street"` | +| **MacroPdf417Sender** | Optional field indicating the source system. | `"aspose"` | +| **MacroPdf417Terminator** | Flag that tells the scanner this is the final segment. | `Pdf417MacroTerminator.Set` | + +> **為什麼需要這些:** 能理解 Macro PDF417 的掃描器可以重新組合多段檔案、使用檢查碼驗證完整性,甚至根據時間戳記拒絕過期資料。這樣就不需要額外的清單檔案。 + +## 步驟 4:儲存條碼影像 + +所有參數設定完畢後,只需呼叫 `Save`。範例會將 PNG 檔寫入你指定的資料夾。 + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **特殊情況:** 若之後要將條碼嵌入 PDF,可能會想使用 `BarCodeImageFormat.Jpeg` 或 `Pdf`。PNG 保留無損細節,方便驗證。 + +## 完整範例程式 + +將所有步驟整合起來,以下是可直接貼到 Console 應用程式的完整程式碼: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### 預期輸出 + +執行程式後會在執行檔所在資料夾產生名為 **ExtPDF417Meta.png** 的檔案。使用任何影像檢視器開啟,即可看到密集且高對比度的 PDF417 條碼。若使用支援 Macro PDF417 的條碼閱讀器掃描,掃描器會回傳我們設定的 metadata 值——檔案 ID `12345678`、第 `12` 段(共 `20` 段)等資訊。 + +## 常見問題與陷阱 + +- **如果條碼看起來模糊怎麼辦?** 增加 `XDimension.Pixels` 或改用更高解析度的影像格式。 +- **是否必須設定所有 metadata 欄位?** 不需要。只需設定下游系統要求的欄位。未使用的欄位可保留預設值。 +- **能自動產生多段檔案嗎?** 可以——對資料迴圈,遞增 `MacroPdf417SegmentID`,為每個段落產生獨立條碼。記得在所有段落中保持 `MacroPdf417FileID` 一致。 +- **支援 Unicode 嗎?** 完全支援。範例文字包含 `Å`、`ó`、`©`,顯示 Aspose.BarCode 內建支援 UTF‑8。 + +## 往後步驟:深入進階應用 + +既然你已掌握 **建立 PDF417 條碼 metadata** 的方法,接下來可以探索: + +- **使用 `Aspose.Pdf` 將條碼嵌入 PDF**,實現端到端文件產生。 +- **使用 `BarcodeReader` 讀回 metadata**,以程式方式驗證掃描結果。 +- **自訂顏色**(前景/背景)以符合品牌需求。 +- **結合資料庫**,自動填入 `FileID` 或 `Timestamp` 等欄位。 + +上述主題皆與我們的次要關鍵字—**macro pdf417**、**aspose barcode c#**、**barcode metadata fields**、**c# barcode generation**—息息相關,讓你有豐富資源持續學習。 + +## 結論 + +我們剛剛示範了一個完整、可投入生產的範例,說明如何在 C# 中 **建立 PDF417 條碼 metadata**。從安裝 Aspose.BarCode、初始化 `BarcodeGenerator`、填寫所有相關 **條碼 metadata 欄位**,到最後儲存為清晰的 PNG,只要掌握正確的屬性,整個流程相當簡單。 + +試著執行、調整各項數值,觀察掃描器的回應。Macro PDF417 的彈性讓你能將下游系統所需的全部資訊嵌入單一可掃描的影像中。祝開發順利,願你的條碼永遠無誤! + +## 接下來該學什麼? + +以下教學涵蓋與本指南技術緊密相關的主題,並提供完整可執行的程式碼範例與逐步說明,協助你精通更多 API 功能,並在自己的專案中探索其他實作方式。 + +- [如何建立條碼 – 使用 Aspose.BarCode 的 Compact PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java 條碼函式庫 – 使用 Aspose 將條碼加入 PDF](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [建立條碼 – 使用 Aspose.BarCode 的緊湊 PDF417(德文)](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/hongkong/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..4a3e11b4d --- /dev/null +++ b/barcode/hongkong/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-07-15 +description: 快速產生 PDF417 條碼,並學習如何在 C# 中設定欄位以產生緊湊的 PDF417 條碼圖像。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: zh-hant +lastmod: 2026-07-15 +og_description: 使用 Aspose.BarCode 產生 PDF417 條碼,並了解如何設定列數以建立緊湊的 PDF417 條碼圖像。 +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: 在 C# 中產生 PDF417 條碼 – 步驟指南 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: 生成 PDF417 條碼(C#) – 完整指南 +url: /zh-hant/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中產生 PDF417 條碼 – 完整指南 + +是否曾經需要在 .NET 專案中 **generate PDF417 barcode**,卻不知從何開始?您並不孤單。在許多企業應用程式中——例如登機證印表機、庫存標籤或行動票證——PDF417 是能在小小視覺空間內容納大量資料的主力條碼。 + +事實上,Aspose.BarCode 函式庫讓整個流程幾乎毫不費力,您甚至可以控制 **how to set columns**,讓條碼盡可能緊湊。完成本教學後,您將擁有一個可直接使用的 PNG 圖片,內容為 **PDF417 barcode image**,可嵌入任何 UI、電子郵件或列印工作中。 + +## 您將學到的內容 + +- 一個完整功能的 C# 主控台應用程式,可產生 PDF417 條碼。 +- 清楚了解 *X‑Dimension*(模組大小)以及其重要性。 +- 逐步說明 **how to set columns** 以產生更緊湊的條碼。 +- 一個已儲存的 `PNG` 檔案,您可立即開啟以驗證結果。 +- 針對常見問題的排除技巧(例如,條碼無法辨識、圖像格式錯誤)。 + +> **先決條件** – .NET 6+ SDK、Visual Studio 2022(或任何您喜歡的編輯器),以及對 `Aspose.BarCode` 的 NuGet 參考。除此之外無需其他。 + +--- + +## 第一步:安裝 Aspose.BarCode NuGet 套件 + +在我們能夠 *generate PDF417 barcode* 之前,必須先在專案中加入此函式庫。 + +```bash +dotnet add package Aspose.BarCode +``` + +那一行指令會將您所需的所有類型引入,包括 `BarcodeGenerator`、`EncodeTypes` 與 `BarCodeImageFormat` 列舉。 + +> **專業提示:** 若您針對 .NET Framework 而非 .NET 6,請在套件管理員主控台中使用傳統的 `Install-Package Aspose.BarCode` PowerShell 指令。 + +--- + +## 第二步:建立最小化的主控台應用程式 + +讓我們快速建立一個只負責產生條碼的簡易程式。開啟新資料夾,執行 `dotnet new console`,然後將自動產生的 `Program.cs` 替換為以下程式碼。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**為什麼這很重要:** +- `EncodeTypes.Pdf417` 告訴函式庫我們需要 PDF417 條碼,而非 QR 或 Code128。 +- `XDimension.Pixels` 控制每個微小黑白模組的解析度。 +- **how to set columns** 區塊直接影響 **PDF417 barcode image** 的形狀。 +- `Truncate = true` 會移除任何不必要的空白列,讓條碼呈現許多掃描器喜愛的「緊湊」外觀。 + +--- + +## 第三步:深入探討 – 了解欄位與截斷 + +### 如何設定欄位 + +PDF417 以 *rows* × *columns* 的矩陣排列資料。函式庫預設為 5 欄,適用於大多數情況。然而,您可能需要更窄的條碼以適配標籤,或更寬的條碼以提升掃描可靠度。此屬性: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +接受 **1** 到 **30** 的值(具體上限取決於資料長度)。以下是一張快速參考表: + +| 欄位 | 大約寬度 (mm) | 適用情況 | +|------|--------------|----------| +| 1‑3 | 非常窄 | 小標籤、空間受限 | +| 4‑6 | 標準 | 大多數收據、票證 | +| 7‑10 | 較寬 | 高密度資料、較佳可讀性 | + +### 截斷(緊湊模式) + +設定 `Truncate = true` 會指示編碼器切除底部所有不必要的空白列。結果會產生 **compact PDF417 barcode image**,佔用最小的區域,同時仍保留全部資料。若遇到「條碼過大無法貼標籤」的錯誤,請切換此旗標。 + +--- + +## 第四步:執行應用程式並驗證輸出 + +編譯並執行: + +```bash +dotnet run +``` + +您應該會在主控台看到確認儲存位置的訊息。前往該資料夾並開啟 `CompactPdf417.png`。圖像大致如下: + +![產生的 PDF417 條碼圖像](./CompactPdf417.png "產生的 PDF417 條碼圖像 – 由 Aspose.BarCode 建立的緊湊 PNG") + +*圖片替代文字:* **Generated PDF417 barcode image** – 由本教學程式碼產生的緊湊 PNG 檔案。 + +如果您的掃描器能讀取它,恭喜您——您已成功 **generate PDF417 barcode**,並掌握 **how to set columns** 以產生整潔的 **PDF417 barcode image**。 + +--- + +## 第五步:常見問題與解決方法 + +| 症狀 | 可能原因 | 快速解決方案 | +|------|----------|--------------| +| 條碼看起來模糊 | `XDimension.Pixels` 太低(例如 1) | 提升至 2‑3 像素以獲得更清晰的圖像。 | +| 掃描器無法讀取 | 對於給定資料而言欄位過多 | 減少 `Columns` 或啟用 `Truncate`。 | +| 檔案格式錯誤 | 誤以 `BarCodeImageFormat.Jpeg` 儲存 | 使用 `BarCodeImageFormat.Png` 以取得無損結果。 | +| 例外 `ArgumentOutOfRangeException` | 欄位數超出允許範圍 | 將欄位數維持在 1‑30 之間,並確保資料能容納。 | + +--- + +## 第六步:更進一步 – 自訂顏色與加入文字 + +如果您想讓條碼符合品牌配色,您可以調整前景與背景顏色: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +或在條碼下方疊加可供人類閱讀的文字: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +這些附加功能屬於選用項目,但它們說明了 **generate PDF417 barcode** 工作流程的彈性。 + +--- + +## 結論 + +我們已完整示範一個從頭到尾的範例,使用 Aspose.BarCode **generate PDF417 barcode**,說明 **how to set columns** 以控制條碼尺寸,並將結果以 PNG 格式儲存為清晰的 **PDF417 barcode image**。此程式碼自足、相容 .NET 6+,且可輕鬆嵌入任何現有專案。 + +接下來可以嘗試編碼更大的資料負載(例如 JSON),實驗不同的圖像格式,或將產生器整合至即時提供條碼的 Web API。沒有任何限制,而您已擁有堅實的基礎可供構建。 + +祝程式開發順利,願您的條碼總能一次即被掃描! + +## 接下來該學什麼? + +以下教學涵蓋與本指南緊密相關的主題,建立於本教學所示技巧之上。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助您精通更多 API 功能,並在自己的專案中探索其他實作方式。 + +- [如何建立條碼 – 使用 Aspose.BarCode 的緊湊 PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [如何在 Java 中產生條碼圖像 – 使用 Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [在 Java 中產生條碼 – 使用 Aspose.BarCode 設定圖像解析度](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/hongkong/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..f89200a09 --- /dev/null +++ b/barcode/hongkong/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,198 @@ +--- +category: general +date: 2026-07-15 +description: 使用 C# 快速產生 PDF417 條碼。學習如何從文字產生條碼、調整條碼大小,以及在數分鐘內設定自訂條碼尺寸。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: zh-hant +lastmod: 2026-07-15 +og_description: 即時在 C# 中產生 PDF417 條碼。本指南說明如何從文字產生條碼、調整條碼尺寸,以及套用自訂條碼尺寸。 +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: 在 C# 中產生 PDF417 條碼 – 完整程式教學 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: 在 C# 中生成 PDF417 條碼 – 完整逐步指南 +url: /zh-hant/net/compact-pdf417-encoding/generate-pdf417-barcode-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# 中產生 PDF417 條碼 – 完整步驟指南 + +是否曾需要 **產生 PDF417 條碼**,卻不確定要調整哪些設定?你並不孤單——許多開發者在第一次接觸 2‑D 條碼時都會卡在同一個地方。好消息是,只要幾行 C# 程式碼,就能把任意字串轉換成可掃描的 PDF417 圖片,精確控制尺寸,甚至自訂欄列佈局。 + +在本教學中,我們將一步步說明如何 **從文字產生條碼**、調整條碼大小,以及設定自訂條碼尺寸 — 全部使用廣受歡迎的 Aspose.BarCode 函式庫。完成後,你將擁有一個可直接放入任何 .NET 專案的完整範例。 + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## 你將建立的內容 + +- 一個編碼字串 `Åspóse.Barcóde©` 的 PDF417 條碼。 +- 精確控制 X‑dimension(每個模組的像素寬度)。 +- 4 欄 9 列的自訂佈局。 +- 儲存至磁碟的 PNG 檔案。 + +不需要外部服務,也不需要魔法棒——只要純粹的 C# 程式碼,現在就可以編譯。 + +## 前置條件 + +- .NET 6.0 或更新版本(此程式碼同樣支援 .NET Framework 4.8)。 +- Visual Studio 2022 或任何支援 C# 的 IDE。 +- Aspose.BarCode for .NET(免費試用版或授權版)。透過 NuGet 安裝: + +```bash +dotnet add package Aspose.BarCode +``` + +就這樣——只要套件已被參考,就可以開始了。 + +## 步驟 1 – 使用文字資料產生 PDF417 條碼 + +首先,我們需要建立一個 `BarcodeGenerator` 實例,告訴它我們使用 PDF417 符號以及要編碼的文字。 + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **為什麼這很重要:** +> `EncodeTypes.Pdf417` 讓函式庫使用 PDF417 2‑D 格式,而第二個參數則是 **從文字產生條碼** 的內容。你在此傳入的任何資料,都會成為條碼矩陣中儲存的資訊。 + +## 步驟 2 – 調整條碼大小(X‑Dimension) + +如果你曾印過太小的條碼,導致掃描器找不到,那就知道 X‑Dimension 多重要。`XDimension` 屬性控制單一模組(最小的黑白方格)的寬度(像素)。 + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **小技巧:** +> 2 px 的數值在大多數螢幕顯示情境下表現良好。若是高解析度列印,可能需要調整到 3 或 4 px。只要記得,X‑Dimension 越大,整體影像尺寸也會跟著變大。 + +## 步驟 3 – 設定自訂條碼尺寸(欄與列) + +PDF417 允許你自行決定條碼佔用的欄與列數。這就是 **自訂條碼尺寸** 發揮作用的地方。調整這些值可以讓條碼更好地貼合緊湊的 UI 空間或符合特定標籤尺寸。 + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **背後發生了什麼?** +> 函式庫會將編碼資料重新分配到指定的格子中。欄數較少會產生較高的條碼;列數較多則會使條碼變矮。根據你的應用需求,調整數值直到視覺平衡為止。 + +## 步驟 4 – 儲存條碼影像 + +設定完成後,只要請生成器寫出 PNG 檔案即可。PNG 為無損格式,模組的銳利度不會受損。 + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +執行程式後,你應該會在 `C:\Barcodes\CustomLayout.png` 看到與上方截圖相似的檔案。使用任何支援 PDF417 的讀取器掃描,即可還原原始字串 `Åspóse.Barcóde©`。 + +## 完整範例程式 + +以下是可直接貼到 Console 應用程式的完整程式碼,包含所有 using 指令與生產環境常見的錯誤處理。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### 預期輸出 + +執行程式會印出: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…並產生一個可在任何影像檢視器開啟的 PNG。若使用行動裝置的條碼掃描 App(例如 iOS/Android 的「Barcode Scanner」),解碼後的文字應該正好是 **Åspóse.Barcóde©**。 + +## 常見問題與邊緣案例 + +| 問題 | 解答 | +|----------|--------| +| **可以使用其他影像格式嗎?** | 可以——支援 `BarCodeImageFormat.Jpeg`、`Bmp`、`Gif` 或 `Svg`。只要在 `Save` 的第二個參數改成對應格式即可。 | +| **如果我的文字包含 Unicode 字元怎麼辦?** | Aspose.BarCode 完全支援 UTF‑8,所以範例中的 `Å` 與 `©` 能直接使用,無需額外處理。 | +| **如何變更錯誤更正等級?** | 使用 `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;`(等級 0‑8)。等級越高冗餘度越大,檔案尺寸也會隨之增長。 | +| **需要透明背景,能做到嗎?** | 在儲存前設定 `generator.Parameters.Barcode.Image.TransparentBackground = true;` 即可。 | +| **能直接把條碼嵌入 PDF 嗎?** | 完全可以。將 `Save` 呼叫改為 `generator.Save("output.pdf", BarCodeImageFormat.Pdf);`,即可得到只含條碼的單頁 PDF。 | + +## 結論 + +現在你已掌握如何在 C# 中 **產生 PDF417 條碼**、**調整條碼大小**,以及套用 **自訂條碼尺寸** 以符合版面需求。這四個步驟——初始化、尺寸、佈局、儲存——涵蓋了大多數 2‑D 條碼情境的核心流程。 + +接下來可以嘗試把 `EncodeTypes.Pdf417` 換成 `EncodeTypes.QR` 或 `EncodeTypes.Code128`,觀察 API 如何因應。再試著變更 `XDimension`、調整欄列矩陣,或把影像嵌入 PDF 報表。可能性幾乎無限,而你已擁有堅實的基礎可以持續建構。 + +有更多問題,或在玩 PDF417 時發現了巧妙的技巧嗎?歡迎在下方留言——讓我們持續交流。祝開發順利! + +## 接下來該學什麼? + +以下教學與本指南緊密相關,能進一步深化你對 API 功能的掌握,並探索在實務專案中可採用的其他實作方式。 + +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Generate DataMatrix Barcode – Pro Guide with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/hongkong/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..6d3d29fda --- /dev/null +++ b/barcode/hongkong/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,310 @@ +--- +category: general +date: 2026-07-15 +description: 如何在 C# 中讀取 PDF417 條碼,並從圖像中讀取多個條碼。學習使用 C# 讀取條碼圖像,提供詳細程式碼與技巧。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: zh-hant +lastmod: 2026-07-15 +og_description: 如何在 C# 中快速讀取 PDF417 條碼。本指南將示範如何從單一圖像中讀取多個條碼並解碼每個屬性。 +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: 如何在 C# 中讀取 PDF417 – 完整程式碼範例與說明 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: 如何在 C# 中讀取 PDF417 – 完整逐步指南 +url: /zh-hant/net/compact-pdf417-encoding/how-to-read-pdf417-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# 中讀取 PDF417 – 完整逐步指南 + +有沒有想過如何使用 C# 從圖像中**讀取 PDF417**?你並不是唯一有此疑問的人。大多數開發人員在需要從掃描文件中提取擴展的 Macro‑PDF417 欄位時會卡住。好消息是,只需幾行程式碼就能解碼 PDF417、在同一張圖片中讀取多個條碼,並取得規格所提供的所有隱藏屬性。 + +在本教學中,我們將逐步說明一個真實案例,展示 **how to read PDF417**、如何從單一檔案**read multiple barcodes**,以及為何 **read barcode image C#** 程式碼會呈現此樣子。完成後,你將擁有一個可直接執行的主控台應用程式,能印出所有可能需要的資訊——檔案 ID、段落 ID、檢查碼、時間戳記,等等。 + +## 前置條件 + +* .NET 6.0 SDK 或更新版本(此程式碼同樣適用於 .NET Core 與 .NET Framework)。 +* Visual Studio 2022(或任何你偏好的編輯器)。 +* **Aspose.BarCode for .NET** NuGet 套件 – 這是實際解析 PDF417 的函式庫。 +* 一張包含 Macro‑PDF417 條碼的範例圖像(例如 `ExtPDF417Meta.png`)。 + +不需要額外設定;此函式庫已內建所有所需的解碼器。 + +## 步驟 1:安裝 Aspose.BarCode + +在終端機中開啟你的專案資料夾,並執行: + +```bash +dotnet add package Aspose.BarCode +``` + +此指令會取得最新的穩定版(截至 2026 年 7 月為 23.12)。如果你偏好在 Visual Studio 內使用套件管理員主控台,請使用: + +```powershell +Install-Package Aspose.BarCode +``` + +> **專業提示:** 在 `.csproj` 中鎖定版本 (`23.12.0`) 以避免日後不慎產生相容性問題。 + +## 步驟 2:建立主控台應用程式骨架 + +如果尚未有專案,請建立新的主控台專案: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +將自動產生的 `Program.cs` 替換為以下程式碼。我們會在接下來的章節說明每個區塊的作用。 + +## 步驟 3:撰寫完整的「How to Read PDF417」程式碼 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### 為何此程式碼可運作 + +* **`BarCodeReader`** 是核心類別,用於串流圖像、偵測條碼,並回傳 `BarCodeResult` 物件的集合。 +* 傳入 **`DecodeType.MacroPdf417`** 會告訴函式庫特別處理 Macro‑PDF417;它仍會回傳普通的 PDF417 符號,滿足 **read multiple barcodes** 的需求。 +* **`Extended.Pdf417.MacroPdf417`** 物件包含 ISO/IEC 15438 標準所定義的所有可選欄位——在此可取得 `FileID`、`SegmentID`、`Checksum` 等資訊。 +* `using` 區塊確保原生資源被釋放,避免長時間執行的服務發生記憶體泄漏。 + +## 步驟 4:執行應用程式並驗證輸出 + +在終端機中執行: + +```bash +dotnet run +``` + +你應該會看到類似以下的結果: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +如果圖像中包含多於一個條碼,迴圈會印出分隔線 (`----------------------------------------`) 並繼續處理下一個結果——這正是實務上 **read multiple barcodes** 的呈現方式。 + +## 常見問題與邊緣案例 + +### 如果圖像同時包含 Macro‑PDF417 與一般 PDF417 符號,該怎麼辦? + +相同的 `BarCodeReader` 呼叫會回傳兩者。你可以透過檢查 `result.CodeType`(`MacroPdf417` 與 `Pdf417`)來區分。對於普通 PDF417,擴充屬性會是 `null`,因此 `if (macro != null)` 的防護可避免 `NullReferenceException`。 + +### 條碼被旋轉或傾斜——讀取器仍能正常工作嗎? + +Aspose.BarCode 內建旋轉與變形補償功能。只要條碼寬度至少佔圖像寬度的 30%,解碼器通常能成功。若遇極端情況,可在呼叫 `ReadBarCodes()` 前啟用 `reader.Options.AllowInvertedBarcodes = true;`。 + +### 如何處理大量圖像批次? + +將讀取邏輯包在 `foreach (var file in Directory.GetFiles(folder, "*.png"))` 迴圈中。`using` 模式確保每張圖像的原生資源在下一次迭代前釋放,從而降低記憶體使用量。 + +## 完整原始碼清單(可直接複製貼上) + +以下是一個完整的程式區塊,方便快速複製貼上。沒有隱藏的相依性——只需要 Aspose.BarCode NuGet 套件。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## 重點回顧 – 本文涵蓋內容 + +* **How to read PDF417** 使用 Aspose.BarCode 於 C#。 +* 從單一圖像**read multiple barcodes** 的完整步驟。 +* 如何**read barcode image C#** 並擷取所有 Macro‑PDF417 欄位。 +* 旋轉、批次處理以及處理缺少擴充資料的技巧。 + +## 往後步驟與相關主題 + +* **Encode PDF417** – 使用 `BarCodeBuilder` 產生自己的 Macro‑PDF417 條碼。 +* **Read other 2‑D symbologies** – QR、DataMatrix、Aztec – 使用相同的 `BarCodeReader` 類別。 +* **Integrate with ASP.NET Core** – 建立接受上傳圖像並回傳解碼欄位 JSON 的 Web 端點。 + +隨意嘗試:更改圖像路徑、將普通 PDF417 放入同一資料夾,或調整 `DecodeType` 旗標觀察函式庫的行為。玩得越多,你就會越熟悉 **read barcode image C#** 的情境。 + +遇到難以解碼的圖像嗎?在下方留言或在範例專案的 GitHub 倉庫開啟 issue。祝開發愉快! + +## 接下來該學什麼? + +以下教學涵蓋與本指南緊密相關的主題,並以此為基礎延伸技術。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通更多 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# – 產生 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/one-dimensional-barcode-types/_index.md b/barcode/hongkong/net/one-dimensional-barcode-types/_index.md index 5802bdbba..fa808d04a 100644 --- a/barcode/hongkong/net/one-dimensional-barcode-types/_index.md +++ b/barcode/hongkong/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ url: /zh-hant/net/one-dimensional-barcode-types/ 了解如何使用 Aspose.BarCode for .NET 產生一維條碼時處理例外狀況。本逐步指南可確保條碼解決方案具有容錯性。現在就開始吧! ### [一維寬窄比配置](./one-dimensional-wide-narrow-ratio-configuration/) 使用 Aspose.BarCode for .NET 輕鬆產生自訂條碼。一維寬窄比配置的分步指南。 +### [使用 Aspose.BarCode 從文字生成條碼 – C# 指南](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +了解如何使用 Aspose.BarCode 在 .NET 中透過 C# 從文字生成條碼,遵循簡明的分步指南。 ## 結論 @@ -89,4 +91,4 @@ url: /zh-hant/net/one-dimensional-barcode-types/ {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/hongkong/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..f9203cf1c --- /dev/null +++ b/barcode/hongkong/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-07-15 +description: 使用 Aspose.BarCode 於 C# 產生文字條碼。了解如何變更列數、儲存條碼影像,以及快速建立 Aspose 條碼解決方案。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: zh-hant +lastmod: 2026-07-15 +og_description: 使用 Aspose.BarCode 從文字產生條碼。本指南示範如何更改列數、儲存條碼圖像,以及在幾行程式碼內產生 Aspose 條碼。 +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: 使用 Aspose.BarCode 從文字生成條碼 – 快速 C# 教學 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: 使用 Aspose.BarCode 從文字產生條碼 – C# 指南 +url: /zh-hant/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose.BarCode 從文字產生條碼 – C# 指南 + +使用 Aspose.BarCode 從文字產生條碼出乎意料地簡單。在本教學中,我們將逐步說明 **如何產生條碼**、調整欄位佈局,最後 **將條碼影像儲存** 為 PNG 檔案。無論您是要建立票務系統、倉庫標籤印表機,或只是試驗 QR 風格的碼,以下步驟都能讓您快速達成目標。 + +## 您將學會 + +- 從任意 Unicode 字串建立條碼(是的,即使是 “Åspóse.Barcóde©” 也能運作)。 +- 調整 MicroPdf417 的 **欄位數** 以適應窄標籤或寬標籤。 +- 將結果以適當的影像格式持久化至磁碟。 +- 處理特殊字元及常見陷阱的技巧,當您 **建立 Aspose 條碼** 解決方案時。 + +不需要外部工具,也不需要命令列技巧——只需純粹的 C# 與 Aspose.BarCode 函式庫。 + +## 前置條件 + +在深入之前,請確保您已具備以下條件: + +1. **.NET 6.0** 或更新版本已安裝(此程式碼亦可在 .NET Framework 4.7+ 上執行)。 +2. Aspose.BarCode 的 **授權**,或您也可以先使用免費評估版。 +3. 一個可寫入的資料夾——在範例中我們稱之為 `YOUR_DIRECTORY`。 + +如果缺少上述任一項,請立即取得 NuGet 套件: + +```bash +dotnet add package Aspose.BarCode +``` + +就這樣——不需要手動複製額外的 DLL。 + +## 步驟 1 – 設定專案與匯入 + +首先,建立一個 console 應用程式(或將程式碼放入任何 C# 專案中)。重要的是要引用正確的命名空間: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +為什麼需要這些 using 陳述式?`BarcodeGenerator` 位於 `Aspose.BarCode.Generation`,而 `BarCodeImageFormat` 列舉則位於 `Aspose.BarCode`。保持匯入整潔可讓後續程式碼讀起來像自然語言。 + +## 步驟 2 – 建立條碼產生器(如何產生條碼) + +現在我們實際 **從文字產生條碼**。`EncodeTypes` 列舉告訴 Aspose 使用哪種符號;此處我們選擇 `MicroPdf417`,因為它能在緊湊的格子中處理長字串。 + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +請注意,字串中包含重音字元與版權符號。Aspose.BarCode 會自動編碼 Unicode,因此不需要預先處理文字。 + +## 步驟 3 – 微調外觀(如何變更欄位數) + +MicroPdf417 允許您控制欄位數量,這直接影響條碼的寬度。較緊湊的佈局適合窄標籤;較寬的佈局則提升大幅列印時的可讀性。 + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +為什麼使用 2 像素模組?它能產生清晰的影像,同時不會使檔案大小暴增。歡迎自行嘗試——1 到 4 之間的值通常表現良好。如果需要不同的欄位數,只需變更 `Columns` 屬性;Aspose 會自動重新計算佈局。 + +## 步驟 4 – 儲存條碼影像(save barcode image) + +設定好產生器後,我們即可 **儲存條碼影像**。`Save` 方法接受檔案路徑與影像格式列舉。PNG 為無損格式,條碼即使放大後仍保持清晰。 + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +小技巧:請始終使用絕對路徑,或確保工作目錄符合預期;否則檔案可能會出現在 bin 資料夾,讓您找不到它。 + +## 完整範例程式 + +將上述所有步驟整合起來,以下是一個可直接貼到 `Program.cs` 並執行的完整程式: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**預期輸出**(主控台): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +若開啟 `MicroPdf417.png`,您會看到一個清晰的 MicroPdf417 條碼,已編碼原始字串,且包含我們提供的特殊字元。 + +## 常見問題與邊緣案例 + +### 如果我的文字超過預設容量怎麼辦? + +當資料超過每列的最大容量時,MicroPdf417 會自動切換為多列佈局。您仍可控制欄位數,但函式庫可能在背後加入額外列。無需額外程式碼——只要留意產生影像的尺寸即可。 + +### 如何將影像格式改為 JPEG 或 BMP? + +將 `BarCodeImageFormat.Png` 替換為 `BarCodeImageFormat.Jpeg`(或 `Bmp`)。請記得 JPEG 會產生壓縮雜訊,可能影響掃描可靠性。PNG 是最安全的預設選項。 + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### 為什麼輸出中會出現浮水印? + +那是 Aspose.BarCode 評估版的浮水印。若要 **建立 Aspose 條碼** 而不出現浮水印,請如 Step 2 註解行所示載入有效的授權檔案。 + +### 我可以產生其他符號類型(QR、Code128 等)嗎? + +當然可以。只要將 `EncodeTypes.MicroPdf417` 替換為 `EncodeTypes` 列舉中的其他值,例如 `EncodeTypes.QR` 或 `EncodeTypes.Code128`。其餘程式碼保持不變,讓此方法具高度可重用性。 + +## 生產環境條碼產生的專業技巧 + +- **快取產生器**,如果您需要大量產生相同設定的條碼,可減少物件建立的開銷。 +- **驗證輸入字串** 的長度限制,這取決於所選符號類型(若過長,Aspose 會拋出 `ArgumentException`)。 +- **使用 `using` 陳述式** 或在完成後呼叫 `Dispose` 以即時釋放原生資源。 +- **設定 DPI**,透過 `generator.Parameters.ImageResolution.DpiX/DpiY`,若需要高解析度列印大型標籤時使用。 + +## 結論 + +您現在已清楚了解如何使用 Aspose.BarCode **從文字產生條碼**、如何 **變更欄位數**,以及正確的 **將條碼影像儲存為 PNG** 方法。上述完整且可執行的範例展示了乾淨、適合生產環境的實作方式 + +## 接下來您可以學習什麼? + +以下教學涵蓋與本指南緊密相關的主題,並以此為基礎延伸技術。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助您精通更多 API 功能,並在專案中探索其他實作方式。 + +- [如何產生條碼 – Code 39 設定與 Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [產生條碼影像 – Code 93 與 Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [如何產生 DataMatrix 條碼(ECC 200)與 Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/hungarian/net/compact-pdf417-encoding/_index.md index 17598f023..c40eff8b2 100644 --- a/barcode/hungarian/net/compact-pdf417-encoding/_index.md +++ b/barcode/hungarian/net/compact-pdf417-encoding/_index.md @@ -82,7 +82,10 @@ Az alapok mellett itt van néhány gyakorlati tipp a munkafolyamat egyszerűsít ## Compact PDF417 kódolási útmutatók ### [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. +### [PDF417 vonalkód metaadatok létrehozása C#‑ban – Teljes lépésről‑lépésre útmutató](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +### [PDF417 vonalkód generálása C#‑ban – Teljes útmutató](./generate-pdf417-barcode-in-c-complete-guide/) +### [PDF417 vonalkód generálása C#‑ban – Teljes lépésről‑lépésre útmutató](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +### [PDF417 olvasása C#‑ban – Teljes lépésről‑lépésre útmutató](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) ## Gyakran Ismételt Kérdések @@ -112,4 +115,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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/hungarian/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..206c6f3ae --- /dev/null +++ b/barcode/hungarian/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-07-15 +description: PDF417 vonalkód metaadatok létrehozása C#-ban az Aspose.BarCode használatával. + Ismerje meg a Macro PDF417 beállításokat, mentse PNG formátumban, és kezelje a Unicode + szöveget. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: hu +lastmod: 2026-07-15 +og_description: PDF417 vonalkód metaadatok létrehozása C#-ban az Aspose.BarCode segítségével. + Ez az útmutató megmutatja az összes beállítást, amelyre szükség van a fájl‑azonosító, + időbélyegek és egyéb adatok beágyazásához. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: PDF417 vonalkód metaadatok létrehozása C#-ban – Teljes programozási útmutató +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: PDF417 vonalkód metaadatok létrehozása C#‑ban – Teljes lépésről‑lépésre útmutató +url: /hu/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF417 vonalkód metaadatok létrehozása C#‑ban – Teljes lépésről‑lépésre útmutató + +Valaha szükséged volt **PDF417 vonalkód metaadatok** létrehozására C#‑ban, de nem tudtad, mely tulajdonságokat kell módosítani? Nem vagy egyedül – a fejlesztők gyakran elakadnak, amikor a specifikáció fájlazonosítókat, szegmensszámokat vagy egyedi időbélyegeket igényel. + +Jó hír, hogy az Aspose.BarCode ezt gyerekjátékká teszi. Ebben az útmutatóban létrehozunk egy `BarcodeGenerator`‑t **Macro PDF417**‑hez, hozzáadjuk az összes fontos metaadatot, és elmentjük az eredményt PNG képként. A végére egy teljes funkcionalitású vonalkódod lesz, amely készen áll bármely ellátási lánc vagy dokumentumkezelő rendszerhez. + +## Mit fed le ez az útmutató + +- Az Aspose.BarCode NuGet csomag beállítása. +- Egy `BarcodeGenerator` inicializálása **Macro PDF417**‑hez. +- Minden hasznos **vonalkód metaadat mező** (fájlazonosító, szegmensazonosító, ellenőrzőösszeg stb.) feltöltése. +- A vonalkód mentése lemezre és a kimenet ellenőrzése. + +Nem szükséges előzetes tapasztalat a Macro PDF417‑hez – elegendő az alap C# tudás és egy aktuális .NET futtatókörnyezet. + +Miért érdekelhet? A gazdag metaadatok közvetlen beágyazása egy vonalkódba lehetővé teszi a downstream szkennerek számára, hogy ellenőrizzék a teljes fájlátvitelt, észleljék a hiányzó szegmenseket, vagy akár automatizált munkafolyamatokat indítsanak. Más szóval, **robusztus, önmagát leíró adatot** kapsz külön adatbázis‑lekérdezés nélkül. + +## Előfeltételek + +- .NET 6.0 vagy újabb (a kód .NET Framework 4.7+‑on is működik). +- Visual Studio 2022 (vagy bármely kedvelt IDE). +- Az **Aspose.BarCode for .NET** NuGet csomag (ingyenes próba elérhető). + +A csomagot a következő parancs segítségével telepítheted: + +```bash +dotnet add package Aspose.BarCode +``` + +Miután megvan az alap, merüljünk el a tényleges megvalósításban. + +## 1. lépés: A BarcodeGenerator inicializálása Macro PDF417‑hez + +Az első dolog, amire szükségünk van, egy `BarcodeGenerator` példány, amely **Macro PDF417**‑re van beállítva. Ez megmondja az Aspose.BarCode‑nak, melyik kódolási algoritmust használja, és helyet biztosít a emberi olvasásra szánt szövegnek. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Miért fontos:** `EncodeTypes.MacroPdf417` aktiválja a kiterjesztett PDF417 módot, amely támogatja a metaadatokat, mint a fájlazonosítók és szegmensszámok. A minta szöveg Unicode karaktereket (`Å`, `ó`, `©`) tartalmaz, hogy bizonyítsa, a generátor zökkenőmentesen kezeli a nem‑ASCII bemenetet. + +## 2. lépés: Alapvető vonalkód megjelenés definiálása + +Mielőtt elkezdenénk a metaadatok hozzáadását, be kell állítanunk néhány vizuális paramétert, hogy a vonalkód ne legyen mikroszkopikus folt. Az `XDimension` szabályozza a modul szélességét, míg a `Columns` befolyásolja az általános alakot. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Pro tipp:** A `2` pixel szélesség jól működik képernyőn és a legtöbb nyomtatón. Ha nagyobb felbontású nyomtatásra van szükség, növeld `3`‑ra vagy `4`‑re. + +## 3. lépés: Macro PDF417 metaadat mezők feltöltése + +Most jön az útmutató szíve – a **vonalkód metaadat mezők** hozzáadása. Minden tulajdonság közvetlenül a Macro PDF417 specifikáció egy szegmensére mutat. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Mit jelent minden egyes tulajdonság + +| Tulajdonság | Cél | Tipikus érték | +|------------|-----|---------------| +| **MacroPdf417FileID** | Globálisan egyedi azonosító a teljes fájlkészlethez. | `12345678` | +| **MacroPdf417SegmentID** | Az aktuális szegmens indexe (0‑tól kezdődik). | `12` | +| **MacroPdf417SegmentsCount** | A fájlhoz várható összes szegmens száma. | `20` | +| **MacroPdf417FileName** | Emberi olvasásra szánt név, gyakran az eredeti fájlnév. | `"file01"` | +| **MacroPdf417Checksum** | 16‑bit CCITT ellenőrzőösszeg hibadetektáláshoz. | `1234` | +| **MacroPdf417FileSize** | Az eredeti fájl mérete bájtokban. | `400000` | +| **MacroPdf417TimeStamp** | Mikor jött létre a fájl. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Opcionális mező a címzett jelzésére. | `"street"` | +| **MacroPdf417Sender** | Opcionális mező a forrásrendszer jelzésére. | `"aspose"` | +| **MacroPdf417Terminator** | Jelző, amely azt mondja a szkennernek, hogy ez az utolsó szegmens. | `Pdf417MacroTerminator.Set` | + +> **Miért van erre szükség:** A Macro PDF417‑et értő szkennerek képesek egy több szegmensből álló fájlt újra összerakni, az ellenőrzőösszeggel ellenőrizni a sértetlenséget, és akár elutasítani a régi adatokat az időbélyeg alapján. Ez megszünteti a különálló manifest fájl szükségességét. + +## 4. lépés: A vonalkód kép mentése + +Miután minden paraméter be van állítva, egyszerűen meghívjuk a `Save`‑et. A példa egy PNG fájlt ír a megadott mappába. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Szélső eset:** Ha később a vonalkódot PDF‑be szeretnéd beágyazni, érdemes lehet a `BarCodeImageFormat.Jpeg` vagy `Pdf` formátumot választani. A PNG veszteségmentes részleteket őrzi, ami a verifikációhoz hasznos. + +## Teljes működő példa + +Mindent összevonva, itt a teljes program, amelyet beilleszthetsz egy konzolos alkalmazásba: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Várt kimenet + +A program futtatása létrehoz egy **ExtPDF417Meta.png** nevű fájlt a végrehajtható mappájában. Nyisd meg bármely képnézővel, és egy sűrű, nagy kontrasztú PDF417 vonalkódot látsz. Ha egy Macro PDF417‑et támogató vonalkódolvasóval szkennelsz, a szkenner visszaadja a beállított metaadat értékeket – fájlazonosító `12345678`, szegmens `12` a `20`‑ból, stb. + +## Gyakori kérdések és buktatók + +- **Mi van, ha a vonalkód elmosódottnak tűnik?** Növeld az `XDimension.Pixels`‑t vagy válts magasabb felbontású képformátumra. +- **Kell-e minden metaadat mezőt beállítanom?** Nem. Csak a downstream rendszerednek szükséges mezők kötelezőek. A nem használt mezők maradhatnak az alapértelmezett értéken. +- **Generálhatok automatikusan több szegmensből álló fájlt?** Igen – iterálj az adatokon, növeld a `MacroPdf417SegmentID`‑t, és minden szegmenshez generálj egy külön vonalkódot. Ne feledd, hogy a `MacroPdf417FileID` minden szegmensben egységes maradjon. +- **Támogatja-e az Unicode‑ot?** Teljesen. A minta szöveg tartalmazza a `Å`, `ó` és `©` karaktereket, ami azt mutatja, hogy az Aspose.BarCode natívan kezeli az UTF‑8‑at. + +## Következő lépések: Alapokon túl + +Miután már tudod, hogyan **hozz létre PDF417 vonalkód metaadatokat**, érdemes lehet felfedezni: + +- **Vonalkódok beágyazása PDF‑ekbe** az `Aspose.Pdf` használatával az vég‑től‑vég dokumentumgeneráláshoz. +- **Metaadatok visszaolvasása** a `BarcodeReader`‑rel a szkennelések programozott ellenőrzéséhez. +- **Színek testreszabása** (előtér/háttér) márkaépítési célokra. +- **Adatbázissal való integráció** a `FileID` vagy `Timestamp` mezők automatikus feltöltéséhez. + +Mindezek a témák visszautalnak a másodlagos kulcsszavainkra – **macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, és **c# barcode generation** – így rengeteg anyagot találsz a további tanuláshoz. + +## Összegzés + +Most végigmentünk egy teljes, termelésre kész példán, amely bemutatja, hogyan **hozz létre PDF417 vonalkód metaadatokat** C#‑ban. Az Aspose.BarCode telepítésétől, egy `BarcodeGenerator` inicializálásán át, minden releváns **vonalkód metaadat mező** kitöltéséig, egészen a tiszta PNG mentéséig a folyamat egyszerű, ha ismered a megfelelő tulajdonságokat. + +Próbáld ki, módosítsd az értékeket, és nézd meg, hogyan reagálnak a szkennerek. A Macro PDF417 rugalmassága lehetővé teszi, hogy mindent beágyazz, amire egy downstream rendszernek szüksége van – mindezt egyetlen, beolvasható képen. Boldog kódolást, és legyenek a vonalkódjaid mindig hibamentesek! + +## Mit érdemes még megtanulni? + +Az alábbi útmutatók szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás tartalmaz teljes működő kódrészleteket 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/) +- [java vonalkód könyvtár – Vonalkód hozzáadása PDF‑hez az Aspose használatával](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [Hogyan készítsünk vonalkódot – Kompakt PDF417 az Aspose.BarCode‑dal](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/hungarian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..6e75ee73a --- /dev/null +++ b/barcode/hungarian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: Generálj PDF417 vonalkódot gyorsan, és tanuld meg, hogyan állítsd be + az oszlopokat egy kompakt PDF417 vonalkód képhez C#-ban. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: hu +lastmod: 2026-07-15 +og_description: PDF417 vonalkód generálása az Aspose.BarCode segítségével, és megtanulhatja, + hogyan állíthatja be az oszlopokat egy kompakt PDF417 vonalkód kép létrehozásához. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: PDF417 vonalkód generálása C#‑ban – Lépésről lépésre útmutató +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: PDF417 vonalkód generálása C#-ban – Teljes útmutató +url: /hu/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-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 – Teljes útmutató + +Valaha szükséged volt **PDF417 vonalkód generálására** egy .NET projektben, de nem tudtad, hol kezdjed? Nem vagy egyedül. Sok vállalati alkalmazásban—gondolj a beszállókártya nyomtatókra, készletcímkékre vagy mobiljegykiadásokra— a PDF417 a munkához szükséges erő, amely sok adatot helyez el egy kis vizuális területen. + +A lényeg: az Aspose.BarCode könyvtár szinte fájdalommentesé teszi a teljes folyamatot, és még **hogyan állítsuk be az oszlopokat** is vezérelheted, hogy a vonalkód a lehető legkompaktabb legyen. A tutorial végére egy kész PNG képet kapsz egy **PDF417 vonalkód képről**, amelyet bármely UI‑ba, e‑mailbe vagy nyomtatási feladatba beilleszthetsz. + +## Mit fogsz elsajátítani + +- Egy teljesen működő C# konzolalkalmazás, amely PDF417 vonalkódot hoz létre. +- Világos megértés az *X‑Dimension* (modulméret) szerepéről és miért fontos. +- Lépésről‑lépésre útmutató **hogyan állítsuk be az oszlopokat** egy szorosabb vonalkódhoz. +- Egy mentett `PNG` fájl, amelyet azonnal megnyithatsz az eredmény ellenőrzéséhez. +- Tippek a gyakori hibák elhárításához (pl. olvashatatlan vonalkódok, rossz képformátum). + +> **Előfeltételek** – .NET 6+ SDK, Visual Studio 2022 (vagy bármely kedvelt szerkesztő), és egy NuGet hivatkozás a `Aspose.BarCode`‑ra. Egyéb semmi. + +--- + +## 1. lépés: Az Aspose.BarCode NuGet csomag telepítése + +Mielőtt *PDF417 vonalkódot generálhatnánk*, a könyvtárnak jelen kell lennie a projektben. + +```bash +dotnet add package Aspose.BarCode +``` + +Ez az egyetlen sor behozza az összes szükséges típust, többek között a `BarcodeGenerator`, `EncodeTypes` és a `BarCodeImageFormat` enumot. + +> **Pro tipp:** Ha .NET Framework‑ot célozol a .NET 6 helyett, használd a klasszikus `Install-Package Aspose.BarCode` PowerShell parancsot a Package Manager Console‑ban. + +--- + +## 2. lépés: Minimális konzolalkalmazás létrehozása + +Készítsünk egy apró programot, amely csak egy vonalkódot generál. Nyiss egy új mappát, futtasd a `dotnet new console` parancsot, majd cseréld le az automatikusan generált `Program.cs`‑t az alábbi kóddal. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Miért fontos:** +- `EncodeTypes.Pdf417` azt mondja a könyvtárnak, hogy PDF417 vonalkódot szeretnénk, nem QR‑t vagy Code128‑at. +- `XDimension.Pixels` szabályozza minden apró fekete vagy fehér modul felbontását. +- A **hogyan állítsuk be az oszlopokat** blokk közvetlenül befolyásolja a **PDF417 vonalkód kép** alakját. +- `Truncate = true` eltávolít minden felesleges üres sort, így a „kompakt” megjelenést kapod, amit a legtöbb szkenner szeret. + +--- + +## 3. lépés: Mélyebben – Az oszlopok és a csonkítás megértése + +### Hogyan állítsuk be az oszlopokat + +PDF417 az adatot egy *sor* × *oszlop* mátrixban rendezi. A könyvtár alapértelmezés szerint 5 oszlopot használ, ami a legtöbb esetben megfelelő. Azonban lehet, hogy szűkebb vonalkódra van szükséged egy címkehez, vagy szélesebbre a szkennelési megbízhatóság javítása érdekében. A property: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +értékeket fogad **1** és **30** között (a pontos határ a adat hosszától függ). Itt egy gyors táblázat: + +| Oszlopok | Kb. szélesség (mm) | Mikor használjuk | +|----------|-------------------|-------------------| +| 1‑3 | Nagyon keskeny | Kis címke, korlátozott hely | +| 4‑6 | Standard | A legtöbb nyugta, jegy | +| 7‑10 | Szélesebb | Nagy sűrűségű adat, jobb olvashatóság | + +### Truncate (Kompakt mód) + +`Truncate = true` beállítás azt mondja a kódolónak, hogy vágja le a felesleges üres sorokat alul. Az eredmény egy **kompakt PDF417 vonalkód kép**, amely a lehető legkisebb területet foglalja el, miközben minden adatot tartalmaz. Ha valaha „a vonalkód túl nagy a címkéhez” hibát kapsz, állítsd át ezt a jelzőt. + +--- + +## 4. lépés: Az alkalmazás futtatása és a kimenet ellenőrzése + +Fordítsd le és futtasd: + +```bash +dotnet run +``` + +A konzolban látnod kell egy üzenetet, amely megerősíti a mentés helyét. Navigálj a mappába, és nyisd meg a `CompactPdf417.png` fájlt. A kép valahogy így fog kinézni: + +![Generált PDF417 vonalkód kép](./CompactPdf417.png "Generált PDF417 vonalkód kép – kompakt PNG, amelyet az Aspose.BarCode hozott létre") + +*Kép alternatív szöveg:* **Generált PDF417 vonalkód kép** – egy kompakt PNG fájl, amelyet a tutorial kód hozott létre. + +Ha a szkennered képes beolvasni, gratulálok—sikeresen **PDF417 vonalkódot generáltál** és elsajátítottad a **hogyan állítsuk be az oszlopokat** a rendezett **PDF417 vonalkód kép** érdekében. + +--- + +## 5. lépés: Gyakori hibák és megoldások + +| Tünet | Valószínű ok | Gyors megoldás | +|-------|--------------|----------------| +| A vonalkód elmosódott | `XDimension.Pixels` túl alacsony (pl. 1) | Emeld 2‑3 pixelre a tisztább képért. | +| A szkenner nem olvas | Túl sok oszlop a megadott adathoz | Csökkentsd a `Columns` értékét vagy engedélyezd a `Truncate`‑t. | +| Rossz fájlformátum | Véletlenül `BarCodeImageFormat.Jpeg`‑ként mentett | Használd a `BarCodeImageFormat.Png`‑t veszteségmentes eredményért. | +| `ArgumentOutOfRangeException` kivétel | Az oszlopszám meghaladja a megengedett tartományt | Tartsd az oszlopokat 1‑30 között, és biztosítsd, hogy az adat elfér. | + +--- + +## 6. lépés: Továbbfejlesztés – Színek testreszabása és szöveg hozzáadása + +Ha szeretnéd, hogy a vonalkód illeszkedjen a márka színpalettájához, módosíthatod az előtér és háttér színeket: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Vagy ember által olvasható szöveget helyezhetsz a vonalkód alá: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Ezek a kiegészítések opcionálisak, de bemutatják, milyen rugalmas a **PDF417 vonalkód generálása** munkafolyamat. + +--- + +## Összegzés + +Áttekintettünk egy teljes, vég‑a‑végig példát, amely **PDF417 vonalkódot generál** az Aspose.BarCode használatával, elmagyarázta a **hogyan állítsuk be az oszlopokat** a vonalkód méretének szabályozásához, és a végeredményt egy tiszta **PDF417 vonalkód képként** PNG formátumban mentette el. A kód önálló, .NET 6+ környezetben működik, és minimális erőfeszítéssel beilleszthető bármely meglévő projektbe. + +Mi következik? Próbálj nagyobb adatcsomagokat kódolni (pl. JSON payloadok), kísérletezz különböző képformátumokkal, vagy integráld a generátort egy web‑API‑ba, amely igény szerint szolgáltat vonalkódokat. A lehetőségek végtelenek, és most már szilárd alapod van a további fejlesztéshez. + +Boldog kódolást, és legyenek a vonalkódjaid mindig első próbálkozásra 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 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 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ód képet Java‑ban az Aspose.BarCode‑dal](/barcode/english/java/barcode-rendering-techniques/) +- [Vonalkód generálás Java – Kép felbontás beállítása az Aspose.BarCode‑dal](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/hungarian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..540c36dcc --- /dev/null +++ b/barcode/hungarian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-07-15 +description: Generálj PDF417 vonalkódot gyorsan C#-ban. Tanuld meg, hogyan generálj + vonalkódot szövegből, állítsd be a vonalkód méretét, és perc alatt állíts be egyedi + vonalkód méreteket. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: hu +lastmod: 2026-07-15 +og_description: PDF417 vonalkód generálása C#-ban azonnal. Ez az útmutató bemutatja, + hogyan lehet szövegből vonalkódot generálni, a vonalkód méretét beállítani, és egyedi + vonalkód-dimenziókat alkalmazni. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: PDF417 vonalkód generálása C#‑ban – Teljes programozási útmutató +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: PDF417 vonalkód generálása C#-ban – Teljes lépésről lépésre útmutató +url: /hu/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-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 – Teljes lépésről‑lépésre útmutató + +Valaha szükséged volt **PDF417 vonalkód generálására**, de nem tudtad, mely beállításokat kell módosítani? Nem vagy egyedül – sok fejlesztő ugyanazzal a problémával szembesül, amikor először 2‑D vonalkódokkal dolgozik. A jó hír? Néhány C# sorral bármilyen karakterláncot átalakíthatsz egy beolvasható PDF417 képpé, pontosan szabályozhatod a méretét, és még egy egyedi oszlop‑sor elrendezést is definiálhatsz. + +Ebben az útmutatóban végigvezetünk a **vonalkód generálásán szövegből**, a vonalkód méretének beállításán, és egyedi vonalkód dimenziók megadásán — mindezt a népszerű Aspose.BarCode könyvtár segítségével. A végére egy kész, futtatható példát kapsz, amelyet bármely .NET projektbe beilleszthetsz. + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## Mit fogsz építeni + +- Egy PDF417 vonalkód, amely a `Åspóse.Barcóde©` karakterláncot kódolja. +- Pontos vezérlés az X‑dimenzió felett (minden modul pixel szélessége). +- Egy egyedi elrendezés 4 oszlop és 9 sor használatával. +- Egy PNG fájl, amely a lemezen kerül mentésre. + +Nincs külső szolgáltatás, nincs varázspálca‑trükk – csak egyszerű C# kód, amelyet most azonnal lefordíthatsz. + +## Előfeltételek + +- .NET 6.0 vagy újabb (a kód .NET Framework 4.8‑on is működik). +- Visual Studio 2022 vagy bármely C#‑ot támogató IDE. +- Aspose.BarCode for .NET (ingyenes próba vagy licencelt verzió). Telepítés NuGet‑en keresztül: + +```bash +dotnet add package Aspose.BarCode +``` + +Ennyi—miután a csomagra hivatkozás megtörtént, már használatra kész vagy. + +## 1. lépés – PDF417 vonalkód generálása szöveges adatokkal + +Az első dolog, amire szükségünk van, egy `BarcodeGenerator` példány, amely tudja, hogy PDF417 szimbólumról van szó, és a pontos szöveget, amelyet kódolni szeretnénk. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Miért fontos:** +> `EncodeTypes.Pdf417` azt mondja a könyvtárnak, hogy a PDF417 2‑D formátumot használja, míg a második argumentum a **vonalkód generálása szövegből** terhelés. Amit ide adsz, az a vonalkód mátrixban tárolt adat lesz. + +## 2. lépés – A vonalkód méretének beállítása (X‑dimenzió) + +Ha valaha nyomtattál egy vonalkódot, amely a nyugtán túl kicsi volt, ismered a szkenner által történő kihagyás frusztrációját. Az `XDimension` tulajdonság szabályozza egyetlen modul (a legkisebb fekete vagy fehér négyzet) pixel szélességét. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Pro tipp:** +> A 2 px érték a legtöbb képernyőn megjelenő esetben jól működik. Magas felbontású nyomatokhoz esetleg 3 vagy 4 px‑re növelheted. Csak ne feledd, hogy a nagyobb X‑dimenziók növelik a kép teljes méretét. + +## 3. lépés – Egyedi vonalkód dimenziók beállítása (oszlopok és sorok) + +A PDF417 lehetővé teszi, hogy meghatározd, hány oszlopot és sort foglaljon el a vonalkód. Itt jönnek képbe az **egyedi vonalkód dimenziók**. Ezeknek az értékeknek a módosítása segíthet a vonalkódot szoros UI‑helyre illeszteni vagy egy adott címkeméretnek megfelelni. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Mi történik a háttérben?** +> A könyvtár újraelosztja a kódolt adatokat a megadott rácson. Kevesebb oszlop magasabb vonalkódot eredményez; több sor alacsonyabbat. Kísérletezz a számokkal, amíg a vizuális egyensúly megfelelőnek tűnik az alkalmazásodban. + +## 4. lépés – A vonalkód kép mentése + +Miután mindent beállítottunk, egyszerűen megkérjük a generátort, hogy egy PNG fájlt írjon. A PNG veszteségmentes, így a modulok élessége megmarad. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +A program futtatásakor a `C:\Barcodes\CustomLayout.png` helyen egy, a fenti képernyőképre hasonló fájlt kell látnod. Bármely PDF417‑kompatibilis olvasóval történő beolvasás visszaadja az eredeti `Åspóse.Barcóde©` karakterláncot. + +## Teljes működő példa + +Az alábbiakban a teljes programot találod, amelyet beilleszthetsz egy konzolos alkalmazásba. Tartalmazza az összes szükséges using direktívát és a gyártási kódban elvárt hibakezelést. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Várható kimenet + +A kód futtatása a következőt írja ki: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…és egy PNG-t hoz létre, amely bármely képnézőben megnyitható. Ha egy mobilalkalmazással (pl. „Barcode Scanner” iOS‑on/Androidon) beolvasod, a dekódolt szövegnek pontosan **Åspóse.Barcóde©**‑nek kell lennie. + +## Gyakori kérdések és szélhelyzetek + +| Question | Answer | +|----------|--------| +| **Használhatok más képformátumot?** | Igen—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` vagy `Svg` mind támogatott. Csak módosítsd a `Save` második argumentumát. | +| **Mi van, ha a szövegem Unicode karaktereket tartalmaz?** | Az Aspose.BarCode teljes mértékben támogatja az UTF‑8‑at, így a `Å` és `©` karaktereket tartalmazó példa azonnal működik. | +| **Hogyan változtathatom meg a hibajavítási szintet?** | Használd a `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` kifejezést (szintek 0‑8). A magasabb szintek növelik a redundanciát, de a méretet is. | +| **Átlátszó háttérre van szükségem – megoldható?** | Állítsd be a `generator.Parameters.Barcode.Image.TransparentBackground = true;` értéket a mentés előtt. | +| **Van mód a vonalkód közvetlenül PDF‑be ágyazására?** | Természetesen. Cseréld le a `Save` hívást erre: `generator.Save("output.pdf", BarCodeImageFormat.Pdf);`, és egy egyoldalas PDF-et kapsz, amely a vonalkódot tartalmazza. | + +## Összegzés + +Most már tudod, hogyan **generálj PDF417 vonalkódot** C#‑ban bármilyen karakterláncból, **állítsd be a vonalkód méretét**, és alkalmazd a **egyedi vonalkód dimenziókat**, hogy illeszkedjenek a layout igényeidhez. A négylépéses folyamat – inicializálás, méret, elrendezés, mentés – lefedi a legtöbb 2‑D vonalkód esetének alapmunkafolyamatát. + +Mi a következő? Próbáld megcserélni a `EncodeTypes.Pdf417`‑t `EncodeTypes.QR`‑re vagy `EncodeTypes.Code128`‑ra, hogy lásd, hogyan alkalmazkodik az API. Kísérletezz különböző `XDimension` értékekkel, játssz az oszlop/sor mátrixszal, vagy ágyazd be a képet egy PDF‑jelentésbe. A lehetőségek gyakorlatilag végtelenek, és most már egy szilárd alapod van a további fejlesztéshez. + +Van még kérdésed, vagy találtál egy ügyes trükköt a PDF417 használata közben? Írj egy megjegyzést alább – tartsuk a beszélgetést folytonosnak. Boldog kódolást! + +## Mit érdemes még megtanulni? + +A következő útmutatók szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás tartalmaz teljesen működő kódrészleteket 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 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/) +- [Hogyan generáljunk vonalkódot – egydimenziós vonalkód típusok](/barcode/english/net/one-dimensional-barcode-types/) +- [DataMatrix vonalkód generálása – Pro útmutató az Aspose.BarCode segítségével](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/hungarian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..2852e4961 --- /dev/null +++ b/barcode/hungarian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,316 @@ +--- +category: general +date: 2026-07-15 +description: Hogyan olvassunk PDF417 vonalkódot C#-ban, és hogyan olvassunk több vonalkódot + egy képről. Tanulja meg, hogyan olvassuk be a vonalkódot C#-ban részletes kóddal + és tippekkel. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: hu +lastmod: 2026-07-15 +og_description: Hogyan olvassuk be gyorsan a PDF417 vonalkódot C#-ban. Ez az útmutató + megmutatja, hogyan olvassunk be több vonalkódot egyetlen képből, és dekódoljuk az + egyes tulajdonságokat. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Hogyan olvassuk a PDF417-et C#-ban – Teljes kódminta és magyarázat +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Hogyan olvassuk a PDF417-et C#‑ban – Teljes lépésről‑lépésre útmutató +url: /hu/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan olvassuk be a PDF417-et C#‑ban – Teljes lépésről‑lépésre útmutató + +Gondolkodtál már azon, **hogyan olvassuk be a PDF417-et** egy képről C#‑ban? Nem vagy egyedül. A legtöbb fejlesztő elakad, amikor egy beolvasott dokumentumból kell kinyerni a kiterjesztett Macro‑PDF417 mezőket. A jó hír? Néhány sor kóddal dekódolhatod a PDF417-et, olvashatsz több vonalkódot ugyanabban a képen, és megszerezheted a specifikáció által kínált minden rejtett tulajdonságot. + +Ebben az útmutatóban egy valós példán keresztül mutatjuk be, hogyan **olvassuk be a PDF417-et**, hogyan **olvassunk több vonalkódot** egyetlen fájlból, és miért néz ki úgy a **read barcode image C#** kód, ahogy. A végére egy azonnal futtatható konzolalkalmazást kapsz, amely kiír minden információt, amire szükséged lehet – fájlazonosító, szegmensazonosító, ellenőrzőösszeg, időbélyegek, stb. + +## Előkövetelmények + +Mielőtt belevágnánk, győződj meg róla, hogy a következők rendelkezésedre állnak: + +* .NET 6.0 SDK vagy újabb (a kód .NET Core‑ral és .NET Framework‑kel is működik). +* Visual Studio 2022 (vagy bármelyik kedvenc szerkesztő). +* **Aspose.BarCode for .NET** NuGet csomag – ez a könyvtár végzi a PDF417 tényleges elemzését. +* Egy minta kép, amely Macro‑PDF417 vonalkódot tartalmaz (például `ExtPDF417Meta.png`). + +Külön konfigurációra nincs szükség; a könyvtár már tartalmazza az összes szükséges dekódert. + +## 1. lépés: Aspose.BarCode telepítése + +Nyisd meg a projekt mappádat egy terminálban, és futtasd: + +```bash +dotnet add package Aspose.BarCode +``` + +Ez a parancs a legújabb stabil verziót (2026. július állása szerint a 23.12‑t) telepíti. Ha a Visual Studio beépített Package Manager Console‑ját részesíted előnyben, használd: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Pro tip:** rögzítsd a verziót (`23.12.0`) a `.csproj` fájlodban, hogy elkerüld a későbbi, esetleg törékeny változásokat. + +## 2. lépés: Konzolalkalmazás váz létrehozása + +Hozz létre egy új konzolprojektet, ha még nincs: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Cseréld le az automatikusan generált `Program.cs` fájlt az alábbi kódra. A következő szakaszokban részletesen elmagyarázzuk minden blokk működését. + +## 3. lépés: A teljes „Hogyan olvassuk be a PDF417-et” kód megírása + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Miért működik ez a kód + +* **`BarCodeReader`** a központi osztály, amely beolvassa a képet, felismeri a vonalkódokat, és egy `BarCodeResult` objektumok gyűjteményét adja vissza. +* A **`DecodeType.MacroPdf417`** megadása azt mondja a könyvtárnak, hogy speciálisan kezelje a Macro‑PDF417‑t; továbbra is egyszerű PDF417 szimbólumokat ad vissza, ami kielégíti a **read multiple barcodes** követelményt. +* A **`Extended.Pdf417.MacroPdf417`** objektum tartalmazza az ISO/IEC 15438 szabvány által definiált minden opcionális mezőt – itt kapod meg a `FileID`, `SegmentID`, `Checksum` stb. értékeket. +* A `using` blokk garantálja a natív erőforrások felszabadítását, megakadályozva a memória‑szivárgást hosszú‑távú szolgáltatásokban. + +## 4. lépés: Az alkalmazás futtatása és a kimenet ellenőrzése + +A terminálból: + +```bash +dotnet run +``` + +A kimenet valami ilyesmi lesz: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Ha a kép több vonalkódot tartalmaz, a ciklus kiír egy elválasztó sort (`----------------------------------------`) és folytatja a következő eredménnyel – pontosan úgy, ahogy a **read multiple barcodes** a gyakorlatban működik. + +## Gyakori kérdések és speciális esetek + +### Mi van, ha a képen egyszerre szerepel Macro‑PDF417 és hagyományos PDF417 szimbólum is? + +Ugyanaz a `BarCodeReader` hívás mindkettőt visszaadja. Megkülönböztetheted őket a `result.CodeType` ellenőrzésével (`MacroPdf417` vs `Pdf417`). A kiterjesztett tulajdonságok `null` értéket kapnak egy egyszerű PDF417‑nél, így az `if (macro != null)` feltétel megakadályozza a `NullReferenceException`‑t. + +### A vonalkódom el van forgatva vagy ferde – a leolvasó még működik? + +Az Aspose.BarCode beépített forgatás‑ és torzítás‑kompenzációval rendelkezik. Amennyiben a vonalkód legalább a kép szélességének 30 %-át elfoglalja, a dekóder általában sikeres. Extrém esetekben engedélyezheted a `reader.Options.AllowInvertedBarcodes = true;` beállítást a `ReadBarCodes()` hívása előtt. + +### Hogyan kezeljek nagy mennyiségű képet? + +A beolvasási logikát helyezd egy `foreach (var file in Directory.GetFiles(folder, "*.png"))` ciklusba. A `using` minta biztosítja, hogy minden kép natív erőforrása felszabadul a következő iteráció előtt, így alacsony marad a memóriahasználat. + +## Teljes forráskód (másolás‑beillesztés kész) + +Az alábbi blokk a teljes programot tartalmazza egyetlen egységben, gyors másoláshoz. Nincsenek rejtett függőségek – csak az Aspose.BarCode NuGet csomag szükséges. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Összefoglalás – Amit megtanultunk + +* **Hogyan olvassuk be a PDF417-et** az Aspose.BarCode segítségével C#‑ban. +* A pontos lépések a **read multiple barcodes** megvalósításához egyetlen képen. +* Hogyan **read barcode image C#** kóddal nyerhetjük ki a Macro‑PDF417 minden mezőjét. +* Tippek forgatás, kötegelt feldolgozás és hiányzó kiterjesztett adatok kezelésére. + +## Következő lépések és kapcsolódó témák + +* **Encode PDF417** – saját Macro‑PDF417 vonalkódok generálása a `BarCodeBuilder`‑rel. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – ugyanazzal a `BarCodeReader` osztállyal. +* **Integrate with ASP.NET Core** – webes végpont létrehozása, amely feltöltött képet fogad, és JSON‑ban visszaadja a dekódolt mezőket. + +Nyugodtan kísérletezz: változtasd meg a kép útvonalát, helyezz egy egyszerű PDF417‑t ugyanabba a mappába, vagy módosítsd a `DecodeType` zászlókat, hogy lásd, hogyan viselkedik a könyvtár. Minél többet játszol vele, annál magabiztosabb leszel a **read barcode image C#** szcenáriókban. + +Van egy nehéz kép, ami nem akar dekódolni? Írj egy megjegyzést alább, vagy nyiss egy issue‑t a minta projekt GitHub repójában. Jó kódolást! + +## Mit érdemes következőként megtanulni? + +Az alábbi oktatóanyagok szorosan kapcsolódnak a jelenlegi témához, és a bemutatott technikákra építenek. Minden forrás teljes, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy könnyedén elsajátíthasd az API további funkcióit, és alternatív megvalósítási megközelítéseket is felfedezhess saját projektjeidben. + +- [Hogyan olvassuk be a DataMatrix vonalkódokat az Aspose.BarCode for .NET‑tel](/barcode/english/net/datamatrix-barcode-reading/) +- [Hogyan hozzunk létre vonalkódot – Compact PDF417 az Aspose.BarCode‑del](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [DataMatrix vonalkód olvasása C#‑ban – DataMatrix mód generálása (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/hungarian/net/one-dimensional-barcode-types/_index.md b/barcode/hungarian/net/one-dimensional-barcode-types/_index.md index 5717cda04..6c1f02a50 100644 --- a/barcode/hungarian/net/one-dimensional-barcode-types/_index.md +++ b/barcode/hungarian/net/one-dimensional-barcode-types/_index.md @@ -69,7 +69,7 @@ Ismerje meg, hogyan szabhatja testre az egydimenziós adatsáv képarányait .NE ### [Egydimenziós adatsor vonalkód magasságállítás](./one-dimensional-databar-barcode-height-adjustment/) Ismerje meg, hogyan állíthatja be az egydimenziós adatsáv vonalkód magasságát az Aspose.BarCode for .NET segítségével. Hozzon létre egyéni vonalkódokat néhány egyszerű lépésben. Fedezze fel a vonalkód testreszabásának erejét. ### [Egydimenziós adattár GS1 kódolás](./one-dimensional-databar-gs1-encoding/) -Ismerje meg a Databar GS1 kódolású vonalkódok létrehozását .NET-ben az Aspose.BarCode segítségével. Generáljon vonalkódokat könnyedén. Kövesse lépésenkénti útmutatónkat. +Ismerje meg a Databar GS1 kódolású vonalkódok létrehozását .NET-ben az Aspose.BarCode segítségével. Generáljon vonalkódokat könnyedén. Kövesse lépésről lépésre útmutatónkat. ### [Egydimenziós adatsorok és oszlopok konfigurációja](./one-dimensional-databar-row-column-configuration/) Dinamikus egydimenziós DataBar vonalkódok létrehozása sor- és oszlopkonfigurációval a .NET-ben az Aspose.BarCode for .NET használatával. A testreszabás egyszerű! ### [Egydimenziós kitöltött rudak konfigurációja](./one-dimensional-filled-bars-configuration/) @@ -78,6 +78,8 @@ megtudhatja, hogyan hozhat létre vonalkódokat .NET-ben az Aspose.BarCode for . Ismerje meg, hogyan kezelheti a kivételeket, miközben egydimenziós vonalkódokat állít elő az Aspose.BarCode for .NET használatával. Ez a lépésenkénti útmutató hibatűrő vonalkód-megoldásokat biztosít. Kezd el most! ### [Egydimenziós széles-keskeny arány konfiguráció](./one-dimensional-wide-narrow-ratio-configuration/) Az Aspose.BarCode for .NET segítségével egyszerűen hozhat létre testreszabott vonalkódokat. Lépésről lépésre útmutató az egydimenziós széles-keskeny arány konfigurációhoz. +### [Szövegből történő vonalkód generálás az Aspose.BarCode segítségével – C# útmutató](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Ismerje meg, hogyan hozhat létre vonalkódot szövegből C#-ban az Aspose.BarCode használatával, lépésről lépésre útmutatóval. ## Következtetés @@ -89,4 +91,4 @@ Ezzel a cikkel nemcsak ismereteket szerezhet a különféle egydimenziós vonalk {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/hungarian/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..2d620cd22 --- /dev/null +++ b/barcode/hungarian/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-07-15 +description: Készítsen vonalkódot szövegből az Aspose.BarCode segítségével C#-ban. + Tanulja meg, hogyan változtathatja meg az oszlopszámot, mentheti a vonalkód képet, + és gyorsan hozhat létre vonalkódos Aspose‑megoldásokat. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: hu +lastmod: 2026-07-15 +og_description: Generáljon vonalkódot szövegből az Aspose.BarCode használatával. Ez + az útmutató bemutatja, hogyan változtathatja meg az oszlopszámot, mentheti a vonalkód + képét, és néhány kódsorral hozhat létre vonalkódot az Aspose segítségével. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Vonalkód generálása szövegből az Aspose.BarCode segítségével – Gyors C# + útmutató +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Vonalkód generálása szövegből az Aspose.BarCode használatával – C# útmutató +url: /hu/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-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 az Aspose.BarCode használatával – C# útmutató + +A szövegből történő vonalkód generálása az Aspose.BarCode segítségével meglepően egyszerű. Ebben az útmutatóban végigvezetünk a **vonalkód generálásának** módján, finomhangoljuk az oszlopelrendezést, és végül **elmentjük a vonalkód képet** PNG fájlként. Akár jegyrendszert, raktári címkenyomtatót építesz, vagy csak QR‑stílusú kódokkal kísérletezel, az alábbi lépések gyorsan eljuttatnak a célhoz. + +## Mit fogsz megtanulni + +- Vonalkód létrehozása bármilyen Unicode karakterláncból (igen, még a “Åspóse.Barcóde©” is működik). +- A **column count** (oszlopszám) beállítása a MicroPdf417-hez, hogy szűk vagy széles címkékhez illeszkedjen. +- Az eredmény mentése lemezre a megfelelő képformátummal. +- Tippek a speciális karakterek kezeléséhez és a gyakori buktatókhoz, amikor **create barcode Aspose** megoldásokat készítesz. + +Nincs szükség külső eszközökre, parancssori trükkökre – csak tiszta C# és az Aspose.BarCode könyvtár. + +## Előfeltételek + +Mielőtt belemerülnénk, győződj meg róla, hogy rendelkezel: + +1. **.NET 6.0** vagy újabb telepítve (a kód a .NET Framework 4.7+ alatt is működik). +2. Egy **license** az Aspose.BarCode-hoz, vagy elindulhatsz az ingyenes értékelő verzióval. +3. Egy mappával, amelybe írhatsz – a példákban `YOUR_DIRECTORY`-nek hívjuk. + +Ha valamelyik hiányzik, szerezd be most a NuGet csomagot: + +```bash +dotnet add package Aspose.BarCode +``` + +Ennyi – nincs szükség extra DLL-ek manuális másolására. + +## 1. lépés – A projekt és az importok beállítása + +Először indíts egy konzolos alkalmazást (vagy illeszd be a kódot bármely C# projektbe). A fontos rész a megfelelő névterek importálása: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Miért ezek a using utasítások? A `BarcodeGenerator` a `Aspose.BarCode.Generation` névtérben található, míg a `BarCodeImageFormat` enum a `Aspose.BarCode` névtérben. A rendezett importok átláthatóbbá teszik a későbbi kódot, mintha egyszerű angol szöveg lenne. + +## 2. lépés – A Barcode Generator létrehozása (hogyan generáljunk vonalkódot) + +Most ténylegesen **vonalkódot generálunk szövegből**. A `EncodeTypes` enum azt mondja meg az Aspose-nak, melyik szimbólumot használja; itt a `MicroPdf417`-et választjuk, mert hosszú karakterláncokat kezel kompakt rácsban. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Vedd észre, hogy a karakterlánc ékezetes betűket és egy szerzői jogi szimbólumot tartalmaz. Az Aspose.BarCode automatikusan kódolja a Unicode-ot, így nem kell előfeldolgozni a szöveget. + +## 3. lépés – A megjelenés finomhangolása (hogyan változtassuk az oszlopszámot) + +A MicroPdf417 lehetővé teszi az oszlopok számának szabályozását, ami közvetlenül befolyásolja a vonalkód szélességét. A szorosabb elrendezés kiváló szűk címkékhez; a szélesebb elrendezés javítja az olvashatóságot nagy nyomatokon. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Miért 2‑pixel modulok? Éles képet ad anélkül, hogy felpörgeznénk a fájlméretet. Nyugodtan kísérletezz – az 1 és 4 közötti értékek általában jól működnek. Ha valaha más oszlopszámra van szükséged, egyszerűen módosítsd a `Columns` tulajdonságot; az Aspose automatikusan újraszámolja az elrendezést. + +## 4. lépés – A vonalkód kép mentése (save barcode image) + +A generátor beállítása után készen állunk a **vonalkód kép mentésére**. A `Save` metódus egy fájlútvonalat és egy képformátum enumot fogad. A PNG veszteségmentes, így a vonalkód még nagyítás után is éles marad. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Gyors tipp: mindig használj abszolút útvonalat, vagy győződj meg róla, hogy a munkakönyvtár a várt helyen van; különben a fájl a bin mappába kerül, és majdnem nem találod. + +## Teljes működő példa + +Összeállítva, itt egy önálló program, amelyet beilleszthetsz a `Program.cs`-be és futtathatsz: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Várható kimenet** (konzol): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +És ha megnyitod a `MicroPdf417.png`-t, egy éles MicroPdf417 vonalkódot látsz, amely a eredeti karakterláncot kódolja, a speciális karakterekkel együtt, amelyeket megadtunk. + +## Gyakori kérdések és speciális esetek + +### Mi van, ha a szövegem hosszabb, mint az alapértelmezett kapacitás? + +A MicroPdf417 automatikusan több soros elrendezésre vált, ha az adat meghaladja a soronkénti maximális mennyiséget. Továbbra is szabályozhatod az oszlopszámot, de a könyvtár a háttérben extra sorokat adhat hozzá. Nem szükséges extra kód – csak figyeld a kapott kép méreteit. + +### Hogyan változtassam meg a képformátumot JPEG-re vagy BMP-re? + +Cseréld le a `BarCodeImageFormat.Png`-t `BarCodeImageFormat.Jpeg`-re (vagy `Bmp`-re). Ne feledd, hogy a JPEG tömörítési hibákat vezet be, ami befolyásolhatja a beolvasás megbízhatóságát. A PNG a legbiztonságosabb alapértelmezett. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Vízjel jelenik meg a kimenetben – mi a probléma? + +Ez az Aspose.BarCode értékelő verziója. A **create barcode Aspose** vízjel nélkül történő használatához tölts be egy érvényes licencfájlt, ahogy a 2. lépés megjegyzett sorában látható. + +### Generálhatok más szimbólumokat (QR, Code128, stb.)? + +Természetesen. Csak cseréld le a `EncodeTypes.MicroPdf417`-t bármely más értékre a `EncodeTypes` enum-ból, például `EncodeTypes.QR` vagy `EncodeTypes.Code128`. A kód többi része változatlan marad, ami nagyon újrahasználhatóvá teszi a megközelítést. + +## Professzionális tippek a termelésre kész vonalkód generáláshoz + +- **Cache the generator** ha sok vonalkódot hozol létre ugyanazzal a beállítással; csökkenti az objektum‑létrehozási terhet. +- **Validate the input string** a választott szimbólumra vonatkozó hosszkorlátozásokra (az Aspose `ArgumentException`-t dob, ha túl hosszú). +- **Use `using` statements** vagy `Dispose` a generátort a használat után, hogy gyorsan felszabadítsd a natív erőforrásokat. +- **Set DPI** a `generator.Parameters.ImageResolution.DpiX/DpiY` segítségével, ha nagy felbontású nyomatokra van szükséged nagy címkéknél. + +## Összegzés + +Most már pontosan tudod, **hogyan generálj vonalkódot szövegből** az Aspose.BarCode segítségével, hogyan **változtasd meg az oszlopszámot**, és a megfelelő módot a **vonalkód kép PNG‑ként való mentésére**. A fenti teljes, futtatható példa egy tiszta, termelésre kész megoldást mutat be + +## Mi legyen a következő tanulnivalód? + +A következő útmutatók 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 generáljunk vonalkódot – Code 39 konfiguráció az Aspose.BarCode-dal](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Vonalkód kép generálása – Code 93 az Aspose.BarCode-dal](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [Hogyan generáljunk DataMatrix vonalkódokat (ECC 200) az Aspose.BarCode for .NET segítségével](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/indonesian/net/compact-pdf417-encoding/_index.md index e49f3f784..096dfb4c3 100644 --- a/barcode/indonesian/net/compact-pdf417-encoding/_index.md +++ b/barcode/indonesian/net/compact-pdf417-encoding/_index.md @@ -77,6 +77,14 @@ Aspose.BarCode memungkinkan Anda mengatur properti `Pdf417ErrorCorrectionLevel` ## Compact PDF417 Encoding Tutorials ### [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. +### [Buat Metadata Barcode PDF417 di C# – Panduan Lengkap Langkah‑per‑Langkah](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +Pelajari cara menambahkan metadata ke barcode PDF417 menggunakan C# dengan Aspose.BarCode, termasuk contoh kode lengkap. +### [Buat Barcode PDF417 di C# – Panduan Lengkap](./generate-pdf417-barcode-in-c-complete-guide/) +Pelajari cara menghasilkan barcode PDF417 menggunakan C# dengan Aspose.BarCode, termasuk contoh kode lengkap. +### [Buat Barcode PDF417 di C# – Panduan Lengkap Langkah‑per‑Langkah](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +Panduan terperinci untuk membuat barcode PDF417 di C# dengan Aspose.BarCode, lengkap dengan contoh kode langkah demi langkah. +### [Cara Membaca PDF417 di C# – Panduan Lengkap Langkah‑per‑Langkah](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) +Pelajari cara membaca barcode PDF417 menggunakan C# dengan Aspose.BarCode, termasuk contoh kode lengkap. ## Frequently Asked Questions @@ -106,4 +114,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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/indonesian/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..9fc85b465 --- /dev/null +++ b/barcode/indonesian/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-07-15 +description: Buat metadata barcode PDF417 dalam C# menggunakan Aspose.BarCode. Pelajari + pengaturan Macro PDF417, simpan sebagai PNG, dan tangani teks Unicode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: id +lastmod: 2026-07-15 +og_description: Buat metadata kode batang PDF417 dalam C# dengan Aspose.BarCode. Panduan + ini menunjukkan setiap pengaturan yang Anda perlukan untuk menyematkan ID file, + cap waktu, dan lainnya. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: Buat Metadata Barcode PDF417 di C# – Panduan Pemrograman Lengkap +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: Buat Metadata Barcode PDF417 di C# – Panduan Langkah-demi-Langkah Lengkap +url: /id/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Membuat Metadata Barcode PDF417 di C# – Panduan Lengkap Langkah‑per‑Langkah + +Pernah perlu **membuat metadata barcode PDF417** di C# tetapi tidak yakin properti mana yang harus diubah? Anda tidak sendirian—para pengembang sering menemui kebingungan ketika spesifikasi menuntut hal‑hal seperti ID file, jumlah segmen, atau timestamp khusus. + +Kabar baiknya, Aspose.BarCode membuat ini menjadi sangat mudah. Dalam tutorial ini kita akan membuat sebuah `BarcodeGenerator` untuk **Macro PDF417**, menambahkan semua metadata penting, dan menyimpan hasilnya sebagai gambar PNG. Pada akhir tutorial Anda akan memiliki barcode lengkap yang siap untuk sistem rantai pasokan atau manajemen dokumen apa pun. + +## Apa yang Dibahas dalam Panduan Ini + +Kita akan meliputi: + +1. Menyiapkan paket NuGet Aspose.BarCode. +2. Menginisialisasi `BarcodeGenerator` untuk **Macro PDF417**. +3. Mengisi setiap **field metadata barcode** yang berguna (file ID, segment ID, checksum, dll.). +4. Menyimpan barcode ke disk dan memverifikasi output. + +Tidak diperlukan pengalaman sebelumnya dengan Macro PDF417—hanya pengetahuan dasar C# dan runtime .NET terbaru. + +Mengapa ini penting? Menyematkan metadata kaya langsung ke dalam barcode memungkinkan pemindai downstream memvalidasi transfer file secara keseluruhan, mendeteksi segmen yang hilang, atau bahkan memicu alur kerja otomatis. Dengan kata lain, Anda mendapatkan **data yang kuat dan self‑describing** tanpa perlu pencarian basis data terpisah. + +## Prasyarat + +- .NET 6.0 atau lebih baru (kode ini juga bekerja pada .NET Framework 4.7+). +- Visual Studio 2022 (atau IDE pilihan Anda). +- Paket NuGet **Aspose.BarCode for .NET** (tersedia trial gratis). + +Anda dapat menginstal paket dengan perintah berikut: + +```bash +dotnet add package Aspose.BarCode +``` + +Setelah fondasi siap, mari masuk ke implementasi sebenarnya. + +## Langkah 1: Inisialisasi BarcodeGenerator untuk Macro PDF417 + +Hal pertama yang kita perlukan adalah sebuah instance `BarcodeGenerator` yang dikonfigurasi untuk **Macro PDF417**. Ini memberi tahu Aspose.BarCode algoritma enkoding mana yang akan dipakai dan menyediakan tempat untuk memasukkan teks yang dapat dibaca manusia. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Mengapa ini penting:** `EncodeTypes.MacroPdf417` mengaktifkan mode PDF417 yang diperluas yang mendukung metadata seperti file ID dan nomor segmen. Teks contoh berisi karakter Unicode (`Å`, `ó`, `©`) untuk membuktikan bahwa generator menangani input non‑ASCII dengan baik. + +## Langkah 2: Tentukan Penampilan Dasar Barcode + +Sebelum menambahkan metadata, kita harus mengatur beberapa parameter visual agar barcode tidak menjadi titik mikroskopik. `XDimension` mengontrol lebar modul, sementara `Columns` memengaruhi bentuk keseluruhan. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Tips pro:** Lebar piksel `2` bekerja baik untuk tampilan layar dan sebagian besar printer. Jika Anda membutuhkan cetakan resolusi lebih tinggi, naikkan menjadi `3` atau `4`. + +## Langkah 3: Isi Field Metadata Macro PDF417 + +Sekarang masuk ke inti tutorial—menambahkan **field metadata barcode**. Setiap properti langsung berhubungan dengan segmen spesifikasi Macro PDF417. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Apa Fungsi Setiap Properti + +| Properti | Tujuan | Nilai Umum | +|----------|--------|------------| +| **MacroPdf417FileID** | Pengidentifikasi unik secara global untuk seluruh set file. | `12345678` | +| **MacroPdf417SegmentID** | Indeks segmen saat ini (dimulai dari `0`). | `12` | +| **MacroPdf417SegmentsCount** | Total segmen yang diharapkan untuk file. | `20` | +| **MacroPdf417FileName** | Nama yang dapat dibaca manusia, biasanya nama file asli. | `"file01"` | +| **MacroPdf417Checksum** | Checksum CCITT 16‑bit untuk deteksi kesalahan. | `1234` | +| **MacroPdf417FileSize** | Ukuran file asli dalam byte. | `400000` | +| **MacroPdf417TimeStamp** | Waktu pembuatan file. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Field opsional yang menunjukkan tujuan. | `"street"` | +| **MacroPdf417Sender** | Field opsional yang menunjukkan sistem sumber. | `"aspose"` | +| **MacroPdf417Terminator** | Flag yang memberi tahu pemindai bahwa ini adalah segmen akhir. | `Pdf417MacroTerminator.Set` | + +> **Mengapa Anda membutuhkannya:** Pemindai yang memahami Macro PDF417 dapat menyusun kembali file multi‑segmen, memverifikasi integritas dengan checksum, dan bahkan menolak data kedaluwarsa berdasarkan timestamp. Ini menghilangkan kebutuhan akan file manifest terpisah. + +## Langkah 4: Simpan Gambar Barcode + +Setelah semua parameter diatur, cukup panggil `Save`. Contoh ini menulis file PNG ke folder yang Anda tentukan. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Kasus tepi:** Jika Anda berencana menyematkan barcode ke dalam PDF nanti, Anda mungkin lebih suka `BarCodeImageFormat.Jpeg` atau `Pdf`. PNG mempertahankan detail lossless, yang berguna untuk verifikasi. + +## Contoh Lengkap yang Berfungsi + +Menggabungkan semuanya, berikut program lengkap yang dapat Anda salin‑tempel ke aplikasi console: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Output yang Diharapkan + +Menjalankan program akan membuat file bernama **ExtPDF417Meta.png** di folder executable. Buka dengan penampil gambar apa pun dan Anda akan melihat barcode PDF417 yang padat dan kontras tinggi. Jika Anda memindainya dengan pembaca barcode yang mendukung Macro PDF417, pemindai akan mengembalikan nilai metadata yang kami set—file ID `12345678`, segmen `12` dari `20`, dan seterusnya. + +## Pertanyaan Umum & Jebakan + +- **Bagaimana jika barcode terlihat buram?** Tingkatkan `XDimension.Pixels` atau beralih ke format gambar resolusi lebih tinggi. +- **Apakah saya harus mengatur semua field metadata?** Tidak. Hanya field yang diperlukan oleh sistem downstream Anda yang wajib diisi. Field yang tidak dipakai dapat dibiarkan dengan nilai default. +- **Bisakah saya menghasilkan file multi‑segmen secara otomatis?** Ya—lakukan loop pada data, tingkatkan `MacroPdf417SegmentID`, dan hasilkan barcode terpisah untuk setiap segmen. Pastikan `MacroPdf417FileID` tetap konsisten di semua segmen. +- **Apakah Unicode didukung?** Tentu saja. Teks contoh berisi `Å`, `ó`, dan `©`, menunjukkan bahwa Aspose.BarCode menangani UTF‑8 secara default. + +## Langkah Selanjutnya: Lebih Dari Dasar + +Setelah Anda tahu cara **membuat metadata barcode PDF417**, Anda mungkin ingin mengeksplor: + +- **Menyematkan barcode ke PDF** menggunakan `Aspose.Pdf` untuk generasi dokumen end‑to‑end. +- **Membaca kembali metadata** dengan `BarcodeReader` untuk memvalidasi pemindaian secara programatik. +- **Menyesuaikan warna** (foreground/background) untuk keperluan branding. +- **Integrasi dengan basis data** untuk mengisi otomatis field seperti `FileID` atau `Timestamp`. + +Semua topik ini kembali ke kata kunci sekunder kami—**macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, dan **c# barcode generation**—sehingga Anda akan menemukan banyak materi untuk terus belajar. + +## Kesimpulan + +Kita baru saja melewati contoh lengkap dan siap produksi tentang cara **membuat metadata barcode PDF417** di C#. Mulai dari menginstal Aspose.BarCode, menginisialisasi `BarcodeGenerator`, mengisi setiap **field metadata barcode** yang relevan, hingga akhirnya menyimpan PNG yang tajam, prosesnya sederhana begitu Anda mengetahui properti yang tepat. + +Cobalah, ubah nilai‑nilainya, dan lihat bagaimana pemindai merespons. Fleksibilitas Macro PDF417 memungkinkan Anda menyematkan semua yang dibutuhkan sistem downstream—semua dalam satu gambar yang dapat dipindai. Selamat coding, semoga barcode Anda selalu bebas error! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap dengan penjelasan langkah‑per‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java barcode library – Add barcode to PDF using Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/indonesian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..f97bba156 --- /dev/null +++ b/barcode/indonesian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: Hasilkan kode batang PDF417 dengan cepat dan pelajari cara mengatur kolom + untuk gambar kode batang PDF417 yang kompak di C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: id +lastmod: 2026-07-15 +og_description: Hasilkan kode batang PDF417 dengan Aspose.BarCode dan pelajari cara + mengatur kolom untuk membuat gambar kode batang PDF417 yang kompak. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: Menghasilkan Barcode PDF417 di C# – Panduan Langkah demi Langkah +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: Menghasilkan Kode Bar PDF417 di C# – Panduan Lengkap +url: /id/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Menghasilkan Barcode PDF417 di C# – Panduan Lengkap + +Pernah perlu **menghasilkan barcode PDF417** dalam proyek .NET tetapi tidak yakin harus mulai dari mana? Anda tidak sendirian. Dalam banyak aplikasi perusahaan—seperti pencetak boarding‑pass, label inventaris, atau tiket seluler—PDF417 adalah pahlawan yang memuat banyak data dalam jejak visual yang kecil. + +Intinya: pustaka Aspose.BarCode membuat seluruh proses hampir tanpa rasa sakit, dan Anda bahkan dapat mengontrol **cara mengatur kolom** sehingga barcode menjadi sekecil mungkin. Pada akhir tutorial ini Anda akan memiliki gambar PNG **barcode PDF417** yang siap pakai dan dapat ditempatkan ke UI mana pun, email, atau pekerjaan cetak. + +## Apa yang Akan Anda Dapatkan + +- Aplikasi konsol C# yang berfungsi penuh untuk membuat barcode PDF417. +- Pemahaman jelas tentang *X‑Dimension* (ukuran modul) dan mengapa itu penting. +- Instruksi langkah‑demi‑langkah tentang **cara mengatur kolom** untuk barcode yang lebih rapat. +- File `PNG` yang disimpan yang dapat Anda buka langsung untuk memverifikasi hasilnya. +- Tips memecahkan masalah umum (mis., barcode tidak terbaca, format gambar salah). + +> **Prasyarat** – .NET 6+ SDK, Visual Studio 2022 (atau editor pilihan Anda), dan referensi NuGet ke `Aspose.BarCode`. Tidak ada yang lain. + +--- + +## Langkah 1: Instal Paket NuGet Aspose.BarCode + +Sebelum kita dapat *menghasilkan barcode PDF417*, pustaka harus ada di proyek. + +```bash +dotnet add package Aspose.BarCode +``` + +Baris tunggal itu menarik semua tipe yang Anda perlukan, termasuk `BarcodeGenerator`, `EncodeTypes`, dan enum `BarCodeImageFormat`. + +> **Tips pro:** Jika Anda menargetkan .NET Framework alih‑alih .NET 6, gunakan perintah PowerShell klasik `Install-Package Aspose.BarCode` di dalam Package Manager Console. + +--- + +## Langkah 2: Buat Aplikasi Konsol Minimal + +Mari susun program kecil yang hanya menghasilkan barcode. Buka folder baru, jalankan `dotnet new console`, lalu ganti `Program.cs` yang dihasilkan secara otomatis dengan kode di bawah ini. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Mengapa ini penting:** +- `EncodeTypes.Pdf417` memberi tahu pustaka bahwa kita menginginkan barcode PDF417, bukan QR atau Code128. +- `XDimension.Pixels` mengontrol resolusi setiap modul hitam atau putih yang sangat kecil. +- Blok **cara mengatur kolom** secara langsung memengaruhi bentuk **gambar barcode PDF417**. +- `Truncate = true` menghilangkan baris kosong yang tidak diperlukan, memberi Anda tampilan “kompak” yang disukai banyak pemindai. + +--- + +## Langkah 3: Selami Lebih Dalam – Memahami Kolom dan Truncation + +### Cara Mengatur Kolom + +PDF417 menyusun data dalam matriks *baris* × *kolom*. Pustaka secara default menggunakan 5 kolom, yang cocok untuk kebanyakan kasus. Namun, Anda mungkin memerlukan barcode yang lebih sempit untuk menyesuaikan label atau yang lebih lebar untuk meningkatkan keandalan pemindaian. Properti: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +menerima nilai dari **1** hingga **30** (batas pasti tergantung pada panjang data). Berikut cheat sheet singkat: + +| Kolom | Lebar Perkiraan (mm) | Kapan Digunakan | +|------|----------------------|-----------------| +| 1‑3 | Sangat sempit | Label kecil, ruang terbatas | +| 4‑6 | Standar | Sebagian besar struk, tiket | +| 7‑10 | Lebih lebar | Data kepadatan tinggi, keterbacaan lebih baik | + +### Truncate (Mode Kompak) + +Menetapkan `Truncate = true` memberi tahu encoder untuk memotong baris kosong yang tidak diperlukan di bagian bawah. Hasilnya adalah **gambar barcode PDF417 kompak** yang menempati area sekecil mungkin sambil tetap berisi semua data. Jika Anda pernah mendapatkan error “barcode terlalu besar untuk label”, alihkan flag ini. + +--- + +## Langkah 4: Jalankan Aplikasi dan Verifikasi Output + +Kompilasi dan eksekusi: + +```bash +dotnet run +``` + +Anda akan melihat pesan konsol yang mengonfirmasi lokasi penyimpanan. Buka folder tersebut dan buka `CompactPdf417.png`. Gambarnya akan terlihat seperti ini: + +![Generated PDF417 barcode image](./CompactPdf417.png "Generated PDF417 barcode image – compact PNG created by Aspose.BarCode") + +*Teks alt gambar:* **Generated PDF417 barcode image** – file PNG kompak yang dihasilkan oleh kode tutorial. + +Jika pemindai Anda dapat membacanya, selamat—Anda telah berhasil **menghasilkan barcode PDF417** dan menguasai **cara mengatur kolom** untuk **gambar barcode PDF417** yang rapi. + +--- + +## Langkah 5: Masalah Umum & Cara Memperbaikinya + +| Gejala | Penyebab Kemungkinan | Perbaikan Cepat | +|--------|----------------------|-----------------| +| Barcode terlihat buram | `XDimension.Pixels` terlalu rendah (mis., 1) | Tingkatkan menjadi 2‑3 piksel untuk gambar yang lebih jelas. | +| Pemindai tidak dapat membaca | Terlalu banyak kolom untuk data yang diberikan | Kurangi `Columns` atau aktifkan `Truncate`. | +| Format file salah | Disimpan dengan `BarCodeImageFormat.Jpeg` secara tidak sengaja | Gunakan `BarCodeImageFormat.Png` untuk hasil lossless. | +| Exception `ArgumentOutOfRangeException` | Jumlah kolom melebihi rentang yang diizinkan | Pertahankan kolom antara 1‑30 dan pastikan data cocok. | + +--- + +## Langkah 6: Lebih Lanjut – Menyesuaikan Warna dan Menambahkan Teks + +Jika Anda ingin barcode cocok dengan palet merek, Anda dapat menyesuaikan warna latar depan dan latar belakang: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Atau menambahkan teks yang dapat dibaca manusia di bawah barcode: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Penambahan ini bersifat opsional, tetapi menunjukkan seberapa fleksibel alur kerja **menghasilkan barcode PDF417** dapat menjadi. + +--- + +## Kesimpulan + +Kami telah menelusuri contoh lengkap end‑to‑end yang **menghasilkan barcode PDF417** menggunakan Aspose.BarCode, menjelaskan **cara mengatur kolom** untuk mengontrol dimensi barcode, dan menyimpan hasilnya sebagai gambar **barcode PDF417** yang tajam dalam format PNG. Kode ini berdiri sendiri, bekerja dengan .NET 6+, dan dapat disisipkan ke proyek apa pun dengan sedikit usaha. + +Apa selanjutnya? Cobalah mengkodekan payload yang lebih besar (mis., payload JSON), bereksperimen dengan format gambar lain, atau integrasikan generator ke dalam API web yang menyajikan barcode sesuai permintaan. Langit adalah batasnya, dan Anda kini memiliki fondasi yang kuat untuk membangunnya. + +Selamat coding, dan semoga barcode Anda selalu dapat dipindai pada percobaan pertama! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan menjelajahi pendekatan implementasi alternatif dalam proyek Anda. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/indonesian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..0e31d306a --- /dev/null +++ b/barcode/indonesian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-07-15 +description: Buat kode batang PDF417 dengan cepat menggunakan C#. Pelajari cara menghasilkan + kode batang dari teks, menyesuaikan ukuran kode batang, dan mengatur dimensi kode + batang khusus dalam hitungan menit. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: id +lastmod: 2026-07-15 +og_description: Hasilkan kode batang PDF417 dalam C# secara instan. Panduan ini menunjukkan + cara menghasilkan kode batang dari teks, menyesuaikan ukuran kode batang, dan menerapkan + dimensi kode batang khusus. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Buat Kode Bar PDF417 di C# – Tutorial Pemrograman Lengkap +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Membuat Kode Barcode PDF417 di C# – Panduan Lengkap Langkah demi Langkah +url: /id/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Membuat Barcode PDF417 di C# – Panduan Lengkap Langkah‑per‑Langkah + +Pernahkah Anda perlu **generate PDF417 barcode** tetapi tidak yakin pengaturan mana yang harus diubah? Anda bukan satu-satunya—banyak pengembang mengalami hal yang sama saat pertama kali bermain dengan barcode 2‑D. Kabar baik? Dengan beberapa baris C# Anda dapat mengubah string apa pun menjadi gambar PDF417 yang dapat dipindai, mengontrol ukuran tepatnya, dan bahkan menentukan tata letak kolom‑baris khusus. + +Dalam tutorial ini kami akan menjelaskan cara **generate barcode from text**, menyesuaikan ukuran barcode, dan mengatur dimensi barcode khusus — semua menggunakan library Aspose.BarCode yang populer. Pada akhir tutorial Anda akan memiliki contoh siap‑jalankan yang dapat Anda masukkan ke proyek .NET mana pun. + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## Apa yang Akan Anda Bangun + +- Sebuah barcode PDF417 yang mengkodekan string `Åspóse.Barcóde©`. +- Kontrol presisi atas X‑dimension (lebar piksel setiap modul). +- Tata letak khusus dengan 4 kolom dan 9 baris. +- File PNG yang disimpan ke disk. + +Tanpa layanan eksternal, tanpa trik tongkat sihir—hanya kode C# biasa yang dapat Anda kompilasi sekarang juga. + +## Prasyarat + +- .NET 6.0 atau lebih baru (kode ini juga berfungsi pada .NET Framework 4.8). +- Visual Studio 2022 atau IDE apa pun yang mendukung C#. +- Aspose.BarCode untuk .NET (versi percobaan gratis atau berlisensi). Instal melalui NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +Itu saja—setelah paket direferensikan Anda siap melanjutkan. + +## Langkah 1 – Generate PDF417 Barcode dengan Data Teks + +Hal pertama yang kita butuhkan adalah sebuah instance `BarcodeGenerator` yang mengetahui bahwa kita menggunakan simbol PDF417 dan teks tepat yang ingin kita enkode. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Mengapa ini penting:** +> `EncodeTypes.Pdf417` memberi tahu library untuk menggunakan format PDF417 2‑D, sementara argumen kedua adalah payload **generate barcode from text**. Apa pun yang Anda berikan di sini menjadi data yang disimpan dalam matriks barcode. + +## Langkah 2 – Sesuaikan Ukuran Barcode (X‑Dimension) + +Jika Anda pernah mencetak barcode yang terlihat terlalu kecil pada struk, Anda tahu frustrasi ketika pemindai tidak dapat menemukannya. Properti `XDimension` mengontrol lebar satu modul (kotak hitam atau putih terkecil) dalam piksel. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Tip pro:** +> Nilai 2 px bekerja dengan baik untuk kebanyakan skenario tampilan layar. Untuk cetakan resolusi tinggi Anda dapat meningkatkan menjadi 3 atau 4 px. Ingatlah bahwa X‑dimension yang lebih besar meningkatkan ukuran gambar secara keseluruhan. + +## Langkah 3 – Atur Dimensi Barcode Kustom (Kolom & Baris) + +PDF417 memungkinkan Anda menentukan berapa banyak kolom dan baris yang harus ditempati barcode. Di sinilah **custom barcode dimensions** berperan. Mengubah nilai-nilai ini dapat membantu Anda menyesuaikan barcode ke ruang UI yang sempit atau memenuhi ukuran label tertentu. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Apa yang terjadi di balik layar?** +> Library mendistribusikan ulang data yang dienkode ke seluruh grid yang ditentukan. Lebih sedikit kolom berarti barcode lebih tinggi; lebih banyak baris membuatnya lebih pendek. Bereksperimenlah dengan angka-angka hingga keseimbangan visual terasa tepat untuk aplikasi Anda. + +## Langkah 4 – Simpan Gambar Barcode + +Sekarang setelah kami mengonfigurasi semuanya, kami cukup meminta generator untuk menulis file PNG. PNG bersifat lossless, sehingga ketajaman modul tetap terjaga. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Saat Anda menjalankan program, Anda akan melihat file di `C:\Barcodes\CustomLayout.png` yang tampak mirip dengan tangkapan layar di atas. Memindainya dengan pembaca yang kompatibel dengan PDF417 apa pun akan mengembalikan string asli `Åspóse.Barcóde©`. + +## Contoh Lengkap yang Berfungsi + +Berikut adalah program lengkap yang dapat Anda salin‑tempel ke aplikasi console. Program ini mencakup semua direktif using dan penanganan error yang Anda harapkan dalam kode produksi. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Output yang Diharapkan + +Menjalankan kode akan mencetak: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…dan membuat PNG yang dapat dibuka di penampil gambar apa pun. Jika Anda memindainya dengan aplikasi seluler (mis., “Barcode Scanner” di iOS/Android), teks yang terdekripsi harus persis **Åspóse.Barcóde©**. + +## Pertanyaan Umum & Kasus Tepi + +| Question | Answer | +|----------|--------| +| **Bisakah saya menggunakan format gambar yang berbeda?** | Ya—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, atau `Svg` semuanya didukung. Cukup ubah argumen kedua dari `Save`. | +| **Bagaimana jika teks saya mengandung karakter Unicode?** | Aspose.BarCode sepenuhnya mendukung UTF‑8, jadi contoh dengan `Å` dan `©` langsung berfungsi. | +| **Bagaimana cara mengubah tingkat koreksi kesalahan?** | Gunakan `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (tingkat 0‑8). Tingkat yang lebih tinggi meningkatkan redundansi tetapi juga ukuran. | +| **Saya membutuhkan latar belakang transparan—apakah bisa?** | Setel `generator.Parameters.Barcode.Image.TransparentBackground = true;` sebelum menyimpan. | +| **Apakah ada cara untuk menyematkan barcode langsung ke PDF?** | Tentu saja. Ganti pemanggilan `Save` dengan `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` dan Anda akan mendapatkan PDF satu halaman yang berisi barcode. | + +## Kesimpulan + +Anda kini tahu cara **generate PDF417 barcode** di C# dari string apa pun, **menyesuaikan ukuran barcode**, dan menerapkan **custom barcode dimensions** untuk memenuhi kebutuhan tata letak Anda. Alur empat langkah—inisialisasi, ukuran, tata letak, simpan—mencakup alur kerja inti untuk kebanyakan skenario barcode 2‑D. + +Apa selanjutnya? Coba ganti `EncodeTypes.Pdf417` dengan `EncodeTypes.QR` atau `EncodeTypes.Code128` untuk melihat bagaimana API beradaptasi. Bereksperimenlah dengan nilai `XDimension` yang berbeda, mainkan matriks kolom/baris, atau sematkan gambar ke dalam laporan PDF. Kemungkinannya hampir tak terbatas, dan kini Anda memiliki fondasi yang kuat untuk membangun. + +Ada pertanyaan lebih lanjut, atau menemukan trik cerdas saat bermain dengan PDF417? Tinggalkan komentar di bawah—mari teruskan diskusi. Selamat coding! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik 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. + +- [Cara menghasilkan barcode Aztec dengan rasio aspek khusus menggunakan Aspose.BarCode untuk .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Cara Menghasilkan Barcode - Jenis Barcode Satu Dimensi](/barcode/english/net/one-dimensional-barcode-types/) +- [Menghasilkan Barcode DataMatrix – Panduan Pro dengan Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/indonesian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..4002c2fce --- /dev/null +++ b/barcode/indonesian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,313 @@ +--- +category: general +date: 2026-07-15 +description: Cara membaca barcode PDF417 dengan C# dan membaca beberapa barcode dari + sebuah gambar. Pelajari cara membaca gambar barcode di C# dengan kode terperinci + dan tips. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: id +lastmod: 2026-07-15 +og_description: Cara membaca kode batang PDF417 di C# dengan cepat. Panduan ini menunjukkan + cara membaca beberapa kode batang dari satu gambar dan mendekode setiap properti. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Cara Membaca PDF417 di C# – Contoh Kode Lengkap & Penjelasan +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Cara Membaca PDF417 di C# – Panduan Lengkap Langkah demi Langkah +url: /id/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-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 Langkah‑per‑Langkah + +Pernah bertanya-tanya **cara membaca PDF417** dari sebuah gambar menggunakan C#? Anda tidak sendirian. Kebanyakan pengembang menemui kendala ketika harus mengambil bidang Macro‑PDF417 yang diperluas dari dokumen yang dipindai. Kabar baiknya? Dengan hanya beberapa baris kode Anda dapat mendekode PDF417, membaca beberapa barcode dalam satu gambar, dan mengambil setiap properti tersembunyi yang ditawarkan spesifikasi. + +Dalam tutorial ini kami akan membahas contoh dunia nyata yang menunjukkan **cara membaca PDF417**, cara **membaca beberapa barcode** dari satu file, dan mengapa kode **read barcode image C#** terlihat seperti itu. Pada akhir tutorial Anda akan memiliki aplikasi console siap‑jalankan yang mencetak setiap informasi yang mungkin Anda perlukan—file ID, segment ID, checksum, timestamp, dan lain‑lain. + +## Prasyarat + +* .NET 6.0 SDK atau yang lebih baru (kode ini bekerja dengan .NET Core dan .NET Framework juga). +* Visual Studio 2022 (atau editor apa pun yang Anda sukai). +* Paket NuGet **Aspose.BarCode for .NET** – ini adalah pustaka yang benar‑benarnya mengurai PDF417. +* Sebuah gambar contoh yang berisi barcode Macro‑PDF417 (misalnya `ExtPDF417Meta.png`). + +Tidak diperlukan konfigurasi tambahan; pustaka ini sudah menyertakan semua decoder yang Anda perlukan. + +## Langkah 1: Instal Aspose.BarCode + +Buka folder proyek Anda di terminal dan jalankan: + +```bash +dotnet add package Aspose.BarCode +``` + +Perintah itu mengambil versi stabil terbaru (per Juli 2026 versi 23.12). Jika Anda lebih suka Package Manager Console di dalam Visual Studio, gunakan: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Tip pro:** kunci versi (`23.12.0`) di file `.csproj` Anda untuk menghindari perubahan yang merusak secara tidak sengaja di kemudian hari. + +## Langkah 2: Buat Kerangka Aplikasi Console + +Buat proyek console baru jika Anda belum memilikinya: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Ganti `Program.cs` yang dihasilkan secara otomatis dengan kode di bawah ini. Kami akan menjelaskan setiap blok pada bagian berikutnya. + +## Langkah 3: Tulis Kode Lengkap “Cara Membaca PDF417” + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Mengapa Kode Ini Berfungsi + +* **`BarCodeReader`** adalah kelas inti yang memproses gambar, mendeteksi barcode, dan mengembalikan koleksi objek `BarCodeResult`. +* Menyertakan **`DecodeType.MacroPdf417`** memberi tahu pustaka untuk memperlakukan Macro‑PDF417 secara khusus; tetap mengembalikan simbol PDF417 biasa, yang memenuhi kebutuhan **read multiple barcodes**. +* Objek **`Extended.Pdf417.MacroPdf417`** menyimpan setiap bidang opsional yang didefinisikan oleh standar ISO/IEC 15438 – di sinilah Anda mendapatkan `FileID`, `SegmentID`, `Checksum`, dll. +* Blok `using` menjamin sumber daya native dibebaskan, mencegah kebocoran memori pada layanan yang berjalan lama. + +## Langkah 4: Jalankan Aplikasi dan Verifikasi Output + +Dari terminal: + +```bash +dotnet run +``` + +Anda akan melihat sesuatu seperti: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Jika gambar berisi lebih dari satu barcode, loop akan mencetak baris pemisah (`----------------------------------------`) dan melanjutkan ke hasil berikutnya—tepat seperti yang terlihat pada **read multiple barcodes** dalam praktik. + +## Pertanyaan Umum & Kasus Tepi + +### Bagaimana jika gambar memiliki simbol Macro‑PDF417 dan PDF417 biasa? + +Pemanggilan `BarCodeReader` yang sama akan mengembalikan keduanya. Anda dapat membedakannya dengan memeriksa `result.CodeType` (`MacroPdf417` vs `Pdf417`). Properti ekstensi akan `null` untuk PDF417 biasa, sehingga pengecekan `if (macro != null)` mencegah `NullReferenceException`. + +### Barcode saya diputar atau miring—apakah pembaca tetap berfungsi? + +Aspose.BarCode menyertakan kompensasi rotasi dan distorsi bawaan. Selama barcode setidaknya 30 % lebar gambar, decoder biasanya berhasil. Untuk kasus ekstrem Anda dapat mengaktifkan `reader.Options.AllowInvertedBarcodes = true;` sebelum memanggil `ReadBarCodes()`. + +### Bagaimana cara menangani batch besar gambar? + +Bungkus logika pembacaan dalam loop `foreach (var file in Directory.GetFiles(folder, "*.png"))`. Pola `using` memastikan sumber daya native setiap gambar dibebaskan sebelum iterasi berikutnya, menjaga penggunaan memori tetap rendah. + +## Daftar Sumber Lengkap (Siap Salin‑Tempel) + +Berikut seluruh program dalam satu blok untuk salin‑tempel cepat. Tidak ada dependensi tersembunyi—hanya paket NuGet Aspose.BarCode. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Ringkasan – Apa yang Telah Dibahas + +* **Cara membaca PDF417** menggunakan Aspose.BarCode di C#. +* Langkah‑langkah tepat untuk **read multiple barcodes** dari satu gambar. +* Cara **read barcode image C#** dan mengekstrak setiap bidang Macro‑PDF417. +* Tips untuk rotasi, pemrosesan batch, dan menangani data ekstensi yang hilang. + +## Langkah Selanjutnya & Topik Terkait + +* **Encode PDF417** – buat barcode Macro‑PDF417 Anda sendiri dengan `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – menggunakan kelas `BarCodeReader` yang sama. +* **Integrate with ASP.NET Core** – expose endpoint web yang menerima gambar yang di‑upload dan mengembalikan JSON dengan bidang yang terdekripsi. + +Silakan bereksperimen: ubah jalur gambar, letakkan PDF417 biasa ke folder yang sama, atau ubah flag `DecodeType` untuk melihat bagaimana pustaka berperilaku. Semakin banyak Anda bermain, semakin nyaman Anda akan menjadi dengan skenario **read barcode image C#**. + +Punya gambar sulit yang tidak dapat didekode? Tinggalkan komentar di bawah atau buka issue di repositori GitHub proyek contoh. Selamat coding! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah‑per‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Cara Membaca Barcode DataMatrix dengan Aspose.BarCode untuk .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Cara Membuat Barcode – Compact PDF417 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/indonesian/net/one-dimensional-barcode-types/_index.md b/barcode/indonesian/net/one-dimensional-barcode-types/_index.md index 7f12b70c9..cef0737c5 100644 --- a/barcode/indonesian/net/one-dimensional-barcode-types/_index.md +++ b/barcode/indonesian/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ dapatkan cara membuat kode batang di .NET dengan Aspose.BarCode untuk .NET. Tuto Pelajari cara menangani pengecualian saat membuat kode batang satu dimensi menggunakan Aspose.BarCode untuk .NET. Panduan langkah demi langkah ini memastikan solusi kode batang yang toleran terhadap kesalahan. Mulai sekarang! ### [Konfigurasi Rasio Lebar-Sempit Satu Dimensi](./one-dimensional-wide-narrow-ratio-configuration/) Hasilkan kode batang khusus dengan mudah menggunakan Aspose.BarCode untuk .NET. Panduan langkah demi langkah untuk konfigurasi rasio lebar-sempit satu dimensi. +### [Menghasilkan barcode dari teks menggunakan Aspose.BarCode – Panduan C#](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Pelajari cara menghasilkan barcode dari teks di .NET menggunakan Aspose.BarCode dengan contoh kode C#. Ikuti panduan langkah demi langkah kami. ## Kesimpulan @@ -89,4 +91,4 @@ Dengan artikel ini, Anda tidak hanya akan memperoleh pengetahuan tentang berbaga {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/indonesian/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..62031ae88 --- /dev/null +++ b/barcode/indonesian/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-07-15 +description: Hasilkan kode batang dari teks menggunakan Aspose.BarCode di C#. Pelajari + cara mengubah jumlah kolom, menyimpan gambar kode batang, dan membuat solusi kode + batang Aspose dengan cepat. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: id +lastmod: 2026-07-15 +og_description: Hasilkan kode batang dari teks menggunakan Aspose.BarCode. Panduan + ini menunjukkan cara mengubah jumlah kolom, menyimpan gambar kode batang, dan membuat + kode batang Aspose dalam beberapa baris kode. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Buat kode batang dari teks dengan Aspose.BarCode – Panduan Cepat C# +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Buat kode batang dari teks menggunakan Aspose.BarCode – Panduan C# +url: /id/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Menghasilkan barcode dari teks menggunakan Aspose.BarCode – Panduan C# + +Menghasilkan barcode dari teks menggunakan Aspose.BarCode ternyata sangat mudah. Pada tutorial ini kita akan membahas **cara menghasilkan barcode**, menyesuaikan tata letak kolom, dan akhirnya **menyimpan gambar barcode** sebagai file PNG. Baik Anda sedang membangun sistem tiket, printer label gudang, atau sekadar bereksperimen dengan kode bergaya QR, langkah‑langkah di bawah ini akan membawa Anda ke sana dengan cepat. + +## Apa yang Akan Anda Pelajari + +- Membuat barcode dari string Unicode apa pun (ya, bahkan “Åspóse.Barcóde©” berfungsi). +- Menyesuaikan **jumlah kolom** untuk MicroPdf417 agar cocok dengan label yang sempit atau lebar. +- Menyimpan hasil ke disk dengan format gambar yang tepat. +- Tips menangani karakter khusus dan jebakan umum saat Anda **membuat barcode Aspose**. + +Tanpa alat eksternal, tanpa hack baris perintah—hanya C# biasa dan pustaka Aspose.BarCode. + +## Prasyarat + +Sebelum kita mulai, pastikan Anda memiliki: + +1. **.NET 6.0** atau yang lebih baru terpasang (kode ini juga bekerja pada .NET Framework 4.7+). +2. **Lisensi** untuk Aspose.BarCode, atau Anda dapat memulai dengan versi evaluasi gratis. +3. Sebuah folder yang dapat ditulisi – kami akan menyebutnya `YOUR_DIRECTORY` dalam contoh. + +Jika Anda belum memiliki salah satu dari ini, unduh paket NuGet sekarang: + +```bash +dotnet add package Aspose.BarCode +``` + +Itu saja—tidak ada DLL tambahan yang harus disalin secara manual. + +## Langkah 1 – Siapkan Proyek dan Impor + +Pertama, buat aplikasi console (atau letakkan kode ini ke proyek C# apa pun). Bagian pentingnya adalah mengimpor namespace yang tepat: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Mengapa menggunakan pernyataan `using` ini? `BarcodeGenerator` berada di `Aspose.BarCode.Generation`, sementara enum `BarCodeImageFormat` berada di `Aspose.BarCode`. Menjaga impor tetap rapi membuat kode selanjutnya terbaca seperti bahasa Inggris biasa. + +## Langkah 2 – Buat Barcode Generator (cara menghasilkan barcode) + +Sekarang kita benar‑benar **menghasilkan barcode dari teks**. Enum `EncodeTypes` memberi tahu Aspose simbol apa yang akan dipakai; di sini kita pilih `MicroPdf417` karena dapat menangani string panjang dalam grid yang kompak. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Perhatikan bahwa string mengandung karakter aksen dan simbol hak cipta. Aspose.BarCode secara otomatis meng‑encode Unicode, jadi Anda tidak perlu memproses teks terlebih dahulu. + +## Langkah 3 – Sesuaikan Penampilan (cara mengubah jumlah kolom) + +MicroPdf417 memungkinkan Anda mengontrol jumlah kolom, yang secara langsung memengaruhi lebar barcode. Tata letak yang lebih rapat cocok untuk label sempit; tata letak yang lebih lebar meningkatkan keterbacaan pada cetakan besar. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Mengapa modul 2‑pixel? Itu menghasilkan gambar yang tajam tanpa memperbesar ukuran file. Silakan bereksperimen—nilai antara 1 dan 4 biasanya bekerja dengan baik. Jika Anda perlu jumlah kolom yang berbeda, cukup ubah properti `Columns`; Aspose akan menghitung ulang tata letak secara otomatis. + +## Langkah 4 – Simpan Gambar Barcode (simpan gambar barcode) + +Setelah generator dikonfigurasi, kita siap **menyimpan gambar barcode**. Metode `Save` menerima jalur file dan enum format gambar. PNG bersifat loss‑less, sehingga barcode tetap tajam meski di‑scale. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Tip cepat: selalu gunakan jalur absolut atau pastikan direktori kerja sesuai harapan; jika tidak, file mungkin berakhir di folder bin dan Anda akan kebingungan mengapa tidak dapat menemukannya. + +## Contoh Lengkap yang Dapat Dijalankan + +Menggabungkan semuanya, berikut program mandiri yang dapat Anda salin‑tempel ke `Program.cs` dan jalankan: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Output yang diharapkan** (console): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +Dan jika Anda membuka `MicroPdf417.png`, Anda akan melihat barcode MicroPdf417 yang tajam yang meng‑encode string asli, lengkap dengan karakter khusus yang kami masukkan. + +## Pertanyaan Umum & Kasus Pinggir + +### Bagaimana jika teks saya lebih panjang dari kapasitas default? + +MicroPdf417 secara otomatis beralih ke tata letak multi‑baris ketika data melebihi maksimum per baris. Anda masih dapat mengontrol jumlah kolom, tetapi pustaka mungkin menambahkan baris ekstra di belakang layar. Tidak perlu kode tambahan—cukup perhatikan dimensi gambar yang dihasilkan. + +### Bagaimana cara mengubah format gambar ke JPEG atau BMP? + +Ganti `BarCodeImageFormat.Png` dengan `BarCodeImageFormat.Jpeg` (atau `Bmp`). Ingat bahwa JPEG menambahkan artefak kompresi, yang dapat memengaruhi keandalan pemindaian. PNG adalah pilihan default yang paling aman. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Saya melihat watermark pada output—apa yang salah? + +Itu adalah versi evaluasi Aspose.BarCode. Untuk **membuat barcode Aspose** tanpa watermark, muat file lisensi yang valid seperti yang ditunjukkan pada baris komentar di Langkah 2. + +### Bisakah saya menghasilkan simbol lain (QR, Code128, dll.)? + +Tentu saja. Cukup ganti `EncodeTypes.MicroPdf417` dengan nilai lain dari enum `EncodeTypes`, misalnya `EncodeTypes.QR` atau `EncodeTypes.Code128`. Sisanya tetap sama, sehingga pendekatan ini sangat dapat digunakan kembali. + +## Tips Profesional untuk Generasi Barcode Siap Produksi + +- **Cache generator** jika Anda membuat banyak barcode dengan pengaturan yang sama; ini mengurangi beban pembuatan objek. +- **Validasi string input** untuk batas panjang yang spesifik pada simbol yang dipilih (Aspose akan melempar `ArgumentException` jika terlalu panjang). +- **Gunakan pernyataan `using`** atau panggil `Dispose` pada generator setelah selesai untuk membebaskan sumber daya native dengan cepat. +- **Atur DPI** melalui `generator.Parameters.ImageResolution.DpiX/DpiY` jika Anda memerlukan cetakan resolusi tinggi untuk label besar. + +## Kesimpulan + +Sekarang Anda sudah tahu **cara menghasilkan barcode dari teks** dengan Aspose.BarCode, **cara mengubah jumlah kolom**, dan cara **menyimpan gambar barcode** sebagai PNG dengan benar. Contoh lengkap yang dapat dijalankan di atas memperlihatkan implementasi bersih yang siap produksi. + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang memperluas teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Generate barcode image – Code 93 with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/italian/net/compact-pdf417-encoding/_index.md index 9fd32044d..9c7348ed9 100644 --- a/barcode/italian/net/compact-pdf417-encoding/_index.md +++ b/barcode/italian/net/compact-pdf417-encoding/_index.md @@ -84,7 +84,19 @@ 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. + +### [Crea metadati del codice a barre PDF417 in C# – Guida completa passo‑per‑step...](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +Scopri come aggiungere e gestire i metadati nei codici a barre PDF417 usando C# e Aspose.BarCode, con esempi pratici passo‑per‑step. + +### [Genera codice a barre PDF417 in C# – Guida completa](./generate-pdf417-barcode-in-c-complete-guide/) +Scopri come generare codici a barre PDF417 in C# con Aspose.BarCode, passo‑per‑passo, includendo esempi di codice e consigli pratici. + +### [Genera codice a barre PDF417 in C# – Guida completa passo‑per‑passo](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +Scopri come generare un codice a barre PDF417 in C# con Aspose.BarCode, seguendo una guida dettagliata passo‑per‑step. + +### [Come leggere PDF417 in C# – Guida completa passo‑per‑step](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) +Scopri come leggere codici a barre PDF417 in C# con Aspose.BarCode, passo‑per‑step, includendo esempi di codice e consigli pratici. ## Domande frequenti @@ -114,4 +126,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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/italian/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..adb4a681a --- /dev/null +++ b/barcode/italian/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-07-15 +description: Crea metadati di codice a barre PDF417 in C# usando Aspose.BarCode. Impara + le impostazioni Macro PDF417, salva come PNG e gestisci il testo Unicode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: it +lastmod: 2026-07-15 +og_description: Crea metadati di codici a barre PDF417 in C# con Aspose.BarCode. Questa + guida mostra tutte le impostazioni necessarie per incorporare ID file, timestamp + e altro. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: Crea metadati del codice a barre PDF417 in C# – Guida completa alla programmazione +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: Crea metadati per il codice a barre PDF417 in C# – Guida completa passo passo +url: /it/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Creare Metadati per Codice a Barre PDF417 in C# – Guida Completa Passo‑Passo + +Hai mai dovuto **creare metadati per codice a barre PDF417** in C# ma non sapevi quali proprietà modificare? Non sei l’unico: gli sviluppatori spesso si trovano in difficoltà quando le specifiche richiedono ID file, conteggio segmenti o timestamp personalizzati. + +La buona notizia è che Aspose.BarCode rende tutto questo un gioco da ragazzi. In questo tutorial avvieremo un `BarcodeGenerator` per **Macro PDF417**, aggiungeremo tutti i metadati importanti e salveremo il risultato come immagine PNG. Alla fine avrai un codice a barre completo, pronto per qualsiasi sistema di supply‑chain o gestione documentale. + +## Cosa Copre Questa Guida + +Affronteremo: + +1. Installazione del pacchetto NuGet Aspose.BarCode. +2. Inizializzazione di un `BarcodeGenerator` per **Macro PDF417**. +3. Popolamento di tutti i **campi di metadati del codice a barre** utili (file ID, segment ID, checksum, ecc.). +4. Salvataggio del codice a barre su disco e verifica dell’output. + +Non è necessaria alcuna esperienza pregressa con Macro PDF417—basta una conoscenza di base di C# e un runtime .NET recente. + +Perché dovresti interessartene? L’inserimento di metadati ricchi direttamente nel codice a barre permette agli scanner a valle di convalidare trasferimenti di file completi, rilevare segmenti mancanti o persino attivare workflow automatizzati. In altre parole, ottieni **dati robusti e auto‑descrittivi** senza dover ricorrere a un database separato. + +## Prerequisiti + +- .NET 6.0 o successivo (il codice funziona anche su .NET Framework 4.7+). +- Visual Studio 2022 (o qualsiasi IDE tu preferisca). +- Il pacchetto NuGet **Aspose.BarCode for .NET** (disponibile una versione di prova gratuita). + +Puoi installare il pacchetto con il seguente comando: + +```bash +dotnet add package Aspose.BarCode +``` + +Ora che abbiamo le basi, immergiamoci nell’implementazione vera e propria. + +## Passo 1: Inizializzare il BarcodeGenerator per Macro PDF417 + +La prima cosa di cui abbiamo bisogno è un’istanza di `BarcodeGenerator` configurata per **Macro PDF417**. Questo indica ad Aspose.BarCode quale algoritmo di codifica utilizzare e ci fornisce un luogo dove inserire il testo leggibile dall’uomo. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Perché è importante:** `EncodeTypes.MacroPdf417` attiva la modalità PDF417 estesa che supporta metadati come ID file e numeri di segmento. Il testo di esempio contiene caratteri Unicode (`Å`, `ó`, `©`) per dimostrare che il generatore gestisce correttamente input non‑ASCII. + +## Passo 2: Definire l’Aspetto Base del Codice a Barre + +Prima di iniziare ad aggiungere i metadati, dovremmo impostare alcuni parametri visivi affinché il codice a barre non sia un puntino microscopico. `XDimension` controlla la larghezza del modulo, mentre `Columns` influenza la forma complessiva. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Consiglio professionale:** Una larghezza di pixel pari a `2` funziona bene per la visualizzazione su schermo e per la maggior parte delle stampanti. Se ti serve una stampa ad alta risoluzione, aumentala a `3` o `4`. + +## Passo 3: Popolare i Campi di Metadati Macro PDF417 + +Ora arriva il cuore del tutorial—l’aggiunta dei **campi di metadati del codice a barre**. Ogni proprietà corrisponde direttamente a una sezione della specifica Macro PDF417. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Cosa Fa Ogni Proprietà + +| Proprietà | Scopo | Valore tipico | +|-----------|-------|---------------| +| **MacroPdf417FileID** | Identificatore univoco globale per l’intero set di file. | `12345678` | +| **MacroPdf417SegmentID** | Indice del segmento corrente (parte da `0`). | `12` | +| **MacroPdf417SegmentsCount** | Numero totale di segmenti attesi per il file. | `20` | +| **MacroPdf417FileName** | Nome leggibile dall’uomo, spesso il nome originale del file. | `"file01"` | +| **MacroPdf417Checksum** | Checksum CCITT a 16 bit per il rilevamento errori. | `1234` | +| **MacroPdf417FileSize** | Dimensione del file originale in byte. | `400000` | +| **MacroPdf417TimeStamp** | Data e ora di generazione del file. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Campo opzionale che indica il destinatario. | `"street"` | +| **MacroPdf417Sender** | Campo opzionale che indica il sistema di origine. | `"aspose"` | +| **MacroPdf417Terminator** | Flag che indica allo scanner che questo è il segmento finale. | `Pdf417MacroTerminator.Set` | + +> **Perché ti servono:** Gli scanner che comprendono Macro PDF417 possono ricomporre un file multi‑segmento, verificare l’integrità con il checksum e persino rifiutare dati obsoleti in base al timestamp. Questo elimina la necessità di un file di manifest separato. + +## Passo 4: Salvare l’Immagine del Codice a Barre + +Una volta impostati tutti i parametri, chiamiamo semplicemente `Save`. L’esempio scrive un file PNG in una cartella da te specificata. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Caso limite:** Se prevedi di incorporare il codice a barre in un PDF in seguito, potresti preferire `BarCodeImageFormat.Jpeg` o `Pdf`. PNG conserva i dettagli senza perdita, utile per la verifica. + +## Esempio Completo Funzionante + +Mettendo tutto insieme, ecco il programma completo che puoi copiare‑incollare in una console app: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Output Atteso + +L’esecuzione del programma crea un file chiamato **ExtPDF417Meta.png** nella cartella dell’eseguibile. Aprilo con qualsiasi visualizzatore di immagini e vedrai un denso codice a barre PDF417 ad alto contrasto. Se lo scansioni con un lettore che supporta Macro PDF417, lo scanner restituirà i valori dei metadati che abbiamo impostato—file ID `12345678`, segmento `12` di `20`, e così via. + +## Domande Frequenti & Trappole + +- **E se il codice a barre appare sfocato?** Aumenta `XDimension.Pixels` o passa a un formato immagine a risoluzione più alta. +- **Devo impostare tutti i campi di metadati?** No. Solo i campi richiesti dal tuo sistema a valle sono obbligatori. I campi inutilizzati possono rimanere ai valori predefiniti. +- **Posso generare automaticamente un file multi‑segmento?** Sì—itera sui dati, incrementa `MacroPdf417SegmentID` e genera un codice a barre separato per ogni segmento. Ricorda di mantenere coerente `MacroPdf417FileID` su tutti i segmenti. +- **Unicode è supportato?** Assolutamente. Il testo di esempio contiene `Å`, `ó` e `©`, dimostrando che Aspose.BarCode gestisce UTF‑8 nativamente. + +## Prossimi Passi: Oltre le Basi + +Ora che sai come **creare metadati per codice a barre PDF417**, potresti voler approfondire: + +- **Incorporare codici a barre in PDF** usando `Aspose.Pdf` per una generazione documentale end‑to‑end. +- **Leggere i metadati** con `BarcodeReader` per convalidare le scansioni programmaticamente. +- **Personalizzare i colori** (foreground/background) per scopi di branding. +- **Integrare con un database** per auto‑popolare campi come `FileID` o `Timestamp`. + +Tutti questi argomenti si collegano alle nostre parole chiave secondarie—**macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, e **c# barcode generation**—quindi troverai molto materiale per continuare a imparare. + +## Conclusione + +Abbiamo appena percorso un esempio completo, pronto per la produzione, su come **creare metadati per codice a barre PDF417** in C#. Dall’installazione di Aspose.BarCode, all’inizializzazione di un `BarcodeGenerator`, al riempimento di ogni **campo di metadati del codice a barre** rilevante, fino al salvataggio di un PNG nitido, il processo è lineare una volta conosciute le proprietà giuste. + +Provalo, modifica i valori e osserva la reazione degli scanner. La flessibilità di Macro PDF417 ti permette di incorporare tutto ciò di cui un sistema a valle ha bisogno—tutto dentro un’unica immagine scansionabile. Buona programmazione, e che i tuoi codici a barre siano sempre privi di errori! + +## 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 con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java barcode library – Add barcode to PDF using Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/italian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..25c1e1e4d --- /dev/null +++ b/barcode/italian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: Genera rapidamente un codice a barre PDF417 e scopri come impostare le + colonne per un'immagine compatta di codice a barre PDF417 in C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: it +lastmod: 2026-07-15 +og_description: Genera il codice a barre PDF417 con Aspose.BarCode e scopri come impostare + le colonne per creare un'immagine compatta del codice a barre PDF417. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: Genera codice a barre PDF417 in C# – Guida passo passo +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: Genera codice a barre PDF417 in C# – Guida completa +url: /it/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generare PDF417 Barcode in C# – Guida Completa + +Hai mai avuto bisogno di **generate PDF417 barcode** in un progetto .NET ma non sapevi da dove cominciare? Non sei solo. In molte applicazioni aziendali—pensa a stampanti di carte d'imbarco, etichette di inventario o ticketing mobile—PDF417 è il cavallo di battaglia che inserisce molti dati in una piccola area visiva. + +Ecco la questione: la libreria Aspose.BarCode rende l'intero processo quasi indolore, e puoi persino controllare **how to set columns** così il codice a barre diventa il più compatto possibile. Alla fine di questo tutorial avrai un'immagine PNG pronta all'uso di un **PDF417 barcode image** che potrai inserire in qualsiasi interfaccia, email o lavoro di stampa. + +## Cosa Otterrai + +- Un'app console C# completamente funzionale che crea un codice a barre PDF417. +- Comprensione chiara della *X‑Dimension* (dimensione del modulo) e del perché è importante. +- Istruzioni passo‑passo su **how to set columns** per un codice a barre più stretto. +- Un file `PNG` salvato che puoi aprire immediatamente per verificare il risultato. +- Suggerimenti per la risoluzione dei problemi comuni (ad esempio, codici a barre illeggibili, formato immagine errato). + +> **Prerequisiti** – .NET 6+ SDK, Visual Studio 2022 (o qualsiasi editor ti piaccia), e un riferimento NuGet a `Aspose.BarCode`. Nient'altro. + +--- + +## Passo 1: Installa il Pacchetto NuGet Aspose.BarCode + +Prima di poter *generate PDF417 barcode*, la libreria deve essere presente nel progetto. + +```bash +dotnet add package Aspose.BarCode +``` + +Quella singola riga importa tutti i tipi di cui avrai bisogno, inclusi `BarcodeGenerator`, `EncodeTypes` e l'enumerazione `BarCodeImageFormat`. + +> **Consiglio professionale:** Se punti a .NET Framework invece di .NET 6, usa il classico comando PowerShell `Install-Package Aspose.BarCode` nella Console di Gestione Pacchetti. + +--- + +## Passo 2: Crea un'Applicazione Console Minima + +Costruiamo una piccola applicazione che non fa altro che generare un codice a barre. Apri una nuova cartella, esegui `dotnet new console`, poi sostituisci il file `Program.cs` generato automaticamente con il codice qui sotto. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Perché è importante:** +- `EncodeTypes.Pdf417` indica alla libreria che vogliamo un codice a barre PDF417, non QR o Code128. +- `XDimension.Pixels` controlla la risoluzione di ogni piccolo modulo nero o bianco. +- Il blocco **how to set columns** influenza direttamente la forma della **PDF417 barcode image**. +- `Truncate = true` elimina tutte le righe vuote non necessarie, fornendoti l'aspetto “compatto” che molti scanner amano. + +--- + +## Passo 3: Approfondisci – Comprendere Colonne e Troncamento + +### Come Impostare le Colonne + +PDF417 organizza i dati in una matrice di *righe* × *colonne*. La libreria usa come predefinito 5 colonne, il che funziona nella maggior parte dei casi. Tuttavia, potresti aver bisogno di un codice a barre più stretto per adattarlo a un'etichetta o più largo per migliorare l'affidabilità della scansione. La proprietà: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +accetta valori da **1** a **30** (il limite esatto dipende dalla lunghezza dei dati). Ecco una rapida tabella di riferimento: + +| Colonne | Larghezza Approx. (mm) | Quando Usare | +|---------|------------------------|--------------| +| 1‑3 | Molto stretta | Etichetta piccola, spazio limitato | +| 4‑6 | Standard | La maggior parte di ricevute, ticket | +| 7‑10 | Più larga | Dati ad alta densità, migliore leggibilità | + +### Truncate (Modalità Compattta) + +Impostare `Truncate = true` indica al codificatore di rimuovere eventuali righe vuote non necessarie nella parte inferiore. Il risultato è una **compact PDF417 barcode image** che occupa l'area più piccola possibile mantenendo tutti i dati. Se dovessi ricevere errori del tipo “barcode too big for label”, attiva/disattiva questo flag. + +--- + +## Passo 4: Esegui l'Applicazione e Verifica l'Uscita + +Compile and execute: + +```bash +dotnet run +``` + +Dovresti vedere il messaggio della console che conferma la posizione di salvataggio. Vai alla cartella e apri `CompactPdf417.png`. L'immagine avrà un aspetto simile a questo: + +![Immagine del codice a barre PDF417 generato](./CompactPdf417.png "Immagine del codice a barre PDF417 generato – PNG compatto creato da Aspose.BarCode") + +*Testo alternativo dell'immagine:* **Immagine del codice a barre PDF417 generato** – un file PNG compatto prodotto dal codice del tutorial. + +Se il tuo scanner riesce a leggerlo, congratulazioni—hai **generate PDF417 barcode** con successo e hai padroneggiato **how to set columns** per una **PDF417 barcode image** ordinata. + +--- + +## Passo 5: Problemi Comuni & Come Risolverli + +| Sintomo | Probabile Causa | Risoluzione Rapida | +|---------|-----------------|--------------------| +| Il codice a barre appare sfocato | `XDimension.Pixels` troppo basso (es., 1) | Aumenta a 2‑3 pixel per un'immagine più chiara. | +| Lo scanner non riesce a leggere | Troppo molte colonne per i dati forniti | Riduci `Columns` o abilita `Truncate`. | +| Formato file errato | Salvato con `BarCodeImageFormat.Jpeg` per errore | Usa `BarCodeImageFormat.Png` per risultati senza perdita. | +| Eccezione `ArgumentOutOfRangeException` | Il conteggio delle colonne supera il range consentito | Mantieni le colonne tra 1‑30 e assicurati che i dati rientrino. | + +--- + +## Passo 6: Approfondire – Personalizzare i Colori e Aggiungere Testo + +Se vuoi far corrispondere il codice a barre a una palette di brand, puoi modificare i colori di primo piano e di sfondo: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Oppure sovrapporre testo leggibile dall'uomo sotto il codice a barre: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Queste aggiunte sono opzionali, ma illustrano quanto sia flessibile il flusso di lavoro **generate PDF417 barcode**. + +--- + +## Conclusione + +Abbiamo attraversato un esempio completo, end‑to‑end, che **generate PDF417 barcode** usando Aspose.BarCode, spiegato **how to set columns** per controllare le dimensioni del codice a barre, e salvato il risultato come una nitida **PDF417 barcode image** in formato PNG. Il codice è autonomo, funziona con .NET 6+, e può essere inserito in qualsiasi progetto esistente con il minimo sforzo. + +Cosa fare dopo? Prova a codificare payload più grandi (ad es., payload JSON), sperimenta con diversi formati immagine, o integra il generatore in una web API che fornisce codici a barre su richiesta. Il cielo è il limite, e ora hai una solida base su cui costruire. + +Buona programmazione, e che i tuoi codici a barre vengano sempre letti al primo tentativo! + +## 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 Creare un Codice a Barre – PDF417 Compatto con Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Come Generare un'Immagine di Codice a Barre in Java con Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Generare Codice a Barre Java – Impostare la Risoluzione dell'Immagine con Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/italian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..4ed4a44dd --- /dev/null +++ b/barcode/italian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-07-15 +description: Genera rapidamente codici a barre PDF417 con C#. Scopri come generare + un codice a barre da testo, regolare le dimensioni del codice a barre e impostare + dimensioni personalizzate in pochi minuti. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: it +lastmod: 2026-07-15 +og_description: Genera codice a barre PDF417 in C# all'istante. Questa guida mostra + come generare il codice a barre dal testo, regolare le dimensioni del codice a barre + e applicare dimensioni personalizzate al codice a barre. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Genera codice a barre PDF417 in C# – Tutorial completo di programmazione +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Genera codice a barre PDF417 in C# – Guida completa passo passo +url: /it/net/compact-pdf417-encoding/generate-pdf417-barcode-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 codice a barre PDF417 in C# – Guida completa passo‑passo + +Hai mai avuto bisogno di **generare un codice a barre PDF417** ma non eri sicuro di quali impostazioni modificare? Non sei l'unico—molti sviluppatori incontrano lo stesso ostacolo quando si avvicinano per la prima volta ai codici a barre 2‑D. La buona notizia? Con poche righe di C# puoi trasformare qualsiasi stringa in un'immagine PDF417 leggibile, controllarne le dimensioni esatte e persino definire un layout personalizzato di colonne‑righe. + +In questo tutorial vedremo come **generare un codice a barre da testo**, regolare le dimensioni del codice a barre e impostare dimensioni personalizzate del codice a barre — tutto usando la popolare libreria Aspose.BarCode. Alla fine avrai un esempio pronto da eseguire che potrai inserire in qualsiasi progetto .NET. + +![Esempio di generazione codice a barre PDF417](https://example.com/og-image.png "Esempio di generazione codice a barre PDF417") + +## Cosa costruirai + +- Un codice a barre PDF417 che codifica la stringa `Åspóse.Barcóde©`. +- Controllo preciso della X‑dimension (larghezza in pixel di ogni modulo). +- Un layout personalizzato di 4 colonne e 9 righe. +- Un file PNG salvato su disco. + +Nessun servizio esterno, nessun trucco magico—solo codice C# puro che puoi compilare subito. + +## Prerequisiti + +- .NET 6.0 o successivo (il codice funziona anche su .NET Framework 4.8). +- Visual Studio 2022 o qualsiasi IDE che supporti C#. +- Aspose.BarCode per .NET (versione di prova gratuita o licenziata). Installa tramite NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +È tutto—una volta referenziato il pacchetto sei pronto per partire. + +## Passo 1 – Generare codice a barre PDF417 con dati di testo + +La prima cosa di cui abbiamo bisogno è un'istanza di `BarcodeGenerator` che sappia che stiamo usando la simbologia PDF417 e il testo esatto che vogliamo codificare. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Perché è importante:** +> `EncodeTypes.Pdf417` indica alla libreria di utilizzare il formato PDF417 2‑D, mentre il secondo argomento è il payload **generate barcode from text**. Qualsiasi cosa tu passi qui diventa il dato memorizzato nella matrice del codice a barre. + +## Passo 2 – Regolare la dimensione del codice a barre (X‑Dimension) + +Se hai mai stampato un codice a barre che sembrava troppo piccolo su uno scontrino, conosci la frustrazione dello scanner che non lo rileva. La proprietà `XDimension` controlla la larghezza di un singolo modulo (il più piccolo quadrato nero o bianco) in pixel. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Consiglio professionale:** +> Un valore di 2 px funziona bene per la maggior parte degli scenari di visualizzazione su schermo. Per stampe ad alta risoluzione potresti aumentarlo a 3 o 4 px. Ricorda solo che X‑dimensioni più grandi aumentano la dimensione complessiva dell'immagine. + +## Passo 3 – Impostare dimensioni personalizzate del codice a barre (Colonne e Righe) + +PDF417 ti permette di specificare quante colonne e righe deve occupare il codice a barre. È qui che entrano in gioco le **custom barcode dimensions**. Modificare questi valori può aiutarti a inserire il codice a barre in uno spazio UI ristretto o a soddisfare una dimensione specifica dell'etichetta. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Cosa succede dietro le quinte?** +> La libreria ridistribuisce i dati codificati sulla griglia specificata. Meno colonne significano codici a barre più alti; più righe li rendono più bassi. Gioca con i numeri finché l'equilibrio visivo non sembra giusto per la tua applicazione. + +## Passo 4 – Salvare l'immagine del codice a barre + +Ora che abbiamo configurato tutto, chiediamo semplicemente al generatore di scrivere un file PNG. PNG è senza perdita, quindi la nitidezza dei moduli rimane intatta. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Quando esegui il programma, dovresti vedere un file in `C:\Barcodes\CustomLayout.png` che appare simile allo screenshot sopra. Scansionandolo con qualsiasi lettore compatibile PDF417 otterrai la stringa originale `Åspóse.Barcóde©`. + +## Esempio completo funzionante + +Di seguito trovi il programma completo che puoi copiare‑incollare in un'app console. Include tutte le direttive using e la gestione degli errori che ti aspetteresti in codice di produzione. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Output previsto + +Running the code prints: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…e crea un PNG che può essere aperto in qualsiasi visualizzatore di immagini. Se lo scansioni con un'app mobile (ad esempio “Barcode Scanner” su iOS/Android), il testo decodificato dovrebbe essere esattamente **Åspóse.Barcóde©**. + +## Domande comuni e casi limite + +| Question | Answer | +|----------|--------| +| **Posso usare un formato immagine diverso?** | Sì—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` o `Svg` sono tutti supportati. Basta cambiare il secondo argomento di `Save`. | +| **E se il mio testo contiene caratteri Unicode?** | Aspose.BarCode supporta pienamente UTF‑8, quindi l'esempio con `Å` e `©` funziona subito. | +| **Come cambio il livello di correzione degli errori?** | Usa `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (livelli 0‑8). Livelli più alti aumentano la ridondanza ma anche le dimensioni. | +| **Ho bisogno di uno sfondo trasparente—è possibile?** | Imposta `generator.Parameters.Barcode.Image.TransparentBackground = true;` prima di salvare. | +| **C'è un modo per incorporare il codice a barre direttamente in un PDF?** | Assolutamente. Sostituisci la chiamata `Save` con `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` e otterrai un PDF di una pagina contenente il codice a barre. | + +## Conclusione + +Ora sai come **generare un codice a barre PDF417** in C# da qualsiasi stringa, **regolare le dimensioni del codice a barre**, e applicare **custom barcode dimensions** per adattarle alle esigenze del tuo layout. Il flusso a quattro passaggi—inizializzare, dimensionare, layout, salvare—copre il flusso di lavoro principale per la maggior parte degli scenari di codici a barre 2‑D. + +Cosa fare dopo? Prova a sostituire `EncodeTypes.Pdf417` con `EncodeTypes.QR` o `EncodeTypes.Code128` per vedere come si adatta l'API. Sperimenta con valori diversi di `XDimension`, gioca con la matrice colonne/righe, o incorpora l'immagine in un report PDF. Le possibilità sono praticamente infinite, e ora hai una solida base su cui costruire. + +Hai altre domande, o hai scoperto un trucco intelligente mentre giocavi con PDF417? Lascia un commento qui sotto—continuiamo la conversazione. Buona programmazione! + +## 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 generare codice a barre Aztec con rapporto d'aspetto personalizzato usando Aspose.BarCode per .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Come generare codice a barre - Tipi di codici a barre unidimensionali](/barcode/english/net/one-dimensional-barcode-types/) +- [Generare codice a barre DataMatrix – Guida Pro con Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/italian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..adb5c29ab --- /dev/null +++ b/barcode/italian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,314 @@ +--- +category: general +date: 2026-07-15 +description: Come leggere il codice a barre PDF417 in C# e leggere più codici a barre + da un'immagine. Impara a leggere immagini di codici a barre in C# con codice dettagliato + e consigli. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: it +lastmod: 2026-07-15 +og_description: Come leggere rapidamente il codice a barre PDF417 in C#. Questa guida + ti mostra come leggere più codici a barre da un'unica immagine e decodificare ogni + proprietà. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Come leggere PDF417 in C# – Esempio di codice completo e spiegazione +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Come leggere PDF417 in C# – Guida completa passo‑passo +url: /it/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-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 passo‑passo + +Ti sei mai chiesto **come leggere PDF417** da un'immagine usando C#? Non sei l'unico. La maggior parte degli sviluppatori si imbatte in un ostacolo quando deve estrarre i campi Macro‑PDF417 estesi da un documento scansionato. La buona notizia? Con poche righe di codice puoi decodificare un PDF417, leggere più codici a barre nella stessa immagine e ottenere tutte le proprietà nascoste offerte dalla specifica. + +In questo tutorial percorreremo un esempio reale che mostra **come leggere PDF417**, come **leggere più codici a barre** da un unico file e perché il codice **read barcode image C#** appare così. Alla fine avrai un'app console pronta all'uso che stampa ogni informazione di cui potresti aver bisogno — ID file, ID segmento, checksum, timestamp, quello che vuoi. + +## Prerequisiti + +* .NET 6.0 SDK o versioni successive (il codice funziona anche con .NET Core e .NET Framework). +* Visual Studio 2022 (o qualsiasi editor tu preferisca). +* Il pacchetto NuGet **Aspose.BarCode for .NET** – è la libreria che effettivamente analizza PDF417. +* Un'immagine di esempio che contiene un codice a barre Macro‑PDF417 (ad esempio `ExtPDF417Meta.png`). + +Non è necessaria alcuna configurazione aggiuntiva; la libreria include tutti i decoder di cui hai bisogno. + +## Passo 1: Installa Aspose.BarCode + +Apri la cartella del tuo progetto in un terminale ed esegui: + +```bash +dotnet add package Aspose.BarCode +``` + +Quel comando scarica l'ultima versione stabile (a luglio 2026 è la 23.12). Se preferisci la Package Manager Console di Visual Studio, usa: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Suggerimento:** blocca la versione (`23.12.0`) nel tuo file `.csproj` per evitare modifiche incompatibili accidentali in futuro. + +## Passo 2: Crea lo scheletro di un'app console + +Crea un nuovo progetto console se non ne hai già uno: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Sostituisci il file `Program.cs` generato automaticamente con il codice qui sotto. Spiegheremo ogni blocco nelle sezioni successive. + +## Passo 3: Scrivi il codice completo “Come leggere PDF417” + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Perché questo codice funziona + +* **`BarCodeReader`** è la classe principale che elabora l'immagine, rileva i codici a barre e restituisce una collezione di oggetti `BarCodeResult`. +* Passare **`DecodeType.MacroPdf417`** indica alla libreria di trattare Macro‑PDF417 in modo speciale; restituisce comunque simboli PDF417 semplici, soddisfacendo il requisito di **read multiple barcodes**. +* L'oggetto **`Extended.Pdf417.MacroPdf417`** contiene tutti i campi opzionali definiti dallo standard ISO/IEC 15438 – è qui che trovi `FileID`, `SegmentID`, `Checksum`, ecc. +* Il blocco `using` garantisce il rilascio delle risorse native, evitando perdite di memoria in servizi a lungo termine. + +## Passo 4: Esegui l'applicazione e verifica l'output + +Dal terminale: + +```bash +dotnet run +``` + +Dovresti vedere qualcosa di simile: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Se l'immagine contiene più di un codice a barre, il ciclo stamperà una linea di separazione (`----------------------------------------`) e continuerà con il risultato successivo — esattamente ciò che **read multiple barcodes** appare nella pratica. + +## Domande comuni e casi particolari + +### E se l'immagine contiene sia simboli Macro‑PDF417 sia PDF417 regolari? + +La stessa chiamata `BarCodeReader` restituirà entrambi. Puoi differenziarli controllando `result.CodeType` (`MacroPdf417` vs `Pdf417`). Le proprietà estese saranno `null` per un PDF417 semplice, quindi la guardia `if (macro != null)` evita una `NullReferenceException`. + +### Il mio codice a barre è ruotato o inclinato — il lettore funzionerà comunque? + +Aspose.BarCode include una compensazione integrata per rotazione e distorsione. Finché il codice a barre occupa almeno il 30 % della larghezza dell'immagine, il decoder di solito riesce. Per casi estremi puoi abilitare `reader.Options.AllowInvertedBarcodes = true;` prima di chiamare `ReadBarCodes()`. + +### Come gestire grandi lotti di immagini? + +Avvolgi la logica di lettura in un ciclo `foreach (var file in Directory.GetFiles(folder, "*.png"))`. Il pattern `using` garantisce che le risorse native di ogni immagine vengano rilasciate prima dell'iterazione successiva, mantenendo basso l'uso di memoria. + +## Elenco completo del codice sorgente (pronto per copia‑incolla) + +Di seguito trovi l'intero programma in un unico blocco per una rapida copia‑incolla. Nessuna dipendenza nascosta — solo il pacchetto NuGet Aspose.BarCode. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Riepilogo – Cosa abbiamo coperto + +* **Come leggere PDF417** usando Aspose.BarCode in C#. +* I passaggi esatti per **leggere più codici a barre** da una singola immagine. +* Come **read barcode image C#** e estrarre ogni campo Macro‑PDF417. +* Suggerimenti per rotazione, elaborazione batch e gestione dei dati estesi mancanti. + +## Prossimi passi e argomenti correlati + +* **Encode PDF417** – genera i tuoi codici a barre Macro‑PDF417 con `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – usando la stessa classe `BarCodeReader`. +* **Integrate with ASP.NET Core** – espone un endpoint web che accetta un'immagine caricata e restituisce JSON con i campi decodificati. + +Sentiti libero di sperimentare: cambia il percorso dell'immagine, inserisci un PDF417 semplice nella stessa cartella o modifica i flag `DecodeType` per vedere come si comporta la libreria. Più giochi, più ti sentirai a tuo agio con gli scenari **read barcode image C#**. + +Hai un'immagine difficile che si rifiuta di decodificare? Lascia un commento qui sotto o apri una issue sul repository GitHub del progetto di esempio. Buon coding! + +## 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à API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Come leggere i codici 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 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/italian/net/one-dimensional-barcode-types/_index.md b/barcode/italian/net/one-dimensional-barcode-types/_index.md index dc08df975..c6c1e292d 100644 --- a/barcode/italian/net/one-dimensional-barcode-types/_index.md +++ b/barcode/italian/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ guadagna come generare codici a barre in .NET con Aspose.BarCode per .NET. Quest Scopri come gestire le eccezioni durante la generazione di codici a barre unidimensionali utilizzando Aspose.BarCode per .NET. Questa guida passo passo garantisce soluzioni per codici a barre tolleranti agli errori. Inizia ora! ### [Configurazione unidimensionale del rapporto largo-stretto](./one-dimensional-wide-narrow-ratio-configuration/) Genera facilmente codici a barre personalizzati con Aspose.BarCode per .NET. Guida passo passo per la configurazione unidimensionale del rapporto largo-stretto. +### [Genera codice a barre da testo con Aspose.BarCode – Guida C#](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Impara a creare codici a barre a partire da testo in C# con Aspose.BarCode. Guida passo passo per una generazione rapida e personalizzabile. ## Conclusione @@ -89,4 +91,4 @@ Con questo articolo non solo acquisirai conoscenze sui vari tipi di codici a bar {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/italian/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..ef4f405bf --- /dev/null +++ b/barcode/italian/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-07-15 +description: Genera codice a barre da testo usando Aspose.BarCode in C#. Scopri come + modificare il conteggio delle colonne, salvare l'immagine del codice a barre e creare + soluzioni di codice a barre Aspose rapidamente. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: it +lastmod: 2026-07-15 +og_description: Genera un codice a barre da testo usando Aspose.BarCode. Questa guida + mostra come modificare il numero di colonne, salvare l'immagine del codice a barre + e creare un codice a barre Aspose in poche righe di codice. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Genera codice a barre da testo con Aspose.BarCode – Guida rapida C# +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Genera codice a barre da testo con Aspose.BarCode – Guida C# +url: /it/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generare codice a barre da testo usando Aspose.BarCode – Guida C# + +Generare un codice a barre da testo usando Aspose.BarCode è sorprendentemente semplice. In questo tutorial vedremo **come generare un codice a barre**, regoleremo il layout delle colonne e infine **salveremo l'immagine del codice a barre** come file PNG. Che tu stia costruendo un sistema di biglietteria, una stampante di etichette per magazzino, o semplicemente sperimentando con codici in stile QR, i passaggi seguenti ti porteranno rapidamente al risultato. + +## Cosa Imparerai + +- Creare un codice a barre da qualsiasi stringa Unicode (sì, anche “Åspóse.Barcóde©” funziona). +- Regolare il **numero di colonne** per MicroPdf417 per adattarsi a etichette strette o larghe. +- Persistere il risultato su disco con il formato immagine appropriato. +- Suggerimenti per gestire caratteri speciali e le insidie comuni quando **crei barcode Aspose** soluzioni. + +Nessuno strumento esterno, nessun trucco da riga di comando—solo puro C# e la libreria Aspose.BarCode. + +## Prerequisiti + +Prima di immergerci, assicurati di avere: + +1. **.NET 6.0** o versioni successive installate (il codice funziona anche su .NET Framework 4.7+). +2. Una **licenza** per Aspose.BarCode, oppure puoi iniziare con la versione di valutazione gratuita. +3. Una cartella in cui puoi scrivere – la chiameremo `YOUR_DIRECTORY` negli esempi. + +Se ti manca qualcuno di questi, scarica subito il pacchetto NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +Tutto qui—nessun DLL extra da copiare manualmente. + +## Passo 1 – Configura il Progetto e le Importazioni + +Per prima cosa, crea un'app console (o inserisci il codice in qualsiasi progetto C#). La parte importante è importare gli spazi dei nomi corretti: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Perché queste istruzioni using? `BarcodeGenerator` si trova in `Aspose.BarCode.Generation`, mentre l'enum `BarCodeImageFormat` è in `Aspose.BarCode`. Mantenere le importazioni ordinate rende il codice successivo leggibile come semplice inglese. + +## Passo 2 – Crea il Generatore di Codice a Barre (come generare barcode) + +Ora generiamo davvero **barcode da testo**. L'enum `EncodeTypes` indica ad Aspose quale simbologia utilizzare; qui scegliamo `MicroPdf417` perché gestisce stringhe lunghe in una griglia compatta. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Nota che la stringa contiene caratteri accentati e un simbolo di copyright. Aspose.BarCode codifica automaticamente Unicode, quindi non è necessario pre‑processare il testo. + +## Passo 3 – Affina l'Aspetto (come cambiare il numero di colonne) + +MicroPdf417 ti permette di controllare il numero di colonne, che influisce direttamente sulla larghezza del codice a barre. Un layout più compatto è ottimo per etichette strette; un layout più ampio migliora la leggibilità su stampe grandi. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Perché moduli da 2 pixel? Forniscono un'immagine nitida senza aumentare eccessivamente le dimensioni del file. Sentiti libero di sperimentare—valori tra 1 e 4 funzionano generalmente bene. Se mai avessi bisogno di un numero di colonne diverso, basta modificare la proprietà `Columns`; Aspose ricalcolerà automaticamente il layout. + +## Passo 4 – Salva l'Immagine del Codice a Barre (salva barcode image) + +Con il generatore configurato, siamo pronti a **salvare l'immagine del barcode**. Il metodo `Save` accetta un percorso file e un enum di formato immagine. PNG è loss‑less, quindi il codice a barre rimane nitido anche dopo lo scaling. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Un suggerimento veloce: usa sempre un percorso assoluto o assicurati che la directory di lavoro sia quella prevista; altrimenti il file potrebbe finire nella cartella bin e ti chiederai perché non riesci a trovarlo. + +## Esempio Completo Funzionante + +Mettendo tutto insieme, ecco un programma autonomo che puoi copiare‑incollare in `Program.cs` ed eseguire: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Output previsto** (console): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +E se apri `MicroPdf417.png`, vedrai un nitido codice a barre MicroPdf417 che codifica la stringa originale, completa dei caratteri speciali che gli abbiamo fornito. + +## Domande Frequenti & Casi Limite + +### E se il mio testo è più lungo della capacità predefinita? + +MicroPdf417 passa automaticamente a un layout multi‑riga quando i dati superano il massimo per riga. Puoi comunque controllare il numero di colonne, ma la libreria potrebbe aggiungere righe extra in background. Non serve codice aggiuntivo—basta tenere d'occhio le dimensioni dell'immagine risultante. + +### Come cambio il formato immagine in JPEG o BMP? + +Sostituisci `BarCodeImageFormat.Png` con `BarCodeImageFormat.Jpeg` (o `Bmp`). Ricorda che JPEG introduce artefatti di compressione, che possono influire sull'affidabilità della scansione. PNG è il valore predefinito più sicuro. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Vedo una filigrana nell'output—cosa c'è di sbagliato? + +Questa è la versione di valutazione di Aspose.BarCode. Per **creare barcode Aspose** senza filigrane, carica un file di licenza valido come mostrato nella riga commentata del Passo 2. + +### Posso generare altre simbologie (QR, Code128, ecc.)? + +Assolutamente. Basta sostituire `EncodeTypes.MicroPdf417` con qualsiasi altro valore dell'enum `EncodeTypes`, ad esempio `EncodeTypes.QR` o `EncodeTypes.Code128`. Il resto del codice rimane invariato, il che rende l'approccio altamente riutilizzabile. + +## Consigli Pro per la Generazione di Codici a Barre Pronti per la Produzione + +- **Cachea il generatore** se crei molti codici a barre con le stesse impostazioni; riduce l'overhead di creazione degli oggetti. +- **Convalida la stringa di input** per i vincoli di lunghezza specifici della simbologia scelta (Aspose lancia `ArgumentException` se è troppo lunga). +- **Usa le istruzioni `using`** o chiama `Dispose` sul generatore al termine per liberare rapidamente le risorse native. +- **Imposta DPI** tramite `generator.Parameters.ImageResolution.DpiX/DpiY` se ti servono stampe ad alta risoluzione per etichette grandi. + +## Conclusione + +Ora sai esattamente **come generare barcode da testo** con Aspose.BarCode, come **cambiare il numero di colonne**, e il modo corretto per **salvare l'immagine del barcode** come PNG. L'esempio completo e eseguibile sopra dimostra un approccio pulito, pronto per la produzione + +## 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à API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Come Generare Codice a Barre – Configurazione Code 39 con Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Genera immagine di codice a barre – Code 93 con Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [Come Generare Codici DataMatrix (ECC 200) con Aspose.BarCode per .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/japanese/net/compact-pdf417-encoding/_index.md index a3cc7ebe8..9ed20fee4 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 バーコードを生成する方法を学びます。ステップバイステップの手順とコード例を含む包括的なガイドです。 +### [C#でPDF417バーコードメタデータを作成する – 完全ステップバイステップガイド](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) + +### [C#でPDF417バーコードを生成する – 完全ガイド](./generate-pdf417-barcode-in-c-complete-guide/) + +### [C#でPDF417バーコードを生成する – 完全ステップバイステップガイド](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) + +### [C#でPDF417を読み取る – 完全ステップバイステップガイド](./how-to-read-pdf417-in-c-complete-step-by-step-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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/japanese/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..9c23eea36 --- /dev/null +++ b/barcode/japanese/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-07-15 +description: Aspose.BarCode を使用して C# で PDF417 バーコードのメタデータを作成します。Macro PDF417 の設定を学び、PNG + として保存し、Unicode テキストを処理します。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: ja +lastmod: 2026-07-15 +og_description: Aspose.BarCode を使用して C# で PDF417 バーコードのメタデータを作成します。このガイドでは、ファイル ID、タイムスタンプなどを埋め込むために必要なすべての設定を示します。 +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: C#でPDF417バーコードメタデータを作成 – フルプログラミングウォークスルー +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: C#でPDF417バーコードメタデータを作成する – 完全ステップバイステップガイド +url: /ja/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で PDF417 バーコードメタデータを作成する – 完全ステップバイステップガイド + +**PDF417 バーコードメタデータ** を C# で作成したいけれど、どのプロパティを設定すればよいか分からないことはありませんか? あなた一人ではありません。開発者は、ファイル ID、セグメント数、カスタムタイムスタンプなど、仕様で求められる項目に壁を感じがちです。 + +良いニュースは、Aspose.BarCode がこの作業をとても簡単にしてくれることです。このチュートリアルでは **Macro PDF417** 用の `BarcodeGenerator` を作成し、重要なメタデータをすべて設定して PNG 画像として保存します。最後には、サプライチェーンや文書管理システムで使える完全なバーコードが手に入ります。 + +## 本ガイドでカバーする内容 + +以下を順に解説します: + +1. Aspose.BarCode NuGet パッケージの導入方法。 +2. **Macro PDF417** 用の `BarcodeGenerator` の初期化。 +3. すべての有用な **バーコードメタデータ フィールド**(ファイル ID、セグメント ID、チェックサムなど)への値設定。 +4. バーコードをディスクに保存し、出力を確認する方法。 + +Macro PDF417 の事前知識は不要です。基本的な C# の知識と最新の .NET ランタイムがあれば始められます。 + +なぜ重要かというと、リッチなメタデータをバーコードに直接埋め込むことで、下流のスキャナーがファイル転送全体を検証したり、欠落セグメントを検出したり、さらには自動ワークフローをトリガーできるようになるからです。言い換えれば、**堅牢で自己記述的なデータ** を別途データベース参照なしで実現できます。 + +## 前提条件 + +- .NET 6.0 以上(.NET Framework 4.7+ でも動作します)。 +- Visual Studio 2022(またはお好みの IDE)。 +- **Aspose.BarCode for .NET** NuGet パッケージ(無料トライアルあり)。 + +以下のコマンドでパッケージをインストールできます: + +```bash +dotnet add package Aspose.BarCode +``` + +これで準備は整いました。実装に進みましょう。 + +## 手順 1: Macro PDF417 用の BarcodeGenerator を初期化 + +まずは **Macro PDF417** 用に設定された `BarcodeGenerator` インスタンスを作成します。これにより Aspose.BarCode が使用すべきエンコーディングアルゴリズムを認識し、人が読めるテキストを供給できるようになります。 + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **ポイント:** `EncodeTypes.MacroPdf417` を指定すると、ファイル ID やセグメント番号といったメタデータをサポートする拡張 PDF417 モードが有効になります。サンプルテキストには Unicode 文字(`Å`, `ó`, `©`)を含め、ジェネレータが非 ASCII 入力を正しく処理できることを示しています。 + +## 手順 2: 基本的なバーコード外観を設定 + +メタデータを追加する前に、バーコードが微細すぎて読めなくならないようにいくつかの視覚パラメータを設定します。`XDimension` はモジュール幅を、`Columns` は全体の形状を決定します。 + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **プロのコツ:** ピクセル幅を `2` にすると、画面表示や多くのプリンターで十分な見やすさが得られます。より高解像度の印刷が必要な場合は `3` や `4` に上げてください。 + +## 手順 3: Macro PDF417 メタデータ フィールドを設定 + +ここが本チュートリアルの核心です — **バーコードメタデータ フィールド** を追加します。各プロパティは Macro PDF417 仕様のセグメントに直接対応しています。 + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### 各プロパティの役割 + +| プロパティ | 目的 | 典型的な値 | +|----------|------|------------| +| **MacroPdf417FileID** | ファイル全体を一意に識別する ID。 | `12345678` | +| **MacroPdf417SegmentID** | 現在のセグメント番号(0 から開始)。 | `12` | +| **MacroPdf417SegmentsCount** | ファイル全体で期待されるセグメント総数。 | `20` | +| **MacroPdf417FileName** | 人が読める名前、通常は元ファイル名。 | `"file01"` | +| **MacroPdf417Checksum** | エラー検出用 16 ビット CCITT チェックサム。 | `1234` | +| **MacroPdf417FileSize** | 元ファイルのバイト数。 | `400000` | +| **MacroPdf417TimeStamp** | ファイルが生成された日時。 | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | 任意の宛先情報。 | `"street"` | +| **MacroPdf417Sender** | 任意の送信元システム情報。 | `"aspose"` | +| **MacroPdf417Terminator** | 最終セグメントであることを示すフラグ。 | `Pdf417MacroTerminator.Set` | + +> **なぜ必要か:** Macro PDF417 を理解したスキャナーは、複数セグメントからなるファイルを再構築し、チェックサムで整合性を検証し、タイムスタンプに基づいて古いデータを拒否できます。これにより別途マニフェストファイルを用意する手間が省けます。 + +## 手順 4: バーコード画像を保存 + +すべてのパラメータ設定が完了したら、`Save` メソッドを呼び出すだけです。例では指定したフォルダーに PNG ファイルを書き出します。 + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **エッジケース:** 後で PDF に埋め込む予定がある場合は、`BarCodeImageFormat.Jpeg` や `Pdf` を選択するとよいでしょう。PNG はロスレスで詳細が保持されるため、検証時に便利です。 + +## 完全動作サンプル + +すべてをまとめたコードは以下の通りです。コンソールアプリにコピー&ペーストして実行できます。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### 期待される出力 + +プログラム実行後、実行ファイルと同じフォルダーに **ExtPDF417Meta.png** が作成されます。任意の画像ビューアで開くと、密度が高くコントラストの強い PDF417 バーコードが表示されます。Macro PDF417 に対応したリーダーでスキャンすると、設定したメタデータ(ファイル ID `12345678`、セグメント `12`/`20` など)が取得できます。 + +## よくある質問と落とし穴 + +- **バーコードがぼやけて見える場合は?** `XDimension.Pixels` を増やすか、解像度の高い画像形式に切り替えてください。 +- **すべてのメタデータ項目を設定する必要がありますか?** 必要なのは下流システムが要求する項目だけです。未使用のフィールドはデフォルトのままで構いません。 +- **マルチセグメントファイルを自動生成できますか?** はい。データをループで処理し、`MacroPdf417SegmentID` をインクリメントして各セグメント用に別々のバーコードを生成します。その際は `MacroPdf417FileID` を全セグメントで統一してください。 +- **Unicode はサポートされていますか?** 完全にサポートされています。サンプルテキストに含まれる `Å`, `ó`, `©` がその証拠です。 + +## 次のステップ: 基礎を超えて + +**PDF417 バーコードメタデータ** の作成方法が分かったら、以下のトピックにも挑戦してみてください。 + +- `Aspose.Pdf` を使って **PDF にバーコードを埋め込む** エンドツーエンドの文書生成。 +- `BarcodeReader` で **メタデータを読み取り、プログラム上で検証**。 +- ブランドカラーに合わせた **前景色・背景色のカスタマイズ**。 +- データベースと連携し、`FileID` や `Timestamp` などのフィールドを自動入力。 + +これらのテーマはすべて、**macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, **c# barcode generation** といったキーワードに結びつきますので、さらなる学習素材が豊富に見つかります。 + +## 結論 + +本稿では、C# で **PDF417 バーコードメタデータ** を作成するための、インストールから `BarcodeGenerator` の初期化、すべての関連 **バーコードメタデータ フィールド** の設定、そして高品質 PNG の保存まで、実践的で本番環境でも使える完全な手順を示しました。 + +ぜひ試してみて、値を調整しながらスキャナーの挙動を確認してください。Macro PDF417 の柔軟性により、下流システムが必要とする情報をすべて 1 つのスキャン可能な画像に埋め込めます。コーディングを楽しみながら、エラーのないバーコードを作成しましょう! + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを応用した関連トピックを扱っています。各リソースには、ステップバイステップの解説と完全なコード例が含まれているので、API の追加機能を習得したり、別の実装アプローチを自分のプロジェクトに取り入れたりするのに役立ちます。 + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java barcode library – Add barcode to PDF using Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/japanese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..c51f06af7 --- /dev/null +++ b/barcode/japanese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,199 @@ +--- +category: general +date: 2026-07-15 +description: PDF417バーコードを素早く生成し、C#でコンパクトなPDF417バーコード画像の列設定方法を学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: ja +lastmod: 2026-07-15 +og_description: Aspose.BarCode を使用して PDF417 バーコードを生成し、列を設定してコンパクトな PDF417 バーコード画像を作成する方法を学びましょう。 +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: C#でPDF417バーコードを生成する – ステップバイステップガイド +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: C#でPDF417バーコードを生成する – 完全ガイド +url: /ja/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で PDF417 バーコードを生成する – 完全ガイド + +.NET プロジェクトで **generate PDF417 barcode** したいと思ったことはありませんか?でも、どこから始めればいいか分からない…という方は多いです。多くのエンタープライズアプリ—例えば搭乗券プリンター、在庫タグ、モバイルチケット—で PDF417 は大量のデータを小さな視覚的フットプリントに詰め込む仕事馬です。 + +ポイントは、Aspose.BarCode ライブラリを使えば、ほぼ手間なく全工程を行えることです。さらに **how to set columns** を制御すれば、バーコードをできるだけコンパクトにできます。このチュートリアルの最後までに、**PDF417 barcode image** の PNG 画像がすぐに使える形で手に入り、任意の UI、メール、印刷ジョブに貼り付けられます。 + +## このチュートリアルで得られるもの + +- PDF417 バーコードを生成する完全に機能する C# コンソール アプリ +- *X‑Dimension*(モジュールサイズ)とその重要性についての明確な理解 +- よりタイトなバーコードのための **how to set columns** に関するステップバイステップの手順 +- 結果をすぐに確認できる保存済み `PNG` ファイル +- 一般的な落とし穴のトラブルシューティングに関するヒント(例:読み取れないバーコード、誤った画像形式) + +> **Prerequisites** – .NET 6+ SDK、Visual Studio 2022(またはお好みのエディタ)、そして `Aspose.BarCode` への NuGet 参照が必要です。それ以外は不要です。 + +## 手順 1: Aspose.BarCode NuGet パッケージをインストールする + +PDF417 バーコードを *generate PDF417 barcode* する前に、ライブラリをプロジェクトに追加する必要があります。 + +```bash +dotnet add package Aspose.BarCode +``` + +その 1 行で、`BarcodeGenerator`、`EncodeTypes`、`BarCodeImageFormat` 列挙体など、必要なすべての型が取得されます。 + +> **Pro tip:** .NET 6 ではなく .NET Framework を対象にする場合は、Package Manager Console 内で従来の `Install-Package Aspose.BarCode` PowerShell コマンドを使用してください。 + +## 手順 2: 最小限のコンソール アプリケーションを作成する + +バーコードを生成するだけの小さなプログラムを作成しましょう。新しいフォルダーを開き、`dotnet new console` を実行し、そして自動生成された `Program.cs` を以下のコードに置き換えます。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Why this matters:** +- `EncodeTypes.Pdf417` は、QR や Code128 ではなく PDF417 バーコードが欲しいことをライブラリに指示します。 +- `XDimension.Pixels` は、各小さな黒または白モジュールの解像度を制御します。 +- **how to set columns** ブロックは、**PDF417 barcode image** の形状に直接影響します。 +- `Truncate = true` は不要な空白行を削除し、多くのスキャナーが好む「コンパクト」な外観を実現します。 + +## 手順 3: 詳細解説 – カラムとトランケーションの理解 + +### カラムの設定方法 + +PDF417 はデータを *rows* × *columns* の行列で配置します。ライブラリのデフォルトは 5 カラムで、ほとんどのケースで機能します。しかし、ラベルに合わせて狭いバーコードが必要だったり、スキャン信頼性向上のために広いバーコードが必要だったりすることがあります。そのプロパティは: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +**1** から **30** までの値を受け入れます(正確な上限はデータ長に依存します)。以下は簡易チートシートです: + +| カラム数 | 概算幅 (mm) | 使用例 | +|----------|------------|--------| +| 1‑3 | 非常に狭い | 小さなラベル、スペースが限られる場合 | +| 4‑6 | 標準 | ほとんどのレシート、チケット | +| 7‑10 | 広め | 高密度データ、読み取りやすさ向上 | + +### トランケート(コンパクトモード) + +`Truncate = true` を設定すると、エンコーダは不要な空白行を下部から削除します。その結果、**compact PDF417 barcode image** が生成され、データをすべて保持しつつ可能な限り最小の領域を占めます。「ラベルに対してバーコードが大きすぎる」エラーが出た場合は、このフラグを切り替えてください。 + +## 手順 4: アプリを実行し、出力を確認する + +コンパイルして実行してください。 + +```bash +dotnet run +``` + +コンソールに保存場所を示すメッセージが表示されます。フォルダーに移動し、`CompactPdf417.png` を開きます。画像は以下のようになります: + +![生成された PDF417 バーコード画像](./CompactPdf417.png "生成された PDF417 バーコード画像 – Aspose.BarCode によって作成されたコンパクト PNG") + +*画像の代替テキスト:* **Generated PDF417 barcode image** – チュートリアルコードで生成されたコンパクト PNG ファイル。 + +スキャナーが読み取れたら、成功です—**generate PDF417 barcode** に成功し、整った **PDF417 barcode image** のための **how to set columns** をマスターしました。 + +## 手順 5: よくある落とし穴と対処法 + +| 症状 | 考えられる原因 | 簡単な対処法 | +|------|----------------|--------------| +| バーコードがぼやけて見える | `XDimension.Pixels` が低すぎる(例: 1) | 2‑3 ピクセルに上げて画像をクリアにする。 | +| スキャナーが読み取れない | データに対してカラム数が多すぎる | `Columns` を減らすか `Truncate` を有効にする。 | +| ファイル形式が間違っている | 誤って `BarCodeImageFormat.Jpeg` で保存した | ロスレスな結果のために `BarCodeImageFormat.Png` を使用する。 | +| 例外 `ArgumentOutOfRangeException` | カラム数が許容範囲を超えている | カラム数を 1‑30 の範囲に保ち、データが収まるようにする。 | + +## 手順 6: さらに進める – 色のカスタマイズとテキストの追加 + +バーコードをブランドのカラーパレットに合わせたい場合は、前景色と背景色を調整できます: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +または、バーコードの下に人が読めるテキストをオーバーレイできます: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +これらの追加はオプションですが、**generate PDF417 barcode** ワークフローがどれだけ柔軟かを示しています。 + +## 結論 + +本稿では、Aspose.BarCode を使用して **generate PDF417 barcode** を行う完全なエンドツーエンドの例を示し、バーコードのサイズを制御する **how to set columns** を解説し、結果を PNG 形式の鮮明な **PDF417 barcode image** として保存しました。コードは自己完結型で、.NET 6+ で動作し、既存のプロジェクトに最小限の手間で組み込めます。 + +次は何をすべきか?より大きなペイロード(例: JSON ペイロード)をエンコードしてみたり、異なる画像形式を試したり、オンデマンドでバーコードを提供する Web API にジェネレータを統合したりしてみてください。可能性は無限で、今やしっかりとした基盤ができました。 + +コーディングを楽しんで、バーコードが常に最初の試みで読み取れますように! + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックを扱っています。各リソースには、ステップバイステップの解説付きの完全な動作コード例が含まれ、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを探求するのに役立ちます。 + +- [Aspose.BarCode を使用したコンパクト PDF417 の作成方法](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Aspose.BarCode を使用した Java でのバーコード画像生成方法](/barcode/english/java/barcode-rendering-techniques/) +- [Aspose.BarCode を使用した Java でのバーコード生成 – 画像解像度の設定](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/japanese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..d28a3fced --- /dev/null +++ b/barcode/japanese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,198 @@ +--- +category: general +date: 2026-07-15 +description: C#でPDF417バーコードを素早く生成しましょう。テキストからバーコードを作成する方法、バーコードサイズの調整、カスタムサイズの設定を数分で学べます。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: ja +lastmod: 2026-07-15 +og_description: C# ですぐに PDF417 バーコードを生成します。このガイドでは、テキストからバーコードを生成する方法、バーコードのサイズを調整する方法、カスタムのバーコード寸法を適用する方法を示します。 +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: C#でPDF417バーコードを生成する – 完全プログラミングチュートリアル +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: C#でPDF417バーコードを生成する – 完全ステップバイステップガイド +url: /ja/net/compact-pdf417-encoding/generate-pdf417-barcode-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# で PDF417 バーコードを生成する – 完全ステップバイステップガイド + +Ever needed to **PDF417 バーコードを生成** but weren’t sure which settings to tweak? You’re not the only one—many developers hit the same wall when they first play with 2‑D barcodes. The good news? With a few lines of C# you can turn any string into a scannable PDF417 image, control its exact size, and even define a custom column‑row layout. + +In this tutorial we’ll walk through how to **テキストからバーコードを生成**, adjust the barcode size, and set custom barcode dimensions — all using the popular Aspose.BarCode library. By the end you’ll have a ready‑to‑run sample you can drop into any .NET project. + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## 作成するもの + +- `Åspóse.Barcóde©` をエンコードする PDF417 バーコード。 +- X‑dimension(各モジュールのピクセル幅)を正確に制御。 +- 4 列 9 行のカスタムレイアウト。 +- ディスクに保存する PNG ファイル。 + +外部サービスや魔法の杖は不要です—今すぐコンパイルできる純粋な C# コードだけです。 + +## 前提条件 + +- .NET 6.0 以降(コードは .NET Framework 4.8 でも動作します)。 +- Visual Studio 2022 または C# をサポートする任意の IDE。 +- Aspose.BarCode for .NET(無料トライアルまたはライセンス版)。NuGet でインストール: + +```bash +dotnet add package Aspose.BarCode +``` + +以上です—パッケージを参照すればすぐに使用できます。 + +## ステップ 1 – テキストデータで PDF417 バーコードを生成 + +最初に必要なのは、PDF417 シンボルを扱い、エンコードしたい正確なテキストを認識する `BarcodeGenerator` のインスタンスです。 + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **なぜ重要か:** +> `EncodeTypes.Pdf417` はライブラリに PDF417 2‑D フォーマットを使用させ、2 番目の引数は **テキストからバーコードを生成** のペイロードです。ここに渡したものすべてがバーコードマトリックスに格納されるデータになります。 + +## ステップ 2 – バーコードサイズの調整(X‑Dimension) + +レシートに印刷したバーコードが小さすぎてスキャナが読み取れなかった経験があるなら、その苛立ちをご存知でしょう。`XDimension` プロパティは、単一モジュール(最小の黒または白の正方形)の幅をピクセル単位で制御します。 + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **プロのコツ:** +> 2 px の値はほとんどの画面表示シナリオでうまく機能します。高解像度印刷の場合は 3 または 4 px に上げても構いません。X‑dimension が大きくなると画像全体のサイズが増えることを覚えておいてください。 + +## ステップ 3 – カスタムバーコード寸法の設定(列と行) + +PDF417 では、バーコードが占める列数と行数を指定できます。ここが **カスタムバーコード寸法** が活躍する場所です。これらの値を変更することで、狭い UI スペースにバーコードを収めたり、特定のラベルサイズに合わせたりできます。 + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **内部で何が起きているか?** +> ライブラリはエンコードされたデータを指定されたグリッドに再配分します。列が少ないとバーコードは縦長になり、行が多いと横長になります。アプリケーションに合う視覚的バランスになるまで数値を調整してください。 + +## ステップ 4 – バーコード画像の保存 + +すべての設定が完了したので、ジェネレータに PNG ファイルを書き出すよう指示するだけです。PNG はロスレスなので、モジュールの鮮明さが保たれます。 + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +プログラムを実行すると、`C:\Barcodes\CustomLayout.png` に上記スクリーンショットと似たファイルが生成されます。PDF417 対応リーダーでスキャンすると、元の文字列 `Åspóse.Barcóde©` が返されます。 + +## 完全動作サンプル + +以下はコンソールアプリにコピー&ペーストできる完全なプログラムです。実運用コードで期待される using ディレクティブとエラーハンドリングがすべて含まれています。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### 期待される出力 + +コードを実行すると次が出力されます: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…そして任意の画像ビューアで開ける PNG が作成されます。モバイルアプリ(例: iOS/Android の “Barcode Scanner”)でスキャンすると、デコードされたテキストは正確に **Åspóse.Barcóde©** になるはずです。 + +## よくある質問とエッジケース + +| Question | Answer | +|----------|--------| +| **別の画像形式を使用できますか?** | はい—`BarCodeImageFormat.Jpeg`、`Bmp`、`Gif`、`Svg` がすべてサポートされています。`Save` の第2引数を変更するだけです。 | +| **テキストに Unicode 文字が含まれている場合はどうなりますか?** | Aspose.BarCode は UTF‑8 を完全にサポートしているため、`Å` や `©` を含む例もそのまま動作します。 | +| **エラー訂正レベルはどう変更しますか?** | `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` を使用します(レベル 0‑8)。レベルが高いほど冗長性が増しますが、サイズも大きくなります。 | +| **透明な背景が必要です—可能ですか?** | 保存する前に `generator.Parameters.Barcode.Image.TransparentBackground = true;` を設定します。 | +| **バーコードを直接 PDF に埋め込む方法はありますか?** | もちろんです。`Save` 呼び出しを `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` に置き換えると、バーコードを含む 1 ページの PDF が得られます。 | + +## 結論 + +これで任意の文字列から C# で **PDF417 バーコードを生成** し、**バーコードサイズを調整**、そして **カスタムバーコード寸法** を適用してレイアウト要件に合わせる方法が分かりました。初期化、サイズ設定、レイアウト、保存の 4 ステップのフローは、ほとんどの 2‑D バーコードシナリオの基本的なワークフローを網羅しています。 + +次は何をしますか? `EncodeTypes.Pdf417` を `EncodeTypes.QR` や `EncodeTypes.Code128` に置き換えて API の挙動を確認してみてください。さまざまな `XDimension` の値を試したり、列/行のマトリックスをいじったり、画像を PDF レポートに埋め込んだりしてみましょう。可能性はほぼ無限で、今やしっかりとした基盤ができました。 + +PDF417 を試していて質問や便利なテクニックを見つけたら、ぜひ下のコメントで教えてください—会話を続けましょう。コーディングを楽しんで! + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックを扱っています。各リソースには、ステップバイステップの解説と完全な動作コード例が含まれており、追加の API 機能を習得し、プロジェクトで代替実装アプローチを探求するのに役立ちます。 + +- [Aspose.BarCode for .NET を使用したカスタムアスペクト比の Aztec バーコード生成方法](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [バーコード生成方法 - 一次元バーコードタイプ](/barcode/english/net/one-dimensional-barcode-types/) +- [DataMatrix バーコード生成 – Aspose.BarCode のプロガイド](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/japanese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..8a683dc4a --- /dev/null +++ b/barcode/japanese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,310 @@ +--- +category: general +date: 2026-07-15 +description: C#でPDF417バーコードを読み取る方法と、画像から複数のバーコードを読み取る方法。詳細なコードとヒントでC#でバーコード画像の読み取りを学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: ja +lastmod: 2026-07-15 +og_description: C#でPDF417バーコードを素早く読み取る方法。このガイドでは、1つの画像から複数のバーコードを読み取り、各プロパティをデコードする手順を示します。 +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: C#でPDF417を読み取る方法 – 完全なコードサンプルと解説 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: C#でPDF417を読み取る方法 – 完全ステップバイステップガイド +url: /ja/net/compact-pdf417-encoding/how-to-read-pdf417-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#でPDF417を読む方法 – 完全ステップバイステップガイド + +C#で画像から **PDF417の読み取り方法** を疑問に思ったことはありませんか? あなただけではありません。多くの開発者は、スキャンしたドキュメントから拡張 Macro‑PDF417 フィールドを取得しようとすると壁にぶつかります。良いニュースは、数行のコードで PDF417 をデコードし、同じ画像内の複数のバーコードを読み取り、仕様が提供するすべての隠れたプロパティを取得できることです。 + +このチュートリアルでは、実際の例を通じて **PDF417の読み取り方法**、単一ファイルから **複数のバーコードを読む方法**、そして **read barcode image C#** コードがそのようになっている理由を解説します。最後まで読むと、ファイル ID、セグメント ID、チェックサム、タイムスタンプなど、必要な情報をすべて出力する実行可能なコンソールアプリが手に入ります。 + +## 前提条件 + +* .NET 6.0 SDK またはそれ以降 (コードは .NET Core および .NET Framework でも動作します)。 +* Visual Studio 2022 (またはお好みのエディタ)。 +* **Aspose.BarCode for .NET** NuGet パッケージ – これは実際に PDF417 を解析するライブラリです。 +* Macro‑PDF417 バーコードを含むサンプル画像 (例: `ExtPDF417Meta.png`)。 + +追加の設定は不要です;ライブラリには必要なデコーダがすべて同梱されています。 + +## ステップ 1: Aspose.BarCode をインストール + +ターミナルでプロジェクトフォルダーを開き、以下を実行します: + +```bash +dotnet add package Aspose.BarCode +``` + +このコマンドは最新の安定版を取得します(2026年7月時点で 23.12)。Visual Studio のパッケージ マネージャ コンソールを使用したい場合は、次を使用してください: + +```powershell +Install-Package Aspose.BarCode +``` + +> **プロのコツ:** 後で予期せぬ破壊的変更を防ぐために、`.csproj` でバージョン (`23.12.0`) を固定してください。 + +## ステップ 2: コンソール アプリの雛形を作成 + +まだ作成していない場合は、新しいコンソール プロジェクトを作成します: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +自動生成された `Program.cs` を以下のコードに置き換えてください。各ブロックは次のセクションで説明します。 + +## ステップ 3: 完全な “PDF417の読み取り方法” コードを書く + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### このコードが機能する理由 + +* **`BarCodeReader`** は画像をストリームし、バーコードを検出し、`BarCodeResult` オブジェクトのコレクションを返すコアクラスです。 +* **`DecodeType.MacroPdf417`** を渡すと、ライブラリは Macro‑PDF417 を特別に扱いますが、依然としてプレーンな PDF417 シンボルを返すため、**read multiple barcodes** の要件を満たします。 +* **`Extended.Pdf417.MacroPdf417`** オブジェクトは ISO/IEC 15438 標準で定義されたすべてのオプションフィールドを保持しており、`FileID`、`SegmentID`、`Checksum` などが取得できます。 +* `using` ブロックはネイティブリソースの解放を保証し、長時間実行されるサービスでのメモリリークを防ぎます。 + +## ステップ 4: アプリケーションを実行し、出力を確認 + +ターミナルから実行します: + +```bash +dotnet run +``` + +以下のような出力が表示されます: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +画像に複数のバーコードが含まれている場合、ループは区切り線 (`----------------------------------------`) を出力し、次の結果に続きます—実際に **read multiple barcodes** がどのように見えるかを正確に示しています。 + +## よくある質問とエッジケース + +### 画像に Macro‑PDF417 と通常の PDF417 シンボルの両方が含まれている場合は? + +同じ `BarCodeReader` 呼び出しで両方が返されます。`result.CodeType` (`MacroPdf417` と `Pdf417`) を確認することで区別できます。プレーンな PDF417 の場合、拡張プロパティは `null` になるため、`if (macro != null)` ガードが `NullReferenceException` を防ぎます。 + +### バーコードが回転または歪んでいる場合、リーダーは動作しますか? + +Aspose.BarCode には回転および歪み補正が組み込まれています。バーコードが画像幅の少なくとも 30 % であれば、デコーダは通常成功します。極端なケースでは、`ReadBarCodes()` を呼び出す前に `reader.Options.AllowInvertedBarcodes = true;` を有効にできます。 + +### 大量の画像バッチを処理するには? + +読み取りロジックを `foreach (var file in Directory.GetFiles(folder, "*.png"))` ループでラップします。`using` パターンにより、次のイテレーションの前に各画像のネイティブリソースが解放され、メモリ使用量が低く抑えられます。 + +## 完全なソースリスト(コピー&ペースト用) + +以下は、すぐにコピー&ペーストできるように 1 つのブロックにまとめたプログラム全体です。隠れた依存関係はなく、Aspose.BarCode NuGet パッケージだけです。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## まとめ – カバーした内容 + +* **How to read PDF417** を Aspose.BarCode と C# で使用する方法。 +* 単一画像から **read multiple barcodes** を行う正確な手順。 +* **read barcode image C#** の方法とすべての Macro‑PDF417 フィールドの抽出方法。 +* 回転、バッチ処理、拡張データが欠落している場合の対処法に関するヒント。 + +## 次のステップと関連トピック + +* **Encode PDF417** – `BarCodeBuilder` を使用して独自の Macro‑PDF417 バーコードを生成します。 +* **Read other 2‑D symbologies** – 同じ `BarCodeReader` クラスを使用して QR、DataMatrix、Aztec を読み取ります。 +* **Integrate with ASP.NET Core** – アップロードされた画像を受け取り、デコードされたフィールドを含む JSON を返す Web エンドポイントを公開します。 + +自由に実験してください:画像パスを変更したり、同じフォルダーにプレーンな PDF417 を置いたり、`DecodeType` フラグを調整してライブラリの挙動を確認したりできます。試せば試すほど、**read barcode image C#** シナリオに慣れるでしょう。 + +デコードできない厄介な画像がありますか?下にコメントを残すか、サンプルプロジェクトの GitHub リポジトリで issue を作成してください。ハッピーコーディング! + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックをカバーしています。各リソースには、ステップバイステップの解説付きの完全な動作コード例が含まれており、追加の 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/japanese/net/one-dimensional-barcode-types/_index.md b/barcode/japanese/net/one-dimensional-barcode-types/_index.md index 5127ab85a..95252acf5 100644 --- a/barcode/japanese/net/one-dimensional-barcode-types/_index.md +++ b/barcode/japanese/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ Aspose.BarCode for .NET を使用して .NET でバーコードを生成する Aspose.BarCode for .NET を使用して 1 次元バーコードを生成する際に例外を処理する方法を学びます。このステップバイステップのガイドは、エラー耐性のあるバーコード ソリューションを保証します。今すぐ始めましょう! ### [1 次元のワイド/ナロー比構成](./one-dimensional-wide-narrow-ratio-configuration/) Aspose.BarCode for .NET を使用して、カスタマイズされたバーコードを簡単に生成します。 1 次元のワイド/ナロー比構成のステップバイステップ ガイド。 +### [Aspose.BarCode を使用してテキストからバーコードを生成する – C# ガイド](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Aspose.BarCode と C# を使って、テキストからバーコードを作成する手順をステップバイステップで解説します。 ## 結論 @@ -89,4 +91,4 @@ Aspose.BarCode for .NET を使用して、カスタマイズされたバーコ {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/japanese/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..08530bd47 --- /dev/null +++ b/barcode/japanese/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-07-15 +description: C# で Aspose.BarCode を使用してテキストからバーコードを生成します。列数の変更方法、バーコード画像の保存方法、そして高速にバーコード + Aspose ソリューションを作成する方法を学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: ja +lastmod: 2026-07-15 +og_description: Aspose.BarCode を使用してテキストからバーコードを生成します。このガイドでは、列数の変更、バーコード画像の保存、数行のコードで + Aspose バーコードを作成する方法を示します。 +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Aspose.BarCodeでテキストからバーコードを生成 – 簡単C#チュートリアル +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Aspose.BarCode を使用してテキストからバーコードを生成する – C# ガイド +url: /ja/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# テキストからバーコードを生成する Aspose.BarCode – C# ガイド + +Aspose.BarCode を使用してテキストからバーコードを生成するのは驚くほど簡単です。このチュートリアルでは **バーコードの生成方法** を順に説明し、列レイアウトを調整し、最後に **バーコード画像を PNG ファイルとして保存** します。チケットシステム、倉庫ラベルプリンターの構築、あるいは QR スタイルのコードを試すだけでも、以下の手順で素早く実現できます。 + +## 学べること + +- 任意の Unicode 文字列からバーコードを作成する(例: “Åspóse.Barcóde©” でも動作します)。 +- MicroPdf417 の **列数** を調整して、狭いラベルや広いラベルに合わせる。 +- 適切な画像形式で結果をディスクに保存する。 +- 特殊文字の取り扱いや、**create barcode Aspose** ソリューションでの一般的な落とし穴に関するヒント。 + +外部ツールやコマンドラインハックは不要です—純粋な C# と Aspose.BarCode ライブラリだけです。 + +## 前提条件 + +ダイブする前に、以下が揃っていることを確認してください: + +1. **.NET 6.0** 以上がインストールされていること(コードは .NET Framework 4.7+ でも動作します)。 +2. Aspose.BarCode の **ライセンス**、または無料評価版で開始できます。 +3. 書き込み可能なフォルダー – 例では `YOUR_DIRECTORY` と呼びます。 + +これらのいずれかが不足している場合は、今すぐ NuGet パッケージを取得してください: + +```bash +dotnet add package Aspose.BarCode +``` + +以上です—手動でコピーする余分な DLL はありません。 + +## Step 1 – プロジェクトとインポートの設定 + +まず、コンソールアプリを作成します(または任意の C# プロジェクトにコードを貼り付けても構いません)。重要なのは正しい名前空間をインポートすることです: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +なぜこれらの using 文が必要かというと、`BarcodeGenerator` は `Aspose.BarCode.Generation` に、`BarCodeImageFormat` 列挙型は `Aspose.BarCode` に存在するからです。インポートを整理しておくと、後のコードが自然な英語のように読めます。 + +## Step 2 – バーコードジェネレーターの作成 (バーコードの生成方法) + +ここで実際に **テキストからバーコードを生成** します。`EncodeTypes` 列挙型は Aspose に使用するシンボロジーを指示します。ここでは長い文字列をコンパクトなグリッドで扱える `MicroPdf417` を選択しています。 + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +文字列にアクセント付き文字や著作権記号が含まれていることに注意してください。Aspose.BarCode は Unicode を自動的にエンコードするため、テキストを事前に処理する必要はありません。 + +## Step 3 – 外観の微調整 (列数の変更方法) + +MicroPdf417 では列数を制御でき、これがバーコードの幅に直接影響します。狭いラベルにはタイトなレイアウトが適し、広いラベルでは可読性が向上します。 + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +なぜ 2 ピクセルモジュールかというと、ファイルサイズを増やさずに鮮明な画像が得られるからです。1〜4 の範囲で試してみても通常はうまく動作します。別の列数が必要な場合は `Columns` プロパティを変更すれば、Aspose が自動的にレイアウトを再計算します。 + +## Step 4 – バーコード画像の保存 (バーコード画像の保存) + +ジェネレーターの設定が完了したので、**バーコード画像を保存**する準備ができました。`Save` メソッドはファイルパスと画像形式の列挙型を受け取ります。PNG はロスレスなので、拡大縮小してもバーコードは鮮明です。 + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +ちょっとしたコツ: 常に絶対パスを使用するか、作業ディレクトリが期待通りであることを確認してください。そうしないとファイルが bin フォルダーに出力され、見つからないことがあります。 + +## 完全な動作例 + +すべてをまとめると、`Program.cs` にコピー&ペーストして実行できる自己完結型プログラムは以下の通りです: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**期待される出力**(コンソール): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +`MicroPdf417.png` を開くと、元の文字列と特殊文字をエンコードした鮮明な MicroPdf417 バーコードが表示されます。 + +## よくある質問とエッジケース + +### テキストがデフォルト容量を超える場合はどうしますか? + +データが1行あたりの最大量を超えると、MicroPdf417 は自動的にマルチロウレイアウトに切り替わります。列数は引き続き制御できますが、ライブラリが裏で追加の行を生成することがあります。追加のコードは不要で、結果画像のサイズを確認してください。 + +### 画像形式を JPEG や BMP に変更するには? + +`BarCodeImageFormat.Png` を `BarCodeImageFormat.Jpeg`(または `Bmp`)に置き換えます。JPEG は圧縮アーティファクトを生むため、スキャンの信頼性に影響する可能性があります。PNG が最も安全なデフォルトです。 + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### 出力に透かしが表示されます—何が問題ですか? + +これは Aspose.BarCode の評価版です。透かしなしで **create barcode Aspose** するには、Step 2 のコメント行に示すように有効なライセンスファイルをロードしてください。 + +### 他のシンボロジー(QR、Code128 など)も生成できますか? + +もちろんです。`EncodeTypes.MicroPdf417` を `EncodeTypes` 列挙型の他の値(例: `EncodeTypes.QR` や `EncodeTypes.Code128`)に置き換えるだけです。残りのコードは同じなので、非常に再利用しやすいアプローチになります。 + +## 本番環境向けバーコード生成のプロティップス + +- 同じ設定で多数のバーコードを生成する場合は **ジェネレーターをキャッシュ** すると、オブジェクト生成のオーバーヘッドが削減されます。 +- 選択したシンボロジー固有の長さ制限について **入力文字列を検証** します(長すぎると Aspose が `ArgumentException` をスローします)。 +- 完了したら **`using` 文** または `Dispose` を使用してジェネレーターを解放し、ネイティブリソースを速やかに解放します。 +- 大きなラベル用に高解像度印刷が必要な場合は、`generator.Parameters.ImageResolution.DpiX/DpiY` で **DPI を設定** します。 + +## 結論 + +これで、Aspose.BarCode を使用して **テキストからバーコードを生成する方法**、**列数を変更する方法**、そして PNG として **バーコード画像を保存する正しい方法** が正確に分かりました。上記の完全な実行可能サンプルは、クリーンで本番環境向けの + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックを扱っています。各リソースには、ステップバイステップの解説と完全な動作コード例が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを検討するのに役立ちます。 + +- [バーコード生成方法 – Code 39 設定 (Aspose.BarCode)](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [バーコード画像生成 – Code 93 (Aspose.BarCode)](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [DataMatrix バーコード生成方法 (ECC 200) – Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/korean/net/compact-pdf417-encoding/_index.md index 0ecfa04d3..8bce8ddd5 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 바코드를 생성하는 방법을 배웁니다. 단계별 지침과 코드 예제가 포함된 포괄적인 가이드입니다. +### [C#에서 PDF417 바코드 메타데이터 만들기 – 완전 단계별 가이드](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +C#을 사용해 PDF417 바코드에 메타데이터를 삽입하고, 전체 과정을 단계별로 안내합니다. + +### [C#에서 PDF417 바코드 생성 – 완전 가이드](./generate-pdf417-barcode-in-c-complete-guide/) +C#을 사용해 PDF417 바코드를 생성하는 전체 과정을 단계별로 안내합니다. + +### [C#에서 PDF417 바코드 생성 – 완전 단계별 가이드](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +C#으로 PDF417 바코드를 만들고, 설정 및 저장까지 전체 과정을 단계별로 자세히 설명합니다. + +### [C#에서 PDF417 읽기 – 완전 단계별 가이드](./how-to-read-pdf417-in-c-complete-step-by-step-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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/korean/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..f02775d77 --- /dev/null +++ b/barcode/korean/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-07-15 +description: Aspose.BarCode를 사용하여 C#에서 PDF417 바코드 메타데이터를 생성합니다. 매크로 PDF417 설정을 배우고 + PNG로 저장하며 유니코드 텍스트를 처리합니다. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: ko +lastmod: 2026-07-15 +og_description: Aspose.BarCode를 사용하여 C#에서 PDF417 바코드 메타데이터를 생성합니다. 이 가이드는 파일 ID, 타임스탬프 + 등을 삽입하는 데 필요한 모든 설정을 보여줍니다. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: C#에서 PDF417 바코드 메타데이터 만들기 – 전체 프로그래밍 가이드 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: C#로 PDF417 바코드 메타데이터 생성하기 – 완전 단계별 가이드 +url: /ko/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 PDF417 바코드 메타데이터 생성 – 완전 단계별 가이드 + +C#에서 **PDF417 바코드 메타데이터를 생성**해야 했지만 어떤 속성을 조정해야 할지 몰라 고민한 적이 있나요? 당신만 그런 것이 아닙니다—개발자들은 파일 ID, 세그먼트 수, 사용자 지정 타임스탬프와 같은 사양 요구사항에 부딪히곤 합니다. + +좋은 소식은 Aspose.BarCode 덕분에 이 작업이 아주 쉬워진다는 것입니다. 이 튜토리얼에서는 **Macro PDF417**용 `BarcodeGenerator`를 생성하고, 모든 중요한 메타데이터를 추가한 뒤 PNG 이미지로 저장합니다. 최종적으로 공급망이나 문서 관리 시스템에서 사용할 수 있는 완전한 바코드를 얻게 됩니다. + +## 이 가이드에서 다루는 내용 + +1. Aspose.BarCode NuGet 패키지를 설정합니다. +2. **Macro PDF417**용 `BarcodeGenerator`를 초기화합니다. +3. 모든 유용한 **바코드 메타데이터 필드**(파일 ID, 세그먼트 ID, 체크섬 등)를 채웁니다. +4. 바코드를 디스크에 저장하고 출력 결과를 검증합니다. + +Macro PDF417에 대한 사전 경험은 필요하지 않으며, 기본적인 C# 지식과 최신 .NET 런타임만 있으면 됩니다. + +왜 신경 써야 할까요? 풍부한 메타데이터를 바코드에 직접 삽입하면 하위 스캐너가 전체 파일 전송을 검증하고, 누락된 세그먼트를 감지하거나 자동 워크플로를 트리거할 수 있습니다. 즉, 별도의 데이터베이스 조회 없이 **견고하고 자체 설명적인 데이터**를 얻을 수 있습니다. + +## 사전 요구 사항 + +- .NET 6.0 이상(코드는 .NET Framework 4.7+에서도 동작합니다). +- Visual Studio 2022(또는 선호하는 IDE). +- **Aspose.BarCode for .NET** NuGet 패키지(무료 체험 제공). + +다음 명령으로 패키지를 설치할 수 있습니다: + +```bash +dotnet add package Aspose.BarCode +``` + +이제 기본 준비가 끝났으니 실제 구현으로 들어가 보겠습니다. + +## 단계 1: Macro PDF417용 BarcodeGenerator 초기화 + +먼저 **Macro PDF417**에 맞게 구성된 `BarcodeGenerator` 인스턴스가 필요합니다. 이는 Aspose.BarCode에 어떤 인코딩 알고리즘을 사용할지 알려주고, 사람이 읽을 수 있는 텍스트를 입력할 수 있는 공간을 제공합니다. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **왜 중요한가:** `EncodeTypes.MacroPdf417`는 파일 ID와 세그먼트 번호와 같은 메타데이터를 지원하는 확장 PDF417 모드를 활성화합니다. 샘플 텍스트에는 유니코드 문자(`Å`, `ó`, `©`)가 포함되어 있어 생성기가 비ASCII 입력을 정상적으로 처리함을 보여줍니다. + +## 단계 2: 기본 바코드 외관 정의 + +메타데이터를 추가하기 전에 바코드가 눈에 보이는 작은 점이 되지 않도록 몇 가지 시각적 매개변수를 설정해야 합니다. `XDimension`은 모듈 너비를 제어하고, `Columns`는 전체 형태에 영향을 줍니다. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **전문가 팁:** 픽셀 너비 `2`는 화면 표시와 대부분의 프린터에 적합합니다. 더 높은 해상도의 인쇄가 필요하면 `3` 또는 `4`로 올리세요. + +## 단계 3: Macro PDF417 메타데이터 필드 채우기 + +이제 튜토리얼의 핵심인 **바코드 메타데이터 필드**를 추가합니다. 각 속성은 Macro PDF417 사양의 해당 세그먼트와 직접 매핑됩니다. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### 각 속성의 역할 + +| 속성 | 목적 | 일반값 | +|----------|---------|---------------| +| **MacroPdf417FileID** | 전체 파일 세트에 대한 전역 고유 식별자. | `12345678` | +| **MacroPdf417SegmentID** | 현재 세그먼트의 인덱스(`0`부터 시작). | `12` | +| **MacroPdf417SegmentsCount** | 파일에 예상되는 전체 세그먼트 수. | `20` | +| **MacroPdf417FileName** | 사람에게 읽히는 이름, 보통 원본 파일명. | `"file01"` | +| **MacroPdf417Checksum** | 오류 검출을 위한 16비트 CCITT 체크섬. | `1234` | +| **MacroPdf417FileSize** | 원본 파일의 바이트 단위 크기. | `400000` | +| **MacroPdf417TimeStamp** | 파일이 생성된 시점. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | 대상지를 나타내는 선택적 필드. | `"street"` | +| **MacroPdf417Sender** | 소스 시스템을 나타내는 선택적 필드. | `"aspose"` | +| **MacroPdf417Terminator** | 스캐너에 이것이 마지막 세그먼트임을 알리는 플래그. | `Pdf417MacroTerminator.Set` | + +> **왜 필요한가:** Macro PDF417를 이해하는 스캐너는 다중 세그먼트 파일을 재조합하고, 체크섬으로 무결성을 검증하며, 타임스탬프를 기준으로 오래된 데이터를 거부할 수도 있습니다. 이를 통해 별도의 매니페스트 파일이 필요 없게 됩니다. + +## 단계 4: 바코드 이미지 저장 + +모든 매개변수를 설정한 후에는 간단히 `Save`를 호출합니다. 예제에서는 지정한 폴더에 PNG 파일을 기록합니다. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **예외 상황:** 나중에 바코드를 PDF에 삽입하려면 `BarCodeImageFormat.Jpeg` 또는 `Pdf`를 선택할 수 있습니다. PNG는 무손실 세부 정보를 유지하므로 검증에 유용합니다. + +## 전체 작업 예제 + +모든 내용을 합치면, 콘솔 앱에 복사·붙여넣기 할 수 있는 전체 프로그램은 다음과 같습니다: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### 예상 출력 + +프로그램을 실행하면 실행 파일 폴더에 **ExtPDF417Meta.png**라는 파일이 생성됩니다. 이미지 뷰어로 열면 촘촘하고 고대비인 PDF417 바코드를 확인할 수 있습니다. Macro PDF417를 지원하는 바코드 리더기로 스캔하면 스캐너가 우리가 설정한 메타데이터 값—파일 ID `12345678`, 세그먼트 `12`/`20` 등—을 반환합니다. + +## 일반적인 질문 및 함정 + +- **바코드가 흐릿하게 보이면 어떻게 하나요?** `XDimension.Pixels`를 늘리거나 고해상도 이미지 형식으로 전환하세요. +- **모든 메타데이터 필드를 설정해야 하나요?** 아닙니다. 하위 시스템에서 요구하는 필드만 필수이며, 사용하지 않는 필드는 기본값 그대로 두면 됩니다. +- **다중 세그먼트 파일을 자동으로 생성할 수 있나요?** 가능합니다—데이터를 반복하면서 `MacroPdf417SegmentID`를 증가시키고 각 세그먼트마다 별도 바코드를 생성하면 됩니다. 모든 세그먼트에서 `MacroPdf417FileID`를 동일하게 유지하는 것을 기억하세요. +- **Unicode를 지원하나요?** 물론입니다. 샘플 텍스트에 `Å`, `ó`, `©`가 포함되어 있어 Aspose.BarCode가 UTF‑8을 기본적으로 처리함을 보여줍니다. + +## 다음 단계: 기본을 넘어 + +이제 **PDF417 바코드 메타데이터 생성** 방법을 알았으니 다음을 살펴볼 수 있습니다: + +- `Aspose.Pdf`를 사용하여 **PDF에 바코드 삽입**을 통해 엔드‑투‑엔드 문서 생성을 구현합니다. +- `BarcodeReader`로 **메타데이터 읽기**를 수행해 스캔을 프로그래밍 방식으로 검증합니다. +- 브랜딩을 위해 **색상 맞춤**(전경/배경)을 적용합니다. +- `FileID`나 `Timestamp`와 같은 필드를 자동으로 채우기 위해 **데이터베이스와 연동**합니다. + +이 모든 주제는 **macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, **c# barcode generation**이라는 보조 키워드와 연결되므로 학습할 자료가 풍부합니다. + +## 결론 + +우리는 이제 **C#에서 PDF417 바코드 메타데이터를 생성**하는 완전하고 실무에 바로 적용 가능한 예제를 살펴보았습니다. Aspose.BarCode 설치, `BarcodeGenerator` 초기화, 모든 관련 **바코드 메타데이터 필드** 채우기, 그리고 선명한 PNG 저장까지, 올바른 속성을 알면 과정은 매우 간단합니다. + +한 번 시도해 보고 값을 조정해 보세요. 스캐너가 어떻게 반응하는지 확인할 수 있습니다. Macro PDF417의 유연성을 활용하면 하위 시스템이 필요로 하는 모든 정보를 하나의 스캔 가능한 이미지에 담을 수 있습니다. 코딩을 즐기시고 바코드가 언제나 오류 없이 작동하길 바랍니다! + +## 다음에 배울 내용은? + +다음 튜토리얼은 이 가이드에서 보여준 기술을 기반으로 하는 밀접한 주제를 다룹니다. 각 자료에는 단계별 설명과 함께 완전한 코드 예제가 포함되어 있어 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색하는 데 도움이 됩니다. + +- [바코드 만들기 – Aspose.BarCode와 함께 Compact PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java 바코드 라이브러리 – Aspose를 이용해 PDF에 바코드 추가](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [바코드 만들기 – Aspose.BarCode와 함께 컴팩트 PDF417 (독일어)](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/korean/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..6e9f899e8 --- /dev/null +++ b/barcode/korean/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-07-15 +description: PDF417 바코드를 빠르게 생성하고 C#에서 컴팩트한 PDF417 바코드 이미지의 열을 설정하는 방법을 배우세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: ko +lastmod: 2026-07-15 +og_description: Aspose.BarCode를 사용하여 PDF417 바코드를 생성하고, 열을 설정하여 컴팩트한 PDF417 바코드 이미지를 + 만드는 방법을 알아보세요. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: C#에서 PDF417 바코드 생성 – 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: C#에서 PDF417 바코드 생성 – 완전 가이드 +url: /ko/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 PDF417 바코드 생성 – 완전 가이드 + +.NET 프로젝트에서 **PDF417 바코드 생성**이 필요했지만 어디서 시작해야 할지 몰랐던 적이 있나요? 당신만 그런 것이 아닙니다. 많은 엔터프라이즈 앱—예를 들어 탑승권 프린터, 재고 라벨, 모바일 티켓팅—에서 PDF417은 작은 시각적 공간에 많은 데이터를 담을 수 있는 핵심 기술입니다. + +핵심은 이렇습니다: Aspose.BarCode 라이브러리를 사용하면 전체 과정이 거의 고통 없이 진행되며, **열 설정 방법**을 제어해 바코드를 가능한 한 컴팩트하게 만들 수 있습니다. 이 튜토리얼을 끝까지 따라오면 **PDF417 바코드 이미지** PNG 파일을 바로 UI, 이메일, 인쇄 작업 등에 삽입할 수 있게 됩니다. + +## 배울 수 있는 내용 + +- PDF417 바코드를 생성하는 완전한 C# 콘솔 앱 +- *X‑Dimension* (모듈 크기)의 의미와 중요성 +- **열 설정 방법**에 대한 단계별 안내 +- 결과를 즉시 확인할 수 있는 `PNG` 파일 저장 +- 일반적인 문제(예: 읽을 수 없는 바코드, 잘못된 이미지 포맷) 해결 팁 + +> **전제 조건** – .NET 6+ SDK, Visual Studio 2022(또는 선호하는 편집기), 그리고 `Aspose.BarCode` NuGet 참조. 그 외는 필요 없습니다. + +--- + +## 단계 1: Aspose.BarCode NuGet 패키지 설치 + +**PDF417 바코드 생성**을 시작하려면 프로젝트에 라이브러리가 있어야 합니다. + +```bash +dotnet add package Aspose.BarCode +``` + +위 한 줄만으로 `BarcodeGenerator`, `EncodeTypes`, `BarCodeImageFormat` 열거형 등 필요한 모든 타입을 가져옵니다. + +> **프로 팁:** .NET 6 대신 .NET Framework를 타깃으로 한다면 패키지 관리자 콘솔에서 클래식 `Install-Package Aspose.BarCode` PowerShell 명령을 사용하세요. + +--- + +## 단계 2: 최소 콘솔 애플리케이션 만들기 + +바코드만 생성하는 작은 프로그램을 만들겠습니다. 새 폴더를 열고 `dotnet new console`을 실행한 뒤 자동 생성된 `Program.cs`를 아래 코드로 교체합니다. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**이 코드가 중요한 이유:** +- `EncodeTypes.Pdf417`은 QR이나 Code128이 아니라 PDF417 바코드를 원한다는 것을 라이브러리에 알려줍니다. +- `XDimension.Pixels`는 각 검은색·흰색 모듈의 해상도를 제어합니다. +- **열 설정 방법** 블록은 **PDF417 바코드 이미지**의 형태에 직접적인 영향을 줍니다. +- `Truncate = true`는 불필요한 빈 행을 제거해 많은 스캐너가 선호하는 “컴팩트” 모양을 제공합니다. + +--- + +## 단계 3: 더 깊이 파보기 – 열과 트렁케이션 이해 + +### 열 설정 방법 + +PDF417은 *행* × *열* 매트릭스로 데이터를 배치합니다. 기본값은 5열이며 대부분의 경우에 적합합니다. 하지만 라벨에 맞게 더 좁게 하거나 스캔 신뢰성을 높이기 위해 더 넓게 할 필요가 있을 수 있습니다. 다음 속성을 사용합니다: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +값은 **1**부터 **30**까지 허용됩니다(정확한 제한은 데이터 길이에 따라 달라짐). 간단히 정리하면: + +| 열 수 | 대략적인 너비 (mm) | 사용 시점 | +|------|-------------------|-----------| +| 1‑3 | 매우 좁음 | 작은 라벨, 공간 제한 | +| 4‑6 | 표준 | 대부분의 영수증·티켓 | +| 7‑10 | 넓음 | 고밀도 데이터, 가독성 향상 | + +### 트렁케이션(컴팩트 모드) + +`Truncate = true`를 설정하면 인코더가 하단의 불필요한 빈 행을 잘라냅니다. 결과는 **컴팩트 PDF417 바코드 이미지**가 되어 가능한 최소 영역에 모든 데이터를 담게 됩니다. “라벨에 바코드가 너무 큽니다”라는 오류가 발생하면 이 플래그를 토글해 보세요. + +--- + +## 단계 4: 앱 실행 및 출력 확인 + +컴파일하고 실행합니다: + +```bash +dotnet run +``` + +콘솔에 저장 위치가 표시될 것입니다. 해당 폴더로 이동해 `CompactPdf417.png`를 열어 보세요. 이미지 예시는 다음과 같습니다: + +![Generated PDF417 barcode image](./CompactPdf417.png "Generated PDF417 barcode image – compact PNG created by Aspose.BarCode") + +*이미지 대체 텍스트:* **Generated PDF417 barcode image** – 튜토리얼 코드가 만든 컴팩트 PNG 파일. + +스캐너가 읽을 수 있다면 축하합니다—**PDF417 바코드 생성**에 성공했고 **열 설정 방법**을 마스터하여 깔끔한 **PDF417 바코드 이미지**를 만들었습니다. + +--- + +## 단계 5: 흔히 겪는 문제와 해결 방법 + +| 증상 | 가능한 원인 | 빠른 해결책 | +|------|-------------|------------| +| 바코드가 흐릿함 | `XDimension.Pixels`가 너무 낮음(예: 1) | 2‑3 픽셀로 올려 선명도 향상 | +| 스캐너가 읽지 못함 | 데이터에 비해 열 수가 많음 | `Columns`를 줄이거나 `Truncate` 활성화 | +| 파일 포맷이 잘못됨 | 실수로 `BarCodeImageFormat.Jpeg` 사용 | 무손실 결과를 위해 `BarCodeImageFormat.Png` 사용 | +| `ArgumentOutOfRangeException` 예외 | 열 수가 허용 범위를 초과 | 열 수를 1‑30 사이로 유지하고 데이터 길이 확인 | + +--- + +## 단계 6: 색상 커스터마이징 및 텍스트 추가 + +바코드를 브랜드 색상에 맞추고 싶다면 전경·배경 색을 조정할 수 있습니다: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +또는 바코드 아래에 사람이 읽을 수 있는 텍스트를 오버레이할 수도 있습니다: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +이 추가 기능은 선택 사항이지만, **PDF417 바코드 생성** 워크플로우가 얼마나 유연한지 보여줍니다. + +--- + +## 결론 + +우리는 Aspose.BarCode를 사용해 **PDF417 바코드 생성**을 완전하게 구현하고, **열 설정 방법**을 통해 바코드 크기를 제어하며, PNG 형식의 선명한 **PDF417 바코드 이미지**를 저장하는 전체 과정을 살펴보았습니다. 코드는 .NET 6+에서 독립적으로 동작하며, 최소한의 수정만으로 기존 프로젝트에 바로 적용할 수 있습니다. + +다음 단계는 무엇일까요? 더 큰 페이로드(예: JSON) 인코딩, 다양한 이미지 포맷 실험, 혹은 바코드를 실시간으로 제공하는 웹 API와 통합해 보세요. 가능성은 무한하며, 이제 탄탄한 기반을 갖추셨습니다. + +코딩 즐겁게, 바코드가 항상 첫 번째 시도에서 스캔되길 바랍니다! + +## 다음에 배울 내용은? + +다음 튜토리얼들은 이 가이드에서 다룬 기술을 확장하고, 추가 API 기능을 마스터하며, 프로젝트에 다양한 구현 방식을 적용할 수 있도록 도와줍니다. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/korean/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..abf18fbea --- /dev/null +++ b/barcode/korean/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,200 @@ +--- +category: general +date: 2026-07-15 +description: C#로 PDF417 바코드를 빠르게 생성하세요. 텍스트에서 바코드를 만드는 방법, 바코드 크기를 조절하는 방법, 그리고 몇 + 분 안에 맞춤 바코드 치수를 설정하는 방법을 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: ko +lastmod: 2026-07-15 +og_description: C#에서 PDF417 바코드를 즉시 생성합니다. 이 가이드는 텍스트에서 바코드를 생성하고, 바코드 크기를 조정하며, 사용자 + 정의 바코드 치수를 적용하는 방법을 보여줍니다. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: C#에서 PDF417 바코드 생성 – 전체 프로그래밍 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: C#로 PDF417 바코드 생성 – 완전한 단계별 가이드 +url: /ko/net/compact-pdf417-encoding/generate-pdf417-barcode-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#에서 PDF417 바코드 생성 – 완전 단계별 가이드 + +PDF417 **바코드 생성**이 필요했지만 어떤 설정을 조정해야 할지 몰랐던 적이 있나요? 여러분만 그런 것이 아닙니다—많은 개발자들이 2‑D 바코드를 처음 다룰 때 같은 장벽에 부딪히곤 합니다. 좋은 소식은? 몇 줄의 C# 코드만으로 문자열을 스캔 가능한 PDF417 이미지로 변환하고, 정확한 크기를 제어하며, 맞춤형 열‑행 레이아웃까지 정의할 수 있다는 것입니다. + +이 튜토리얼에서는 **텍스트에서 바코드 생성**, 바코드 크기 조정, 맞춤형 바코드 차원 설정 — 모두 인기 있는 Aspose.BarCode 라이브러리를 사용해 진행합니다. 마지막에는 .NET 프로젝트에 바로 넣어 실행할 수 있는 샘플을 제공할 것입니다. + +![PDF417 바코드 생성 예시](https://example.com/og-image.png "PDF417 바코드 생성 예시") + +## 만들게 될 내용 + +- 문자열 `Åspóse.Barcóde©`를 인코딩하는 PDF417 바코드 +- X‑dimension(각 모듈의 픽셀 너비) 정밀 제어 +- 4열 9행의 맞춤 레이아웃 +- 디스크에 저장되는 PNG 파일 + +외부 서비스 없이, 마법 같은 트릭 없이—그냥 지금 바로 컴파일할 수 있는 순수 C# 코드만 있으면 됩니다. + +## 사전 준비 사항 + +- .NET 6.0 이상 (코드는 .NET Framework 4.8에서도 동작합니다) +- Visual Studio 2022 또는 C#을 지원하는 IDE +- Aspose.BarCode for .NET (무료 체험판 또는 정식 라이선스). NuGet을 통해 설치: + +```bash +dotnet add package Aspose.BarCode +``` + +이것만으로 패키지를 참조하면 준비 완료입니다. + +## 1단계 – 텍스트 데이터를 사용해 PDF417 바코드 생성 + +먼저 PDF417 심볼을 사용하고 인코딩할 정확한 텍스트를 알고 있는 `BarcodeGenerator` 인스턴스를 만들어야 합니다. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **왜 중요한가:** +> `EncodeTypes.Pdf417`은 라이브러리에게 PDF417 2‑D 포맷을 사용하도록 지시하고, 두 번째 인자는 **텍스트에서 바코드 생성**을 위한 페이로드입니다. 여기 전달하는 모든 내용이 바코드 매트릭스에 저장됩니다. + +## 2단계 – 바코드 크기 조정 (X‑Dimension) + +영수증에 너무 작게 인쇄된 바코드를 본 적이 있다면 스캐너가 인식하지 못하는 답답함을 잘 아실 겁니다. `XDimension` 속성은 단일 모듈(가장 작은 검은색 또는 흰색 사각형)의 너비를 픽셀 단위로 제어합니다. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **프로 팁:** +> 2 px 값은 대부분 화면 표시 시나리오에 잘 맞습니다. 고해상도 인쇄가 필요하면 3 px 또는 4 px로 올려 보세요. 단, X‑dimension이 커질수록 전체 이미지 크기도 증가한다는 점을 기억하세요. + +## 3단계 – 맞춤 바코드 차원 설정 (열 및 행) + +PDF417은 바코드가 차지할 열과 행 수를 직접 지정할 수 있게 해줍니다. 여기서 **맞춤 바코드 차원**이 등장합니다. 이 값을 변경하면 UI의 좁은 공간에 바코드를 맞추거나 특정 라벨 크기에 맞출 수 있습니다. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **내부에서 무슨 일이 일어나나요?** +> 라이브러리는 지정된 그리드에 인코딩된 데이터를 재분배합니다. 열이 적으면 바코드가 높아지고, 행이 많으면 짧아집니다. 원하는 시각적 균형이 맞을 때까지 숫자를 조정해 보세요. + +## 4단계 – 바코드 이미지 저장 + +이제 모든 설정이 끝났으니 생성기를 호출해 PNG 파일을 저장합니다. PNG는 손실이 없기 때문에 모듈의 선명함이 그대로 유지됩니다. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +프로그램을 실행하면 `C:\Barcodes\CustomLayout.png` 위치에 위 스크린샷과 유사한 파일이 생성됩니다. PDF417을 지원하는 리더기로 스캔하면 원본 문자열 `Åspóse.Barcóde©`가 반환됩니다. + +## 전체 작업 예제 + +아래는 콘솔 앱에 복사·붙여넣기 할 수 있는 완전한 프로그램입니다. 필요한 `using` 지시문과 실제 환경에서 기대하는 오류 처리까지 모두 포함했습니다. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### 예상 출력 + +코드를 실행하면 다음과 같이 출력됩니다: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…그리고 PNG 파일이 생성되어 모든 이미지 뷰어에서 열 수 있습니다. 모바일 앱(예: iOS/Android의 “Barcode Scanner”)으로 스캔하면 디코딩된 텍스트가 정확히 **Åspóse.Barcóde©**가 됩니다. + +## 자주 묻는 질문 및 예외 상황 + +| 질문 | 답변 | +|----------|--------| +| **다른 이미지 포맷을 사용할 수 있나요?** | 네—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, `Svg` 모두 지원됩니다. `Save` 메서드의 두 번째 인자를 변경하면 됩니다. | +| **텍스트에 유니코드 문자가 포함되면 어떻게 되나요?** | Aspose.BarCode는 UTF‑8을 완벽히 지원하므로 `Å`와 `©`가 포함된 예제도 바로 동작합니다. | +| **오류 정정 수준을 바꾸려면?** | `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (레벨 0‑8)와 같이 설정합니다. 레벨이 높을수록 중복성이 증가하지만 이미지 크기도 커집니다. | +| **투명 배경이 필요합니다—가능한가요?** | 저장하기 전에 `generator.Parameters.Barcode.Image.TransparentBackground = true;` 로 설정하면 됩니다. | +| **바코드를 직접 PDF에 삽입할 수 있나요?** | 물론 가능합니다. `Save` 호출을 `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` 로 바꾸면 바코드가 포함된 한 페이지 PDF가 생성됩니다. | + +## 결론 + +이제 C#에서 **PDF417 바코드 생성**, **바코드 크기 조정**, **맞춤 바코드 차원 적용** 방법을 알게 되었습니다. 초기화 → 크기 설정 → 레이아웃 지정 → 저장의 네 단계 흐름은 대부분의 2‑D 바코드 시나리오에 적용됩니다. + +다음은? `EncodeTypes.Pdf417`를 `EncodeTypes.QR`이나 `EncodeTypes.Code128`으로 바꿔 API가 어떻게 동작하는지 확인해 보세요. 다양한 `XDimension` 값을 실험하고, 열/행 매트릭스를 조정하거나 이미지를 PDF 보고서에 삽입해 보세요. 가능성은 무궁무진하며, 이제 탄탄한 기반을 갖추었습니다. + +PDF417을 사용하면서 궁금한 점이나 멋진 트릭을 발견했다면 아래에 댓글을 남겨 주세요—대화를 이어갑시다. 즐거운 코딩 되세요! + +## 다음에 배워야 할 내용 + +다음 튜토리얼들은 이번 가이드에서 다룬 기술을 기반으로 하여 관련 주제를 깊이 있게 다룹니다. 각 자료에는 단계별 설명과 완전한 코드 예제가 포함되어 있어 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용하는 데 도움이 됩니다. + +- [Aspose.BarCode for .NET을 사용해 맞춤 종횡비로 Aztec 바코드 생성](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [바코드 생성 – 일차원 바코드 종류](/barcode/english/net/one-dimensional-barcode-types/) +- [DataMatrix 바코드 생성 – Aspose.BarCode와 함께하는 전문가 가이드](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/korean/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..9ea5afcb6 --- /dev/null +++ b/barcode/korean/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,313 @@ +--- +category: general +date: 2026-07-15 +description: C#에서 PDF417 바코드를 읽고 이미지에서 여러 바코드를 읽는 방법. 자세한 코드와 팁으로 C# 바코드 이미지 읽기를 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: ko +lastmod: 2026-07-15 +og_description: C#에서 PDF417 바코드를 빠르게 읽는 방법. 이 가이드는 하나의 이미지에서 여러 바코드를 읽고 각 속성을 디코딩하는 + 방법을 보여줍니다. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: C#에서 PDF417 읽는 방법 – 전체 코드 샘플 및 설명 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: C#에서 PDF417 읽는 방법 – 완전 단계별 가이드 +url: /ko/net/compact-pdf417-encoding/how-to-read-pdf417-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#에서 PDF417 읽는 방법 – 완전 단계별 가이드 + +C#를 사용하여 이미지에서 **PDF417을 읽는 방법**을 궁금해 본 적 있나요? 당신만 그런 것이 아닙니다. 대부분의 개발자는 스캔된 문서에서 확장된 Macro‑PDF417 필드를 추출해야 할 때 난관에 부딪힙니다. 좋은 소식은? 몇 줄의 코드만으로 PDF417을 디코딩하고, 같은 사진에서 여러 바코드를 읽으며, 사양이 제공하는 모든 숨겨진 속성을 가져올 수 있다는 것입니다. + +이 튜토리얼에서는 **PDF417을 읽는 방법**, 단일 파일에서 **여러 바코드를 읽는 방법**, 그리고 **read barcode image C#** 코드가 왜 그렇게 보이는지를 보여주는 실제 예제를 단계별로 살펴보겠습니다. 끝까지 진행하면 파일 ID, 세그먼트 ID, 체크섬, 타임스탬프 등 필요할 수 있는 모든 정보를 출력하는 실행 가능한 콘솔 앱을 얻게 됩니다. + +## 필수 조건 + +시작하기 전에 다음이 준비되어 있는지 확인하세요: + +* .NET 6.0 SDK 이상 (코드는 .NET Core와 .NET Framework에서도 작동합니다). +* Visual Studio 2022 (또는 선호하는 편집기). +* **Aspose.BarCode for .NET** NuGet 패키지 – PDF417을 실제로 파싱하는 라이브러리입니다. +* Macro‑PDF417 바코드가 포함된 샘플 이미지 (예: `ExtPDF417Meta.png`). + +추가 설정은 필요하지 않습니다; 라이브러리는 필요한 모든 디코더를 포함하고 있습니다. + +## Step 1: Aspose.BarCode 설치 + +터미널에서 프로젝트 폴더를 열고 다음을 실행하세요: + +```bash +dotnet add package Aspose.BarCode +``` + +이 명령은 최신 안정 버전(2026년 7월 현재 23.12)을 가져옵니다. Visual Studio 내부의 Package Manager Console를 선호한다면 다음을 사용하세요: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Pro tip:** 나중에 의도치 않은 깨지는 변경을 방지하려면 `.csproj` 파일에 버전(`23.12.0`)을 고정하세요. + +## Step 2: 콘솔 앱 골격 만들기 + +콘솔 프로젝트가 아직 없다면 새로 만들세요: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +자동 생성된 `Program.cs`를 아래 코드로 교체합니다. 다음 섹션에서 각 블록을 자세히 설명합니다. + +## Step 3: Write the Full “How to Read PDF417” Code + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Why This Code Works + +* **`BarCodeReader`**는 이미지를 스트리밍하고 바코드를 감지하며 `BarCodeResult` 객체 컬렉션을 반환하는 핵심 클래스입니다. +* **`DecodeType.MacroPdf417`**을 전달하면 라이브러리가 Macro‑PDF417을 특별히 처리하도록 지시합니다; 여전히 일반 PDF417 심볼도 반환하므로 **read multiple barcodes** 요구사항을 만족합니다. +* **`Extended.Pdf417.MacroPdf417`** 객체는 ISO/IEC 15438 표준에 정의된 모든 선택 필드를 보유하고 있어 `FileID`, `SegmentID`, `Checksum` 등을 얻을 수 있습니다. +* `using` 블록은 네이티브 리소스가 해제되도록 보장하여 장기 실행 서비스에서 메모리 누수를 방지합니다. + +## Step 4: Run the Application and Verify Output + +터미널에서 다음을 실행하세요: + +```bash +dotnet run +``` + +다음과 같은 출력이 표시됩니다: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +이미지에 바코드가 두 개 이상 포함되어 있으면 루프가 구분선(`----------------------------------------`)을 출력하고 다음 결과로 계속 진행합니다—이는 **read multiple barcodes**가 실제로 어떻게 동작하는지 보여줍니다. + +## 일반적인 질문 및 특수 상황 + +### 이미지에 Macro‑PDF417와 일반 PDF417 심볼이 모두 포함되어 있다면? + +동일한 `BarCodeReader` 호출이 두 종류 모두 반환합니다. `result.CodeType`(`MacroPdf417` vs `Pdf417`)을 확인하여 구분할 수 있습니다. 일반 PDF417의 경우 확장 속성이 `null`이므로 `if (macro != null)` 가드가 `NullReferenceException`을 방지합니다. + +### 바코드가 회전되었거나 왜곡되었을 때도 리더가 작동하나요? + +Aspose.BarCode는 회전 및 왜곡 보정 기능을 내장하고 있습니다. 바코드가 이미지 너비의 최소 30 % 이상이면 디코더가 보통 성공합니다. 극단적인 경우 `reader.Options.AllowInvertedBarcodes = true;` 를 `ReadBarCodes()` 호출 전에 활성화할 수 있습니다. + +### 대량 이미지 배치를 어떻게 처리하나요? + +`foreach (var file in Directory.GetFiles(folder, "*.png"))` 루프 안에 읽기 로직을 넣으세요. `using` 패턴은 각 이미지의 네이티브 리소스를 다음 반복 전에 해제하므로 메모리 사용량을 낮게 유지합니다. + +## Full Source Listing (Copy‑Paste Ready) + +아래는 빠른 복사를 위해 한 블록에 모아둔 전체 프로그램입니다. 숨겨진 의존성은 없으며 Aspose.BarCode NuGet 패키지만 필요합니다. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Recap – What We Covered + +* Aspose.BarCode를 사용한 **PDF417 읽는 방법** in C#. +* 단일 이미지에서 **여러 바코드를 읽는 정확한 단계**. +* **read barcode image C#**를 통해 모든 Macro‑PDF417 필드를 추출하는 방법. +* 회전, 배치 처리, 확장 데이터 누락 상황에 대한 팁. + +## Next Steps & Related Topics + +* **Encode PDF417** – `BarCodeBuilder`를 사용해 자체 Macro‑PDF417 바코드를 생성합니다. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec 등 동일한 `BarCodeReader` 클래스로 읽습니다. +* **Integrate with ASP.NET Core** – 업로드된 이미지를 받아 디코딩된 필드를 JSON으로 반환하는 웹 엔드포인트를 노출합니다. + +자유롭게 실험해 보세요: 이미지 경로를 바꾸거나 같은 폴더에 일반 PDF417을 넣거나 `DecodeType` 플래그를 조정해 라이브러리 동작을 확인해 보세요. 많이 할수록 **read barcode image C#** 시나리오에 익숙해집니다. + +디코딩이 어려운 이미지가 있나요? 아래 댓글을 남기거나 샘플 프로젝트의 GitHub 저장소에 이슈를 열어 주세요. 즐거운 코딩 되세요! + +## What Should You Learn Next? + +다음 튜토리얼들은 이 가이드에서 배운 기술을 기반으로 하여 밀접하게 관련된 주제를 다룹니다. 각 리소스는 완전한 코드 예제와 단계별 설명을 포함하고 있어 추가 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# – 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/one-dimensional-barcode-types/_index.md b/barcode/korean/net/one-dimensional-barcode-types/_index.md index 5196c2e2a..a182aad1a 100644 --- a/barcode/korean/net/one-dimensional-barcode-types/_index.md +++ b/barcode/korean/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,7 @@ Aspose.BarCode를 사용하여 .NET에서 Databar GS1 인코딩 바코드를 만 .NET용 Aspose.BarCode를 사용하여 1차원 바코드를 생성하는 동안 예외를 처리하는 방법을 알아보세요. 이 단계별 가이드는 오류 방지 바코드 솔루션을 보장합니다. 지금 시작하세요! ### [1차원 광폭-협폭 구성](./one-dimensional-wide-narrow-ratio-configuration/) .NET용 Aspose.BarCode를 사용하여 맞춤형 바코드를 쉽게 생성하세요. 1차원 광폭-협폭 비율 구성을 위한 단계별 가이드입니다. +### [Aspose.BarCode를 사용하여 텍스트에서 바코드 생성 – C# 가이드](./generate-barcode-from-text-using-aspose-barcode-c-guide/) ## 결론 @@ -89,4 +90,4 @@ Aspose.BarCode를 사용하여 .NET에서 Databar GS1 인코딩 바코드를 만 {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/korean/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..89fcfa8ed --- /dev/null +++ b/barcode/korean/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-07-15 +description: C#에서 Aspose.BarCode를 사용해 텍스트로부터 바코드를 생성합니다. 열 개수 변경 방법, 바코드 이미지 저장 방법, + 그리고 빠르게 바코드 Aspose 솔루션을 만드는 방법을 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: ko +lastmod: 2026-07-15 +og_description: Aspose.BarCode를 사용하여 텍스트에서 바코드를 생성합니다. 이 가이드는 열 수를 변경하고, 바코드 이미지를 + 저장하며, 몇 줄의 코드로 Aspose 바코드를 만드는 방법을 보여줍니다. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Aspose.BarCode로 텍스트에서 바코드 생성 – 빠른 C# 안내 +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Aspose.BarCode를 사용하여 텍스트에서 바코드 생성 – C# 가이드 +url: /ko/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 텍스트에서 바코드 생성하기 Aspose.BarCode 사용 – C# 가이드 + +Aspose.BarCode를 사용해 텍스트에서 바코드를 생성하는 것은 놀라울 정도로 간단합니다. 이 튜토리얼에서는 **바코드 생성 방법**을 단계별로 살펴보고, 컬럼 레이아웃을 조정한 뒤, 최종적으로 **바코드 이미지를** PNG 파일로 **저장**하는 과정을 안내합니다. 티켓 발행 시스템, 창고 라벨 프린터를 구축하거나 QR‑스타일 코드를 실험하고 있든, 아래 단계만 따라 하면 빠르게 원하는 결과를 얻을 수 있습니다. + +## 배울 내용 + +- 모든 유니코드 문자열(예: “Åspóse.Barcóde©”도 가능)에서 바코드 생성 +- MicroPdf417의 **컬럼 수**를 조정해 좁은 라벨이나 넓은 라벨에 맞추기 +- 적절한 이미지 포맷으로 결과를 디스크에 저장 +- 특수 문자 처리 및 **Aspose 바코드 생성** 시 흔히 발생하는 문제에 대한 팁 + +외부 도구 없이, 명령줄 해킹 없이—그냥 순수 C#과 Aspose.BarCode 라이브러리만 있으면 됩니다. + +## 사전 준비 + +시작하기 전에 다음이 준비되어 있는지 확인하세요: + +1. **.NET 6.0** 이상이 설치되어 있어야 합니다(.NET Framework 4.7+에서도 동작합니다). +2. Aspose.BarCode **라이선스**가 있거나, 무료 평가판 버전을 사용할 수 있습니다. +3. 쓰기 가능한 폴더—예시에서는 `YOUR_DIRECTORY` 라고 부릅니다. + +위 항목 중 하나라도 없으면 지금 NuGet 패키지를 받아 주세요: + +```bash +dotnet add package Aspose.BarCode +``` + +이것만 있으면 됩니다—추가로 복사할 DLL은 없습니다. + +## 1단계 – 프로젝트 설정 및 네임스페이스 가져오기 + +먼저 콘솔 앱을 만들거나(또는 기존 C# 프로젝트에) 코드를 추가합니다. 중요한 부분은 올바른 네임스페이스를 가져오는 것입니다: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +왜 이 `using` 문이 필요한가요? `BarcodeGenerator`는 `Aspose.BarCode.Generation`에, `BarCodeImageFormat` 열거형은 `Aspose.BarCode`에 정의되어 있습니다. 가져오기를 깔끔하게 하면 이후 코드를 마치 자연어처럼 읽을 수 있습니다. + +## 2단계 – 바코드 생성기 만들기 (how to generate barcode) + +이제 실제로 **텍스트에서 바코드 생성**을 수행합니다. `EncodeTypes` 열거형은 Aspose에게 사용할 심볼로지를 알려 주며, 여기서는 긴 문자열을 컴팩트한 그리드로 처리할 수 있는 `MicroPdf417`을 선택합니다. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +문자열에 억양 문자와 저작권 기호가 포함되어 있음을 확인하세요. Aspose.BarCode는 유니코드를 자동으로 인코딩하므로 텍스트를 별도로 전처리할 필요가 없습니다. + +## 3단계 – 외관 미세 조정 (how to change column count) + +MicroPdf417은 컬럼 수를 제어할 수 있어 바코드 너비에 직접적인 영향을 줍니다. 좁은 라벨에는 촘촘한 레이아웃이, 큰 인쇄물에는 넓은 레이아웃이 가독성을 높입니다. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +왜 2픽셀 모듈인가요? 파일 크기를 크게 늘리지 않으면서 선명한 이미지를 제공합니다. 1~4 사이의 값을 실험해 보세요. 다른 컬럼 수가 필요하면 `Columns` 속성만 바꾸면 Aspose가 레이아웃을 자동으로 재계산합니다. + +## 4단계 – 바코드 이미지 저장 (save barcode image) + +생성기가 설정되었으니 **바코드 이미지 저장**을 진행합니다. `Save` 메서드는 파일 경로와 이미지 포맷 열거형을 인수로 받습니다. PNG는 무손실 포맷이므로 확대해도 바코드가 선명하게 유지됩니다. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +팁: 절대 경로를 사용하거나 작업 디렉터리가 예상대로인지 확인하세요. 그렇지 않으면 파일이 `bin` 폴더에 저장돼 찾기 어려울 수 있습니다. + +## 전체 작동 예제 + +아래 코드를 `Program.cs`에 복사‑붙여넣기 하면 바로 실행할 수 있는 완전한 프로그램입니다: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**예상 출력** (콘솔): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +`MicroPdf417.png` 파일을 열면 원본 문자열과 특수 문자를 그대로 인코딩한 선명한 MicroPdf417 바코드를 확인할 수 있습니다. + +## 자주 묻는 질문 및 예외 상황 + +### 기본 용량보다 텍스트가 길면 어떻게 하나요? + +데이터가 행당 최대치를 초과하면 MicroPdf417은 자동으로 다중 행 레이아웃으로 전환합니다. 컬럼 수는 여전히 조정 가능하지만, 라이브러리가 내부적으로 추가 행을 삽입합니다. 별도 코딩 없이 이미지 크기만 확인하면 됩니다. + +### 이미지 포맷을 JPEG이나 BMP로 바꾸려면? + +`BarCodeImageFormat.Png`를 `BarCodeImageFormat.Jpeg`(또는 `Bmp`)으로 교체하면 됩니다. JPEG은 압축 아티팩트가 발생해 스캔 신뢰도에 영향을 줄 수 있으니, PNG를 기본으로 권장합니다. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### 출력에 워터마크가 보인다—무엇이 문제인가요? + +평가판 Aspose.BarCode에서는 워터마크가 삽입됩니다. 워터마크 없이 **Aspose 바코드 생성**을 원한다면 2단계에 주석 처리된 라인처럼 유효한 라이선스 파일을 로드하세요. + +### 다른 심볼(QR, Code128 등)도 생성할 수 있나요? + +물론 가능합니다. `EncodeTypes.MicroPdf417`을 `EncodeTypes.QR`, `EncodeTypes.Code128` 등 `EncodeTypes` 열거형의 다른 값으로 교체하면 됩니다. 나머지 코드는 그대로 유지되므로 재사용성이 높습니다. + +## 프로덕션 수준 바코드 생성 팁 + +- 동일한 설정으로 여러 바코드를 만들 경우 **생성기 객체를 캐시**하면 객체 생성 오버헤드를 줄일 수 있습니다. +- 선택한 심볼에 맞는 **입력 문자열 길이**를 검증하세요. 길이가 초과되면 Aspose가 `ArgumentException`을 발생시킵니다. +- 사용이 끝난 뒤 **using** 문이나 `Dispose`를 호출해 네이티브 리소스를 즉시 해제하세요. +- 대형 라벨용 고해상도 출력이 필요하면 `generator.Parameters.ImageResolution.DpiX/DpiY` 로 **DPI**를 설정하세요. + +## 결론 + +이제 Aspose.BarCode를 이용해 **텍스트에서 바코드 생성**, **컬럼 수 변경**, 그리고 **PNG 형식으로 바코드 이미지 저장**까지 전체 과정을 마스터했습니다. 위의 완전한 실행 예제는 깔끔하고 프로덕션에 바로 적용 가능한 코드를 보여줍니다. + +## 다음에 배울 내용은? + +아래 튜토리얼들은 이번 가이드에서 다룬 기술을 확장하여 추가 API 기능을 익히고, 다양한 구현 방식을 탐색할 수 있도록 도와줍니다. 모든 예제는 완전한 코드와 단계별 설명을 포함하고 있습니다. + +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Generate barcode image – Code 93 with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/polish/net/compact-pdf417-encoding/_index.md index 90d161b27..e461f3947 100644 --- a/barcode/polish/net/compact-pdf417-encoding/_index.md +++ b/barcode/polish/net/compact-pdf417-encoding/_index.md @@ -86,7 +86,13 @@ Poza podstawami, oto kilka praktycznych wskazówek, które usprawnią Twój prze ### [Tworzenie kodów Compact PDF417](./compact-pdf417-basic-configuration/) -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. +### [Utwórz metadane kodu kreskowego PDF417 w C# – Kompletny przewodnik krok po kroku](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) + +### [Generowanie kodu kreskowego PDF417 w C# – Kompletny przewodnik](./generate-pdf417-barcode-in-c-complete-guide/) + +### [Generowanie kodu kreskowego PDF417 w C# – Kompletny przewodnik krok po kroku](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) + +### [Jak odczytać PDF417 w C# – Kompletny przewodnik krok po kroku](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) ## Najczęściej zadawane pytania @@ -116,4 +122,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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/polish/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..b480eab95 --- /dev/null +++ b/barcode/polish/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-07-15 +description: Utwórz metadane kodu kreskowego PDF417 w C# przy użyciu Aspose.BarCode. + Poznaj ustawienia Macro PDF417, zapisz jako PNG i obsłuż tekst Unicode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: pl +lastmod: 2026-07-15 +og_description: Utwórz metadane kodu kreskowego PDF417 w C# przy użyciu Aspose.BarCode. + Ten przewodnik pokazuje wszystkie ustawienia potrzebne do osadzenia identyfikatora + pliku, znaczników czasu i innych. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: Tworzenie metadanych kodu kreskowego PDF417 w C# – Kompletny przewodnik + programistyczny +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: Tworzenie metadanych kodu kreskowego PDF417 w C# – Kompletny przewodnik krok + po kroku +url: /pl/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tworzenie metadanych kodu kreskowego PDF417 w C# – Kompletny przewodnik krok po kroku + +Kiedykolwiek potrzebowałeś **utworzyć metadane kodu kreskowego PDF417** w C#, ale nie wiedziałeś, które właściwości należy zmienić? Nie jesteś sam — programiści często napotykają trudności, gdy specyfikacja wymaga takich elementów jak identyfikatory plików, liczba segmentów czy własne znaczniki czasu. + +Dobrą wiadomością jest to, że Aspose.BarCode czyni to dziecinnie prostym. W tym samouczku uruchomimy `BarcodeGenerator` dla **Macro PDF417**, dodamy wszystkie istotne metadane i zapiszemy wynik jako obraz PNG. Po zakończeniu będziesz mieć w pełni funkcjonalny kod kreskowy gotowy do użycia w systemach łańcucha dostaw lub zarządzania dokumentami. + +## Co obejmuje ten przewodnik + +Przejdziemy przez: + +1. Instalację pakietu NuGet Aspose.BarCode. +2. Inicjalizację `BarcodeGenerator` dla **Macro PDF417**. +3. Wypełnienie każdego przydatnego **pola metadanych kodu kreskowego** (ID pliku, ID segmentu, suma kontrolna itp.). +4. Zapis kodu kreskowego na dysku i weryfikację wyniku. + +Wcześniejsze doświadczenie z Macro PDF417 nie jest wymagane — wystarczy podstawowa znajomość C# oraz aktualny runtime .NET. + +Dlaczego to ważne? Osadzenie bogatych metadanych bezpośrednio w kodzie kreskowym pozwala skanerom weryfikować całe transfery plików, wykrywać brakujące segmenty lub nawet uruchamiać zautomatyzowane przepływy pracy. Inaczej mówiąc, otrzymujesz **solidne, samopisujące się dane** bez konieczności odwoływania się do osobnej bazy danych. + +## Wymagania wstępne + +- .NET 6.0 lub nowszy (kod działa także na .NET Framework 4.7+). +- Visual Studio 2022 (lub dowolne inne IDE). +- Pakiet NuGet **Aspose.BarCode for .NET** (dostępna wersja próbna). + +Pakiet można zainstalować poleceniem: + +```bash +dotnet add package Aspose.BarCode +``` + +Teraz, gdy mamy podstawy, przejdźmy do właściwej implementacji. + +## Krok 1: Inicjalizacja BarcodeGenerator dla Macro PDF417 + +Pierwszą rzeczą, której potrzebujemy, jest instancja `BarcodeGenerator` skonfigurowana dla **Macro PDF417**. Dzięki temu Aspose.BarCode wie, którego algorytmu kodowania użyć i zapewnia miejsce na tekst czytelny dla człowieka. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Dlaczego to ważne:** `EncodeTypes.MacroPdf417` aktywuje rozszerzony tryb PDF417, który obsługuje metadane takie jak identyfikatory plików i numery segmentów. Przykładowy tekst zawiera znaki Unicode (`Å`, `ó`, `©`), aby udowodnić, że generator radzi sobie z danymi nie‑ASCII. + +## Krok 2: Definiowanie podstawowego wyglądu kodu kreskowego + +Zanim zaczniemy dodawać metadane, warto ustawić kilka parametrów wizualnych, aby kod kreskowy nie był mikroskopijną plamką. `XDimension` kontroluje szerokość modułu, a `Columns` wpływa na ogólny kształt. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Pro tip:** Szerokość piksela `2` dobrze sprawdza się na ekranach i większości drukarek. Jeśli potrzebujesz wydruku o wyższej rozdzielczości, zwiększ ją do `3` lub `4`. + +## Krok 3: Wypełnianie pól metadanych Macro PDF417 + +Teraz przechodzi do serca samouczka — dodawania **pól metadanych kodu kreskowego**. Każda właściwość mapuje się bezpośrednio na segment specyfikacji Macro PDF417. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Co robi każda właściwość + +| Property | Purpose | Typical Value | +|----------|---------|---------------| +| **MacroPdf417FileID** | Globalnie unikalny identyfikator całego zestawu plików. | `12345678` | +| **MacroPdf417SegmentID** | Indeks bieżącego segmentu (zaczyna się od `0`). | `12` | +| **MacroPdf417SegmentsCount** | Łączna liczba segmentów oczekiwanych dla pliku. | `20` | +| **MacroPdf417FileName** | Czytelna nazwa, często oryginalna nazwa pliku. | `"file01"` | +| **MacroPdf417Checksum** | 16‑bitowa suma kontrolna CCITT służąca wykrywaniu błędów. | `1234` | +| **MacroPdf417FileSize** | Rozmiar oryginalnego pliku w bajtach. | `400000` | +| **MacroPdf417TimeStamp** | Moment wygenerowania pliku. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Opcjonalne pole wskazujące odbiorcę. | `"street"` | +| **MacroPdf417Sender** | Opcjonalne pole wskazujące system nadawcy. | `"aspose"` | +| **MacroPdf417Terminator** | Flaga informująca skaner, że jest to ostatni segment. | `Pdf417MacroTerminator.Set` | + +> **Dlaczego ich potrzebujesz:** Skanery rozumiejące Macro PDF417 mogą złożyć plik wielosegmentowy, zweryfikować integralność przy użyciu sumy kontrolnej i nawet odrzucić przestarzałe dane na podstawie znacznika czasu. Eliminuje to potrzebę osobnego pliku manifestu. + +## Krok 4: Zapis obrazu kodu kreskowego + +Gdy wszystkie parametry są ustawione, po prostu wywołujemy `Save`. Przykład zapisuje plik PNG do wskazanego folderu. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Edge case:** Jeśli planujesz później osadzić kod kreskowy w PDF, możesz wybrać `BarCodeImageFormat.Jpeg` lub `Pdf`. PNG zachowuje szczegóły bezstratnie, co jest przydatne przy weryfikacji. + +## Pełny działający przykład + +Łącząc wszystko razem, oto kompletny program, który możesz skopiować i wkleić do aplikacji konsolowej: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Oczekiwany wynik + +Uruchomienie programu tworzy plik o nazwie **ExtPDF417Meta.png** w folderze wykonywalnym. Otwórz go w dowolnym przeglądarce obrazów, a zobaczysz gęsty, wysokokontrastowy kod kreskowy PDF417. Jeśli zeskanujesz go czytnikiem obsługującym Macro PDF417, odczyta on ustawione wartości metadanych — ID pliku `12345678`, segment `12` z `20`, itp. + +## Częste pytania i pułapki + +- **Co zrobić, gdy kod kreskowy jest rozmyty?** Zwiększ `XDimension.Pixels` lub przełącz się na format obrazu o wyższej rozdzielczości. +- **Czy muszę ustawiać każde pole metadanych?** Nie. Wymagane są tylko te pola, które są niezbędne dla Twojego systemu docelowego. Nieużywane pola mogą pozostać w wartościach domyślnych. +- **Czy mogę automatycznie generować plik wielosegmentowy?** Tak — iteruj po danych, zwiększaj `MacroPdf417SegmentID` i generuj osobny kod kreskowy dla każdego segmentu. Pamiętaj, aby `MacroPdf417FileID` był spójny we wszystkich segmentach. +- **Czy Unicode jest obsługiwany?** Absolutnie. Przykładowy tekst zawiera `Å`, `ó` i `©`, co pokazuje, że Aspose.BarCode obsługuje UTF‑8 od ręki. + +## Kolejne kroki: wyjście poza podstawy + +Teraz, gdy wiesz, jak **tworzyć metadane kodu kreskowego PDF417**, możesz zgłębić: + +- **Osadzanie kodów kreskowych w PDF** przy użyciu `Aspose.Pdf` w celu pełnej automatyzacji generacji dokumentów. +- **Odczyt metadanych** za pomocą `BarcodeReader`, aby programowo weryfikować skany. +- **Dostosowywanie kolorów** (pierwszy plan/tło) w celach brandingowych. +- **Integrację z bazą danych** w celu automatycznego wypełniania pól takich jak `FileID` czy `Timestamp`. + +Wszystkie te tematy łączą się z naszymi drugorzędnymi słowami kluczowymi — **macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, oraz **c# barcode generation** — więc znajdziesz mnóstwo materiałów, które pomogą Ci kontynuować naukę. + +## Podsumowanie + +Przeszliśmy kompletny, gotowy do produkcji przykład, jak **tworzyć metadane kodu kreskowego PDF417** w C#. Od instalacji Aspose.BarCode, przez inicjalizację `BarcodeGenerator`, wypełnienie wszystkich istotnych **pól metadanych kodu kreskowego**, po zapis wyraźnego PNG — proces jest prosty, gdy znasz właściwe właściwości. + +Wypróbuj, zmodyfikuj wartości i zobacz, jak reagują skanery. Elastyczność Macro PDF417 pozwala osadzić wszystko, czego potrzebuje system downstream, w jednej, skanowalnej grafice. Powodzenia w kodowaniu i niech Twoje kody kreskowe zawsze będą wolne od błędów! + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne przykłady kodu oraz szczegółowe wyjaśnienia, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia w własnych projektach. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java barcode library – Add barcode to PDF using Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/polish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..680f52080 --- /dev/null +++ b/barcode/polish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: Szybko generuj kod kreskowy PDF417 i dowiedz się, jak ustawić kolumny + dla kompaktowego obrazu kodu PDF417 w C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: pl +lastmod: 2026-07-15 +og_description: Generuj kod kreskowy PDF417 przy użyciu Aspose.BarCode i dowiedz się, + jak ustawić kolumny, aby stworzyć kompaktowy obraz kodu PDF417. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: Generowanie kodu kreskowego PDF417 w C# – Przewodnik krok po kroku +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: Generowanie kodu kreskowego PDF417 w C# – Kompletny przewodnik +url: /pl/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generowanie kodu kreskowego PDF417 w C# – Kompletny przewodnik + +Czy kiedykolwiek potrzebowałeś **generate PDF417 barcode** w projekcie .NET, ale nie wiedziałeś od czego zacząć? Nie jesteś sam. W wielu aplikacjach korporacyjnych — myśl o drukarkach biletów lotniczych, etykietach inwentaryzacyjnych czy mobilnym biletowaniu — PDF417 jest wszechstronnym rozwiązaniem, które mieści dużo danych w małym wizualnym obszarze. + +Oto co: biblioteka Aspose.BarCode sprawia, że cały proces jest prawie bezbolesny, a dodatkowo możesz kontrolować **how to set columns**, aby kod kreskowy był jak najbardziej zwarty. Po zakończeniu tego samouczka będziesz mieć gotowy do użycia obraz PNG **PDF417 barcode image**, który możesz wstawić do dowolnego interfejsu, e‑maila lub zadania drukowania. + +## Co zdobędziesz po przeczytaniu + +- W pełni funkcjonalna aplikacja konsolowa C#, która tworzy kod kreskowy PDF417. +- Jasne zrozumienie *X‑Dimension* (rozmiar modułu) i dlaczego jest to istotne. +- Instrukcje krok po kroku dotyczące **how to set columns** dla bardziej zwartego kodu kreskowego. +- Zapisany plik `PNG`, który możesz od razu otworzyć, aby zweryfikować wynik. +- Wskazówki dotyczące rozwiązywania typowych problemów (np. nieczytelne kody kreskowe, nieprawidłowy format obrazu). + +> **Wymagania wstępne** – .NET 6+ SDK, Visual Studio 2022 (lub dowolny edytor), oraz odwołanie NuGet do `Aspose.BarCode`. Nic więcej. + +--- + +## Krok 1: Zainstaluj pakiet NuGet Aspose.BarCode + +Zanim będziemy mogli *generate PDF417 barcode*, biblioteka musi być obecna w projekcie. + +```bash +dotnet add package Aspose.BarCode +``` + +Ta pojedyncza linia pobiera wszystkie potrzebne typy, w tym `BarcodeGenerator`, `EncodeTypes` oraz enum `BarCodeImageFormat`. + +> **Porada:** Jeśli celujesz w .NET Framework zamiast .NET 6, użyj klasycznego polecenia PowerShell `Install-Package Aspose.BarCode` w konsoli Package Manager. + +--- + +## Krok 2: Utwórz minimalną aplikację konsolową + +Zbudujmy mały program, który nic nie robi oprócz generowania kodu kreskowego. Otwórz nowy folder, uruchom `dotnet new console`, a następnie zamień automatycznie wygenerowany plik `Program.cs` na poniższy kod. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Dlaczego to ważne:** +- `EncodeTypes.Pdf417` informuje bibliotekę, że chcemy kod kreskowy PDF417, a nie QR czy Code128. +- `XDimension.Pixels` kontroluje rozdzielczość każdego małego czarnego lub białego modułu. +- Blok **how to set columns** bezpośrednio wpływa na kształt **PDF417 barcode image**. +- `Truncate = true` usuwa niepotrzebne puste wiersze, dając „zwarty” wygląd, który lubią wiele skanerów. + +--- + +## Krok 3: Zagłęb się – Zrozumienie kolumn i przycinania + +### Jak ustawić kolumny + +PDF417 układa dane w macierzy *wierszy* × *kolumn*. Biblioteka domyślnie używa 5 kolumn, co działa w większości przypadków. Jednak możesz potrzebować węższego kodu kreskowego, aby zmieścić go na etykiecie, lub szerszego, aby poprawić niezawodność skanowania. Właściwość: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +przyjmuje wartości od **1** do **30** (dokładny limit zależy od długości danych). Oto szybka ściągawka: + +| Kolumny | Przybliżona szerokość (mm) | Kiedy używać | +|---------|----------------------------|---------------| +| 1‑3 | Bardzo wąska | Mała etykieta, ograniczona przestrzeń | +| 4‑6 | Standardowa | Większość paragonów, biletów | +| 7‑10 | Szersza | Dane o wysokiej gęstości, lepsza czytelność | + +### Truncate (Tryb zwarty) + +Ustawienie `Truncate = true` nakazuje enkoderowi odciąć niepotrzebne puste wiersze na dole. Wynikiem jest **compact PDF417 barcode image**, które zajmuje najmniejszy możliwy obszar, jednocześnie zawierając wszystkie dane. Jeśli kiedykolwiek pojawi się błąd „kod kreskowy za duży dla etykiety”, przełącz ten flag. + +--- + +## Krok 4: Uruchom aplikację i zweryfikuj wynik + +Skompiluj i uruchom: + +```bash +dotnet run +``` + +Powinieneś zobaczyć komunikat w konsoli potwierdzający lokalizację zapisu. Przejdź do folderu i otwórz `CompactPdf417.png`. Obraz będzie wyglądał mniej więcej tak: + +![Generated PDF417 barcode image](./CompactPdf417.png "Generated PDF417 barcode image – compact PNG created by Aspose.BarCode") + +*Image alt text:* **Generated PDF417 barcode image** – skompaktowany plik PNG wygenerowany przez kod tutoriala. + +Jeśli Twój skaner może go odczytać, gratulacje — udało Ci się **generate PDF417 barcode** i opanowano **how to set columns** dla schludnego **PDF417 barcode image**. + +--- + +## Krok 5: Typowe problemy i jak je naprawić + +| Objaw | Prawdopodobna przyczyna | Szybka naprawa | +|-------|--------------------------|----------------| +| Kod kreskowy jest rozmyty | `XDimension.Pixels` za niskie (np. 1) | Zwiększ do 2‑3 pikseli dla wyraźniejszego obrazu. | +| Skaner nie odczytuje | Zbyt wiele kolumn dla danych | Zmniejsz `Columns` lub włącz `Truncate`. | +| Nieprawidłowy format pliku | Zapisano z `BarCodeImageFormat.Jpeg` przez pomyłkę | Użyj `BarCodeImageFormat.Png` dla wyników bezstratnych. | +| Wyjątek `ArgumentOutOfRangeException` | Liczba kolumn przekracza dozwolony zakres | Trzymaj kolumny w przedziale 1‑30 i upewnij się, że dane mieszczą się. | + +--- + +## Krok 6: Idź dalej – Dostosowywanie kolorów i dodawanie tekstu + +Jeśli chcesz, aby kod kreskowy pasował do palety marki, możesz dostosować kolory pierwszego planu i tła: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Lub nałożyć czytelny dla człowieka tekst pod kodem kreskowym: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Te dodatki są opcjonalne, ale ilustrują, jak elastyczny może być przepływ pracy **generate PDF417 barcode**. + +--- + +## Zakończenie + +Przeszliśmy przez kompletny przykład od początku do końca, który **generate PDF417 barcode** przy użyciu Aspose.BarCode, wyjaśniliśmy **how to set columns**, aby kontrolować wymiary kodu kreskowego, i zapisaliśmy wynik jako wyraźny **PDF417 barcode image** w formacie PNG. Kod jest samodzielny, działa z .NET 6+ i może być wstawiony do dowolnego istniejącego projektu z minimalnym wysiłkiem. + +Co dalej? Spróbuj kodować większe ładunki (np. ładunki JSON), eksperymentuj z różnymi formatami obrazu lub zintegrować generator z API webowym, które dostarcza kody kreskowe na żądanie. Nie ma granic, a Ty masz teraz solidne podstawy do dalszej pracy. + +Miłego kodowania i niech Twoje kody kreskowe zawsze będą odczytywane za pierwszym razem! + +## 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 instrukcjami 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 z Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Jak wygenerować obraz kodu kreskowego w Javie z Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Generowanie kodu kreskowego w Javie – ustaw rozdzielczość obrazu z Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/polish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..062d46ced --- /dev/null +++ b/barcode/polish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-07-15 +description: Szybko generuj kod kreskowy PDF417 w C#. Dowiedz się, jak generować kod + kreskowy z tekstu, dostosować jego rozmiar i ustawić własne wymiary w kilka minut. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: pl +lastmod: 2026-07-15 +og_description: Generuj kod kreskowy PDF417 w C# natychmiast. Ten przewodnik pokazuje, + jak wygenerować kod kreskowy z tekstu, dostosować rozmiar kodu i zastosować niestandardowe + wymiary kodu. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Generowanie kodu kreskowego PDF417 w C# – Pełny samouczek programistyczny +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Generowanie kodu kreskowego PDF417 w C# – Kompletny przewodnik krok po kroku +url: /pl/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generowanie kodu kreskowego PDF417 w C# – Kompletny przewodnik krok po kroku + +Kiedykolwiek potrzebowałeś **wygenerować kod kreskowy PDF417**, ale nie wiedziałeś, które ustawienia zmienić? Nie jesteś sam — wielu programistów napotyka ten sam problem, gdy po raz pierwszy pracuje z kodami 2‑D. Dobra wiadomość? Kilka linijek C# pozwoli Ci zamienić dowolny ciąg znaków w skanowalny obraz PDF417, kontrolować jego dokładny rozmiar i nawet zdefiniować własny układ kolumn‑wierszy. + +W tym samouczku przejdziemy przez **generowanie kodu kreskowego z tekstu**, regulację rozmiaru kodu oraz ustawienie własnych wymiarów — wszystko przy użyciu popularnej biblioteki Aspose.BarCode. Po zakończeniu będziesz mieć gotowy przykład, który możesz wkleić do dowolnego projektu .NET. + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## Co zbudujesz + +- Kod kreskowy PDF417, który koduje ciąg `Åspóse.Barcóde©`. +- Precyzyjną kontrolę nad wymiarem X (szerokość każdego modułu w pikselach). +- Własny układ 4 kolumn i 9 wierszy. +- Plik PNG zapisany na dysku. + +Bez zewnętrznych usług, bez magicznych sztuczek — po prostu czysty kod C#, który możesz skompilować od razu. + +## Wymagania wstępne + +- .NET 6.0 lub nowszy (kod działa także na .NET Framework 4.8). +- Visual Studio 2022 lub dowolne IDE obsługujące C#. +- Aspose.BarCode for .NET (wersja próbna lub licencjonowana). Instalacja przez NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +To wszystko — po dodaniu pakietu możesz przystąpić do pracy. + +## Krok 1 – Generowanie kodu PDF417 z danymi tekstowymi + +Pierwszą rzeczą, której potrzebujemy, jest instancja `BarcodeGenerator`, która wie, że używamy symbologii PDF417 oraz dokładnego tekstu, który chcemy zakodować. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Dlaczego to ważne:** +> `EncodeTypes.Pdf417` informuje bibliotekę, że ma używać formatu PDF417 2‑D, a drugi argument to ładunek **generowania kodu kreskowego z tekstu**. Wszystko, co tu podasz, zostaje zapisane w macierzy kodu. + +## Krok 2 – Regulacja rozmiaru kodu (wymiar X) + +Jeśli kiedykolwiek drukowałeś kod kreskowy, który był zbyt mały na paragonie, znasz frustrację, gdy skaner go nie wykrywa. Właściwość `XDimension` kontroluje szerokość pojedynczego modułu (najmniejszego czarnego lub białego kwadratu) w pikselach. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Porada:** +> Wartość 2 px sprawdza się w większości scenariuszy wyświetlania na ekranie. Przy wydrukach wysokiej rozdzielczości możesz podnieść ją do 3 lub 4 px. Pamiętaj, że większe wymiary X zwiększają ogólny rozmiar obrazu. + +## Krok 3 – Ustawienie własnych wymiarów kodu (kolumny i wiersze) + +PDF417 pozwala określić, ile kolumn i wierszy ma zajmować kod. To właśnie tutaj wchodzą w grę **własne wymiary kodu**. Zmiana tych wartości może pomóc dopasować kod do ciasnego interfejsu UI lub spełnić określone wymagania etykiety. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Co się dzieje pod maską?** +> Biblioteka rozdziela zakodowane dane na określoną siatkę. Mniej kolumn oznacza wyższy kod; więcej wierszy — niższy. Eksperymentuj z liczbami, aż uzyskasz pożądany balans wizualny dla swojej aplikacji. + +## Krok 4 – Zapis obrazu kodu + +Po skonfigurowaniu wszystkiego po prostu prosimy generator o zapisanie pliku PNG. PNG jest bezstratny, więc ostrość modułów pozostaje nienaruszona. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Po uruchomieniu programu powinien pojawić się plik w `C:\Barcodes\CustomLayout.png`, który wygląda podobnie do zrzutu ekranu powyżej. Zeskanowanie go dowolnym czytnikiem obsługującym PDF417 zwróci oryginalny ciąg `Åspóse.Barcóde©`. + +## Pełny działający przykład + +Poniżej znajduje się kompletny program, który możesz skopiować i wkleić do aplikacji konsolowej. Zawiera wszystkie dyrektywy `using` oraz obsługę błędów, jaką można oczekiwać w kodzie produkcyjnym. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Oczekiwany wynik + +Uruchomienie kodu wypisuje: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…i tworzy plik PNG, który można otworzyć w dowolnym przeglądarce obrazów. Jeśli zeskanujesz go aplikacją mobilną (np. „Barcode Scanner” na iOS/Android), odkodowany tekst powinien być dokładnie **Åspóse.Barcóde©**. + +## Często zadawane pytania i przypadki brzegowe + +| Pytanie | Odpowiedź | +|----------|--------| +| **Czy mogę użyć innego formatu obrazu?** | Tak — `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` lub `Svg` są obsługiwane. Wystarczy zmienić drugi argument metody `Save`. | +| **Co jeśli mój tekst zawiera znaki Unicode?** | Aspose.BarCode w pełni obsługuje UTF‑8, więc przykład z `Å` i `©` działa od razu. | +| **Jak zmienić poziom korekcji błędów?** | Użyj `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (poziomy 0‑8). Wyższe poziomy zwiększają redundancję, ale także rozmiar. | +| **Potrzebuję przezroczystego tła — czy to możliwe?** | Ustaw `generator.Parameters.Barcode.Image.TransparentBackground = true;` przed zapisem. | +| **Czy da się osadzić kod bezpośrednio w pliku PDF?** | Oczywiście. Zastąp wywołanie `Save` przez `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` i otrzymasz jednosktronicowy PDF zawierający kod. | + +## Zakończenie + +Teraz wiesz, jak **generować kod kreskowy PDF417** w C# z dowolnego ciągu, **regulować rozmiar kodu** i stosować **własne wymiary kodu**, aby dopasować go do swojego układu. Czterostopniowy przepływ — inicjalizacja, rozmiar, układ, zapis — obejmuje podstawowy proces dla większości scenariuszy kodów 2‑D. + +Co dalej? Spróbuj zamienić `EncodeTypes.Pdf417` na `EncodeTypes.QR` lub `EncodeTypes.Code128`, aby zobaczyć, jak API się zachowuje. Eksperymentuj z różnymi wartościami `XDimension`, baw się macierzą kolumn/wierszy lub osadź obraz w raporcie PDF. Możliwości są praktycznie nieograniczone, a Ty masz solidne podstawy do dalszej pracy. + +Masz więcej pytań lub odkryłeś sprytny trik podczas pracy z PDF417? Dodaj komentarz poniżej — kontynuujmy dyskusję. Szczęśliwego kodowania! + + +## Co powinieneś nauczyć się dalej? + + +Poniższe samouczki dotyczą ściśle powiązanych tematów, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu oraz wyjaśnienia krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i poznać alternatywne podejścia w własnych projektach. + +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Generate DataMatrix Barcode – Pro Guide with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/polish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..929e286f4 --- /dev/null +++ b/barcode/polish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,313 @@ +--- +category: general +date: 2026-07-15 +description: Jak odczytać kod kreskowy PDF417 w C# oraz odczytać wiele kodów kreskowych + z obrazu. Dowiedz się, jak odczytywać obrazy kodów kreskowych w C# z szczegółowym + kodem i wskazówkami. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: pl +lastmod: 2026-07-15 +og_description: Jak szybko odczytać kod kreskowy PDF417 w C#. Ten przewodnik pokazuje, + jak odczytać wiele kodów kreskowych z jednego obrazu i zdekodować każdą właściwość. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Jak odczytać PDF417 w C# – Pełny przykład kodu i wyjaśnienie +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Jak odczytać PDF417 w C# – Kompletny przewodnik krok po kroku +url: /pl/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-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 krok po kroku + +Zastanawiałeś się kiedyś **jak odczytać PDF417** z obrazu przy użyciu C#? Nie jesteś jedyny. Większość programistów napotyka problem, gdy muszą wyciągnąć rozszerzone pola Macro‑PDF417 ze zeskanowanego dokumentu. Dobra wiadomość? Dzięki kilku linijkom kodu możesz zdekodować PDF417, odczytać wiele kodów kreskowych na tym samym zdjęciu i pobrać wszystkie ukryte właściwości, które oferuje specyfikacja. + +W tym samouczku przeprowadzimy Cię przez praktyczny przykład, który pokazuje **jak odczytać PDF417**, jak **odczytać wiele kodów kreskowych** z jednego pliku oraz dlaczego kod **read barcode image C#** wygląda tak, jak wygląda. Po zakończeniu będziesz mieć gotową do uruchomienia aplikację konsolową, która wypisze każdą potrzebną informację — ID pliku, ID segmentu, sumę kontrolną, znaczniki czasu, cokolwiek potrzebujesz. + +## Wymagania wstępne + +* .NET 6.0 SDK lub nowszy (kod działa również z .NET Core i .NET Framework). +* Visual Studio 2022 (lub dowolny edytor, który preferujesz). +* Pakiet NuGet **Aspose.BarCode for .NET** – to biblioteka, która faktycznie parsuje PDF417. +* Przykładowy obraz zawierający kod Macro‑PDF417 (np. `ExtPDF417Meta.png`). + +Nie wymagana jest dodatkowa konfiguracja; biblioteka dostarcza wszystkie potrzebne dekodery. + +## Krok 1: Zainstaluj Aspose.BarCode + +Otwórz folder projektu w terminalu i uruchom: + +```bash +dotnet add package Aspose.BarCode +``` + +To polecenie pobiera najnowszą stabilną wersję (stan na lipiec 2026 to 23.12). Jeśli wolisz konsolę Package Manager w Visual Studio, użyj: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Wskazówka:** zablokuj wersję (`23.12.0`) w pliku `.csproj`, aby uniknąć przypadkowych niekompatybilnych zmian w przyszłości. + +## Krok 2: Utwórz szkielet aplikacji konsolowej + +Utwórz nowy projekt konsolowy, jeśli jeszcze go nie masz: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Zastąp automatycznie wygenerowany plik `Program.cs` poniższym kodem. Wyjaśnimy każdy fragment w kolejnych sekcjach. + +## Krok 3: Napisz pełny kod „Jak odczytać PDF417” + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Dlaczego ten kod działa + +* **`BarCodeReader`** jest klasą podstawową, która wczytuje obraz, wykrywa kody kreskowe i zwraca kolekcję obiektów `BarCodeResult`. +* Przekazanie **`DecodeType.MacroPdf417`** informuje bibliotekę, aby traktowała Macro‑PDF417 w specjalny sposób; nadal zwraca zwykłe symbole PDF417, co spełnia wymaganie **read multiple barcodes**. +* Obiekt **`Extended.Pdf417.MacroPdf417`** zawiera wszystkie opcjonalne pola zdefiniowane w standardzie ISO/IEC 15438 – to tam znajdują się `FileID`, `SegmentID`, `Checksum` itd. +* Blok `using` zapewnia zwolnienie zasobów natywnych, zapobiegając wyciekom pamięci w usługach działających długo. + +## Krok 4: Uruchom aplikację i zweryfikuj wyjście + +Z terminala: + +```bash +dotnet run +``` + +Powinieneś zobaczyć coś podobnego: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Jeśli obraz zawiera więcej niż jeden kod kreskowy, pętla wydrukuje linię separatora (`----------------------------------------`) i przejdzie do kolejnego wyniku — dokładnie to, co w praktyce oznacza **read multiple barcodes**. + +## Częste pytania i przypadki brzegowe + +### Co zrobić, gdy obraz zawiera zarówno symbole Macro‑PDF417, jak i zwykłe PDF417? + +To samo wywołanie `BarCodeReader` zwróci oba typy. Możesz je odróżnić, sprawdzając `result.CodeType` (`MacroPdf417` vs `Pdf417`). Rozszerzone właściwości będą `null` dla zwykłego PDF417, więc warunek `if (macro != null)` zapobiega `NullReferenceException`. + +### Mój kod jest obrócony lub pochyły — czy czytnik nadal zadziała? + +Aspose.BarCode zawiera wbudowaną kompensację rotacji i zniekształceń. Jeśli kod zajmuje co najmniej 30 % szerokości obrazu, dekoder zazwyczaj się powiedzie. W skrajnych przypadkach możesz włączyć `reader.Options.AllowInvertedBarcodes = true;` przed wywołaniem `ReadBarCodes()`. + +### Jak obsłużyć duże partie obrazów? + +Umieść logikę odczytu w pętli `foreach (var file in Directory.GetFiles(folder, "*.png"))`. Wzorzec `using` zapewnia zwolnienie natywnych zasobów każdego obrazu przed kolejną iteracją, utrzymując niskie zużycie pamięci. + +## Pełny listing źródłowy (gotowy do kopiowania i wklejania) + +Poniżej znajduje się cały program w jednym bloku, gotowy do szybkiego kopiowania i wklejania. Brak ukrytych zależności — jedynie pakiet NuGet Aspose.BarCode. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Podsumowanie – Co omówiliśmy + +* **How to read PDF417** przy użyciu Aspose.BarCode w C#. +* Dokładne kroki, aby **read multiple barcodes** z jednego obrazu. +* Jak **read barcode image C#** i wyodrębnić każde pole Macro‑PDF417. +* Wskazówki dotyczące rotacji, przetwarzania wsadowego i obsługi brakujących rozszerzonych danych. + +## Kolejne kroki i powiązane tematy + +* **Encode PDF417** – generuj własne kody Macro‑PDF417 przy użyciu `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – przy użyciu tej samej klasy `BarCodeReader`. +* **Integrate with ASP.NET Core** – udostępnij endpoint webowy przyjmujący przesłany obraz i zwracający JSON z zdekodowanymi polami. + +Śmiało eksperymentuj: zmień ścieżkę obrazu, wrzuć zwykły PDF417 do tego samego folderu lub zmodyfikuj flagi `DecodeType`, aby zobaczyć, jak biblioteka się zachowuje. Im więcej będziesz się bawić, tym pewniej będziesz się czuł w scenariuszach **read barcode image C#**. + +Masz trudny obraz, który odmawia dekodowania? Dodaj komentarz poniżej lub otwórz zgłoszenie w repozytorium GitHub projektu przykładowego. Szczęśliwego kodowania! + +## 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 pełne 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 przy użyciu Aspose.BarCode dla .NET](/barcode/english/net/datamatrix-barcode-reading/) +- [Jak utworzyć kod kreskowy – Compact PDF417 przy użyciu Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Odczyt kodu DataMatrix 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/polish/net/one-dimensional-barcode-types/_index.md b/barcode/polish/net/one-dimensional-barcode-types/_index.md index 8fef375f6..44f8d337a 100644 --- a/barcode/polish/net/one-dimensional-barcode-types/_index.md +++ b/barcode/polish/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ zarabiaj, jak generować kody kreskowe w .NET za pomocą Aspose.BarCode dla .NET Dowiedz się, jak obsługiwać wyjątki podczas generowania jednowymiarowych kodów kreskowych przy użyciu Aspose.BarCode dla .NET. Ten przewodnik krok po kroku zapewnia rozwiązania odporne na błędy w zakresie kodów kreskowych. Zacznij teraz! ### [Konfiguracja jednowymiarowego szerokiego i wąskiego współczynnika](./one-dimensional-wide-narrow-ratio-configuration/) Z łatwością generuj niestandardowe kody kreskowe za pomocą Aspose.BarCode dla .NET. Przewodnik krok po kroku dotyczący konfiguracji jednowymiarowego współczynnika szerokiego i wąskiego. +### [Generowanie kodu kreskowego z tekstu przy użyciu Aspose.BarCode – przewodnik C#](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Dowiedz się, jak generować kody kreskowe z tekstu w .NET przy użyciu Aspose.BarCode w C#. Przewodnik krok po kroku. ## Wniosek @@ -89,4 +91,4 @@ Dzięki temu artykułowi nie tylko zdobędziesz wiedzę na temat różnych typó {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/polish/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..cbe82bd11 --- /dev/null +++ b/barcode/polish/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-07-15 +description: Generuj kod kreskowy z tekstu przy użyciu Aspose.BarCode w C#. Dowiedz + się, jak zmienić liczbę kolumn, zapisać obraz kodu kreskowego i szybko tworzyć rozwiązania + Aspose dla kodów kreskowych. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: pl +lastmod: 2026-07-15 +og_description: Generuj kod kreskowy z tekstu przy użyciu Aspose.BarCode. Ten przewodnik + pokazuje, jak zmienić liczbę kolumn, zapisać obraz kodu kreskowego i utworzyć kod + kreskowy Aspose w kilku linijkach kodu. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Generowanie kodu kreskowego z tekstu przy użyciu Aspose.BarCode – szybki + przewodnik C# +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Generowanie kodu kreskowego z tekstu przy użyciu Aspose.BarCode – przewodnik + C# +url: /pl/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generowanie kodu kreskowego z tekstu przy użyciu Aspose.BarCode – Przewodnik C# + +Generate barcode from text using Aspose.BarCode is surprisingly simple. In this tutorial we’ll walk through **how to generate barcode**, tweak the column layout, and finally **save barcode image** as a PNG file. Whether you’re building a ticketing system, a warehouse label printer, or just experimenting with QR‑style codes, the steps below will get you there quickly. + +## Czego się nauczysz + +- Utwórz kod kreskowy z dowolnego ciągu Unicode (tak, nawet „Åspóse.Barcóde©” działa). +- Dostosuj **liczbę kolumn** dla MicroPdf417, aby pasowała do wąskich lub szerokich etykiet. +- Zachowaj wynik na dysku w odpowiednim formacie obrazu. +- Wskazówki dotyczące obsługi znaków specjalnych i typowych pułapek przy **create barcode Aspose** rozwiązaniach. + +Bez zewnętrznych narzędzi, bez hacków w wierszu poleceń — tylko czysty C# i biblioteka Aspose.BarCode. + +## Wymagania wstępne + +Zanim zaczniemy, upewnij się, że masz: + +1. **.NET 6.0** lub nowszy zainstalowany (kod działa także na .NET Framework 4.7+). +2. **Licencję** na Aspose.BarCode, lub możesz rozpocząć od darmowej wersji ewaluacyjnej. +3. Folder, do którego możesz zapisywać — w przykładach nazwaliśmy go `YOUR_DIRECTORY`. + +Jeśli brakuje Ci któregoś z tych elementów, pobierz pakiet NuGet już teraz: + +```bash +dotnet add package Aspose.BarCode +``` + +To wszystko — nie ma dodatkowych plików DLL do ręcznego kopiowania. + +## Krok 1 — Konfiguracja projektu i importy + +Najpierw utwórz aplikację konsolową (lub wstaw kod do dowolnego projektu C#). Ważne jest, aby zaimportować właściwe przestrzenie nazw: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Po co te instrukcje using? `BarcodeGenerator` znajduje się w `Aspose.BarCode.Generation`, natomiast enum `BarCodeImageFormat` jest w `Aspose.BarCode`. Utrzymanie importów w porządku sprawia, że późniejszy kod czyta się jak zwykły angielski. + +## Krok 2 — Utworzenie generatora kodu kreskowego (jak generować kod kreskowy) + +Teraz naprawdę **generujemy kod kreskowy z tekstu**. Enum `EncodeTypes` informuje Aspose, jaką symbologię użyć; tutaj wybieramy `MicroPdf417`, ponieważ radzi sobie z długimi ciągami w zwartym układzie. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Zauważ, że ciąg zawiera znaki diakrytyczne i symbol praw autorskich. Aspose.BarCode automatycznie koduje Unicode, więc nie musisz wstępnie przetwarzać tekstu. + +## Krok 3 — Dostosowanie wyglądu (jak zmienić liczbę kolumn) + +MicroPdf417 pozwala kontrolować liczbę kolumn, co bezpośrednio wpływa na szerokość kodu kreskowego. Bardziej zwarty układ jest świetny dla wąskich etykiet; szerszy układ poprawia czytelność przy dużych wydrukach. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Dlaczego moduły 2‑pikselowe? Dają wyraźny obraz bez zwiększania rozmiaru pliku. Śmiało eksperymentuj — wartości od 1 do 4 zazwyczaj działają dobrze. Jeśli kiedykolwiek potrzebujesz innej liczby kolumn, po prostu zmień właściwość `Columns`; Aspose automatycznie przeliczy układ. + +## Krok 4 — Zapis obrazu kodu kreskowego (zapisz obraz kodu kreskowego) + +Po skonfigurowaniu generatora jesteśmy gotowi do **zapisania obrazu kodu kreskowego**. Metoda `Save` przyjmuje ścieżkę pliku oraz enum formatu obrazu. PNG jest bezstratny, więc kod kreskowy pozostaje ostry nawet po skalowaniu. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Szybka wskazówka: zawsze używaj ścieżki bezwzględnej lub upewnij się, że bieżący katalog jest taki, jak oczekujesz; w przeciwnym razie plik może trafić do folderu bin i będziesz się zastanawiać, dlaczego go nie możesz znaleźć. + +## Pełny działający przykład + +Łącząc wszystko razem, oto samodzielny program, który możesz skopiować i wkleić do `Program.cs`, a następnie uruchomić: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Oczekiwany wynik** (konsola): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +A jeśli otworzysz `MicroPdf417.png`, zobaczysz wyraźny kod MicroPdf417, który koduje oryginalny ciąg, wraz ze specjalnymi znakami, które mu przekazaliśmy. + +## Częste pytania i przypadki brzegowe + +### Co zrobić, gdy mój tekst jest dłuższy niż domyślna pojemność? + +MicroPdf417 automatycznie przełącza się na układ wielowierszowy, gdy dane przekraczają maksymalną liczbę znaków w wierszu. Nadal możesz kontrolować liczbę kolumn, ale biblioteka może dodać dodatkowe wiersze w tle. Nie potrzeba dodatkowego kodu — po prostu obserwuj wymiary powstałego obrazu. + +### Jak zmienić format obrazu na JPEG lub BMP? + +Zastąp `BarCodeImageFormat.Png` przez `BarCodeImageFormat.Jpeg` (lub `Bmp`). Pamiętaj, że JPEG wprowadza artefakty kompresji, które mogą wpływać na niezawodność skanowania. PNG jest najbezpieczniejszym domyślnym wyborem. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Widzę znak wodny w wyniku — co jest nie tak? + +To wersja ewaluacyjna Aspose.BarCode. Aby **create barcode Aspose** bez znaków wodnych, załaduj prawidłowy plik licencji, jak pokazano w zakomentowanej linii kroku 2. + +### Czy mogę generować inne symbologie (QR, Code128, itp.)? + +Oczywiście. Po prostu zamień `EncodeTypes.MicroPdf417` na dowolną inną wartość z enumu `EncodeTypes`, np. `EncodeTypes.QR` lub `EncodeTypes.Code128`. Reszta kodu pozostaje niezmieniona, co czyni podejście bardzo wielokrotnego użytku. + +## Profesjonalne wskazówki dla produkcyjnego generowania kodów kreskowych + +- **Cache generator** jeśli tworzysz wiele kodów kreskowych z tymi samymi ustawieniami; zmniejsza to narzut związany z tworzeniem obiektów. +- **Validate the input string** pod kątem ograniczeń długości specyficznych dla wybranej symbologii (Aspose rzuca `ArgumentException`, jeśli jest za długa). +- **Use `using` statements** lub `Dispose` generator po zakończeniu, aby szybko zwolnić zasoby natywne. +- **Set DPI** za pomocą `generator.Parameters.ImageResolution.DpiX/DpiY`, jeśli potrzebujesz wydruków o wysokiej rozdzielczości dla dużych etykiet. + +## Podsumowanie + +Teraz wiesz dokładnie **jak generować kod kreskowy z tekstu** przy użyciu Aspose.BarCode, jak **zmienić liczbę kolumn** oraz właściwy sposób **zapisania obrazu kodu kreskowego** jako PNG. Pełny, działający przykład powyżej demonstruje czyste, gotowe do produkcji + +## 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. + +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Generate barcode image – Code 93 with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/portuguese/net/compact-pdf417-encoding/_index.md index 9b00326c0..75e9dbbdc 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. +### [Criar Metadados de Código de Barras PDF417 em C# – Guia Completo Passo a Passo](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu-com/) +Aprenda a adicionar e manipular metadados em códigos de barras PDF417 usando C# com exemplos detalhados e melhores práticas. + +### [Gerar Código de Barras PDF417 em C# – Guia Completo](./generate-pdf417-barcode-in-c-complete-guide/) +Aprenda a gerar códigos de barras PDF417 em C# com um guia completo, incluindo exemplos de código e melhores práticas. + +### [Gerar Código de Barras PDF417 em C# – Guia Completo Passo a Passo](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +Aprenda a gerar códigos de barras PDF417 em C# com instruções detalhadas, exemplos de código e dicas de implementação. + +### [Como Ler PDF417 em C# – Guia Completo Passo a Passo](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) +Aprenda a ler códigos de barras PDF417 em C# com um guia completo, passo a passo, 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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/portuguese/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..ef7d12ae5 --- /dev/null +++ b/barcode/portuguese/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-07-15 +description: Crie metadados de código de barras PDF417 em C# usando Aspose.BarCode. + Aprenda as configurações Macro PDF417, salve como PNG e manipule texto Unicode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: pt +lastmod: 2026-07-15 +og_description: Crie metadados de código de barras PDF417 em C# com Aspose.BarCode. + Este guia mostra todas as configurações necessárias para incorporar ID do arquivo, + marcadores de tempo e muito mais. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: Criar Metadados de Código de Barras PDF417 em C# – Guia Completo de Programação +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: Criar Metadados de Código de Barras PDF417 em C# – Guia Completo Passo a Passo +url: /pt/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar Metadados de Código de Barras PDF417 em C# – Guia Completo Passo a Passo + +Já precisou **criar metadados de código de barras PDF417** em C# mas não sabia quais propriedades ajustar? Você não está sozinho—desenvolvedores frequentemente se deparam com a necessidade de definir IDs de arquivo, contagem de segmentos ou timestamps personalizados. + +A boa notícia é que o Aspose.BarCode torna isso muito simples. Neste tutorial vamos instanciar um `BarcodeGenerator` para **Macro PDF417**, inserir todos os metadados importantes e salvar o resultado como uma imagem PNG. Ao final, você terá um código de barras completo pronto para qualquer sistema de cadeia de suprimentos ou gerenciamento de documentos. + +## O que este Guia Abrange + +Vamos percorrer: + +1. Configuração do pacote NuGet Aspose.BarCode. +2. Inicialização de um `BarcodeGenerator` para **Macro PDF417**. +3. Preenchimento de todos os **campos de metadados do código de barras** (file ID, segment ID, checksum, etc.). +4. Salvamento do código de barras em disco e verificação da saída. + +Não é necessário ter experiência prévia com Macro PDF417—apenas conhecimentos básicos de C# e um runtime .NET recente. + +Por que isso importa? Incorporar metadados ricos diretamente no código de barras permite que scanners downstream validem transferências de arquivos completas, detectem segmentos ausentes ou até acionem fluxos de trabalho automatizados. Em outras palavras, você obtém **dados robustos e auto‑descritivos** sem precisar de uma consulta a banco de dados separado. + +## Pré‑requisitos + +- .NET 6.0 ou superior (o código também funciona no .NET Framework 4.7+). +- Visual Studio 2022 (ou qualquer IDE de sua preferência). +- O pacote NuGet **Aspose.BarCode for .NET** (versão de avaliação disponível). + +Instale o pacote com o seguinte comando: + +```bash +dotnet add package Aspose.BarCode +``` + +Agora que temos a base, vamos mergulhar na implementação real. + +## Etapa 1: Inicializar o BarcodeGenerator para Macro PDF417 + +A primeira coisa que precisamos é de uma instância `BarcodeGenerator` configurada para **Macro PDF417**. Isso informa ao Aspose.BarCode qual algoritmo de codificação usar e nos fornece um local para inserir o texto legível. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Por que isso importa:** `EncodeTypes.MacroPdf417` ativa o modo PDF417 estendido que suporta metadados como IDs de arquivo e números de segmento. O texto de exemplo contém caracteres Unicode (`Å`, `ó`, `©`) para provar que o gerador lida com entrada não‑ASCII sem problemas. + +## Etapa 2: Definir a Aparência Básica do Código de Barras + +Antes de começar a inserir metadados, devemos definir alguns parâmetros visuais para que o código de barras não fique microscópico. `XDimension` controla a largura do módulo, enquanto `Columns` influencia a forma geral. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Dica de especialista:** Uma largura de pixel de `2` funciona bem para exibição em tela e a maioria das impressoras. Se precisar de impressão em alta resolução, aumente para `3` ou `4`. + +## Etapa 3: Preencher os Campos de Metadados do Macro PDF417 + +Agora vem o coração do tutorial—adicionar **campos de metadados do código de barras**. Cada propriedade mapeia diretamente para um segmento da especificação Macro PDF417. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### O que Cada Propriedade Faz + +| Propriedade | Propósito | Valor Típico | +|-------------|-----------|--------------| +| **MacroPdf417FileID** | Identificador globalmente único para todo o conjunto de arquivos. | `12345678` | +| **MacroPdf417SegmentID** | Índice do segmento atual (começa em `0`). | `12` | +| **MacroPdf417SegmentsCount** | Total de segmentos esperados para o arquivo. | `20` | +| **MacroPdf417FileName** | Nome legível, geralmente o nome original do arquivo. | `"file01"` | +| **MacroPdf417Checksum** | Checksum CCITT de 16 bits para detecção de erros. | `1234` | +| **MacroPdf417FileSize** | Tamanho do arquivo original em bytes. | `400000` | +| **MacroPdf417TimeStamp** | Data/hora em que o arquivo foi gerado. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Campo opcional que indica o destinatário. | `"street"` | +| **MacroPdf417Sender** | Campo opcional que indica o sistema de origem. | `"aspose"` | +| **MacroPdf417Terminator** | Bandeira que informa ao scanner que este é o segmento final. | `Pdf417MacroTerminator.Set` | + +> **Por que você precisa disso:** Scanners que entendem Macro PDF417 podem reconstituir um arquivo de múltiplos segmentos, verificar a integridade com o checksum e até rejeitar dados desatualizados com base no timestamp. Isso elimina a necessidade de um arquivo de manifesto separado. + +## Etapa 4: Salvar a Imagem do Código de Barras + +Com todos os parâmetros definidos, basta chamar `Save`. O exemplo grava um arquivo PNG em uma pasta que você especificar. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Caso extremo:** Se pretender incorporar o código de barras em um PDF posteriormente, pode preferir `BarCodeImageFormat.Jpeg` ou `Pdf`. PNG preserva detalhes sem perdas, o que é útil para verificação. + +## Exemplo Completo Funcional + +Juntando tudo, aqui está o programa completo que você pode copiar‑colar em um aplicativo de console: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Saída Esperada + +Ao executar o programa, um arquivo chamado **ExtPDF417Meta.png** será criado na pasta do executável. Abra-o com qualquer visualizador de imagens e você verá um denso código de barras PDF417 de alto contraste. Se escaneá‑lo com um leitor que suporte Macro PDF417, o scanner retornará os valores de metadados que definimos—file ID `12345678`, segmento `12` de `20`, etc. + +## Perguntas Frequentes & Armadilhas + +- **E se o código de barras ficar borrado?** Aumente `XDimension.Pixels` ou troque para um formato de imagem de maior resolução. +- **Preciso definir todos os campos de metadados?** Não. Apenas os campos exigidos pelo seu sistema downstream são obrigatórios. Campos não usados podem permanecer com os valores padrão. +- **Posso gerar um arquivo de múltiplos segmentos automaticamente?** Sim—faça um loop sobre os dados, incremente `MacroPdf417SegmentID` e gere um código de barras separado para cada segmento. Lembre‑se de manter `MacroPdf417FileID` consistente em todos os segmentos. +- **Unicode é suportado?** Absolutamente. O texto de exemplo contém `Å`, `ó` e `©`, demonstrando que o Aspose.BarCode lida com UTF‑8 nativamente. + +## Próximos Passos: Indo Além do Básico + +Agora que você sabe como **criar metadados de código de barras PDF417**, pode explorar: + +- **Incorporar códigos de barras em PDFs** usando `Aspose.Pdf` para geração de documentos de ponta a ponta. +- **Ler metadados de volta** com `BarcodeReader` para validar digitalizações programaticamente. +- **Personalizar cores** (primeiro plano/fundo) para fins de branding. +- **Integrar com um banco de dados** para autopreencher campos como `FileID` ou `Timestamp`. + +Todos esses tópicos se relacionam com nossas palavras‑chave secundárias—**macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, e **c# barcode generation**—então você encontrará muito material para continuar aprendendo. + +## Conclusão + +Acabamos de percorrer um exemplo completo, pronto para produção, de como **criar metadados de código de barras PDF417** em C#. Desde a instalação do Aspose.BarCode, inicialização de um `BarcodeGenerator`, preenchimento de cada **campo de metadados do código de barras**, até o salvamento de um PNG nítido, o processo é direto quando você conhece as propriedades corretas. + +Experimente, ajuste os valores e veja como os scanners reagem. A flexibilidade do Macro PDF417 permite que você incorpore tudo que um sistema downstream precisa—tudo dentro de uma única imagem escaneável. Boa codificação, e que seus códigos de barras estejam sempre livres de erros! + +## 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 com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens 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/) +- [java barcode library – Add barcode to PDF using Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/portuguese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..5ea967d14 --- /dev/null +++ b/barcode/portuguese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: Gere código de barras PDF417 rapidamente e aprenda como definir colunas + para uma imagem de código de barras PDF417 compacta em C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: pt +lastmod: 2026-07-15 +og_description: Gere código de barras PDF417 com Aspose.BarCode e aprenda como definir + colunas para criar uma imagem compacta de código de barras PDF417. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: Gerar código de barras PDF417 em C# – Guia passo a passo +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: Gerar código de barras PDF417 em C# – Guia completo +url: /pt/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-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 Completo + +Já precisou **gerar código de barras PDF417** em um projeto .NET, mas não sabia por onde começar? Você não está sozinho. Em muitos aplicativos corporativos—pense em impressoras de cartões de embarque, etiquetas de inventário ou bilhetes móveis—PDF417 é o cavalo de batalha que compacta muitos dados em uma pequena área visual. + +Veja: a biblioteca Aspose.BarCode torna todo o processo quase indolor, e você pode até controlar **como definir colunas** para que o código de barras fique o mais compacto possível. Ao final deste tutorial, você terá uma imagem PNG pronta para uso de um **imagem de código de barras PDF417** que pode inserir em qualquer interface, e‑mail ou tarefa de impressão. + +## O que Você Vai Aprender + +- Um aplicativo console C# totalmente funcional que cria um código de barras PDF417. +- Compreensão clara da *X‑Dimension* (tamanho do módulo) e por que isso importa. +- Instruções passo a passo sobre **como definir colunas** para um código de barras mais compacto. +- Um arquivo `PNG` salvo que você pode abrir instantaneamente para verificar o resultado. +- Dicas para solucionar armadilhas comuns (por exemplo, códigos de barras ilegíveis, formato de imagem errado). + +> **Pré-requisitos** – SDK .NET 6+, Visual Studio 2022 (ou qualquer editor de sua preferência) e uma referência NuGet para `Aspose.BarCode`. Nada mais. + +--- + +## Etapa 1: Instalar o Pacote NuGet Aspose.BarCode + +Antes de podermos *gerar código de barras PDF417*, a biblioteca precisa estar presente no projeto. + +```bash +dotnet add package Aspose.BarCode +``` + +Essa única linha traz todos os tipos que você precisará, incluindo `BarcodeGenerator`, `EncodeTypes` e o enum `BarCodeImageFormat`. + +**Dica profissional:** Se você direcionar o .NET Framework em vez do .NET 6, use o comando clássico `Install-Package Aspose.BarCode` no PowerShell dentro do Console do Gerenciador de Pacotes. + +--- + +## Etapa 2: Criar um Aplicativo Console Minimalista + +Vamos montar um pequeno programa que não faz nada além de gerar um código de barras. Abra uma nova pasta, execute `dotnet new console` e, em seguida, substitua o `Program.cs` gerado automaticamente pelo código abaixo. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Por que isso importa:** +- `EncodeTypes.Pdf417` indica à biblioteca que queremos um código de barras PDF417, não QR ou Code128. +- `XDimension.Pixels` controla a resolução de cada pequeno módulo preto ou branco. +- O bloco **como definir colunas** influencia diretamente a forma da **imagem de código de barras PDF417**. +- `Truncate = true` elimina quaisquer linhas vazias desnecessárias, proporcionando o visual “compacto” que muitos leitores adoram. + +--- + +## Etapa 3: Aprofundar – Entendendo Colunas e Truncamento + +### Como Definir Colunas + +PDF417 organiza os dados em uma matriz de *linhas* × *colunas*. A biblioteca usa 5 colunas por padrão, o que funciona na maioria dos casos. Contudo, você pode precisar de um código de barras mais estreito para caber em uma etiqueta ou mais largo para melhorar a confiabilidade da leitura. A propriedade: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +aceita valores de **1** até **30** (o limite exato depende do tamanho dos dados). Aqui está uma planilha rápida: + +| Colunas | Largura Aproximada (mm) | Quando Usar | +|---------|--------------------------|-------------| +| 1‑3 | Muito estreita | Etiqueta pequena, espaço limitado | +| 4‑6 | Padrão | A maioria dos recibos, tickets | +| 7‑10 | Mais larga | Dados de alta densidade, melhor legibilidade | + +### Truncar (Modo Compacto) + +Definir `Truncate = true` indica ao codificador que corte quaisquer linhas em branco desnecessárias na parte inferior. O resultado é uma **imagem de código de barras PDF417 compacta** que ocupa a menor área possível, mantendo todos os dados. Se você receber erros como “código de barras muito grande para a etiqueta”, alterne essa opção. + +--- + +## Etapa 4: Executar o Aplicativo e Verificar a Saída + +Compile e execute: + +```bash +dotnet run +``` + +Você deverá ver a mensagem no console confirmando o local de salvamento. Navegue até a pasta e abra `CompactPdf417.png`. A imagem terá algo parecido com isto: + +![Imagem de código de barras PDF417 gerado](./CompactPdf417.png "Imagem de código de barras PDF417 gerado – PNG compacto criado pela Aspose.BarCode") + +*Texto alternativo da imagem:* **Imagem de código de barras PDF417 gerado** – um arquivo PNG compacto produzido pelo código do tutorial. + +Se o seu leitor conseguir lê‑lo, parabéns—você **gerou código de barras PDF417** com sucesso e dominou **como definir colunas** para uma **imagem de código de barras PDF417** organizada. + +--- + +## Etapa 5: Armadilhas Comuns & Como Corrigi‑las + +| Sintoma | Causa Provável | Correção Rápida | +|---------|----------------|-----------------| +| Código de barras aparece borrado | `XDimension.Pixels` muito baixo (ex.: 1) | Aumente para 2‑3 pixels para uma imagem mais nítida. | +| Leitor não consegue ler | Colunas demais para os dados fornecidos | Reduza `Columns` ou habilite `Truncate`. | +| Formato de arquivo errado | Salvo com `BarCodeImageFormat.Jpeg` por engano | Use `BarCodeImageFormat.Png` para resultados sem perdas. | +| Exceção `ArgumentOutOfRangeException` | Contagem de colunas excede o intervalo permitido | Mantenha colunas entre 1‑30 e garanta que os dados caibam. | + +--- + +## Etapa 6: Avançando – Personalizando Cores e Adicionando Texto + +Se quiser que o código de barras combine com a paleta da marca, você pode ajustar as cores de primeiro plano e de fundo: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Ou sobrepor texto legível por humanos abaixo do código de barras: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Essas adições são opcionais, mas ilustram quão flexível o fluxo de trabalho de **gerar código de barras PDF417** pode ser. + +--- + +## Conclusão + +Percorremos um exemplo completo, de ponta a ponta, que **gera código de barras PDF417** usando Aspose.BarCode, explicou **como definir colunas** para controlar as dimensões do código de barras e salvou o resultado como uma nítida **imagem de código de barras PDF417** em formato PNG. O código é autônomo, funciona com .NET 6+ e pode ser inserido em qualquer projeto existente com pouca complicação. + +Qual o próximo passo? Tente codificar cargas maiores (ex.: payloads JSON), experimente diferentes formatos de imagem ou integre o gerador a uma API web que forneça códigos de barras sob demanda. O céu é o limite, e agora você tem uma base sólida para construir. + +Feliz codificação, e que seus códigos de barras sempre sejam lidos na primeira tentativa! + +## O que Você Deve Aprender a Seguir? + +Os tutoriais a seguir abordam tópicos intimamente 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 alternativas de implementação 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 Imagem de Código de Barras em Java com Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Gerar Código de Barras Java – Definir Resolução da Imagem com Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/portuguese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..22e91fe37 --- /dev/null +++ b/barcode/portuguese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-07-15 +description: Gere código de barras PDF417 rapidamente com C#. Aprenda a gerar o código + de barras a partir de texto, ajustar o tamanho do código de barras e definir dimensões + personalizadas do código de barras em minutos. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: pt +lastmod: 2026-07-15 +og_description: Gere código de barras PDF417 em C# instantaneamente. Este guia mostra + como gerar o código de barras a partir de texto, ajustar o tamanho do código de + barras e aplicar dimensões personalizadas ao código de barras. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Gerar Código de Barras PDF417 em C# – Tutorial Completo de Programação +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Gerar código de barras PDF417 em C# – Guia completo passo a passo +url: /pt/net/compact-pdf417-encoding/generate-pdf417-barcode-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 PDF417 em C# – Guia Completo Passo a Passo + +Já precisou **gerar código de barras PDF417** mas não tinha certeza de quais configurações ajustar? Você não está sozinho—muitos desenvolvedores encontram o mesmo obstáculo quando começam a trabalhar com códigos de barras 2‑D. A boa notícia? Com algumas linhas de C# você pode transformar qualquer string em uma imagem PDF417 escaneável, controlar seu tamanho exato e até definir um layout personalizado de colunas‑linhas. + +Neste tutorial, vamos percorrer como **gerar código de barras a partir de texto**, ajustar o tamanho do código de barras e definir dimensões personalizadas — tudo usando a popular biblioteca Aspose.BarCode. Ao final, você terá um exemplo pronto‑para‑executar que pode ser inserido em qualquer projeto .NET. + +![Exemplo de geração de código de barras PDF417](https://example.com/og-image.png "Exemplo de geração de código de barras PDF417") + +## O que você vai construir + +- Um código de barras PDF417 que codifica a string `Åspóse.Barcóde©`. +- Controle preciso sobre a X‑dimension (largura em pixels de cada módulo). +- Um layout personalizado de 4 colunas e 9 linhas. +- Um arquivo PNG salvo no disco. + +Sem serviços externos, sem truques de varinha mágica—apenas código C# puro que você pode compilar agora mesmo. + +## Pré-requisitos + +- .NET 6.0 ou posterior (o código funciona também no .NET Framework 4.8). +- Visual Studio 2022 ou qualquer IDE que suporte C#. +- Aspose.BarCode para .NET (versão de avaliação gratuita ou licenciada). Instale via NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +É isso—uma vez que o pacote esteja referenciado, você está pronto para prosseguir. + +## Etapa 1 – Gerar Código de Barras PDF417 com Dados de Texto + +A primeira coisa que precisamos é uma instância de `BarcodeGenerator` que saiba que estamos lidando com a simbologia PDF417 e o texto exato que queremos codificar. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Por que isso importa:** +> `EncodeTypes.Pdf417` indica à biblioteca que use o formato PDF417 2‑D, enquanto o segundo argumento é a carga útil de **gerar código de barras a partir de texto**. Tudo o que você passar aqui se torna os dados armazenados na matriz do código de barras. + +## Etapa 2 – Ajustar o Tamanho do Código de Barras (X‑Dimension) + +Se você já imprimiu um código de barras que parecia muito pequeno em um recibo, conhece a frustração de o scanner não reconhecê‑lo. A propriedade `XDimension` controla a largura de um único módulo (o menor quadrado preto ou branco) em pixels. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Dica profissional:** +> Um valor de 2 px funciona bem na maioria dos cenários de exibição em tela. Para impressões de alta resolução, você pode aumentá‑lo para 3 ou 4 px. Apenas lembre‑se de que dimensões X maiores aumentam o tamanho geral da imagem. + +## Etapa 3 – Definir Dimensões Personalizadas do Código de Barras (Colunas e Linhas) + +O PDF417 permite que você defina quantas colunas e linhas o código de barras deve ocupar. É aqui que as **dimensões personalizadas do código de barras** entram em ação. Alterar esses valores pode ajudá‑lo a encaixar o código de barras em um espaço de UI apertado ou atender a um tamanho de etiqueta específico. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **O que está acontecendo nos bastidores?** +> A biblioteca redistribui os dados codificados pela grade especificada. Menos colunas resultam em códigos de barras mais altos; mais linhas os tornam mais curtos. Brinque com os números até que o equilíbrio visual pareça adequado para sua aplicação. + +## Etapa 4 – Salvar a Imagem do Código de Barras + +Agora que configuramos tudo, simplesmente pedimos ao gerador que escreva um arquivo PNG. PNG é sem perdas, portanto a nitidez dos módulos permanece intacta. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Ao executar o programa, você deverá ver um arquivo em `C:\Barcodes\CustomLayout.png` que se parece com a captura de tela acima. Escaneá‑lo com qualquer leitor compatível com PDF417 retornará a string original `Åspóse.Barcóde©`. + +## Exemplo Completo Funcional + +Abaixo está o programa completo que você pode copiar‑colar em um aplicativo de console. Ele inclui todas as diretivas using e o tratamento de erros que você esperaria em código de produção. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Saída Esperada + +Executar o código imprime: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…e cria um PNG que pode ser aberto em qualquer visualizador de imagens. Se você escaneá‑lo com um aplicativo móvel (por exemplo, “Barcode Scanner” no iOS/Android), o texto decodificado deverá ser exatamente **Åspóse.Barcóde©**. + +## Perguntas Frequentes & Casos Limite + +| Pergunta | Resposta | +|----------|----------| +| **Posso usar um formato de imagem diferente?** | Sim—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` ou `Svg` são todos suportados. Basta mudar o segundo argumento de `Save`. | +| **E se meu texto contiver caracteres Unicode?** | Aspose.BarCode suporta totalmente UTF‑8, então o exemplo com `Å` e `©` funciona pronto para uso. | +| **Como altero o nível de correção de erro?** | Use `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (níveis 0‑8). Níveis mais altos aumentam a redundância, mas também o tamanho. | +| **Preciso de fundo transparente—posso fazer isso?** | Defina `generator.Parameters.Barcode.Image.TransparentBackground = true;` antes de salvar. | +| **Existe uma maneira de incorporar o código de barras diretamente em um PDF?** | Claro. Substitua a chamada `Save` por `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` e você obterá um PDF de uma página contendo o código de barras. | + +## Conclusão + +Agora você sabe como **gerar código de barras PDF417** em C# a partir de qualquer string, **ajustar o tamanho do código de barras** e aplicar **dimensões personalizadas do código de barras** para atender às necessidades do seu layout. O fluxo de quatro etapas—inicializar, dimensionar, layout, salvar—cobre o fluxo de trabalho principal para a maioria dos cenários de códigos de barras 2‑D. + +Qual o próximo passo? Experimente trocar `EncodeTypes.Pdf417` por `EncodeTypes.QR` ou `EncodeTypes.Code128` para ver como a API se adapta. Experimente diferentes valores de `XDimension`, brinque com a matriz de colunas/linhas ou incorpore a imagem em um relatório PDF. As possibilidades são praticamente infinitas, e agora você tem uma base sólida para construir. + +Tem mais perguntas ou descobriu um truque inteligente ao brincar com PDF417? Deixe um comentário abaixo—vamos manter a conversa rolando. Feliz 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ódigo de barras Aztec com proporção personalizada usando Aspose.BarCode para .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Como Gerar Código de Barras - Tipos de Código de Barras Unidimensionais](/barcode/english/net/one-dimensional-barcode-types/) +- [Gerar Código de Barras DataMatrix – Guia Profissional com Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/portuguese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..975aeee86 --- /dev/null +++ b/barcode/portuguese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-07-15 +description: Como ler código de barras PDF417 em C# e ler vários códigos de barras + de uma imagem. Aprenda a ler imagens de códigos de barras em C# com código detalhado + e dicas. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: pt +lastmod: 2026-07-15 +og_description: Como ler código de barras PDF417 em C# rapidamente. Este guia mostra + como ler vários códigos de barras de uma única imagem e decodificar cada propriedade. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Como ler PDF417 em C# – Exemplo completo de código e explicação +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Como ler PDF417 em C# – Guia completo passo a passo +url: /pt/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-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 Passo a Passo + +Já se perguntou **como ler PDF417** a partir de uma imagem usando C#? Você não está sozinho. A maioria dos desenvolvedores bate em um muro quando precisam extrair os campos estendidos Macro‑PDF417 de um documento escaneado. A boa notícia? Com apenas algumas linhas de código você pode decodificar um PDF417, ler vários códigos de barras na mesma imagem e capturar todas as propriedades ocultas que a especificação oferece. + +Neste tutorial vamos percorrer um exemplo real que mostra **como ler PDF417**, como **ler múltiplos códigos de barras** de um único arquivo, e por que o código **read barcode image C#** tem a aparência que tem. Ao final, você terá um aplicativo console pronto para executar que imprime todas as informações que você possa precisar — ID do arquivo, ID do segmento, checksum, timestamps, o que for. + +## Pré‑requisitos + +Antes de mergulharmos, certifique‑se de que você tem: + +* .NET 6.0 SDK ou superior (o código funciona também com .NET Core e .NET Framework). +* Visual Studio 2022 (ou qualquer editor de sua preferência). +* O pacote NuGet **Aspose.BarCode for .NET** – esta é a biblioteca que realmente analisa PDF417. +* Uma imagem de exemplo que contenha um código de barras Macro‑PDF417 (por exemplo `ExtPDF417Meta.png`). + +Nenhuma configuração extra é necessária; a biblioteca já inclui todos os decodificadores que você precisa. + +## Etapa 1: Instalar Aspose.BarCode + +Abra a pasta do seu projeto em um terminal e execute: + +```bash +dotnet add package Aspose.BarCode +``` + +Esse comando obtém a versão estável mais recente (em julho 2026 é a 23.12). Se preferir o Package Manager Console dentro do Visual Studio, use: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Dica profissional:** fixe a versão (`23.12.0`) no seu `.csproj` para evitar alterações inesperadas mais tarde. + +## Etapa 2: Criar a Estrutura de um Aplicativo Console + +Crie um novo projeto console caso ainda não tenha um: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Substitua o `Program.cs` gerado automaticamente pelo código abaixo. Explicaremos cada bloco nas próximas seções. + +## Etapa 3: Escrever o Código Completo “Como Ler PDF417” + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Por Que Este Código Funciona + +* **`BarCodeReader`** é a classe central que processa a imagem, detecta códigos de barras e devolve uma coleção de objetos `BarCodeResult`. +* Passar **`DecodeType.MacroPdf417`** indica à biblioteca que deve tratar Macro‑PDF417 de forma especial; ela ainda devolve símbolos PDF417 simples, atendendo ao requisito de **read multiple barcodes**. +* O objeto **`Extended.Pdf417.MacroPdf417`** contém todos os campos opcionais definidos pela norma ISO/IEC 15438 – é aqui que você obtém `FileID`, `SegmentID`, `Checksum`, etc. +* O bloco `using` garante que os recursos nativos sejam liberados, evitando vazamentos de memória em serviços de longa execução. + +## Etapa 4: Executar o Aplicativo e Verificar a Saída + +No terminal: + +```bash +dotnet run +``` + +Você deverá ver algo como: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Se a imagem contiver mais de um código de barras, o laço imprimirá uma linha separadora (`----------------------------------------`) e continuará com o próximo resultado — exatamente como o **read multiple barcodes** se comporta na prática. + +## Perguntas Frequentes & Casos de Borda + +### E se a imagem tiver símbolos Macro‑PDF417 e PDF417 normais? + +A mesma chamada `BarCodeReader` retornará ambos. Você pode diferenciá‑los verificando `result.CodeType` (`MacroPdf417` vs `Pdf417`). As propriedades estendidas serão `null` para um PDF417 simples, portanto a verificação `if (macro != null)` impede um `NullReferenceException`. + +### Meu código de barras está rotacionado ou inclinado — o leitor ainda funciona? + +Aspose.BarCode inclui compensação de rotação e distorção embutida. Desde que o código de barras ocupe pelo menos 30 % da largura da imagem, o decodificador geralmente tem sucesso. Para casos extremos, você pode habilitar `reader.Options.AllowInvertedBarcodes = true;` antes de chamar `ReadBarCodes()`. + +### Como lidar com grandes lotes de imagens? + +Envolva a lógica de leitura em um laço `foreach (var file in Directory.GetFiles(folder, "*.png"))`. O padrão `using` garante que os recursos nativos de cada imagem sejam liberados antes da próxima iteração, mantendo o uso de memória baixo. + +## Listagem Completa do Código (Pronta para Copiar e Colar) + +A seguir está o programa inteiro em um único bloco para cópia rápida. Sem dependências ocultas — apenas o pacote NuGet Aspose.BarCode. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Recapitulação – O Que Cobremos + +* **Como ler PDF417** usando Aspose.BarCode em C#. +* Os passos exatos para **read multiple barcodes** a partir de uma única imagem. +* Como **read barcode image C#** e extrair cada campo Macro‑PDF417. +* Dicas para rotação, processamento em lote e tratamento de dados estendidos ausentes. + +## Próximos Passos & Tópicos Relacionados + +* **Encode PDF417** – gere seus próprios códigos de barras Macro‑PDF417 com `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – usando a mesma classe `BarCodeReader`. +* **Integrate with ASP.NET Core** – exponha um endpoint web que aceita uma imagem enviada e devolve JSON com os campos decodificados. + +Sinta‑se à vontade para experimentar: altere o caminho da imagem, coloque um PDF417 simples na mesma pasta ou ajuste as flags `DecodeType` para ver como a biblioteca se comporta. Quanto mais você brincar, mais confortável ficará com cenários de **read barcode image C#**. + +Tem uma imagem complicada que se recusa a ser decodificada? Deixe um comentário abaixo ou abra uma issue no repositório GitHub do projeto de exemplo. Boa codificação! + +## 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 com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas em seus próprios projetos. + +- [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/portuguese/net/one-dimensional-barcode-types/_index.md b/barcode/portuguese/net/one-dimensional-barcode-types/_index.md index 5c81ef2a1..091242dc8 100644 --- a/barcode/portuguese/net/one-dimensional-barcode-types/_index.md +++ b/barcode/portuguese/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ aprenda como gerar códigos de barras em .NET com Aspose.BarCode for .NET. Este Aprenda como lidar com exceções ao gerar códigos de barras unidimensionais usando Aspose.BarCode for .NET. Este guia passo a passo garante soluções de código de barras tolerantes a erros. Comece agora! ### [Configuração de relação ampla-estreita unidimensional](./one-dimensional-wide-narrow-ratio-configuration/) Gere códigos de barras personalizados facilmente com Aspose.BarCode for .NET. Guia passo a passo para configuração unidimensional de proporção larga-estreita. +### [Gerar código de barras a partir de texto usando Aspose.BarCode – Guia C#](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Aprenda a gerar códigos de barras a partir de texto em C# com Aspose.BarCode, passo a passo para integração rápida. ## Conclusão @@ -89,4 +91,4 @@ Com este artigo, você não apenas obterá conhecimento sobre vários tipos de c {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/portuguese/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..09ea9fd1a --- /dev/null +++ b/barcode/portuguese/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-07-15 +description: Gere código de barras a partir de texto usando Aspose.BarCode em C#. + Aprenda como alterar a contagem de colunas, salvar a imagem do código de barras + e criar soluções de código de barras Aspose rapidamente. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: pt +lastmod: 2026-07-15 +og_description: Gere código de barras a partir de texto usando Aspose.BarCode. Este + guia mostra como alterar a contagem de colunas, salvar a imagem do código de barras + e criar código de barras Aspose em poucas linhas de código. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Gerar código de barras a partir de texto com Aspose.BarCode – Guia rápido + em C# +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Gerar código de barras a partir de texto usando Aspose.BarCode – Guia C# +url: /pt/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-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 usando Aspose.BarCode – Guia C# + +Gerar código de barras a partir de texto usando Aspose.BarCode é surpreendentemente simples. Neste tutorial vamos percorrer **como gerar código de barras**, ajustar o layout de colunas e, finalmente, **salvar a imagem do código de barras** como um arquivo PNG. Seja você quem está construindo um sistema de bilhetagem, uma impressora de etiquetas de armazém ou apenas experimentando códigos no estilo QR, os passos abaixo o levarão rapidamente ao resultado. + +## O que você aprenderá + +- Criar um código de barras a partir de qualquer string Unicode (sim, até “Åspóse.Barcóde©” funciona). +- Ajustar a **contagem de colunas** para MicroPdf417 para se adequar a etiquetas estreitas ou largas. +- Persistir o resultado no disco com o formato de imagem adequado. +- Dicas para lidar com caracteres especiais e armadilhas comuns ao **criar código de barras Aspose** soluções. + +Sem ferramentas externas, sem truques de linha de comando — apenas C# puro e a biblioteca Aspose.BarCode. + +## Pré-requisitos + +Antes de mergulharmos, certifique‑se de que você tem: + +1. **.NET 6.0** ou posterior instalado (o código também funciona no .NET Framework 4.7+). +2. Uma **licença** para Aspose.BarCode, ou você pode começar com a versão de avaliação gratuita. +3. Uma pasta onde você possa gravar — a chamaremos de `YOUR_DIRECTORY` nos exemplos. + +Se estiver faltando algum desses, obtenha o pacote NuGet agora: + +```bash +dotnet add package Aspose.BarCode +``` + +É isso — sem DLLs extras para copiar manualmente. + +## Etapa 1 – Configurar o Projeto e as Importações + +Primeiro, crie um aplicativo de console (ou insira o código em qualquer projeto C#). A parte importante é importar os namespaces corretos: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Por que essas instruções using? `BarcodeGenerator` está em `Aspose.BarCode.Generation`, enquanto o enum `BarCodeImageFormat` está em `Aspose.BarCode`. Manter as importações organizadas faz com que o código posterior seja lido como inglês simples. + +## Etapa 2 – Criar o Gerador de Código de Barras (como gerar código de barras) + +Agora realmente **geramos código de barras a partir de texto**. O enum `EncodeTypes` indica à Aspose qual simbologia usar; aqui escolhemos `MicroPdf417` porque ele lida com strings longas em uma grade compacta. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Observe que a string contém caracteres acentuados e um símbolo de copyright. Aspose.BarCode codifica Unicode automaticamente, portanto você não precisa pré‑processar o texto. + +## Etapa 3 – Ajustar a Aparência (como mudar a contagem de colunas) + +MicroPdf417 permite controlar o número de colunas, o que influencia diretamente a largura do código de barras. Um layout mais compacto é ótimo para etiquetas estreitas; um layout mais amplo melhora a legibilidade em impressões grandes. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Por que módulos de 2 pixels? Eles fornecem uma imagem nítida sem inflar o tamanho do arquivo. Sinta‑se à vontade para experimentar — valores entre 1 e 4 geralmente funcionam bem. Se precisar de uma contagem de colunas diferente, basta alterar a propriedade `Columns`; a Aspose recalculará o layout automaticamente. + +## Etapa 4 – Salvar a Imagem do Código de Barras (salvar imagem do código de barras) + +Com o gerador configurado, estamos prontos para **salvar a imagem do código de barras**. O método `Save` aceita um caminho de arquivo e um enum de formato de imagem. PNG é sem perdas, portanto o código de barras permanece nítido mesmo após redimensionamento. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Dica rápida: sempre use um caminho absoluto ou garanta que o diretório de trabalho seja o esperado; caso contrário, o arquivo pode acabar na pasta bin e você se perguntará por que não o encontra. + +## Exemplo Completo Funcional + +Juntando tudo, aqui está um programa autônomo que você pode copiar‑colar em `Program.cs` e executar: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Saída esperada** (console): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +E se você abrir `MicroPdf417.png`, verá um código de barras MicroPdf417 nítido que codifica a string original, completa com os caracteres especiais que fornecemos. + +## Perguntas Frequentes & Casos Limítrofes + +### E se o meu texto for mais longo que a capacidade padrão? + +MicroPdf417 muda automaticamente para um layout de múltiplas linhas quando os dados excedem o máximo por linha. Você ainda pode controlar a contagem de colunas, mas a biblioteca pode adicionar linhas extras nos bastidores. Não é necessário código extra — apenas fique de olho nas dimensões da imagem resultante. + +### Como mudar o formato da imagem para JPEG ou BMP? + +Substitua `BarCodeImageFormat.Png` por `BarCodeImageFormat.Jpeg` (ou `Bmp`). Lembre‑se de que JPEG introduz artefatos de compressão, o que pode afetar a confiabilidade da leitura. PNG é a opção padrão mais segura. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Estou vendo uma marca d’água na saída — o que há de errado? + +Essa é a versão de avaliação do Aspose.BarCode. Para **criar código de barras Aspose** sem marcas d’água, carregue um arquivo de licença válido como mostrado na linha comentada da Etapa 2. + +### Posso gerar outras simbologias (QR, Code128, etc.)? + +Com certeza. Basta trocar `EncodeTypes.MicroPdf417` por qualquer outro valor do enum `EncodeTypes`, por exemplo, `EncodeTypes.QR` ou `EncodeTypes.Code128`. O restante do código permanece o mesmo, o que torna a abordagem altamente reutilizável. + +## Dicas Profissionais para Geração de Código de Barras Pronta para Produção + +- **Cache o gerador** se você estiver criando muitos códigos de barras com as mesmas configurações; isso reduz a sobrecarga de criação de objetos. +- **Valide a string de entrada** quanto às restrições de comprimento específicas da simbologia escolhida (Aspose lança `ArgumentException` se for muito longa). +- **Use instruções `using`** ou `Dispose` o gerador quando terminar para liberar os recursos nativos rapidamente. +- **Defina DPI** via `generator.Parameters.ImageResolution.DpiX/DpiY` se precisar de impressões em alta resolução para etiquetas grandes. + +## Conclusão + +Agora você sabe exatamente **como gerar código de barras a partir de texto** com Aspose.BarCode, como **alterar a contagem de colunas**, e a forma correta de **salvar a imagem do código de barras** como PNG. O exemplo completo e executável acima demonstra uma solução limpa e pronta para produção + +## O que você deve aprender a seguir? + +Os tutoriais a seguir cobrem tópicos intimamente 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ódigo de Barras – Configuração Code 39 com Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Gerar imagem de código de barras – Code 93 com Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [Como Gerar Códigos DataMatrix (ECC 200) com Aspose.BarCode para .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/russian/net/compact-pdf417-encoding/_index.md index 18a43fe66..831ae0f35 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. Полное руководство с пошаговыми инструкциями и примерами кода. +### [Создание метаданных штрих‑кода PDF417 в C# – Полное пошаговое руководство](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +Узнайте, как добавить и управлять метаданными PDF417 штрих‑кода в C# с помощью Aspose.BarCode. +### [Генерация штрих‑кода PDF417 в C# – Полное руководство](./generate-pdf417-barcode-in-c-complete-guide/) +Полное пошаговое руководство по генерации штрих‑кода PDF417 в C# с использованием Aspose.BarCode. +### [Генерация штрих‑кода PDF417 в C# – Полное пошаговое руководство](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +Подробное руководство по созданию штрих‑кода PDF417 в C# с использованием Aspose.BarCode, включающее все шаги и примеры кода. +### [Как читать PDF417 в C# – Полное пошаговое руководство](./how-to-read-pdf417-in-c-complete-step-by-step-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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/russian/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..7944fe27a --- /dev/null +++ b/barcode/russian/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-07-15 +description: Создайте метаданные штрихкода PDF417 на C# с использованием Aspose.BarCode. + Изучите настройки Macro PDF417, сохраните в PNG и обработайте Unicode‑текст. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: ru +lastmod: 2026-07-15 +og_description: Создайте метаданные штрих‑кода PDF417 на C# с помощью Aspose.BarCode. + Это руководство показывает все настройки, необходимые для внедрения идентификатора + файла, меток времени и прочего. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: Создание метаданных штрихкода PDF417 на C# – Полный программный обзор +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: Создание метаданных штрихкода PDF417 в C# – Полное пошаговое руководство +url: /ru/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание метаданных штрих‑кода PDF417 в C# – Полное пошаговое руководство + +Когда‑нибудь нужно было **создать метаданные штрих‑кода PDF417** в C#, но вы не знали, какие свойства менять? Вы не одиноки — разработчики часто сталкиваются с проблемой, когда спецификация требует такие параметры, как идентификаторы файлов, количество сегментов или пользовательские метки времени. + +Хорошая новость в том, что Aspose.BarCode делает это элементарным. В этом руководстве мы создадим `BarcodeGenerator` для **Macro PDF417**, добавим все важные метаданные и сохраним результат в виде PNG‑изображения. К концу вы получите полностью готовый штрих‑код, пригодный для любой системы управления цепочками поставок или документами. + +## Что покрывает это руководство + +Мы пройдемся по: + +1. Установке пакета Aspose.BarCode через NuGet. +2. Инициализации `BarcodeGenerator` для **Macro PDF417**. +3. Заполнению всех полезных **полей метаданных штрих‑кода** (file ID, segment ID, checksum и т.д.). +4. Сохранению штрих‑кода на диск и проверке результата. + +Предыдущий опыт работы с Macro PDF417 не требуется — достаточно базовых знаний C# и актуального .NET‑runtime. + +Зачем это нужно? Встраивание богатых метаданных непосредственно в штрих‑код позволяет сканерам проверять целостность передачи файлов, обнаруживать недостающие сегменты или даже запускать автоматические рабочие процессы. Иными словами, вы получаете **надёжные, самодокументирующиеся данные** без необходимости отдельного поиска в базе данных. + +## Требования + +- .NET 6.0 или новее (код также работает на .NET Framework 4.7+). +- Visual Studio 2022 (или любая другая IDE). +- NuGet‑пакет **Aspose.BarCode for .NET** (доступна бесплатная пробная версия). + +Установить пакет можно следующей командой: + +```bash +dotnet add package Aspose.BarCode +``` + +Теперь, когда подготовка завершена, перейдём к реализации. + +## Шаг 1: Инициализация BarcodeGenerator для Macro PDF417 + +Первое, что нам нужно — экземпляр `BarcodeGenerator`, настроенный для **Macro PDF417**. Это указывает Aspose.BarCode, какой алгоритм кодирования использовать, и предоставляет место для ввода человекочитаемого текста. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Почему это важно:** `EncodeTypes.MacroPdf417` активирует расширенный режим PDF417, поддерживающий метаданные, такие как file ID и номера сегментов. Пример текста содержит Unicode‑символы (`Å`, `ó`, `©`), чтобы продемонстрировать корректную работу генератора с не‑ASCII вводом. + +## Шаг 2: Определение базового внешнего вида штрих‑кода + +Прежде чем добавлять метаданные, следует задать несколько визуальных параметров, чтобы штрих‑код не был микроскопическим пятном. `XDimension` управляет шириной модуля, а `Columns` влияет на общую форму. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Совет:** Ширина в `2` пикселя хорошо подходит для отображения на экране и большинства принтеров. Если требуется печать более высокого разрешения, увеличьте значение до `3` или `4`. + +## Шаг 3: Заполнение полей метаданных Macro PDF417 + +Теперь переходим к основной части руководства — добавлению **полей метаданных штрих‑кода**. Каждое свойство напрямую соответствует сегменту спецификации Macro PDF417. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Что делает каждое свойство + +| Свойство | Назначение | Типичное значение | +|----------|------------|-------------------| +| **MacroPdf417FileID** | Глобальный уникальный идентификатор набора файлов. | `12345678` | +| **MacroPdf417SegmentID** | Индекс текущего сегмента (начинается с `0`). | `12` | +| **MacroPdf417SegmentsCount** | Общее количество сегментов, ожидаемых для файла. | `20` | +| **MacroPdf417FileName** | Человекочитаемое имя, обычно оригинальное имя файла. | `"file01"` | +| **MacroPdf417Checksum** | 16‑битовая контрольная сумма CCITT для обнаружения ошибок. | `1234` | +| **MacroPdf417FileSize** | Размер оригинального файла в байтах. | `400000` | +| **MacroPdf417TimeStamp** | Время генерации файла. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Необязательное поле, указывающее получателя. | `"street"` | +| **MacroPdf417Sender** | Необязательное поле, указывающее систему‑отправитель. | `"aspose"` | +| **MacroPdf417Terminator** | Флаг, сообщающий сканеру, что это последний сегмент. | `Pdf417MacroTerminator.Set` | + +> **Зачем это нужно:** Сканеры, понимающие Macro PDF417, могут собрать файл из нескольких сегментов, проверить целостность с помощью контрольной суммы и даже отклонить устаревшие данные, основываясь на метке времени. Это устраняет необходимость в отдельном манифест‑файле. + +## Шаг 4: Сохранение изображения штрих‑кода + +После установки всех параметров достаточно вызвать `Save`. В примере PNG‑файл сохраняется в указанную вами папку. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Особый случай:** Если планируете позже внедрять штрих‑код в PDF, можно использовать `BarCodeImageFormat.Jpeg` или `Pdf`. PNG сохраняет детали без потерь, что удобно для проверки. + +## Полный рабочий пример + +Объединив всё вместе, получаем полную программу, которую можно скопировать и вставить в консольное приложение: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Ожидаемый результат + +Запуск программы создаёт файл **ExtPDF417Meta.png** в папке исполняемого файла. Откройте его в любом просмотрщике изображений — вы увидите плотный, контрастный PDF417‑штрих‑код. При сканировании его сканером, поддерживающим Macro PDF417, будут возвращены установленные нами метаданные: file ID `12345678`, сегмент `12` из `20` и т.д. + +## Часто задаваемые вопросы и подводные камни + +- **Что делать, если штрих‑код выглядит размытым?** Увеличьте `XDimension.Pixels` или переключитесь на формат изображения более высокого разрешения. +- **Нужно ли задавать каждое поле метаданных?** Нет. Обязательными являются только те поля, которые требуются вашей downstream‑системой. Неиспользуемые поля могут оставаться со значениями по умолчанию. +- **Можно ли автоматически генерировать файл из нескольких сегментов?** Да — выполните цикл по данным, увеличивая `MacroPdf417SegmentID`, и генерируйте отдельный штрих‑код для каждого сегмента. Не забудьте сохранять одинаковый `MacroPdf417FileID` во всех сегментах. +- **Поддерживается ли Unicode?** Абсолютно. Пример текста содержит `Å`, `ó` и `©`, показывая, что Aspose.BarCode работает с UTF‑8 «из коробки». + +## Следующие шаги: выход за рамки базового уровня + +Теперь, когда вы умеете **создавать метаданные штрих‑кода PDF417**, можете изучить: + +- **Встраивание штрих‑кодов в PDF** с помощью `Aspose.Pdf` для полного цикла генерации документов. +- **Чтение метаданных** с помощью `BarcodeReader` для программной проверки сканов. +- **Настройку цветов** (foreground/background) для брендирования. +- **Интеграцию с базой данных** для автоматического заполнения полей, таких как `FileID` или `Timestamp`. + +Все эти темы связаны с нашими вторичными ключевыми словами — **macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, и **c# barcode generation** — так что вы найдёте массу материалов для дальнейшего обучения. + +## Заключение + +Мы прошли полный, готовый к продакшну пример того, как **создать метаданные штрих‑кода PDF417** в C#. От установки Aspose.BarCode, инициализации `BarcodeGenerator`, заполнения всех релевантных **полей метаданных штрих‑кода** до сохранения чёткого PNG‑изображения — процесс прост, как только вы знаете нужные свойства. + +Попробуйте, поиграйте с параметрами и посмотрите, как реагируют сканеры. Гибкость Macro PDF417 позволяет вложить всё, что требуется downstream‑системе, в одну сканируемую картинку. Удачной разработки, и пусть ваши штрих‑коды всегда будут без ошибок! + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом руководстве. Каждый ресурс содержит полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java barcode library – Add barcode to PDF using Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/russian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..d6d1db480 --- /dev/null +++ b/barcode/russian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: Быстро генерируйте штрих‑код PDF417 и узнайте, как задать количество + столбцов для компактного изображения штрих‑кода PDF417 в C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: ru +lastmod: 2026-07-15 +og_description: Создавайте штрих‑код PDF417 с помощью Aspose.BarCode и узнайте, как + установить количество столбцов для создания компактного изображения штрих‑кода PDF417. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: Создание штрих‑кода PDF417 на C# – пошаговое руководство +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: Генерация штрихкода PDF417 в C# – Полное руководство +url: /ru/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Генерация штрих‑кода PDF417 в C# – Полное руководство + +Когда‑то вам нужно **сгенерировать штрих‑код PDF417** в проекте .NET, но вы не знаете, с чего начать? Вы не одиноки. Во многих корпоративных приложениях — будь то принтеры посадочных талонов, бирки инвентаря или мобильные билеты — PDF417 является рабочей лошадкой, упаковывающей большое количество данных в небольшой визуальный след. + +Дело в том, что библиотека Aspose.BarCode делает весь процесс почти безболезненным, и вы даже можете управлять **тем, как задать столбцы**, чтобы штрих‑код был максимально компактным. К концу этого руководства у вас будет готовое PNG‑изображение **штрих‑кода PDF417**, которое можно вставить в любой UI, письмо или задачу печати. + +## Что вы получите в результате + +- Полностью рабочее консольное приложение C#, создающее штрих‑код PDF417. +- Чёткое понимание *X‑Dimension* (размера модуля) и почему это важно. +- Пошаговые инструкции о **том, как задать столбцы** для более плотного штрих‑кода. +- Сохранённый файл `PNG`, который можно сразу открыть для проверки результата. +- Советы по устранению распространённых проблем (например, нечитаемые штрих‑коды, неверный формат изображения). + +> **Prerequisites** – .NET 6+ SDK, Visual Studio 2022 (или любой другой редактор), и ссылка NuGet на `Aspose.BarCode`. Больше ничего не требуется. + +--- + +## Шаг 1: Установите пакет Aspose.BarCode через NuGet + +Прежде чем мы сможем *сгенерировать штрих‑код PDF417*, библиотека должна быть добавлена в проект. + +```bash +dotnet add package Aspose.BarCode +``` + +Эта единственная строка подтягивает все типы, которые вам понадобятся, включая `BarcodeGenerator`, `EncodeTypes` и перечисление `BarCodeImageFormat`. + +> **Pro tip:** Если вы таргетируете .NET Framework вместо .NET 6, используйте классическую команду PowerShell `Install-Package Aspose.BarCode` в консоли Package Manager. + +--- + +## Шаг 2: Создайте минимальное консольное приложение + +Сделаем небольшую программу, которая ничего не делает, кроме как генерирует штрих‑код. Откройте новую папку, выполните `dotnet new console`, затем замените автоматически сгенерированный `Program.cs` кодом ниже. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Почему это важно:** +- `EncodeTypes.Pdf417` сообщает библиотеке, что нам нужен штрих‑код PDF417, а не QR или Code128. +- `XDimension.Pixels` управляет разрешением каждого крошечного чёрного или белого модуля. +- Блок **how to set columns** напрямую влияет на форму **изображения штрих‑кода PDF417**. +- `Truncate = true` убирает все лишние пустые строки, давая «компактный» вид, который любят многие сканеры. + +--- + +## Шаг 3: Углубляемся – Понимание столбцов и усечения + +### Как задать столбцы + +PDF417 располагает данные в матрице *строк* × *столбцов*. По умолчанию библиотека использует 5 столбцов, что подходит для большинства случаев. Однако вам может потребоваться более узкий штрих‑код для этикетки или более широкий для повышения надёжности сканирования. Свойство: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +принимает значения от **1** до **30** (точный лимит зависит от длины данных). Ниже быстрый шпаргалка: + +| Столбцы | Прибл. ширина (мм) | Когда использовать | +|---------|-------------------|----------------------| +| 1‑3 | Очень узко | Маленькая этикетка, ограниченное пространство | +| 4‑6 | Стандартно | Большинство чеков, билетов | +| 7‑10 | Шире | Высокоплотные данные, лучшая читаемость | + +### Truncate (режим компактности) + +Установка `Truncate = true` заставляет кодировщик отрезать все ненужные пустые строки внизу. Результат — **компактное изображение штрих‑кода PDF417**, занимающее минимальную площадь при сохранении всех данных. Если вы получаете ошибку «штрих‑код слишком велик для этикетки», переключите этот флаг. + +--- + +## Шаг 4: Запустите приложение и проверьте результат + +Скомпилируйте и выполните: + +```bash +dotnet run +``` + +Вы должны увидеть сообщение в консоли, подтверждающее место сохранения. Перейдите в папку и откройте `CompactPdf417.png`. Изображение будет выглядеть примерно так: + +![Generated PDF417 barcode image](./CompactPdf417.png "Generated PDF417 barcode image – compact PNG created by Aspose.BarCode") + +*Текст альтернативного описания:* **Сгенерированное изображение штрих‑кода PDF417** — компактный PNG‑файл, полученный с помощью кода из руководства. + +Если ваш сканер смог его прочитать, поздравляем — вы успешно **сгенерировали штрих‑код PDF417** и освоили **то, как задать столбцы** для аккуратного **изображения штрих‑кода PDF417**. + +--- + +## Шаг 5: Распространённые проблемы и их решения + +| Симптом | Вероятная причина | Быстрое решение | +|---------|-------------------|-----------------| +| Штрих‑код выглядит размытым | `XDimension.Pixels` слишком низкое (например, 1) | Увеличьте до 2‑3 пикселей для более чёткого изображения. | +| Сканер не читает | Слишком много столбцов для заданных данных | Уменьшите `Columns` или включите `Truncate`. | +| Неправильный формат файла | По ошибке сохранено с `BarCodeImageFormat.Jpeg` | Используйте `BarCodeImageFormat.Png` для без потерь. | +| Исключение `ArgumentOutOfRangeException` | Количество столбцов превышает допустимый диапазон | Держите столбцы в пределах 1‑30 и убедитесь, что данные помещаются. | + +--- + +## Шаг 6: Дальше — настройка цветов и добавление текста + +Если хотите, чтобы штрих‑код соответствовал фирменной палитре, можно изменить цвета переднего плана и фона: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Или добавить человекочитаемый текст под штрих‑кодом: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Эти дополнения необязательны, но показывают, насколько гибким может быть процесс **генерации штрих‑кода PDF417**. + +--- + +## Заключение + +Мы прошли полный пример от начала до конца, который **генерирует штрих‑код PDF417** с помощью Aspose.BarCode, объяснил **как задать столбцы** для управления размерами штрих‑кода и сохранил результат в виде чёткого **изображения штрих‑кода PDF417** в формате PNG. Код автономный, работает с .NET 6+ и может быть добавлен в любой существующий проект без лишних хлопот. + +Что дальше? Попробуйте кодировать более крупные полезные нагрузки (например, JSON), поэкспериментируйте с различными форматами изображений или интегрируйте генератор в веб‑API, который будет отдавать штрих‑коды по запросу. Возможности безграничны, а у вас теперь есть надёжная база для дальнейшего развития. + +Счастливого кодинга, и пусть ваши штрих‑коды всегда сканируются с первой попытки! + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/russian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..20b8f3765 --- /dev/null +++ b/barcode/russian/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-07-15 +description: Быстро генерируйте штрих‑код PDF417 с помощью C#. Узнайте, как создать + штрих‑код из текста, настроить его размер и задать пользовательские размеры штрих‑кода + за считанные минуты. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: ru +lastmod: 2026-07-15 +og_description: Генерируйте штрих‑код PDF417 в C# мгновенно. Это руководство показывает, + как создать штрих‑код из текста, настроить размер штрих‑кода и задать пользовательские + размеры штрих‑кода. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Генерация штрих‑кода PDF417 в C# – Полный учебник по программированию +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Генерация штрихкода PDF417 в C# – полное пошаговое руководство +url: /ru/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Генерация штрих‑кода PDF417 на C# – Полное пошаговое руководство + +Когда‑то вам нужно было **создать штрих‑код PDF417**, но вы не знали, какие параметры менять? Вы не одиноки — многие разработчики сталкиваются с тем же самым, когда впервые работают с 2‑D штрих‑кодами. Хорошая новость? Пара строк кода на C# позволяют превратить любую строку в сканируемое изображение PDF417, точно задать его размер и даже определить пользовательскую раскладку столбцов‑строк. + +В этом руководстве мы пройдёмся по тому, как **создать штрих‑код из текста**, настроить его размер и задать пользовательские размеры штрих‑кода — всё с помощью популярной библиотеки Aspose.BarCode. К концу вы получите готовый пример, который можно сразу вставить в любой .NET‑проект. + +![Создать пример штрих‑кода PDF417](https://example.com/og-image.png "Создать пример штрих‑кода PDF417") + +## Что вы создадите + +- Штрих‑код PDF417, кодирующий строку `Åspóse.Barcóde©`. +- Точный контроль над X‑размером (ширина в пикселях каждого модуля). +- Пользовательскую раскладку из 4 столбцов и 9 строк. +- PNG‑файл, сохранённый на диск. + +Никаких внешних сервисов, никаких волшебных палочек — только чистый C#‑код, который можно сразу скомпилировать. + +## Требования + +- .NET 6.0 или новее (код также работает на .NET Framework 4.8). +- Visual Studio 2022 или любой IDE, поддерживающий C#. +- Aspose.BarCode for .NET (бесплатная пробная версия или лицензия). Установите через NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +Вот и всё — как только пакет подключён, можно начинать. + +## Шаг 1 – Генерация штрих‑кода PDF417 из текстовых данных + +Первым делом нам нужен экземпляр `BarcodeGenerator`, который знает, что мы работаем с символьностью PDF417 и с тем текстом, который хотим закодировать. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Почему это важно:** +> `EncodeTypes.Pdf417` указывает библиотеке использовать 2‑D формат PDF417, а второй аргумент — это **генерация штрих‑кода из текста**. Всё, что вы передаёте сюда, становится данными, хранящимися в матрице штрих‑кода. + +## Шаг 2 – Регулировка размера штрих‑кода (X‑размер) + +Если вы когда‑либо печатали штрих‑код, который получался слишком крошечным на чеке, знаете, как раздражает, когда сканер его не видит. Свойство `XDimension` управляет шириной одного модуля (самого маленького чёрного или белого квадратика) в пикселях. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Совет профессионала:** +> Значение 2 px хорошо подходит для большинства сценариев отображения на экране. Для печати высокого разрешения можно увеличить его до 3 или 4 px. Помните, что больший X‑размер увеличивает общий размер изображения. + +## Шаг 3 – Задание пользовательских размеров штрих‑кода (Столбцы и строки) + +PDF417 позволяет задать, сколько столбцов и строк будет занимать штрих‑код. Здесь вступают в действие **пользовательские размеры штрих‑кода**. Изменение этих параметров помогает разместить штрих‑код в ограниченном пространстве UI или соответствовать конкретному размеру этикетки. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Что происходит под капотом?** +> Библиотека перераспределяет закодированные данные по указанной сетке. Меньшее количество столбцов делает штрих‑код выше; больше строк — короче. Поэкспериментируйте с числами, пока визуальный баланс не будет выглядеть правильно для вашего приложения. + +## Шаг 4 – Сохранение изображения штрих‑кода + +После настройки всех параметров просто просим генератор записать PNG‑файл. PNG — это формат без потерь, поэтому чёткость модулей сохраняется. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Запустив программу, вы увидите файл `C:\Barcodes\CustomLayout.png`, похожий на скриншот выше. Сканирование его любой программой, поддерживающей PDF417, вернёт исходную строку `Åspóse.Barcóde©`. + +## Полный рабочий пример + +Ниже представлен полностью готовый код, который можно скопировать в консольное приложение. В нём присутствуют все директивы `using` и обработка ошибок, ожидаемая в продакшн‑коде. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Ожидаемый вывод + +При запуске код выводит: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…и создаёт PNG, который открывается в любой программе просмотра изображений. Если просканировать его мобильным приложением (например, «Barcode Scanner» на iOS/Android), декодированный текст будет точно **Åspóse.Barcóde©**. + +## Часто задаваемые вопросы и особые случаи + +| Вопрос | Ответ | +|----------|--------| +| **Можно ли использовать другой формат изображения?** | Да — поддерживаются `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` и `Svg`. Просто измените второй аргумент метода `Save`. | +| **Что если мой текст содержит Unicode‑символы?** | Aspose.BarCode полностью поддерживает UTF‑8, поэтому пример с `Å` и `©` работает «из коробки». | +| **Как изменить уровень коррекции ошибок?** | Используйте `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (уровни 0‑8). Более высокий уровень повышает избыточность, но и размер. | +| **Мне нужен прозрачный фон — это возможно?** | Установите `generator.Parameters.Barcode.Image.TransparentBackground = true;` перед сохранением. | +| **Можно ли встроить штрих‑код напрямую в PDF?** | Конечно. Замените вызов `Save` на `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` — вы получите одностраничный PDF с штрих‑кодом. | + +## Заключение + +Теперь вы знаете, как **генерировать штрих‑код PDF417** на C# из любой строки, **регулировать размер штрих‑кода** и применять **пользовательские размеры** для соответствия вашим требованиям к макету. Четырёхшаговый процесс — инициализация, размер, раскладка, сохранение — охватывает основной рабочий поток для большинства сценариев 2‑D штрих‑кодов. + +Что дальше? Попробуйте заменить `EncodeTypes.Pdf417` на `EncodeTypes.QR` или `EncodeTypes.Code128`, чтобы увидеть, как API адаптируется. Поэкспериментируйте с различными значениями `XDimension`, меняйте матрицу столбцов/строк или внедряйте изображение в PDF‑отчёт. Возможности практически безграничны, и теперь у вас есть прочный фундамент для дальнейшего развития. + +Есть вопросы или вы нашли интересный приём, работая с PDF417? Оставляйте комментарий ниже — давайте поддерживать обсуждение. Приятного кодинга! + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом пособии. Каждый ресурс содержит полностью рабочие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Generate DataMatrix Barcode – Pro Guide with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/russian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..eb378cebc --- /dev/null +++ b/barcode/russian/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-07-15 +description: Как считывать штрих‑код PDF417 в C# и читать несколько штрих‑кодов с + изображения. Узнайте, как читать изображение штрих‑кода в C# с подробным кодом и + советами. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: ru +lastmod: 2026-07-15 +og_description: Как быстро считывать штрих‑код PDF417 в C#. Это руководство покажет, + как считывать несколько штрих‑кодов с одного изображения и декодировать каждое свойство. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Как читать PDF417 в C# – полный пример кода и объяснение +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Как считывать PDF417 в C# — полное пошаговое руководство +url: /ru/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как считывать PDF417 в C# – Полное пошаговое руководство + +Когда‑нибудь задумывались **как считывать PDF417** с изображения с помощью C#? Вы не одиноки. Большинство разработчиков сталкиваются с проблемой, когда нужно извлечь расширенные поля Macro‑PDF417 из отсканированного документа. Хорошая новость? Всего несколькими строками кода можно декодировать PDF417, считать несколько штрихкодов на одной картинке и получить каждое скрытое свойство, которое описывает спецификация. + +В этом руководстве мы пройдем реальный пример, показывающий **как считывать PDF417**, как **считывать несколько штрихкодов** из одного файла и почему код **read barcode image C#** выглядит именно так. К концу вы получите готовое консольное приложение, которое выводит всю необходимую информацию — ID файла, ID сегмента, контрольную сумму, метки времени и т.д. + +## Требования + +Прежде чем начать, убедитесь, что у вас есть: + +* .NET 6.0 SDK или новее (код работает и с .NET Core, и с .NET Framework). +* Visual Studio 2022 (или любой другой предпочитаемый редактор). +* NuGet‑пакет **Aspose.BarCode for .NET** — это библиотека, которая действительно парсит PDF417. +* Пример изображения, содержащего штрихкод Macro‑PDF417 (например `ExtPDF417Meta.png`). + +Дополнительная конфигурация не требуется; библиотека поставляется со всеми необходимыми декодерами. + +## Шаг 1: Установить Aspose.BarCode + +Откройте папку проекта в терминале и выполните: + +```bash +dotnet add package Aspose.BarCode +``` + +Эта команда загрузит последнюю стабильную версию (на июль 2026 это 23.12). Если вы предпочитаете Package Manager Console в Visual Studio, используйте: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Pro tip:** зафиксируйте версию (`23.12.0`) в вашем `.csproj`, чтобы избежать случайных несовместимых изменений в будущем. + +## Шаг 2: Создать каркас консольного приложения + +Создайте новый консольный проект, если у вас его ещё нет: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Замените автоматически сгенерированный `Program.cs` кодом ниже. Мы разберём каждый блок в следующих разделах. + +## Шаг 3: Написать полный код «Как считывать PDF417» + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Почему этот код работает + +* **`BarCodeReader`** — основной класс, который читает изображение, обнаруживает штрихкоды и возвращает коллекцию объектов `BarCodeResult`. +* Передача **`DecodeType.MacroPdf417`** сообщает библиотеке обрабатывать Macro‑PDF417 особым образом; при этом она всё равно возвращает обычные символы PDF417, что удовлетворяет требованию **read multiple barcodes**. +* Объект **`Extended.Pdf417.MacroPdf417`** содержит все необязательные поля, определённые стандартом ISO/IEC 15438 — здесь вы получаете `FileID`, `SegmentID`, `Checksum` и т.д. +* Блок `using` гарантирует освобождение нативных ресурсов, предотвращая утечки памяти в длительно работающих сервисах. + +## Шаг 4: Запустить приложение и проверить вывод + +В терминале: + +```bash +dotnet run +``` + +Вы должны увидеть что‑то вроде: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Если изображение содержит более одного штрихкода, цикл выведет разделительную строку (`----------------------------------------`) и продолжит с следующим результатом — именно так выглядит **read multiple barcodes** на практике. + +## Часто задаваемые вопросы и особые случаи + +### Что делать, если изображение содержит как Macro‑PDF417, так и обычные PDF417 символы? + +Тот же вызов `BarCodeReader` вернёт оба типа. Их можно различать, проверяя `result.CodeType` (`MacroPdf417` vs `Pdf417`). Расширенные свойства будут `null` для обычного PDF417, поэтому условие `if (macro != null)` предотвращает `NullReferenceException`. + +### Мой штрихкод повернут или искажен — будет ли работать считыватель? + +Aspose.BarCode включает встроенную компенсацию вращения и искажений. Пока штрихкод занимает минимум 30 % ширины изображения, декодер обычно справляется. Для экстремальных случаев можно включить `reader.Options.AllowInvertedBarcodes = true;` перед вызовом `ReadBarCodes()`. + +### Как обрабатывать большие партии изображений? + +Обёрните логику чтения в цикл `foreach (var file in Directory.GetFiles(folder, "*.png"))`. Паттерн `using` гарантирует освобождение нативных ресурсов каждого изображения перед следующей итерацией, поддерживая низкое потребление памяти. + +## Полный листинг исходного кода (готов к копированию) + +Ниже представлен весь код программы в одном блоке для быстрого копирования. Нет скрытых зависимостей — только NuGet‑пакет Aspose.BarCode. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Итоги – Что мы рассмотрели + +* **Как считывать PDF417** с помощью Aspose.BarCode в C#. +* Точные шаги для **read multiple barcodes** из одного изображения. +* Как **read barcode image C#** и извлечь каждое поле Macro‑PDF417. +* Советы по работе с вращением, пакетной обработкой и отсутствующими расширенными данными. + +## Следующие шаги и смежные темы + +* **Encode PDF417** — генерируйте свои собственные Macro‑PDF417 штрихкоды с помощью `BarCodeBuilder`. +* **Read other 2‑D symbologies** — QR, DataMatrix, Aztec — используя тот же класс `BarCodeReader`. +* **Integrate with ASP.NET Core** — создайте веб‑конечную точку, принимающую загруженное изображение и возвращающую JSON с декодированными полями. + +Экспериментируйте: меняйте путь к изображению, бросайте обычный PDF417 в ту же папку или меняйте флаги `DecodeType`, чтобы увидеть, как библиотека реагирует. Чем больше вы играете, тем увереннее будете себя чувствовать в сценариях **read barcode image C#**. + +Есть сложное изображение, которое отказывается декодироваться? Оставьте комментарий ниже или откройте issue в репозитории GitHub примера проекта. Приятного кодинга! + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом гиде. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [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/russian/net/one-dimensional-barcode-types/_index.md b/barcode/russian/net/one-dimensional-barcode-types/_index.md index 8a11b64f3..a26993cd0 100644 --- a/barcode/russian/net/one-dimensional-barcode-types/_index.md +++ b/barcode/russian/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ url: /ru/net/one-dimensional-barcode-types/ Узнайте, как обрабатывать исключения при создании одномерных штрих-кодов с помощью Aspose.BarCode для .NET. Это пошаговое руководство обеспечивает устойчивые к ошибкам решения в области штрих-кодов. Начать сейчас! ### [Одномерная конфигурация с широким и узким соотношением](./one-dimensional-wide-narrow-ratio-configuration/) Легко создавайте индивидуальные штрих-коды с помощью Aspose.BarCode для .NET. Пошаговое руководство по одномерной конфигурации с широким и узким соотношением сторон. +### [Генерация штрих-кода из текста с помощью Aspose.BarCode – руководство C#](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Узнайте, как создать штрих-код из текста в C# с помощью Aspose.BarCode. Пошаговое руководство. ## Заключение @@ -89,4 +91,4 @@ url: /ru/net/one-dimensional-barcode-types/ {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/russian/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..eec286201 --- /dev/null +++ b/barcode/russian/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-07-15 +description: Создайте штрих‑код из текста с помощью Aspose.BarCode в C#. Узнайте, + как изменить количество столбцов, сохранить изображение штрих‑кода и быстро создавать + решения Aspose для штрих‑кодов. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: ru +lastmod: 2026-07-15 +og_description: Создайте штрих‑код из текста с помощью Aspose.BarCode. Это руководство + показывает, как изменить количество столбцов, сохранить изображение штрих‑кода и + создать штрих‑код Aspose в несколько строк кода. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Генерация штрихкода из текста с Aspose.BarCode – Быстрый обзор C# +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Генерация штрихкода из текста с использованием Aspose.BarCode – руководство + по C# +url: /ru/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Генерация штрихкода из текста с помощью Aspose.BarCode – Руководство C# + +Генерация штрихкода из текста с помощью Aspose.BarCode удивительно проста. В этом руководстве мы пройдёмся по **созданию штрихкода**, настроим расположение колонок и, наконец, **сохраним изображение штрихкода** в файл PNG. Независимо от того, создаёте ли вы систему билетов, принтер этикеток для склада или просто экспериментируете с QR‑подобными кодами, нижеописанные шаги быстро приведут вас к результату. + +## Чему вы научитесь + +- Создать штрихкод из любой Unicode‑строки (да, даже «Åspóse.Barcóde©» работает). +- Настроить **количество колонок** для MicroPdf417, чтобы подогнать под узкие или широкие этикетки. +- Сохранить результат на диск в нужном формате изображения. +- Советы по работе со специальными символами и типичные подводные камни при **создании штрихкода Aspose**. + +Никаких внешних инструментов, без командных строк — только чистый C# и библиотека Aspose.BarCode. + +## Предварительные требования + +Прежде чем приступить, убедитесь, что у вас есть: + +1. **.NET 6.0** или новее (код также работает на .NET Framework 4.7+). +2. **Лицензия** на Aspose.BarCode, либо вы можете начать с бесплатной оценочной версии. +3. Папка, в которую можно записывать файлы — в примерах мы назовём её `YOUR_DIRECTORY`. + +Если чего‑то не хватает, скачайте пакет NuGet прямо сейчас: + +```bash +dotnet add package Aspose.BarCode +``` + +Вот и всё — никаких дополнительных DLL для копирования вручную. + +## Шаг 1 – Настройка проекта и импортов + +Сначала создайте консольное приложение (или вставьте код в любой C#‑проект). Главное — подключить нужные пространства имён: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Зачем эти using? `BarcodeGenerator` находится в `Aspose.BarCode.Generation`, а перечисление `BarCodeImageFormat` — в `Aspose.BarCode`. Чистый импорт делает последующий код более читаемым, как обычный английский текст. + +## Шаг 2 – Создание генератора штрихкода (как генерировать штрихкод) + +Теперь мы действительно **генерируем штрихкод из текста**. Перечисление `EncodeTypes` указывает Aspose, какую символьную систему использовать; здесь мы выбираем `MicroPdf417`, потому что он умеет компактно размещать длинные строки. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Обратите внимание, строка содержит символы с диакритикой и знак ©. Aspose.BarCode автоматически кодирует Unicode, так что предварительная обработка текста не требуется. + +## Шаг 3 – Точная настройка внешнего вида (как изменить количество колонок) + +MicroPdf417 позволяет управлять числом колонок, что напрямую влияет на ширину штрихкода. Более плотная раскладка подходит для узких этикеток; более широкая — улучшает читаемость на больших печатных листах. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Почему модули 2 пикселя? Это даёт чёткое изображение без излишнего увеличения размера файла. Экспериментируйте — значения от 1 до 4 обычно работают хорошо. Если понадобится другое количество колонок, просто измените свойство `Columns`; Aspose автоматически пересчитает макет. + +## Шаг 4 – Сохранение изображения штрихкода (сохранить изображение штрихкода) + +Сгенерировав объект, мы готовы **сохранить изображение штрихкода**. Метод `Save` принимает путь к файлу и перечисление формата изображения. PNG — без потерь, поэтому штрихкод остаётся чётким даже после масштабирования. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Полезный совет: всегда используйте абсолютный путь или убедитесь, что рабочая директория соответствует вашим ожиданиям; иначе файл может оказаться в папке bin, и вы не сможете его найти. + +## Полный рабочий пример + +Объединив всё вместе, получаем автономную программу, которую можно скопировать в `Program.cs` и запустить: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Ожидаемый вывод** (консоль): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +И если открыть `MicroPdf417.png`, вы увидите чёткий штрихкод MicroPdf417, который кодирует исходную строку, включая все специальные символы, которые мы передали. + +## Часто задаваемые вопросы и особые случаи + +### Что делать, если мой текст длиннее стандартной ёмкости? + +MicroPdf417 автоматически переходит в многострочный макет, когда данные превышают максимум на одну строку. Вы всё равно можете управлять количеством колонок, но библиотека может добавить дополнительные строки «за кулисами». Дополнительный код не нужен — просто следите за размерами получаемого изображения. + +### Как изменить формат изображения на JPEG или BMP? + +Замените `BarCodeImageFormat.Png` на `BarCodeImageFormat.Jpeg` (или `Bmp`). Помните, что JPEG вводит артефакты сжатия, что может повлиять на надёжность сканирования. PNG остаётся самым безопасным вариантом. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Я вижу водяной знак в результате — в чём проблема? + +Это оценочная версия Aspose.BarCode. Чтобы **создать штрихкод Aspose** без водяных знаков, загрузите действительный файл лицензии, как показано в закомментированной строке Шага 2. + +### Можно ли генерировать другие символьные системы (QR, Code128 и т.д.)? + +Конечно. Просто замените `EncodeTypes.MicroPdf417` на любое другое значение из перечисления `EncodeTypes`, например `EncodeTypes.QR` или `EncodeTypes.Code128`. Остальная часть кода остаётся без изменений, что делает подход очень переиспользуемым. + +## Профессиональные советы для готовой к продакшну генерации штрихкодов + +- **Кешируйте генератор**, если создаёте много штрихкодов с одинаковыми настройками; это уменьшит накладные расходы на создание объектов. +- **Проверяйте входную строку** на ограничения длины, характерные для выбранной символьной системы (Aspose бросает `ArgumentException`, если строка слишком длинная). +- **Используйте конструкции `using`** или вызывайте `Dispose` у генератора после завершения работы, чтобы своевременно освободить нативные ресурсы. +- **Устанавливайте DPI** через `generator.Parameters.ImageResolution.DpiX/DpiY`, если нужны высокоразрешающие печати для больших этикеток. + +## Заключение + +Теперь вы точно знаете **как генерировать штрихкод из текста** с помощью Aspose.BarCode, как **изменять количество колонок** и как правильно **сохранять изображение штрихкода** в PNG. Полный, исполняемый пример выше демонстрирует чистый, готовый к продакшну подход. + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные варианты реализации в собственных проектах. + +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Generate barcode image – Code 93 with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/spanish/net/compact-pdf417-encoding/_index.md index 6c5e3bd09..3771908e4 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. +### [Crear metadatos de código de barras PDF417 en C# – Guía completa paso a paso](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +Aprende a generar metadatos en códigos de barras PDF417 con C# usando Aspose.BarCode, paso a paso y con ejemplos claros. +### [Generar código de barras PDF417 en C# – Guía completa](./generate-pdf417-barcode-in-c-complete-guide/) +Aprende a crear códigos de barras PDF417 en C# con Aspose.BarCode, paso a paso y con ejemplos claros. +### [Generar código de barras PDF417 en C# – Guía completa paso a paso](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +Guía detallada para generar códigos de barras PDF417 en C# usando Aspose.BarCode, con ejemplos y mejores prácticas. +### [Cómo leer PDF417 en C# – Guía completa paso a paso](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) +Aprende a leer códigos de barras PDF417 en C# usando Aspose.BarCode, paso a paso y con ejemplos claros. ## 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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/spanish/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..01aa75540 --- /dev/null +++ b/barcode/spanish/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-07-15 +description: Crear metadatos de código de barras PDF417 en C# usando Aspose.BarCode. + Aprender la configuración Macro PDF417, guardar como PNG y manejar texto Unicode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: es +lastmod: 2026-07-15 +og_description: Crea metadatos de código de barras PDF417 en C# con Aspose.BarCode. + Esta guía muestra cada configuración que necesitas para incrustar ID de archivo, + marcas de tiempo y más. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: Crear metadatos de código de barras PDF417 en C# – Guía completa de programación +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: Crear metadatos de código de barras PDF417 en C# – Guía completa paso a paso +url: /es/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear metadatos de código de barras PDF417 en C# – Guía completa paso a paso + +¿Alguna vez necesitaste **crear metadatos de código de barras PDF417** en C# pero no sabías qué propiedades ajustar? No eres el único: los desarrolladores a menudo se quedan atascados cuando la especificación exige cosas como IDs de archivo, recuentos de segmentos o marcas de tiempo personalizadas. + +La buena noticia es que Aspose.BarCode lo hace muy fácil. En este tutorial crearemos un `BarcodeGenerator` para **Macro PDF417**, añadiremos todos los metadatos importantes y guardaremos el resultado como una imagen PNG. Al final tendrás un código de barras totalmente funcional listo para cualquier sistema de cadena de suministro o gestión documental. + +## Qué cubre esta guía + +Recorreremos: + +1. Configurar el paquete NuGet Aspose.BarCode. +2. Inicializar un `BarcodeGenerator` para **Macro PDF417**. +3. Rellenar cada **campo de metadatos del código de barras** útil (file ID, segment ID, checksum, etc.). +4. Guardar el código de barras en disco y verificar la salida. + +No se requiere experiencia previa con Macro PDF417, solo conocimientos básicos de C# y un runtime .NET reciente. + +¿Por qué debería importarte? Incrustar metadatos ricos directamente en un código de barras permite que los escáneres posteriores validen transferencias de archivos completas, detecten segmentos faltantes o incluso activen flujos de trabajo automatizados. En otras palabras, obtienes **datos robustos y autodescriptivos** sin necesidad de una base de datos externa. + +## Requisitos previos + +- .NET 6.0 o superior (el código también funciona en .NET Framework 4.7+). +- Visual Studio 2022 (o cualquier IDE que prefieras). +- El paquete NuGet **Aspose.BarCode for .NET** (prueba gratuita disponible). + +Puedes instalar el paquete con el siguiente comando: + +```bash +dotnet add package Aspose.BarCode +``` + +Ahora que tenemos la base, vamos a sumergirnos en la implementación real. + +## Paso 1: Inicializar el BarcodeGenerator para Macro PDF417 + +Lo primero que necesitamos es una instancia de `BarcodeGenerator` configurada para **Macro PDF417**. Esto le indica a Aspose.BarCode qué algoritmo de codificación usar y nos brinda un lugar para introducir el texto legible por humanos. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Por qué es importante:** `EncodeTypes.MacroPdf417` activa el modo PDF417 extendido que soporta metadatos como IDs de archivo y números de segmento. El texto de ejemplo contiene caracteres Unicode (`Å`, `ó`, `©`) para demostrar que el generador maneja entradas no ASCII sin problemas. + +## Paso 2: Definir la apariencia básica del código de barras + +Antes de comenzar a añadir metadatos, debemos establecer algunos parámetros visuales para que el código de barras no sea un punto microscópico. `XDimension` controla el ancho del módulo, mientras que `Columns` influye en la forma general. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Consejo profesional:** Un ancho de píxel de `2` funciona bien para visualización en pantalla y la mayoría de impresoras. Si necesitas una impresión de mayor resolución, aumenta a `3` o `4`. + +## Paso 3: Rellenar los campos de metadatos de Macro PDF417 + +Ahora llega el corazón del tutorial: añadir **campos de metadatos del código de barras**. Cada propiedad se corresponde directamente con un segmento de la especificación Macro PDF417. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Qué hace cada propiedad + +| Property | Propósito | Valor Típico | +|----------|-----------|--------------| +| **MacroPdf417FileID** | Identificador único global para todo el conjunto de archivos. | `12345678` | +| **MacroPdf417SegmentID** | Índice del segmento actual (comienza en `0`). | `12` | +| **MacroPdf417SegmentsCount** | Total de segmentos esperados para el archivo. | `20` | +| **MacroPdf417FileName** | Nombre legible por humanos, a menudo el nombre original del archivo. | `"file01"` | +| **MacroPdf417Checksum** | Checksum CCITT de 16 bits para detección de errores. | `1234` | +| **MacroPdf417FileSize** | Tamaño del archivo original en bytes. | `400000` | +| **MacroPdf417TimeStamp** | Momento en que se generó el archivo. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Campo opcional que indica el destinatario. | `"street"` | +| **MacroPdf417Sender** | Campo opcional que indica el sistema origen. | `"aspose"` | +| **MacroPdf417Terminator** | Indicador que le dice al escáner que este es el segmento final. | `Pdf417MacroTerminator.Set` | + +> **Por qué los necesitas:** Los escáneres que entienden Macro PDF417 pueden reensamblar un archivo de varios segmentos, verificar la integridad con el checksum e incluso rechazar datos obsoletos según la marca de tiempo. Esto elimina la necesidad de un archivo de manifiesto separado. + +## Paso 4: Guardar la imagen del código de barras + +Una vez que todos los parámetros están configurados, simplemente llamamos a `Save`. El ejemplo escribe un archivo PNG en la carpeta que especifiques. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Caso límite:** Si planeas incrustar el código de barras en un PDF más adelante, podrías preferir `BarCodeImageFormat.Jpeg` o `Pdf`. PNG conserva los detalles sin pérdida, lo que resulta útil para la verificación. + +## Ejemplo completo funcionando + +Juntando todo, aquí tienes el programa completo que puedes copiar y pegar en una aplicación de consola: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Salida esperada + +Al ejecutar el programa se crea un archivo llamado **ExtPDF417Meta.png** en la carpeta del ejecutable. Ábrelo con cualquier visor de imágenes y verás un denso código de barras PDF417 de alto contraste. Si lo escaneas con un lector que soporte Macro PDF417, el escáner devolverá los valores de metadatos que configuramos: file ID `12345678`, segmento `12` de `20`, etc. + +## Preguntas frecuentes y trampas comunes + +- **¿Qué pasa si el código de barras se ve borroso?** Aumenta `XDimension.Pixels` o cambia a un formato de imagen de mayor resolución. +- **¿Tengo que establecer todos los campos de metadatos?** No. Solo los campos requeridos por tu sistema posterior son obligatorios. Los campos no usados pueden quedar con sus valores predeterminados. +- **¿Puedo generar automáticamente un archivo de varios segmentos?** Sí: recorre los datos, incrementa `MacroPdf417SegmentID` y genera un código de barras separado para cada segmento. Recuerda mantener `MacroPdf417FileID` constante en todos los segmentos. +- **¿Se soporta Unicode?** Absolutamente. El texto de ejemplo contiene `Å`, `ó` y `©`, demostrando que Aspose.BarCode maneja UTF‑8 de forma nativa. + +## Próximos pasos: Más allá de lo básico + +Ahora que sabes cómo **crear metadatos de código de barras PDF417**, podrías explorar: + +- **Incrustar códigos de barras en PDFs** usando `Aspose.Pdf` para generación de documentos de extremo a extremo. +- **Leer los metadatos** con `BarcodeReader` para validar escaneos programáticamente. +- **Personalizar colores** (primer plano/fondo) para fines de branding. +- **Integrar con una base de datos** para autocompletar campos como `FileID` o `Timestamp`. + +Todos estos temas están vinculados a nuestras palabras clave secundarias—**macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, y **c# barcode generation**—por lo que encontrarás mucho material para seguir aprendiendo. + +## Conclusión + +Acabamos de recorrer un ejemplo completo y listo para producción de cómo **crear metadatos de código de barras PDF417** en C#. Desde la instalación de Aspose.BarCode, la inicialización de un `BarcodeGenerator`, el llenado de cada **campo de metadatos del código de barras**, hasta guardar un PNG nítido, el proceso es sencillo una vez conoces las propiedades correctas. + +Pruébalo, ajusta los valores y observa cómo reaccionan los escáneres. La flexibilidad de Macro PDF417 te permite incrustar todo lo que un sistema posterior necesita, todo dentro de una única imagen escaneable. ¡Feliz codificación y que tus códigos de barras estén siempre libres de errores! + +## ¿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 con 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/) +- [java barcode library – Add barcode to PDF using Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/spanish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..84daafa39 --- /dev/null +++ b/barcode/spanish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: Genera código de barras PDF417 rápidamente y aprende cómo establecer + columnas para una imagen de código de barras PDF417 compacta en C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: es +lastmod: 2026-07-15 +og_description: Genera código de barras PDF417 con Aspose.BarCode y aprende cómo establecer + columnas para crear una imagen de código de barras PDF417 compacta. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: Generar código de barras PDF417 en C# – Guía paso a paso +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: Generar código de barras PDF417 en C# – Guía completa +url: /es/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-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 completa + +¿Alguna vez necesitaste **generar código de barras PDF417** en un proyecto .NET pero no sabías por dónde empezar? No estás solo. En muchas aplicaciones empresariales—piensa en impresoras de tarjetas de embarque, etiquetas de inventario o tickets móviles—PDF417 es el caballo de batalla que empaqueta muchos datos en una pequeña huella visual. + +Esto es lo que ocurre: la biblioteca Aspose.BarCode hace que todo el proceso sea casi indoloro, y puedes incluso controlar **cómo establecer columnas** para que el código de barras sea lo más compacto posible. Al final de este tutorial tendrás una imagen PNG lista para usar de una **imagen de código de barras PDF417** que puedes insertar en cualquier interfaz, correo electrónico o trabajo de impresión. + +## Lo que obtendrás + +- Una aplicación de consola C# totalmente funcional que crea un código de barras PDF417. +- Comprensión clara de la *X‑Dimension* (tamaño del módulo) y por qué es importante. +- Instrucciones paso a paso sobre **cómo establecer columnas** para un código de barras más compacto. +- Un archivo `PNG` guardado que puedes abrir al instante para verificar el resultado. +- Consejos para solucionar problemas comunes (p. ej., códigos de barras ilegibles, formato de imagen incorrecto). + +> **Prerequisitos** – SDK .NET 6+, Visual Studio 2022 (o cualquier editor que prefieras), y una referencia NuGet a `Aspose.BarCode`. Nada más. + +--- + +## Paso 1: Instalar el paquete NuGet Aspose.BarCode + +Antes de que podamos *generar código de barras PDF417*, la biblioteca debe estar presente en el proyecto. + +```bash +dotnet add package Aspose.BarCode +``` + +Esa única línea trae todos los tipos que necesitarás, incluyendo `BarcodeGenerator`, `EncodeTypes` y el enum `BarCodeImageFormat`. + +> **Consejo profesional:** Si apuntas a .NET Framework en lugar de .NET 6, usa el comando clásico de PowerShell `Install-Package Aspose.BarCode` dentro de la Consola del Administrador de Paquetes. + +--- + +## Paso 2: Crear una aplicación de consola mínima + +Vamos a esbozar un pequeño programa que no hace nada más que generar un código de barras. Abre una nueva carpeta, ejecuta `dotnet new console`, luego reemplaza el `Program.cs` autogenerado con el código a continuación. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Por qué esto importa:** +- `EncodeTypes.Pdf417` indica a la biblioteca que queremos un código de barras PDF417, no QR ni Code128. +- `XDimension.Pixels` controla la resolución de cada pequeño módulo negro o blanco. +- El bloque de **cómo establecer columnas** influye directamente en la forma de la **imagen de código de barras PDF417**. +- `Truncate = true` elimina cualquier fila vacía innecesaria, dándote ese aspecto “compacto” que a muchos escáneres les encanta. + +--- + +## Paso 3: Profundizar – Entendiendo columnas y truncamiento + +### Cómo establecer columnas + +PDF417 organiza los datos en una matriz de *filas* × *columnas*. La biblioteca usa por defecto 5 columnas, lo que funciona en la mayoría de los casos. Sin embargo, podrías necesitar un código de barras más estrecho para ajustarse a una etiqueta o uno más ancho para mejorar la fiabilidad del escaneo. La propiedad: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +acepta valores desde **1** hasta **30** (el límite exacto depende de la longitud de los datos). Aquí tienes una hoja de referencia rápida: + +| Columnas | Ancho aprox. (mm) | Cuándo usar | +|----------|-------------------|-------------| +| 1‑3 | Muy estrecho | Etiqueta pequeña, espacio limitado | +| 4‑6 | Estándar | La mayoría de recibos, tickets | +| 7‑10 | Más ancho | Datos de alta densidad, mejor legibilidad | + +### Truncar (Modo compacto) + +Configurar `Truncate = true` indica al codificador que elimine cualquier fila en blanco innecesaria en la parte inferior. El resultado es una **imagen de código de barras PDF417 compacta** que ocupa el área más pequeña posible mientras sigue conteniendo todos los datos. Si alguna vez recibes errores de “código de barras demasiado grande para la etiqueta”, cambia este indicador. + +--- + +## Paso 4: Ejecutar la aplicación y verificar la salida + +Compila y ejecuta: + +```bash +dotnet run +``` + +Deberías ver el mensaje en la consola confirmando la ubicación de guardado. Navega a la carpeta y abre `CompactPdf417.png`. La imagen se verá algo así: + +![Imagen generada de código de barras PDF417](./CompactPdf417.png "Imagen generada de código de barras PDF417 – PNG compacto creado por Aspose.BarCode") + +*Texto alternativo de la imagen:* **Imagen generada de código de barras PDF417** – un archivo PNG compacto producido por el código del tutorial. + +Si tu escáner puede leerlo, felicidades—has **generado código de barras PDF417** con éxito y dominado **cómo establecer columnas** para una **imagen de código de barras PDF417** ordenada. + +--- + +## Paso 5: Problemas comunes y cómo solucionarlos + +| Síntoma | Causa probable | Solución rápida | +|---------|----------------|-----------------| +| El código de barras aparece borroso | `XDimension.Pixels` demasiado bajo (p. ej., 1) | Aumentar a 2‑3 píxeles para una imagen más clara. | +| El escáner no puede leer | Demasiadas columnas para los datos proporcionados | Reducir `Columns` o habilitar `Truncate`. | +| Formato de archivo incorrecto | Guardado con `BarCodeImageFormat.Jpeg` por error | Usar `BarCodeImageFormat.Png` para resultados sin pérdida. | +| Excepción `ArgumentOutOfRangeException` | El recuento de columnas supera el rango permitido | Mantener columnas entre 1‑30 y asegurar que los datos caben. | + +--- + +## Paso 6: Ir más allá – Personalizar colores y añadir texto + +Si deseas que el código de barras coincida con la paleta de una marca, puedes ajustar los colores de primer plano y fondo: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +O superponer texto legible por humanos bajo el código de barras: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Estas adiciones son opcionales, pero ilustran cuán flexible puede ser el flujo de trabajo para **generar código de barras PDF417**. + +--- + +## Conclusión + +Hemos recorrido un ejemplo completo, de extremo a extremo, que **genera código de barras PDF417** usando Aspose.BarCode, explicó **cómo establecer columnas** para controlar las dimensiones del código de barras, y guardó el resultado como una nítida **imagen de código de barras PDF417** en formato PNG. El código es autónomo, funciona con .NET 6+ y puede integrarse en cualquier proyecto existente con mínima complicación. + +¿Qué sigue? Prueba codificar cargas útiles más grandes (p. ej., cargas JSON), experimenta con diferentes formatos de imagen, o integra el generador en una API web que sirva códigos de barras bajo demanda. El cielo es el límite, y ahora tienes una base sólida sobre la que construir. + +¡Feliz codificación, y que tus códigos de barras siempre se lean en el primer intento! + +## ¿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 funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Cómo crear código de barras – PDF417 compacto con Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Cómo generar imagen de código de barras en Java con Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Generar código de barras Java – Establecer resolución de imagen con Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/spanish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..ef5911a78 --- /dev/null +++ b/barcode/spanish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-07-15 +description: Genera códigos de barras PDF417 rápidamente con C#. Aprende a generar + un código de barras a partir de texto, ajustar su tamaño y establecer dimensiones + personalizadas en minutos. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: es +lastmod: 2026-07-15 +og_description: Genera códigos de barras PDF417 en C# al instante. Esta guía muestra + cómo generar el código de barras a partir de texto, ajustar su tamaño y aplicar + dimensiones personalizadas. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Generar código de barras PDF417 en C# – Tutorial completo de programación +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Generar código de barras PDF417 en C# – Guía completa paso a paso +url: /es/net/compact-pdf417-encoding/generate-pdf417-barcode-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 PDF417 en C# – Guía completa paso a paso + +¿Alguna vez necesitaste **generar un código de barras PDF417** pero no estabas seguro de qué configuraciones ajustar? No eres el único: muchos desarrolladores se topan con el mismo obstáculo cuando juegan por primera vez con códigos de barras 2‑D. ¿La buena noticia? Con unas pocas líneas de C# puedes convertir cualquier cadena en una imagen PDF417 escaneable, controlar su tamaño exacto e incluso definir un diseño personalizado de columnas y filas. + +En este tutorial recorreremos cómo **generar un código de barras a partir de texto**, ajustar el tamaño del código y establecer dimensiones personalizadas — todo usando la popular biblioteca Aspose.BarCode. Al final tendrás un ejemplo listo para ejecutar que puedes incorporar en cualquier proyecto .NET. + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## Lo que construirás + +- Un código de barras PDF417 que codifique la cadena `Åspóse.Barcóde©`. +- Control preciso sobre la X‑dimension (ancho en píxeles de cada módulo). +- Un diseño personalizado de 4 columnas y 9 filas. +- Un archivo PNG guardado en disco. + +Sin servicios externos, sin trucos de varita mágica—solo código C# puro que puedes compilar ahora mismo. + +## Requisitos previos + +- .NET 6.0 o posterior (el código también funciona en .NET Framework 4.8). +- Visual Studio 2022 o cualquier IDE que soporte C#. +- Aspose.BarCode para .NET (versión de prueba gratuita o con licencia). Instálalo vía NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +Eso es todo—una vez referenciado el paquete, estás listo para comenzar. + +## Paso 1 – Generar código de barras PDF417 con datos de texto + +Lo primero que necesitamos es una instancia de `BarcodeGenerator` que sepa que estamos trabajando con la simbología PDF417 y el texto exacto que queremos codificar. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Por qué es importante:** +> `EncodeTypes.Pdf417` indica a la biblioteca que use el formato PDF417 2‑D, mientras que el segundo argumento es la carga útil de **generar código de barras a partir de texto**. Todo lo que pases aquí se convierte en los datos almacenados en la matriz del código de barras. + +## Paso 2 – Ajustar el tamaño del código de barras (X‑Dimension) + +Si alguna vez imprimiste un código de barras que quedó demasiado pequeño en un recibo, conoces la frustración de que el escáner no lo detecte. La propiedad `XDimension` controla el ancho de un solo módulo (el cuadrado negro o blanco más pequeño) en píxeles. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Consejo profesional:** +> Un valor de 2 px funciona bien para la mayoría de los escenarios de visualización en pantalla. Para impresiones de alta resolución podrías aumentarlo a 3 o 4 px. Solo recuerda que dimensiones X mayores incrementan el tamaño total de la imagen. + +## Paso 3 – Establecer dimensiones personalizadas del código de barras (Columnas y Filas) + +PDF417 te permite decidir cuántas columnas y filas debe ocupar el código de barras. Aquí es donde entran en juego las **dimensiones personalizadas del código de barras**. Cambiar estos valores puede ayudarte a encajar el código en un espacio UI estrecho o cumplir con un tamaño de etiqueta específico. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **¿Qué ocurre detrás de escena?** +> La biblioteca redistribuye los datos codificados a lo largo de la cuadrícula especificada. Menos columnas generan códigos de barras más altos; más filas los hacen más cortos. Juega con los números hasta que el equilibrio visual se sienta adecuado para tu aplicación. + +## Paso 4 – Guardar la imagen del código de barras + +Ahora que hemos configurado todo, simplemente le pedimos al generador que escriba un archivo PNG. PNG es sin pérdida, por lo que la nitidez de los módulos se mantiene intacta. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Al ejecutar el programa, deberías ver un archivo en `C:\Barcodes\CustomLayout.png` que se parece a la captura de pantalla anterior. Escanearlo con cualquier lector compatible con PDF417 devolverá la cadena original `Åspóse.Barcóde©`. + +## Ejemplo completo funcional + +A continuación tienes el programa completo que puedes copiar y pegar en una aplicación de consola. Incluye todas las directivas `using` y el manejo de errores que esperarías en código de producción. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Salida esperada + +Al ejecutar el código se imprime: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…y crea un PNG que puede abrirse con cualquier visor de imágenes. Si lo escaneas con una aplicación móvil (p. ej., “Barcode Scanner” en iOS/Android), el texto decodificado será exactamente **Åspóse.Barcóde©**. + +## Preguntas frecuentes y casos límite + +| Pregunta | Respuesta | +|----------|-----------| +| **¿Puedo usar un formato de imagen diferente?** | Sí—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` o `Svg` son compatibles. Simplemente cambia el segundo argumento de `Save`. | +| **¿Qué pasa si mi texto contiene caracteres Unicode?** | Aspose.BarCode soporta completamente UTF‑8, por lo que el ejemplo con `Å` y `©` funciona sin ajustes. | +| **¿Cómo cambio el nivel de corrección de errores?** | Usa `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (niveles 0‑8). Niveles más altos aumentan la redundancia pero también el tamaño. | +| **Necesito un fondo transparente—¿es posible?** | Configura `generator.Parameters.Barcode.Image.TransparentBackground = true;` antes de guardar. | +| **¿Hay forma de incrustar el código de barras directamente en un PDF?** | Claro. Reemplaza la llamada a `Save` por `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` y obtendrás un PDF de una página que contiene el código de barras. | + +## Conclusión + +Ahora sabes cómo **generar un código de barras PDF417** en C# a partir de cualquier cadena, **ajustar el tamaño del código de barras** y aplicar **dimensiones personalizadas del código de barras** para adaptarlo a tus necesidades de diseño. El flujo de cuatro pasos—inicializar, dimensionar, diseñar, guardar—cubre el proceso central para la mayoría de los escenarios de códigos de barras 2‑D. + +¿Qué sigue? Prueba cambiar `EncodeTypes.Pdf417` por `EncodeTypes.QR` o `EncodeTypes.Code128` para ver cómo la API se adapta. Experimenta con diferentes valores de `XDimension`, juega con la matriz de columnas/filas o incrusta la imagen en un informe PDF. Las posibilidades son prácticamente infinitas, y ahora tienes una base sólida sobre la que construir. + +¿Tienes más preguntas o descubriste un truco ingenioso mientras trabajabas con PDF417? Deja un comentario abajo—mantengamos la conversación en marcha. ¡Feliz codificación! + +## ¿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 con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Cómo generar código de barras Aztec con relación de aspecto personalizada usando Aspose.BarCode para .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Cómo generar códigos de barras - Tipos de códigos de barras unidimensionales](/barcode/english/net/one-dimensional-barcode-types/) +- [Generar código de barras DataMatrix – Guía profesional con Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/spanish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..117cf4b6e --- /dev/null +++ b/barcode/spanish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,316 @@ +--- +category: general +date: 2026-07-15 +description: Cómo leer códigos de barras PDF417 en C# y leer varios códigos de barras + de una imagen. Aprende a leer imágenes de códigos de barras en C# con código detallado + y consejos. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: es +lastmod: 2026-07-15 +og_description: Cómo leer códigos de barras PDF417 en C# rápidamente. Esta guía te + muestra cómo leer varios códigos de barras de una sola imagen y decodificar cada + propiedad. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Cómo leer PDF417 en C# – Ejemplo de código completo y explicación +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Cómo leer PDF417 en C# – Guía completa paso a paso +url: /es/net/compact-pdf417-encoding/how-to-read-pdf417-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ómo leer PDF417 en C# – Guía completa paso a paso + +¿Alguna vez te has preguntado **cómo leer PDF417** de una imagen usando C#? No eres el único. La mayoría de los desarrolladores se topan con un obstáculo cuando necesitan extraer los campos extendidos Macro‑PDF417 de un documento escaneado. ¿La buena noticia? Con solo unas pocas líneas de código puedes decodificar un PDF417, leer varios códigos de barras en la misma imagen y obtener todas las propiedades ocultas que la especificación ofrece. + +En este tutorial recorreremos un ejemplo del mundo real que muestra **cómo leer PDF417**, cómo **leer varios códigos de barras** de un solo archivo, y por qué el código **read barcode image C#** tiene esa forma. Al final tendrás una aplicación de consola lista para ejecutar que imprime cada pieza de información que puedas necesitar: ID de archivo, ID de segmento, checksum, marcas de tiempo, lo que sea. + +## Prerrequisitos + +Antes de sumergirnos, asegúrate de contar con: + +* .NET 6.0 SDK o posterior (el código funciona también con .NET Core y .NET Framework). +* Visual Studio 2022 (o cualquier editor que prefieras). +* El paquete NuGet **Aspose.BarCode for .NET** – es la biblioteca que realmente analiza PDF417. +* Una imagen de muestra que contenga un código de barras Macro‑PDF417 (por ejemplo `ExtPDF417Meta.png`). + +No se requiere configuración adicional; la biblioteca incluye todos los decodificadores que necesitas. + +## Paso 1: Instalar Aspose.BarCode + +Abre la carpeta de tu proyecto en una terminal y ejecuta: + +```bash +dotnet add package Aspose.BarCode +``` + +Ese comando descarga la última versión estable (a julio 2026 es la 23.12). Si prefieres la consola del Administrador de paquetes dentro de Visual Studio, usa: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Consejo profesional:** bloquea la versión (`23.12.0`) en tu `.csproj` para evitar cambios incompatibles accidentales más adelante. + +## Paso 2: Crear la estructura básica de una aplicación de consola + +Crea un nuevo proyecto de consola si aún no tienes uno: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Reemplaza el `Program.cs` autogenerado con el código que aparece a continuación. Explicaremos cada bloque en las siguientes secciones. + +## Paso 3: Escribir el código completo “Cómo leer PDF417” + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Por qué este código funciona + +* **`BarCodeReader`** es la clase central que procesa la imagen, detecta los códigos de barras y devuelve una colección de objetos `BarCodeResult`. +* Pasar **`DecodeType.MacroPdf417`** indica a la biblioteca que trate Macro‑PDF417 de forma especial; sigue devolviendo símbolos PDF417 simples, lo que satisface el requisito de **read multiple barcodes**. +* El objeto **`Extended.Pdf417.MacroPdf417`** contiene todos los campos opcionales definidos por la norma ISO/IEC 15438 – ahí obtienes `FileID`, `SegmentID`, `Checksum`, etc. +* El bloque `using` garantiza que los recursos nativos se liberen, evitando fugas de memoria en servicios de larga ejecución. + +## Paso 4: Ejecutar la aplicación y verificar la salida + +Desde la terminal: + +```bash +dotnet run +``` + +Deberías ver algo como: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Si la imagen contiene más de un código de barras, el bucle imprimirá una línea separadora (`----------------------------------------`) y continuará con el siguiente resultado—exactamente lo que representa **read multiple barcodes** en la práctica. + +## Preguntas frecuentes y casos límite + +### ¿Qué pasa si la imagen tiene símbolos Macro‑PDF417 y PDF417 normales? + +La misma llamada a `BarCodeReader` devolverá ambos. Puedes diferenciarlos comprobando `result.CodeType` (`MacroPdf417` vs `Pdf417`). Las propiedades extendidas serán `null` para un PDF417 simple, por lo que la condición `if (macro != null)` evita una `NullReferenceException`. + +### ¿Mi código de barras está rotado o sesgado—seguirá funcionando el lector? + +Aspose.BarCode incluye compensación integrada de rotación y distorsión. Mientras el código de barras ocupe al menos el 30 % del ancho de la imagen, el decodificador suele tener éxito. En casos extremos puedes habilitar `reader.Options.AllowInvertedBarcodes = true;` antes de llamar a `ReadBarCodes()`. + +### ¿Cómo manejo lotes grandes de imágenes? + +Envuelve la lógica de lectura en un bucle `foreach (var file in Directory.GetFiles(folder, "*.png"))`. El patrón `using` asegura que los recursos nativos de cada imagen se liberen antes de la siguiente iteración, manteniendo bajo el consumo de memoria. + +## Listado completo del código (listo para copiar y pegar) + +A continuación tienes todo el programa en un solo bloque para copiar y pegar rápidamente. No hay dependencias ocultas—solo el paquete NuGet Aspose.BarCode. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Resumen – Lo que cubrimos + +* **Cómo leer PDF417** usando Aspose.BarCode en C#. +* Los pasos exactos para **read multiple barcodes** desde una sola imagen. +* Cómo **read barcode image C#** y extraer cada campo Macro‑PDF417. +* Consejos para rotación, procesamiento por lotes y manejo de datos extendidos ausentes. + +## Próximos pasos y temas relacionados + +* **Encode PDF417** – genera tus propios códigos de barras Macro‑PDF417 con `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – usando la misma clase `BarCodeReader`. +* **Integrate with ASP.NET Core** – expón un endpoint web que acepte una imagen subida y devuelva JSON con los campos decodificados. + +Siéntete libre de experimentar: cambia la ruta de la imagen, coloca un PDF417 simple en la misma carpeta, o ajusta las banderas `DecodeType` para ver cómo se comporta la biblioteca. Cuanto más juegues, más cómodo te sentirás con los escenarios **read barcode image C#**. + +¿Tienes una imagen complicada que se niega a decodificar? Deja un comentario abajo o abre un issue en el repositorio GitHub del proyecto de ejemplo. ¡Feliz codificación! + +## ¿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 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/spanish/net/one-dimensional-barcode-types/_index.md b/barcode/spanish/net/one-dimensional-barcode-types/_index.md index ca6d74659..0f11c6688 100644 --- a/barcode/spanish/net/one-dimensional-barcode-types/_index.md +++ b/barcode/spanish/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ Aprenda cómo generar códigos de barras en .NET con Aspose.BarCode para .NET. E Aprenda a manejar excepciones mientras genera códigos de barras unidimensionales utilizando Aspose.BarCode para .NET. Esta guía paso a paso garantiza soluciones de códigos de barras tolerantes a errores. ¡Empieza ahora! ### [Configuración unidimensional de relación ancha-estrecha](./one-dimensional-wide-narrow-ratio-configuration/) Genere códigos de barras personalizados fácilmente con Aspose.BarCode para .NET. Guía paso a paso para la configuración unidimensional de relación ancha-estrecha. +### [Generar código de barras a partir de texto usando Aspose.BarCode – Guía C#](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Aprenda a crear códigos de barras desde texto en .NET con Aspose.BarCode y C#. Guía paso a paso. ## Conclusión @@ -89,4 +91,4 @@ Con este artículo, no sólo obtendrá conocimientos sobre varios tipos de códi {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/spanish/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..7cd7ef9aa --- /dev/null +++ b/barcode/spanish/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-07-15 +description: Genera códigos de barras a partir de texto usando Aspose.BarCode en C#. + Aprende a cambiar el número de columnas, guardar la imagen del código de barras + y crear soluciones de códigos de barras con Aspose rápidamente. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: es +lastmod: 2026-07-15 +og_description: Genera código de barras a partir de texto usando Aspose.BarCode. Esta + guía muestra cómo cambiar el recuento de columnas, guardar la imagen del código + de barras y crear un código de barras Aspose en unas pocas líneas de código. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Generar código de barras a partir de texto con Aspose.BarCode – Guía rápida + en C# +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Generar código de barras a partir de texto usando Aspose.BarCode – Guía de + C# +url: /es/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-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 usando Aspose.BarCode – Guía C# + +Generar código de barras a partir de texto usando Aspose.BarCode es sorprendentemente simple. En este tutorial recorreremos **cómo generar código de barras**, ajustaremos el diseño de columnas y, finalmente, **guardaremos la imagen del código de barras** como un archivo PNG. Ya sea que estés construyendo un sistema de tickets, una impresora de etiquetas de almacén, o simplemente experimentando con códigos estilo QR, los pasos a continuación te llevarán allí rápidamente. + +## Lo que aprenderás + +- Crear un código de barras a partir de cualquier cadena Unicode (sí, incluso “Åspóse.Barcóde©” funciona). +- Ajustar el **column count** para MicroPdf417 para adaptarse a etiquetas estrechas o anchas. +- Persistir el resultado en disco con el formato de imagen adecuado. +- Consejos para manejar caracteres especiales y problemas comunes al **create barcode Aspose** soluciones. + +Sin herramientas externas, sin trucos de línea de comandos—solo C# puro y la biblioteca Aspose.BarCode. + +## Requisitos previos + +Antes de comenzar, asegúrate de tener: + +1. **.NET 6.0** o posterior instalado (el código también funciona en .NET Framework 4.7+). +2. Una **licencia** para Aspose.BarCode, o puedes comenzar con la versión de evaluación gratuita. +3. Una carpeta a la que puedas escribir – la llamaremos `YOUR_DIRECTORY` en los ejemplos. + +Si te falta alguno de estos, obtén el paquete NuGet ahora: + +```bash +dotnet add package Aspose.BarCode +``` + +Eso es todo—no hay DLLs extra que copiar manualmente. + +## Paso 1 – Configurar el proyecto e importaciones + +Primero, crea una aplicación de consola (o inserta el código en cualquier proyecto C#). La parte importante es incluir los espacios de nombres correctos: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +¿Por qué estas sentencias using? `BarcodeGenerator` está en `Aspose.BarCode.Generation`, mientras que el enum `BarCodeImageFormat` está en `Aspose.BarCode`. Mantener las importaciones ordenadas hace que el código posterior se lea como inglés sencillo. + +## Paso 2 – Crear el generador de código de barras (cómo generar código de barras) + +Ahora realmente **generamos código de barras a partir de texto**. El enum `EncodeTypes` indica a Aspose qué simbología usar; aquí elegimos `MicroPdf417` porque maneja cadenas largas en una cuadrícula compacta. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Observa que la cadena contiene caracteres acentuados y un símbolo de copyright. Aspose.BarCode codifica Unicode automáticamente, por lo que no necesitas pre‑procesar el texto. + +## Paso 3 – Ajustar la apariencia (cómo cambiar el número de columnas) + +MicroPdf417 te permite controlar el número de columnas, lo que influye directamente en el ancho del código de barras. Un diseño más compacto es ideal para etiquetas estrechas; un diseño más amplio mejora la legibilidad en impresiones grandes. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +¿Por qué módulos de 2 píxeles? Proporcionan una imagen nítida sin inflar el tamaño del archivo. Siéntete libre de experimentar—los valores entre 1 y 4 suelen funcionar bien. Si alguna vez necesitas un número de columnas diferente, simplemente cambia la propiedad `Columns`; Aspose recalculará el diseño automáticamente. + +## Paso 4 – Guardar la imagen del código de barras (guardar imagen del código de barras) + +Con el generador configurado, estamos listos para **guardar la imagen del código de barras**. El método `Save` acepta una ruta de archivo y un enum de formato de imagen. PNG es sin pérdida, por lo que el código de barras permanece nítido incluso después de escalar. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Un consejo rápido: siempre usa una ruta absoluta o asegura que el directorio de trabajo sea el que esperas; de lo contrario el archivo podría terminar en la carpeta bin y te preguntarás por qué no lo encuentras. + +## Ejemplo completo funcional + +Juntando todo, aquí tienes un programa autocontenido que puedes copiar y pegar en `Program.cs` y ejecutar: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Salida esperada** (consola): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +Y si abres `MicroPdf417.png`, verás un código de barras MicroPdf417 nítido que codifica la cadena original, completa con los caracteres especiales que le suministramos. + +## Preguntas comunes y casos límite + +### ¿Qué pasa si mi texto es más largo que la capacidad predeterminada? + +MicroPdf417 cambia automáticamente a un diseño de varias filas cuando los datos superan el máximo por fila. aún puedes controlar el número de columnas, pero la biblioteca puede agregar filas extra en segundo plano. No se necesita código adicional—solo vigila las dimensiones de la imagen resultante. + +### ¿Cómo cambio el formato de imagen a JPEG o BMP? + +Reemplaza `BarCodeImageFormat.Png` por `BarCodeImageFormat.Jpeg` (o `Bmp`). Recuerda que JPEG introduce artefactos de compresión, lo que puede afectar la fiabilidad del escaneo. PNG es la opción predeterminada más segura. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Veo una marca de agua en la salida—¿qué está mal? + +Esa es la versión de evaluación de Aspose.BarCode. Para **create barcode Aspose** sin marcas de agua, carga un archivo de licencia válido como se muestra en la línea comentada del Paso 2. + +### ¿Puedo generar otras simbologías (QR, Code128, etc.)? + +Absolutamente. Simplemente reemplaza `EncodeTypes.MicroPdf417` por cualquier otro valor del enum `EncodeTypes`, por ejemplo, `EncodeTypes.QR` o `EncodeTypes.Code128`. El resto del código permanece igual, lo que hace que el enfoque sea altamente reutilizable. + +## Consejos profesionales para generación de códigos de barras lista para producción + +- **Cache the generator** si estás creando muchos códigos de barras con la misma configuración; reduce la sobrecarga de creación de objetos. +- **Validate the input string** para restricciones de longitud específicas de la simbología elegida (Aspose lanza `ArgumentException` si es demasiado larga). +- **Use `using` statements** o `Dispose` el generador cuando termines para liberar los recursos nativos rápidamente. +- **Set DPI** mediante `generator.Parameters.ImageResolution.DpiX/DpiY` si necesitas impresiones de alta resolución para etiquetas grandes. + +## Conclusión + +Ahora sabes exactamente **cómo generar código de barras a partir de texto** con Aspose.BarCode, cómo **cambiar el número de columnas**, y la forma correcta de **guardar la imagen del código de barras** como PNG. El ejemplo completo y ejecutable anterior demuestra una solución limpia y lista para producció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. + +- [Cómo generar código de barras – Configuración Code 39 con Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Generar imagen de código de barras – Code 93 con Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [Cómo generar códigos de barras DataMatrix (ECC 200) con Aspose.BarCode para .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/swedish/net/compact-pdf417-encoding/_index.md index cc613e6f8..23a06e049 100644 --- a/barcode/swedish/net/compact-pdf417-encoding/_index.md +++ b/barcode/swedish/net/compact-pdf417-encoding/_index.md @@ -84,6 +84,13 @@ 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. +### [Skapa PDF417-streckkodmetadata i C# – Komplett steg‑för‑steg‑guide](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +### [Generera PDF417-streckkod i C# – Komplett guide](./generate-pdf417-barcode-in-c-complete-guide/) +Lär dig att skapa PDF417‑streckkoder i C# med en fullständig steg‑för‑steg‑instruktioner och kodexempel. +### [Generera PDF417-streckkod i C# – Komplett steg‑för‑steg‑guide](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +Detaljerad guide för att generera PDF417‑streckkoder i C# med kodexempel och bästa praxis. +### [Hur man läser PDF417 i C# – Komplett steg‑för‑steg‑guide](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) +Lär dig att läsa PDF417‑streckkoder i C# med en detaljerad steg‑för‑steg‑instruktion och kodexempel. ## Vanliga frågor @@ -113,4 +120,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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/swedish/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..7710dbd24 --- /dev/null +++ b/barcode/swedish/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-07-15 +description: Skapa PDF417‑streckkodmetadata i C# med Aspose.BarCode. Lär dig Macro + PDF417‑inställningar, spara som PNG och hantera Unicode‑text. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: sv +lastmod: 2026-07-15 +og_description: Skapa PDF417-streckkodmetadata i C# med Aspose.BarCode. Denna guide + visar alla inställningar du behöver för att bädda in fil‑ID, tidsstämplar och mer. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: Skapa PDF417‑streckkodmetadata i C# – Fullständig programmeringsgenomgång +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: Skapa PDF417-streckkodmetadata i C# – Komplett steg‑för‑steg‑guide +url: /sv/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa PDF417-streckkodmetadata i C# – Komplett steg‑för‑steg‑guide + +Har du någonsin behövt **skapa PDF417-streckkodmetadata** i C# men varit osäker på vilka egenskaper du ska justera? Du är inte ensam—utvecklare stöter ofta på problem när specifikationen kräver saker som fil‑ID:n, segmentantal eller anpassade tidsstämplar. + +Den goda nyheten är att Aspose.BarCode gör detta till en barnlek. I den här handledningen kommer vi att skapa en `BarcodeGenerator` för **Macro PDF417**, strö över all viktig metadata och spara resultatet som en PNG‑bild. I slutet har du en fullständigt utrustad streckkod redo för alla leveranskedjor eller dokumenthanteringssystem. + +## Vad den här guiden täcker + +Vi går igenom: + +1. Installera Aspose.BarCode NuGet‑paketet. +2. Initiera en `BarcodeGenerator` för **Macro PDF417**. +3. Fyll i varje användbart **streckkodmetadatafält** (fil‑ID, segment‑ID, kontrollsumma osv.). +4. Spara streckkoden till disk och verifiera resultatet. + +Ingen tidigare erfarenhet av Macro PDF417 krävs—bara grundläggande C#‑kunskaper och en aktuell .NET‑runtime. + +Varför bör du bry dig? Genom att bädda in rik metadata direkt i en streckkod kan nedströmsläsare validera hela filöverföringar, upptäcka saknade segment eller till och med trigga automatiserade arbetsflöden. Med andra ord får du **robust, självbeskrivande data** utan en separat databassökning. + +## Förutsättningar + +- .NET 6.0 eller senare (koden fungerar även på .NET Framework 4.7+). +- Visual Studio 2022 (eller någon annan IDE du föredrar). +- NuGet‑paketet **Aspose.BarCode for .NET** (gratis provversion tillgänglig). + +Du kan installera paketet med följande kommando: + +```bash +dotnet add package Aspose.BarCode +``` + +Nu när vi har grunderna, låt oss dyka ner i själva implementeringen. + +## Steg 1: Initiera BarcodeGenerator för Macro PDF417 + +Det första vi behöver är en `BarcodeGenerator`‑instans konfigurerad för **Macro PDF417**. Detta talar om för Aspose.BarCode vilken kodningsalgoritm som ska användas och ger oss en plats att mata in den mänskligt läsbara texten. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Varför detta är viktigt:** `EncodeTypes.MacroPdf417` aktiverar det utökade PDF417‑läget som stödjer metadata som fil‑ID:n och segmentnummer. Exempeltexten innehåller Unicode‑tecken (`Å`, `ó`, `©`) för att bevisa att generatorn hanterar icke‑ASCII‑inmatning smidigt. + +## Steg 2: Definiera grundläggande streckkodutseende + +Innan vi börjar lägga till metadata bör vi ställa in några visuella parametrar så att streckkoden inte blir en mikroskopisk prick. `XDimension` styr modulbredden, medan `Columns` påverkar den övergripande formen. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Proffstips:** En pixelbredd på `2` fungerar bra för skärmvisning och de flesta skrivare. Om du behöver en högre upplösning, öka den till `3` eller `4`. + +## Steg 3: Fyll i Macro PDF417‑metadatafält + +Nu kommer hjärtat i handledningen—att lägga till **streckkodmetadatafält**. Varje egenskap motsvarar direkt ett segment i Macro PDF417‑specifikationen. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Vad varje egenskap gör + +| Egenskap | Syfte | Typiskt värde | +|----------|-------|---------------| +| **MacroPdf417FileID** | Globalt unikt identifierare för hela filuppsättningen. | `12345678` | +| **MacroPdf417SegmentID** | Index för det aktuella segmentet (börjar på `0`). | `12` | +| **MacroPdf417SegmentsCount** | Totalt antal segment som förväntas för filen. | `20` | +| **MacroPdf417FileName** | Mänskligt läsbart namn, ofta det ursprungliga filnamnet. | `"file01"` | +| **MacroPdf417Checksum** | 16‑bit CCITT‑kontrollsumma för felupptäckt. | `1234` | +| **MacroPdf417FileSize** | Storlek på den ursprungliga filen i byte. | `400000` | +| **MacroPdf417TimeStamp** | När filen genererades. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Valfritt fält som anger mottagaren. | `"street"` | +| **MacroPdf417Sender** | Valfritt fält som anger källsystemet. | `"aspose"` | +| **MacroPdf417Terminator** | Flagga som talar om för läsaren att detta är det sista segmentet. | `Pdf417MacroTerminator.Set` | + +> **Varför du behöver dessa:** Läsare som förstår Macro PDF417 kan återmontera en flersegmentfil, verifiera integritet med kontrollsumman och till och med avvisa föråldrade data baserat på tidsstämpeln. Detta eliminerar behovet av en separat manifestfil. + +## Steg 4: Spara streckkodsbilden + +När alla parametrar är satta anropar vi helt enkelt `Save`. Exemplet skriver en PNG‑fil till en mapp du anger. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Edge case:** Om du planerar att bädda in streckkoden i en PDF senare kan du föredra `BarCodeImageFormat.Jpeg` eller `Pdf`. PNG bevarar förlustfri detalj, vilket är praktiskt för verifiering. + +## Fullt fungerande exempel + +När vi sätter ihop allt, här är det kompletta programmet som du kan kopiera‑klistra in i en konsolapp: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Förväntat resultat + +När programmet körs skapas en fil med namnet **ExtPDF417Meta.png** i den körbara filens mapp. Öppna den med någon bildvisare så ser du en tät, högkontrast PDF417‑streckkod. Om du skannar den med en streckkodsläsare som stödjer Macro PDF417 kommer läsaren att returnera de metadata‑värden vi satte—fil‑ID `12345678`, segment `12` av `20`, osv. + +## Vanliga frågor & fallgropar + +- **Vad händer om streckkoden ser suddig ut?** Öka `XDimension.Pixels` eller byt till ett bildformat med högre upplösning. +- **Behöver jag sätta varje metadatafält?** Nej. Endast de fält som krävs av ditt nedströmsystem är obligatoriska. Oanvända fält kan behålla sina standardvärden. +- **Kan jag generera en flersegmentfil automatiskt?** Ja—loopa över data, öka `MacroPdf417SegmentID` och generera en separat streckkod för varje segment. Kom ihåg att hålla `MacroPdf417FileID` konsekvent över alla segment. +- **Stöds Unicode?** Absolut. Exempeltexten innehåller `Å`, `ó` och `©`, vilket visar att Aspose.BarCode hanterar UTF‑8 direkt. + +## Nästa steg: Gå bortom grunderna + +Nu när du vet hur man **skapar PDF417-streckkodmetadata**, kanske du vill utforska: + +- **Bädda in streckkoder i PDF** med `Aspose.Pdf` för end‑to‑end‑dokumentgenerering. +- **Läsa tillbaka metadata** med `BarcodeReader` för att programatiskt validera skanningar. +- **Anpassa färger** (förgrund/bakgrund) för varumärkesändamål. +- **Integrera med en databas** för att automatiskt fylla i fält som `FileID` eller `Timestamp`. + +Alla dessa ämnen knyter tillbaka till våra sekundära nyckelord—**macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, och **c# barcode generation**—så du hittar massor av material för att fortsätta lära dig. + +## Slutsats + +Vi har just gått igenom ett komplett, produktionsklart exempel på hur man **skapar PDF417-streckkodmetadata** i C#. Från att installera Aspose.BarCode, initiera en `BarcodeGenerator`, fylla i varje relevant **streckkodmetadatafält**, till att slutligen spara en skarp PNG, är processen enkel när du känner till rätt egenskaper. + +Prova det, justera värdena och se hur läsarna reagerar. Flexibiliteten i Macro PDF417 innebär att du kan bädda in allt ett nedströmsystem behöver—allt i en enda skannbar bild. Lycka till med kodningen, och må dina streckkoder alltid vara felfria! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närliggande ä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 implementeringsmetoder i dina egna projekt. + +- [Hur man skapar streckkod – Compact PDF417 med Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java streckkodsbibliotek – Lägg till streckkod i PDF med Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [Så skapar du en streckkod – Kompakt PDF417 med Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/swedish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..e146945a1 --- /dev/null +++ b/barcode/swedish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,201 @@ +--- +category: general +date: 2026-07-15 +description: Generera PDF417‑streckkod snabbt och lär dig hur du ställer in kolumner + för en kompakt PDF417‑streckkodsbild i C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: sv +lastmod: 2026-07-15 +og_description: Generera PDF417‑streckkod med Aspose.BarCode och lär dig hur du ställer + in kolumner för att skapa en kompakt PDF417‑streckkodsbild. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: Generera PDF417‑streckkod i C# – Steg‑för‑steg‑guide +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: Generera PDF417-streckkod i C# – Komplett guide +url: /sv/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generera PDF417-streckkod i C# – Komplett guide + +Har du någonsin behövt **generate PDF417 barcode** i ett .NET‑projekt men varit osäker på var du ska börja? Du är inte ensam. I många företagsapplikationer—tänk boarding‑pass‑skrivare, inventarietaggar eller mobilticketing—är PDF417 arbetshästen som packar mycket data i ett litet visuellt fotavtryck. + +Här är grejen: Aspose.BarCode‑biblioteket gör hela processen nästan smärtfri, och du kan till och med kontrollera **how to set columns** så att streckkoden blir så kompakt som möjligt. I slutet av den här handledningen har du en färdig‑att‑använda PNG‑bild av en **PDF417 barcode image** som du kan lägga in i vilken UI, e‑post eller utskriftsuppgift som helst. + +## Vad du får med dig + +- En fullt fungerande C#‑konsolapp som skapar en PDF417‑streckkod. +- Klar förståelse för *X‑Dimension* (modulstorlek) och varför den är viktig. +- Steg‑för‑steg‑instruktioner om **how to set columns** för en tätare streckkod. +- En sparad `PNG`‑fil som du kan öppna omedelbart för att verifiera resultatet. +- Tips för felsökning av vanliga fallgropar (t.ex. oläsliga streckkoder, fel bildformat). + +> **Prerequisites** – .NET 6+ SDK, Visual Studio 2022 (eller någon annan editor du föredrar), och ett NuGet‑referens till `Aspose.BarCode`. Inget annat. + +## Steg 1: Installera Aspose.BarCode NuGet‑paketet + +Innan vi kan *generate PDF417 barcode* måste biblioteket finnas i projektet. + +```bash +dotnet add package Aspose.BarCode +``` + +Den enda raden hämtar alla typer du behöver, inklusive `BarcodeGenerator`, `EncodeTypes` och enum‑en `BarCodeImageFormat`. + +> **Pro tip:** Om du riktar dig mot .NET Framework istället för .NET 6, använd det klassiska PowerShell‑kommandot `Install-Package Aspose.BarCode` i Package Manager Console. + +## Steg 2: Skapa en minimal konsolapplikation + +Låt oss skapa ett litet program som bara producerar en streckkod. Öppna en ny mapp, kör `dotnet new console`, och ersätt sedan den automatiskt genererade `Program.cs` med koden nedan. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Varför detta är viktigt:** +- `EncodeTypes.Pdf417` talar om för biblioteket att vi vill ha en PDF417‑streckkod, inte QR eller Code128. +- `XDimension.Pixels` styr upplösningen för varje liten svart eller vit modul. +- Blocket **how to set columns** påverkar direkt formen på **PDF417 barcode image**. +- `Truncate = true` tar bort onödiga tomma rader, vilket ger dig det ”kompakta” utseendet som många skannrar älskar. + +## Steg 3: Gå djupare – Förstå kolumner och trunkering + +### Hur man sätter kolumner + +PDF417 ordnar data i en matris av *rows* × *columns*. Biblioteket har som standard 5 kolumner, vilket fungerar i de flesta fall. Du kan dock behöva en smalare streckkod för att passa en etikett eller en bredare för att förbättra skanningspålitligheten. Egenskapen: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +accepterar värden från **1** upp till **30** (den exakta gränsen beror på datalängden). Här är ett snabbt fuskblad: + +| Kolumner | Ungefärlig bredd (mm) | När det bör användas | +|----------|-----------------------|-----------------------| +| 1‑3 | Mycket smal | Liten etikett, begränsat utrymme | +| 4‑6 | Standard | De flesta kvitton, biljetter | +| 7‑10 | Bredare | Högdensitetsdata, bättre läsbarhet | + +### Truncate (Komprimerat läge) + +Att sätta `Truncate = true` instruerar kodaren att klippa bort onödiga tomma rader längst ner. Resultatet blir en **compact PDF417 barcode image** som upptar så liten yta som möjligt samtidigt som den innehåller all data. Om du någonsin får felmeddelandet ”barcode too big for label”, växla detta flagga. + +## Steg 4: Kör appen och verifiera resultatet + +Compile and execute: + +```bash +dotnet run +``` + +Du bör se konsolmeddelandet som bekräftar sparplatsen. Navigera till mappen och öppna `CompactPdf417.png`. Bilden kommer att se ut ungefär så här: + +![Genererad PDF417 streckkod bild](./CompactPdf417.png "Genererad PDF417 streckkod bild – kompakt PNG skapad av Aspose.BarCode") + +*Bild alt‑text:* **Generated PDF417 barcode image** – en kompakt PNG‑fil skapad av tutorial‑koden. + +Om din skanner kan läsa den, grattis—du har framgångsrikt **generate PDF417 barcode** och bemästrat **how to set columns** för en prydlig **PDF417 barcode image**. + +## Steg 5: Vanliga fallgropar & hur man åtgärdar dem + +| Symptom | Trolig orsak | Snabb åtgärd | +|---------|--------------|--------------| +| Streckkoden blir suddig | `XDimension.Pixels` för låg (t.ex. 1) | Öka till 2‑3 pixlar för en tydligare bild. | +| Skannern kan inte läsa | För många kolumner för den givna datan | Minska `Columns` eller aktivera `Truncate`. | +| Fel filformat | Sparad med `BarCodeImageFormat.Jpeg` av misstag | Använd `BarCodeImageFormat.Png` för förlustfri resultat. | +| Undantag `ArgumentOutOfRangeException` | Kolumnantalet överskrider tillåtet intervall | Håll kolumner mellan 1‑30 och säkerställ att data får plats. | + +## Steg 6: Gå vidare – Anpassa färger och lägga till text + +Om du vill att streckkoden ska matcha en varumärkespalett kan du justera förgrunds‑ och bakgrundsfärger: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Eller lägga över mänskligt läsbar text under streckkoden: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Dessa tillägg är valfria, men de visar hur flexibel **generate PDF417 barcode**‑arbetsflödet kan vara. + +## Slutsats + +Vi har gått igenom ett komplett, end‑to‑end‑exempel som **generate PDF417 barcode** med Aspose.BarCode, förklarat **how to set columns** för att kontrollera streckkodens dimensioner, och sparat resultatet som en skarp **PDF417 barcode image** i PNG‑format. Koden är självständig, fungerar med .NET 6+, och kan slängas in i vilket befintligt projekt som helst med minimal ansträngning. + +Vad blir nästa? Prova att koda större nyttolaster (t.ex. JSON‑payloads), experimentera med olika bildformat, eller integrera generatorn i ett webb‑API som levererar streckkoder på begäran. Himlen är gränsen, och du har nu en solid grund att bygga vidare på. + +Lycka till med kodandet, och må dina streckkoder alltid skannas på första försöket! + +## 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 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 bild i Java med Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Generera streckkod Java – Ställ in bildupplösning med Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/swedish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..8a79b2964 --- /dev/null +++ b/barcode/swedish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-07-15 +description: Generera PDF417‑streckkod snabbt med C#. Lär dig hur du genererar streckkod + från text, justerar streckkodens storlek och ställer in anpassade streckkodsdimensioner + på några minuter. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: sv +lastmod: 2026-07-15 +og_description: Generera PDF417-streckkod i C# omedelbart. Denna guide visar hur du + genererar streckkod från text, justerar streckkodens storlek och använder anpassade + streckkodsdimensioner. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Generera PDF417‑streckkod i C# – Fullständig programmeringshandledning +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Generera PDF417‑streckkod i C# – Komplett steg‑för‑steg‑guide +url: /sv/net/compact-pdf417-encoding/generate-pdf417-barcode-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 PDF417-streckkod i C# – Komplett steg‑för‑steg‑guide + +Har du någonsin behövt **generera PDF417 barcode** men varit osäker på vilka inställningar du ska justera? Du är inte ensam—många utvecklare stöter på samma problem när de först börjar arbeta med 2‑D-streckkoder. Den goda nyheten? Med några rader C# kan du omvandla vilken sträng som helst till en skannbar PDF417‑bild, kontrollera dess exakta storlek och till och med definiera en anpassad kolumn‑rad‑layout. + +I den här handledningen går vi igenom hur man **genererar streckkod från text**, justerar streckkodens storlek och ställer in anpassade streckkodsdimensioner — allt med det populära Aspose.BarCode‑biblioteket. I slutet har du ett färdigt exempel som du kan lägga till i vilket .NET‑projekt som helst. + +![Exempel på PDF417-streckkod](https://example.com/og-image.png "Exempel på PDF417-streckkod") + +## Vad du kommer att bygga + +- En PDF417-streckkod som kodar strängen `Åspóse.Barcóde©`. +- Precisionskontroll över X‑dimensionen (pixelbredden för varje modul). +- En anpassad layout med 4 kolumner och 9 rader. +- En PNG‑fil sparad på disk. + +Inga externa tjänster, inga magiska trollstavar—bara ren C#‑kod som du kan kompilera direkt nu. + +## Förutsättningar + +- .NET 6.0 eller senare (koden fungerar även på .NET Framework 4.8). +- Visual Studio 2022 eller någon IDE som stödjer C#. +- Aspose.BarCode för .NET (gratis provversion eller licensierad version). Installera via NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +Det är allt—så snart paketet är refererat är du redo att köra. + +## Steg 1 – Generera PDF417-streckkod med textdata + +Det första vi behöver är en instans av `BarcodeGenerator` som vet att vi arbetar med PDF417‑symbologi och den exakta texten vi vill koda. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Varför detta är viktigt:** +> `EncodeTypes.Pdf417` talar om för biblioteket att använda PDF417‑2‑D‑formatet, medan det andra argumentet är **generera streckkod från text**‑payloaden. Allt du skickar här blir data som lagras i streckkodsmatrisen. + +## Steg 2 – Justera streckkodens storlek (X‑dimension) + +Om du någonsin har skrivit ut en streckkod som var för liten på ett kvitto, känner du frustrationen när skannern missar den. `XDimension`‑egenskapen styr bredden på en enskild modul (den minsta svarta eller vita fyrkanten) i pixlar. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Proffstips:** +> Ett värde på 2 px fungerar bra för de flesta skärmvisningsscenarier. För högupplösta utskrifter kan du öka detta till 3 eller 4 px. Kom bara ihåg att större X‑dimensioner ökar den totala bildstorleken. + +## Steg 3 – Ställ in anpassade streckkodsdimensioner (kolumner & rader) + +PDF417 låter dig bestämma hur många kolumner och rader streckkoden ska uppta. Det är här **custom barcode dimensions** kommer in i bilden. Att ändra dessa värden kan hjälpa dig att passa streckkoden i ett trångt UI‑utrymme eller uppfylla en specifik etikettstorlek. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Vad händer under huven?** +> Biblioteket omfördelar den kodade datan över det angivna rutnätet. Färre kolumner innebär högre streckkoder; fler rader gör dem kortare. Lek med siffrorna tills den visuella balansen känns rätt för din applikation. + +## Steg 4 – Spara streckkodens bild + +Nu när vi har konfigurerat allt ber vi helt enkelt generatorn att skriva en PNG‑fil. PNG är förlustfri, så skärpan i modulerna förblir intakt. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +När du kör programmet bör du se en fil på `C:\Barcodes\CustomLayout.png` som ser liknande ut som skärmdumpen ovan. Att skanna den med någon PDF417‑kompatibel läsare returnerar den ursprungliga strängen `Åspóse.Barcóde©`. + +## Fullt fungerande exempel + +Nedan är det kompletta programmet som du kan kopiera‑klistra in i en konsolapp. Det inkluderar alla using‑direktiv och felhantering du förväntar dig i produktionskod. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Förväntad utdata + +Att köra koden skriver ut: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…och skapar en PNG som kan öppnas i vilken bildvisare som helst. Om du skannar den med en mobilapp (t.ex. “Barcode Scanner” på iOS/Android) bör den avkodade texten vara exakt **Åspóse.Barcóde©**. + +## Vanliga frågor & kantfall + +| Question | Answer | +|----------|--------| +| **Kan jag använda ett annat bildformat?** | Ja—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` eller `Svg` stöds alla. Ändra bara det andra argumentet till `Save`. | +| **Vad händer om min text innehåller Unicode‑tecken?** | Aspose.BarCode har fullt stöd för UTF‑8, så exemplet med `Å` och `©` fungerar direkt. | +| **Hur ändrar jag felkorrigeringsnivån?** | Använd `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (nivåer 0‑8). Högre nivåer ökar redundansen men också storleken. | +| **Jag behöver en transparent bakgrund—kan jag göra det?** | Ställ in `generator.Parameters.Barcode.Image.TransparentBackground = true;` innan du sparar. | +| **Finns det ett sätt att bädda in streckkoden direkt i en PDF?** | Absolut. Ersätt `Save`‑anropet med `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` så får du en en‑sides PDF som innehåller streckkoden. | + +## Slutsats + +Du vet nu hur du **genererar PDF417 barcode** i C# från vilken sträng som helst, **justerar streckkodens storlek**, och tillämpar **custom barcode dimensions** för att passa dina layoutbehov. Det fyrastegsflödet—initiera, storlek, layout, spara—täcker huvudarbetsflödet för de flesta 2‑D‑streckkodsscenarier. + +Vad blir nästa steg? Prova att byta `EncodeTypes.Pdf417` mot `EncodeTypes.QR` eller `EncodeTypes.Code128` för att se hur API:et anpassar sig. Experimentera med olika `XDimension`‑värden, lek med kolumn‑/rad‑matrisen, eller bädda in bilden i en PDF‑rapport. Möjligheterna är praktiskt taget oändliga, och nu har du en solid grund att bygga vidare på. + +Har du fler frågor, eller har du upptäckt ett smart knep när du lekt med PDF417? Lägg en kommentar nedan—låt oss hålla samtalet igång. 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 implementeringsmetoder i dina egna projekt. + +- [Hur man genererar Aztec-streckkod med anpassat bildförhållande med Aspose.BarCode för .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Hur man genererar streckkod – En-dimensionella streckkodstyper](/barcode/english/net/one-dimensional-barcode-types/) +- [Generera DataMatrix-streckkod – Pro‑guide med Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/swedish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..bd556c5ca --- /dev/null +++ b/barcode/swedish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-07-15 +description: Hur man läser PDF417‑streckkod i C# och läser flera streckkoder från + en bild. Lär dig att läsa streckkodsbilder i C# med detaljerad kod och tips. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: sv +lastmod: 2026-07-15 +og_description: Hur man läser PDF417‑streckkod i C# snabbt. Den här guiden visar hur + du läser flera streckkoder från en enda bild och avkodar varje egenskap. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Hur man läser PDF417 i C# – Fullt kodexempel och förklaring +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Hur man läser PDF417 i C# – Komplett steg‑för‑steg‑guide +url: /sv/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-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 steg‑för‑steg‑guide + +Har du någonsin undrat **hur man läser PDF417** från en bild med C#? Du är inte ensam. De flesta utvecklare stöter på problem när de måste hämta de utökade Macro‑PDF417-fälten från ett skannat dokument. Den goda nyheten? Med bara några rader kod kan du avkoda en PDF417, läsa flera streckkoder i samma bild och hämta varje dold egenskap som specifikationen erbjuder. + +I den här handledningen går vi igenom ett verkligt exempel som visar **hur man läser PDF417**, hur man **läser flera streckkoder** från en enda fil, och varför **read barcode image C#**‑kod ser ut som den gör. I slutet har du en färdigkörbar konsolapp som skriver ut varje bit information du kan behöva—fil‑ID, segment‑ID, kontrollsumma, tidsstämplar, du namnger det. + +## Förutsättningar + +* .NET 6.0 SDK eller senare (koden fungerar även med .NET Core och .NET Framework). +* Visual Studio 2022 (eller någon annan editor du föredrar). +* NuGet‑paketet **Aspose.BarCode for .NET** – detta är biblioteket som faktiskt parsar PDF417. +* En exempelbild som innehåller en Macro‑PDF417‑streckkod (t.ex. `ExtPDF417Meta.png`). + +Ingen extra konfiguration krävs; biblioteket levereras med alla dekodrar du behöver. + +## Steg 1: Installera Aspose.BarCode + +Öppna din projektmapp i en terminal och kör: + +```bash +dotnet add package Aspose.BarCode +``` + +Det kommandot hämtar den senaste stabila versionen (i juli 2026 är den 23.12). Om du föredrar Package Manager Console i Visual Studio, använd: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Proffstips:** lås versionen (`23.12.0`) i din `.csproj` för att undvika oavsiktliga brytande förändringar senare. + +## Steg 2: Skapa ett konsolapp‑skelett + +Skapa ett nytt konsolprojekt om du inte redan har ett: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Ersätt den automatiskt genererade `Program.cs` med koden nedan. Vi kommer att förklara varje block i nästa avsnitt. + +## Steg 3: Skriv den kompletta “How to Read PDF417”-koden + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Varför den här koden fungerar + +* **`BarCodeReader`** är kärnklassen som strömmar bilden, upptäcker streckkoder och returnerar en samling av `BarCodeResult`‑objekt. +* Att skicka **`DecodeType.MacroPdf417`** talar om för biblioteket att behandla Macro‑PDF417 speciellt; det returnerar fortfarande vanliga PDF417‑symboler, vilket uppfyller kravet på **read multiple barcodes**. +* Objektet **`Extended.Pdf417.MacroPdf417`** innehåller alla valfria fält som definieras av ISO/IEC 15438‑standarden – där får du `FileID`, `SegmentID`, `Checksum` osv. +* `using`‑blocket garanterar att de inhemska resurserna frigörs, vilket förhindrar minnesläckor i långkörande tjänster. + +## Steg 4: Kör applikationen och verifiera utskrift + +Från terminalen: + +```bash +dotnet run +``` + +Du bör se något liknande: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Om bilden innehåller mer än en streckkod kommer loopen att skriva ut en avgränsningslinje (`----------------------------------------`) och fortsätta med nästa resultat—precis vad **read multiple barcodes** ser ut som i praktiken. + +## Vanliga frågor & specialfall + +### Vad händer om bilden har både Macro‑PDF417 och vanliga PDF417‑symboler? + +Samma `BarCodeReader`‑anrop returnerar båda. Du kan skilja dem åt genom att kontrollera `result.CodeType` (`MacroPdf417` vs `Pdf417`). De utökade egenskaperna blir `null` för en vanlig PDF417, så skyddet `if (macro != null)` förhindrar ett `NullReferenceException`. + +### Min streckkod är roterad eller skev—kommer läsaren fortfarande fungera? + +Aspose.BarCode innehåller inbyggd kompensation för rotation och förvrängning. Så länge streckkoden täcker minst 30 % av bildens bredd lyckas dekodern oftast. För extrema fall kan du aktivera `reader.Options.AllowInvertedBarcodes = true;` innan du anropar `ReadBarCodes()`. + +### Hur hanterar jag stora bildbatcher? + +Omslut läslogiken i en `foreach (var file in Directory.GetFiles(folder, "*.png"))`‑loop. `using`‑mönstret säkerställer att varje bilds inhemska resurser frigörs innan nästa iteration, vilket håller minnesanvändningen låg. + +## Fullständig källkodslista (klar för kopiering och inklistring) + +Nedan är hela programmet i ett block för snabb kopiering och inklistring. Inga dolda beroenden—bara Aspose.BarCode‑NuGet‑paketet. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Sammanfattning – Vad vi gick igenom + +* **How to read PDF417** using Aspose.BarCode in C#. +* De exakta stegen för att **read multiple barcodes** från en enda bild. +* Hur man **read barcode image C#** och extraherar varje Macro‑PDF417‑fält. +* Tips för rotation, batch‑bearbetning och hantering av saknade utökade data. + +## Nästa steg & relaterade ämnen + +* **Encode PDF417** – generera dina egna Macro‑PDF417‑streckkoder med `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – med samma `BarCodeReader`‑klass. +* **Integrate with ASP.NET Core** – exponera en web‑endpoint som tar emot en uppladdad bild och returnerar JSON med de avkodade fälten. + +Känn dig fri att experimentera: ändra bildsökvägen, släng in en vanlig PDF417 i samma mapp, eller justera `DecodeType`‑flaggorna för att se hur biblioteket beter sig. Ju mer du leker, desto bekvämare blir du med **read barcode image C#**‑scenarier. + +Har du en knepig bild som vägrar att avkodas? Lämna en kommentar nedan eller öppna ett ärende i GitHub‑repot för exempelprojektet. Lycka till med kodandet! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger 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/swedish/net/one-dimensional-barcode-types/_index.md b/barcode/swedish/net/one-dimensional-barcode-types/_index.md index e2ec8e481..2df9e09e1 100644 --- a/barcode/swedish/net/one-dimensional-barcode-types/_index.md +++ b/barcode/swedish/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ tjäna hur man genererar streckkoder i .NET med Aspose.BarCode för .NET. Den h Lär dig hur du hanterar undantag samtidigt som du genererar endimensionella streckkoder med Aspose.BarCode för .NET. Denna steg-för-steg-guide säkerställer feltoleranta streckkodslösningar. Börja nu! ### [Endimensionell Wide-Narrow Ratio Configuration](./one-dimensional-wide-narrow-ratio-configuration/) Generera anpassade streckkoder enkelt med Aspose.BarCode för .NET. Steg-för-steg-guide för endimensionell bred-smal konfiguration. +### [Generera streckkod från text med Aspose.BarCode – C#-guide](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Lär dig hur du skapar streckkoder från text i C# med Aspose.BarCode. ## Slutsats @@ -89,4 +91,4 @@ Med den här artikeln kommer du inte bara att få kunskap om olika endimensionel {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/swedish/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..414b954bf --- /dev/null +++ b/barcode/swedish/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-07-15 +description: Generera streckkod från text med Aspose.BarCode i C#. Lär dig hur du + ändrar kolumnantal, sparar streckkodsbild och skapar Aspose‑streckkodslösningar + snabbt. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: sv +lastmod: 2026-07-15 +og_description: Generera streckkod från text med Aspose.BarCode. Denna guide visar + hur du ändrar kolumnantalet, sparar streckkodsbilden och skapar streckkod med Aspose + i några rader kod. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Generera streckkod från text med Aspose.BarCode – Snabb C#‑genomgång +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Generera streckkod från text med Aspose.BarCode – C#‑guide +url: /sv/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generera streckkod från text med Aspose.BarCode – C# Guide + +Att generera streckkod från text med Aspose.BarCode är förvånansvärt enkelt. I den här handledningen går vi igenom **hur man genererar streckkod**, justerar kolumnlayouten och slutligen **sparar streckkodsbild** som en PNG‑fil. Oavsett om du bygger ett biljettsystem, en lageretikett‑skrivare eller bara experimenterar med QR‑liknande koder, så kommer stegen nedan snabbt att leda dig dit. + +## Vad du kommer att lära dig + +- Skapa en streckkod från en godtycklig Unicode‑sträng (ja, även “Åspóse.Barcóde©” fungerar). +- Justera **column count** för MicroPdf417 för att passa smala eller breda etiketter. +- Spara resultatet på disk med rätt bildformat. +- Tips för att hantera specialtecken och vanliga fallgropar när du **create barcode Aspose**‑lösningar. + +Inga externa verktyg, inga kommandorads‑hack—bara ren C# och Aspose.BarCode‑biblioteket. + +## Förutsättningar + +Innan vi dyker ner, se till att du har: + +1. **.NET 6.0** eller senare installerat (koden fungerar även på .NET Framework 4.7+). +2. En **license** för Aspose.BarCode, eller så kan du börja med den kostnadsfria utvärderingsversionen. +3. En mapp du kan skriva till – vi kallar den `YOUR_DIRECTORY` i exemplen. + +Om du saknar någon av dessa, hämta NuGet‑paketet nu: + +```bash +dotnet add package Aspose.BarCode +``` + +Det är allt—inga extra DLL‑filer att kopiera manuellt. + +## Steg 1 – Ställ in projektet och importerna + +Först, skapa en konsolapp (eller klistra in koden i vilket C#‑projekt som helst). Det viktiga är att importera rätt namnrymder: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Varför dessa using‑satser? `BarcodeGenerator` finns i `Aspose.BarCode.Generation`, medan `BarCodeImageFormat`‑enumen finns i `Aspose.BarCode`. Att hålla importerna organiserade gör den efterföljande koden lättläst som vanlig engelska. + +## Steg 2 – Skapa Barcode‑generatorn (how to generate barcode) + +Nu **genererar vi streckkod från text**. `EncodeTypes`‑enumen talar om för Aspose vilken symbologi som ska användas; här väljer vi `MicroPdf417` eftersom den hanterar långa strängar i ett kompakt rutnät. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Observera att strängen innehåller accentuerade tecken och en copyright‑symbol. Aspose.BarCode kodar automatiskt Unicode, så du behöver inte förbehandla texten. + +## Steg 3 – Finjustera utseendet (how to change column count) + +MicroPdf417 låter dig styra antalet kolumner, vilket direkt påverkar streckkodens bredd. En kompakt layout är bra för smala etiketter; en bredare layout förbättrar läsbarheten på stora utskrifter. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Varför 2‑pixel‑moduler? Det ger en skarp bild utan att öka filstorleken. Känn dig fri att experimentera—värden mellan 1 och 4 fungerar vanligtvis bra. Om du någonsin behöver ett annat antal kolumner, ändra bara `Columns`‑egenskapen; Aspose räknar om layouten automatiskt. + +## Steg 4 – Spara streckkodsbilden (save barcode image) + +Med generatorn konfigurerad är vi redo att **save barcode image**. `Save`‑metoden accepterar en filsökväg och en bildformat‑enum. PNG är förlustfri, så streckkoden förblir skarp även efter skalning. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Ett snabbt tips: använd alltid en absolut sökväg eller säkerställ att arbetskatalogen är den du förväntar dig; annars kan filen hamna i bin‑mappen och du undrar varför du inte kan hitta den. + +## Fullt fungerande exempel + +När allt sätts ihop, här är ett självständigt program du kan kopiera‑klistra in i `Program.cs` och köra: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Förväntad output** (konsol): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +Och om du öppnar `MicroPdf417.png` kommer du att se en skarp MicroPdf417‑streckkod som kodar den ursprungliga strängen, komplett med de specialtecken vi matade in. + +## Vanliga frågor & kantfall + +### Vad händer om min text är längre än standardkapaciteten? + +MicroPdf417 byter automatiskt till en flerradslayout när data överskrider max per rad. Du kan fortfarande styra antalet kolumner, men biblioteket kan lägga till extra rader i bakgrunden. Ingen extra kod behövs—håll bara ett öga på bildens dimensioner. + +### Hur ändrar jag bildformatet till JPEG eller BMP? + +Byt `BarCodeImageFormat.Png` mot `BarCodeImageFormat.Jpeg` (eller `Bmp`). Kom ihåg att JPEG introducerar komprimeringsartefakter, vilket kan påverka skanningspålitligheten. PNG är det säkraste standardalternativet. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Jag ser ett vattenmärke i resultatet—vad är fel? + +Det är utvärderingsversionen av Aspose.BarCode. För att **create barcode Aspose** utan vattenmärken, ladda en giltig licensfil som visas i den kommenterade raden i Steg 2. + +### Kan jag generera andra symbologier (QR, Code128, etc.)? + +Absolut. Byt bara `EncodeTypes.MicroPdf417` mot ett annat värde från `EncodeTypes`‑enum, t.ex. `EncodeTypes.QR` eller `EncodeTypes.Code128`. Resten av koden förblir densamma, vilket gör metoden mycket återanvändbar. + +## Pro‑tips för produktionsklar streckkodsgenerering + +- **Cache generatorn** om du skapar många streckkoder med samma inställningar; det minskar overhead för objekt‑skapande. +- **Validera inmatningssträngen** för längdbegränsningar specifika för den valda symbologin (Aspose kastar `ArgumentException` om den är för lång). +- **Använd `using`‑satser** eller `Dispose` generatorn när du är klar för att snabbt frigöra inhemska resurser. +- **Ställ in DPI** via `generator.Parameters.ImageResolution.DpiX/DpiY` om du behöver högupplösta utskrifter för stora etiketter. + +## Slutsats + +Du vet nu exakt **how to generate barcode from text** med Aspose.BarCode, hur du **change column count**, och det korrekta sättet att **save barcode image** som PNG. Det kompletta, körbara exemplet ovan visar ett rent, produktionsklart + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger 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 implementeringsmetoder i dina egna projekt. + +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Generate barcode image – Code 93 with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/thai/net/compact-pdf417-encoding/_index.md index 642025381..7afd01ff5 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 คู่มือครบถ้วนพร้อมขั้นตอนและตัวอย่างโค้ด +### [สร้างเมตาดาต้าบาร์โค้ด PDF417 ด้วย C# – คู่มือขั้นตอนเต็ม](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +เรียนรู้วิธีเพิ่มเมตาดาต้าให้บาร์โค้ด PDF417 ด้วย C# อย่างละเอียด พร้อมตัวอย่างโค้ดครบถ้วน +### [สร้างบาร์โค้ด PDF417 ด้วย C# – คู่มือครบถ้วน](./generate-pdf417-barcode-in-c-complete-guide/) +เรียนรู้วิธีสร้างบาร์โค้ด PDF417 ด้วย C# อย่างละเอียด พร้อมตัวอย่างโค้ดและการตั้งค่าต่าง ๆ +### [สร้างบาร์โค้ด PDF417 ด้วย C# – คู่มือขั้นตอนเต็ม](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +เรียนรู้วิธีสร้างบาร์โค้ด PDF417 ด้วย C# อย่างครบถ้วน พร้อมขั้นตอนและตัวอย่างโค้ด +### [วิธีอ่าน PDF417 ใน C# – คู่มือขั้นตอนเต็ม](./how-to-read-pdf417-in-c-complete-step-by-step-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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/thai/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..76565d050 --- /dev/null +++ b/barcode/thai/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-07-15 +description: สร้างข้อมูลเมตาดาต้า PDF417 barcode ด้วย C# โดยใช้ Aspose.BarCode เรียนรู้การตั้งค่า + Macro PDF417 บันทึกเป็น PNG และจัดการข้อความ Unicode +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: th +lastmod: 2026-07-15 +og_description: สร้างเมตาดาต้า PDF417 barcode ด้วย C# และ Aspose.BarCode คู่มือนี้แสดงการตั้งค่าทั้งหมดที่คุณต้องใช้เพื่อฝังไฟล์‑ID, + ตราประทับเวลา, และอื่น ๆ +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: สร้างเมตาดาต้าบาร์โค้ด PDF417 ด้วย C# – คู่มือการเขียนโปรแกรมเต็มรูปแบบ +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: สร้างเมตาดาต้า Barcode PDF417 ด้วย C# – คู่มือขั้นตอนเต็มรูปแบบ +url: /th/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างเมตาดาต้า PDF417 Barcode ใน C# – คู่มือขั้นตอนเต็ม + +เคยต้องการ **สร้างเมตาดาต้า PDF417 barcode** ใน C# แต่ไม่แน่ใจว่าต้องปรับคุณสมบัติใดบ้างหรือไม่? คุณไม่ได้เป็นคนเดียว—นักพัฒนามักเจออุปสรรคเมื่อสเปคต้องการอย่างเช่นไฟล์ ID, จำนวนเซกเมนต์, หรือ timestamp ที่กำหนดเอง + +ข่าวดีคือ Aspose.BarCode ทำให้เรื่องนี้ง่ายมาก ในบทเรียนนี้เราจะสร้าง `BarcodeGenerator` สำหรับ **Macro PDF417**, เติมเมตาดาต้าที่สำคัญทั้งหมด, แล้วบันทึกผลลัพธ์เป็นภาพ PNG. เมื่อจบคุณจะได้บาร์โค้ดเต็มรูปแบบพร้อมใช้ในระบบซัพพลายเชนหรือการจัดการเอกสารใด ๆ + +## สิ่งที่คู่มือนี้ครอบคลุม + +1. การตั้งค่าแพ็กเกจ NuGet ของ Aspose.BarCode. +2. การเริ่มต้น `BarcodeGenerator` สำหรับ **Macro PDF417**. +3. การเติมข้อมูลใน **barcode metadata field** ทุกฟิลด์ที่มีประโยชน์ (file ID, segment ID, checksum ฯลฯ). +4. การบันทึกบาร์โค้ดลงดิสก์และตรวจสอบผลลัพธ์. + +ไม่จำเป็นต้องมีประสบการณ์กับ Macro PDF417 มาก่อน—แค่ความรู้พื้นฐาน C# และ .NET runtime เวอร์ชันล่าสุด + +ทำไมคุณควรสนใจ? การฝังเมตาดาต้าที่สมบูรณ์ลงในบาร์โค้ดทำให้สแกนเนอร์ด้านล่างสามารถตรวจสอบการโอนย้ายไฟล์ทั้งหมด, ตรวจจับเซกเมนต์ที่หายไป, หรือแม้กระทั่งเรียกใช้เวิร์กโฟลว์อัตโนมัติ กล่าวคือคุณจะได้ **ข้อมูลที่แข็งแรงและอธิบายตัวเอง** โดยไม่ต้องอ้างอิงฐานข้อมูลแยก + +## ข้อกำหนดเบื้องต้น + +- .NET 6.0 หรือใหม่กว่า (โค้ดนี้ทำงานบน .NET Framework 4.7+ ด้วย) +- Visual Studio 2022 (หรือ IDE ใดก็ได้ที่คุณชอบ) +- แพ็กเกจ NuGet **Aspose.BarCode for .NET** (มีรุ่นทดลองฟรี) + +คุณสามารถติดตั้งแพ็กเกจด้วยคำสั่งต่อไปนี้: + +```bash +dotnet add package Aspose.BarCode +``` + +เมื่อเรามีพื้นฐานแล้ว, มาเริ่มลงมือทำการนำไปใช้จริงกัน + +## ขั้นตอนที่ 1: เริ่มต้น BarcodeGenerator สำหรับ Macro PDF417 + +สิ่งแรกที่เราต้องการคืออินสแตนซ์ `BarcodeGenerator` ที่กำหนดค่าให้ใช้ **Macro PDF417**. สิ่งนี้บอก Aspose.BarCode ว่าอัลกอริทึมการเข้ารหัสใดที่จะใช้และให้เรามีที่สำหรับใส่ข้อความที่มนุษย์อ่านได้ + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **ทำไมเรื่องนี้สำคัญ:** `EncodeTypes.MacroPdf417` เปิดโหมด PDF417 ขยายที่รองรับเมตาดาต้าเช่น file IDs และ segment numbers. ตัวอย่างข้อความมีอักขระ Unicode (`Å`, `ó`, `©`) เพื่อพิสูจน์ว่า generator จัดการอินพุตที่ไม่ใช่ ASCII ได้อย่างราบรื่น + +## ขั้นตอนที่ 2: กำหนดลักษณะพื้นฐานของบาร์โค้ด + +ก่อนที่เราจะเริ่มเติมเมตาดาต้า, เราควรตั้งค่าพารามิเตอร์ภาพบางอย่างเพื่อให้บาร์โค้ดไม่เป็นจุดจิ๋ว `XDimension` ควบคุมความกว้างของโมดูล, ส่วน `Columns` มีผลต่อรูปทรงโดยรวม + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **เคล็ดลับ:** ความกว้างพิกเซล `2` ทำงานได้ดีสำหรับการแสดงบนหน้าจอและเครื่องพิมพ์ส่วนใหญ่. หากต้องการพิมพ์ความละเอียดสูงขึ้น, เพิ่มเป็น `3` หรือ `4`. + +## ขั้นตอนที่ 3: เติมฟิลด์เมตาดาต้า Macro PDF417 + +ต่อไปคือหัวใจของบทเรียน—การเพิ่ม **barcode metadata fields**. แต่ละคุณสมบัติตรงกับส่วนหนึ่งของสเปค Macro PDF417 + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### รายละเอียดของแต่ละ Property + +| Property | จุดประสงค์ | ค่าที่พบบ่อย | +|----------|-------------|---------------| +| **MacroPdf417FileID** | ตัวระบุที่ไม่ซ้ำกันทั่วทั้งชุดไฟล์ | `12345678` | +| **MacroPdf417SegmentID** | ดัชนีของเซกเมนต์ปัจจุบัน (เริ่มที่ `0`) | `12` | +| **MacroPdf417SegmentsCount** | จำนวนเซกเมนต์ทั้งหมดที่คาดว่าจะมี | `20` | +| **MacroPdf417FileName** | ชื่อที่มนุษย์อ่านได้, มักเป็นชื่อไฟล์ต้นฉบับ | `"file01"` | +| **MacroPdf417Checksum** | ตรวจสอบความถูกต้อง 16‑bit CCITT | `1234` | +| **MacroPdf417FileSize** | ขนาดของไฟล์ต้นฉบับเป็นไบต์ | `400000` | +| **MacroPdf417TimeStamp** | เวลาที่ไฟล์ถูกสร้าง | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | ฟิลด์เลือกเสริมระบุผู้รับ | `"street"` | +| **MacroPdf417Sender** | ฟิลด์เลือกเสริมระบุระบบต้นทาง | `"aspose"` | +| **MacroPdf417Terminator** | ธงบอกสแกนเนอร์ว่านี่คือเซกเมนต์สุดท้าย | `Pdf417MacroTerminator.Set` | + +> **ทำไมคุณต้องใช้สิ่งเหล่านี้:** สแกนเนอร์ที่รองรับ Macro PDF417 สามารถประกอบไฟล์หลายเซกเมนต์, ตรวจสอบความสมบูรณ์ด้วย checksum, และแม้กระทั่งปฏิเสธข้อมูลที่ล้าสมัยตาม timestamp. นี้ทำให้ไม่ต้องมีไฟล์ manifest แยกต่างหาก + +## ขั้นตอนที่ 4: บันทึกภาพบาร์โค้ด + +เมื่อกำหนดพารามิเตอร์ทั้งหมดแล้ว, เราเพียงเรียก `Save`. ตัวอย่างจะเขียนไฟล์ PNG ไปยังโฟลเดอร์ที่คุณระบุ + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **กรณีขอบ:** หากคุณวางแผนจะฝังบาร์โค้ดใน PDF ต่อไป, คุณอาจเลือก `BarCodeImageFormat.Jpeg` หรือ `Pdf`. PNG รักษารายละเอียดแบบ lossless, ซึ่งเหมาะสำหรับการตรวจสอบ + +## ตัวอย่างทำงานเต็มรูปแบบ + +เมื่อนำทุกอย่างมารวมกัน, นี่คือโปรแกรมเต็มที่คุณสามารถคัดลอก‑วางลงในแอปคอนโซลได้: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +การรันโปรแกรมจะสร้างไฟล์ชื่อ **ExtPDF417Meta.png** ในโฟลเดอร์ของไฟล์ executable. เปิดด้วยโปรแกรมดูภาพใดก็ได้แล้วคุณจะเห็น PDF417 barcode ที่หนาและคอนทราสต์สูง. หากสแกนด้วยเครื่องอ่านบาร์โค้ดที่รองรับ Macro PDF417, สแกนเนอร์จะคืนค่ามีเดียที่เราตั้งไว้—file ID `12345678`, segment `12` ของ `20`, เป็นต้น + +## คำถามทั่วไป & ข้อผิดพลาดที่พบบ่อย + +- **ถ้าบาร์โค้ดดูเบลอ?** เพิ่มค่า `XDimension.Pixels` หรือเปลี่ยนเป็นรูปแบบภาพความละเอียดสูงกว่า. +- **ต้องตั้งค่าทุกฟิลด์เมตาดาต้าหรือไม่?** ไม่จำเป็น. เพียงฟิลด์ที่ระบบ downstream ของคุณต้องการเท่านั้นที่ต้องตั้งค่า. ฟิลด์ที่ไม่ได้ใช้สามารถปล่อยเป็นค่าเริ่มต้น. +- **สามารถสร้างไฟล์หลายเซกเมนต์โดยอัตโนมัติได้หรือไม่?** ได้—วนลูปข้อมูล, เพิ่มค่า `MacroPdf417SegmentID`, และสร้างบาร์โค้ดแยกสำหรับแต่ละเซกเมนต์. จำไว้ว่าต้องทำให้ `MacroPdf417FileID` เหมือนกันในทุกเซกเมนต์. +- **รองรับ Unicode หรือไม่?** แน่นอน. ตัวอย่างข้อความมี `Å`, `ó`, และ `©`, แสดงว่า Aspose.BarCode รองรับ UTF‑8 ตั้งแต่ต้น + +## ขั้นตอนต่อไป: ไปไกลกว่าพื้นฐาน + +เมื่อคุณรู้วิธี **สร้างเมตาดาต้า PDF417 barcode** แล้ว, คุณอาจอยากสำรวจ: + +- **ฝังบาร์โค้ดใน PDF** ด้วย `Aspose.Pdf` สำหรับการสร้างเอกสารแบบ end‑to‑end. +- **อ่านเมตาดาต้ากลับ** ด้วย `BarcodeReader` เพื่อยืนยันการสแกนแบบโปรแกรม. +- **ปรับสี** (foreground/background) เพื่อการสร้างแบรนด์. +- **เชื่อมต่อกับฐานข้อมูล** เพื่อเติมฟิลด์อัตโนมัติ เช่น `FileID` หรือ `Timestamp`. + +หัวข้อทั้งหมดนี้เชื่อมโยงกับคีย์เวิร์ดรองของเรา—**macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, และ **c# barcode generation**—ดังนั้นคุณจะพบเอกสารมากมายสำหรับการเรียนต่อ + +## สรุป + +เราเพิ่งอธิบายตัวอย่างเต็มรูปแบบพร้อมใช้งานในผลิตภัณฑ์ว่าอย่างไร **สร้างเมตาดาต้า PDF417 barcode** ใน C#. ตั้งแต่การติดตั้ง Aspose.BarCode, การเริ่มต้น `BarcodeGenerator`, การเติมทุก **barcode metadata field** ที่เกี่ยวข้อง, จนถึงการบันทึก PNG ที่คมชัด, กระบวนการนี้ง่ายดายเมื่อคุณรู้คุณสมบัติที่ต้องใช้ + +ลองทำดู, ปรับค่าต่าง ๆ, แล้วสังเกตว่าตัวสแกนเนอร์ตอบสนองอย่างไร. ความยืดหยุ่นของ Macro PDF417 ทำให้คุณสามารถฝังทุกอย่างที่ระบบ downstream ต้องการ—ทั้งหมดในภาพเดียวที่สแกนได้. ขอให้เขียนโค้ดสนุกและบาร์โค้ดของคุณปราศจากข้อผิดพลาด! + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้. แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการนำไปใช้แบบอื่นในโปรเจคของคุณ. + +- [วิธีสร้าง Barcode – Compact PDF417 ด้วย Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [ไลบรารี barcode ภาษา Java – เพิ่ม barcode ลงใน PDF ด้วย Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [วิธีสร้าง Barcode – Compact PDF417 ด้วย Aspose.BarCode (ภาษาเยอรมัน)](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/thai/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..74d4adcbf --- /dev/null +++ b/barcode/thai/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: สร้างบาร์โค้ด PDF417 อย่างรวดเร็วและเรียนรู้วิธีตั้งค่าคอลัมน์สำหรับภาพบาร์โค้ด + PDF417 แบบกะทัดรัดใน C# +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: th +lastmod: 2026-07-15 +og_description: สร้างบาร์โค้ด PDF417 ด้วย Aspose.BarCode และเรียนรู้วิธีตั้งค่าคอลัมน์เพื่อสร้างภาพบาร์โค้ด + PDF417 ที่กะทัดรัด +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: สร้างบาร์โค้ด PDF417 ด้วย C# – คู่มือขั้นตอนโดยละเอียด +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: สร้างบาร์โค้ด PDF417 ด้วย C# – คู่มือฉบับสมบูรณ์ +url: /th/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างบาร์โค้ด PDF417 ด้วย C# – คู่มือฉบับสมบูรณ์ + +เคยต้อง **สร้างบาร์โค้ด PDF417** ในโปรเจกต์ .NET แต่ไม่รู้ว่าจะเริ่มจากตรงไหนหรือไม่? คุณไม่ได้อยู่คนเดียว ในแอปพลิเคชันระดับองค์กรหลาย ๆ ตัว—เช่น เครื่องพิมพ์บอร์ดดิ้งพาส, ป้ายสินค้าคงคลัง, หรือระบบตั๋วมือถือ—PDF417 คือเครื่องมือหลักที่บรรจุข้อมูลจำนวนมากในพื้นที่ภาพที่เล็กลง + +สิ่งที่สำคัญคือ: ไลบรารี Aspose.BarCode ทำให้กระบวนการทั้งหมดง่ายดายเกือบไม่มีอุปสรรค และคุณยังสามารถควบคุม **วิธีตั้งค่าคอลัมน์** เพื่อให้บาร์โค้ดกระชับที่สุดได้ อีกทั้งเมื่อทำตามบทเรียนนี้แล้ว คุณจะได้ภาพ PNG ของ **บาร์โค้ด PDF417** ที่พร้อมนำไปใช้ใน UI, อีเมล หรือการพิมพ์ใด ๆ + +## สิ่งที่คุณจะได้เรียนรู้ + +- แอปคอนโซล C# ที่ทำงานเต็มรูปแบบสำหรับสร้างบาร์โค้ด PDF417 +- ความเข้าใจที่ชัดเจนเกี่ยวกับ *X‑Dimension* (ขนาดโมดูล) และเหตุผลที่สำคัญ +- คำแนะนำขั้นตอนต่อขั้นตอนเกี่ยวกับ **วิธีตั้งค่าคอลัมน์** เพื่อให้บาร์โค้ดกระชับยิ่งขึ้น +- ไฟล์ `PNG` ที่บันทึกไว้และสามารถเปิดดูได้ทันทีเพื่อยืนยันผลลัพธ์ +- เคล็ดลับการแก้ไขปัญหาที่พบบ่อย (เช่น บาร์โค้ดอ่านไม่ออก, รูปแบบไฟล์ผิด) + +> **ข้อกำหนดเบื้องต้น** – .NET 6+ SDK, Visual Studio 2022 (หรือเครื่องมือแก้ไขที่คุณชอบ), และการอ้างอิง NuGet ไปยัง `Aspose.BarCode` เท่านั้น + +--- + +## ขั้นตอนที่ 1: ติดตั้งแพคเกจ NuGet Aspose.BarCode + +ก่อนที่เราจะ *สร้างบาร์โค้ด PDF417* ไลบรารีต้องถูกเพิ่มเข้าไปในโปรเจกต์ + +```bash +dotnet add package Aspose.BarCode +``` + +บรรทัดเดียวนี้จะดึงชนิดข้อมูลทั้งหมดที่คุณต้องใช้ รวมถึง `BarcodeGenerator`, `EncodeTypes` และ enum `BarCodeImageFormat` + +> **เคล็ดลับ:** หากคุณพัฒนาเป็น .NET Framework แทน .NET 6 ให้ใช้คำสั่ง PowerShell แบบคลาสสิก `Install-Package Aspose.BarCode` ภายใน Package Manager Console + +--- + +## ขั้นตอนที่ 2: สร้างแอปคอนโซลขนาดเล็กที่สุด + +มาสร้างโปรแกรมง่าย ๆ ที่ทำหน้าที่สร้างบาร์โค้ดเท่านั้น เปิดโฟลเดอร์ใหม่, รัน `dotnet new console`, แล้วแทนที่ไฟล์ `Program.cs` ที่สร้างอัตโนมัติด้วยโค้ดด้านล่าง + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**เหตุผลที่สำคัญ:** +- `EncodeTypes.Pdf417` บอกไลบรารีว่าเราต้องการบาร์โค้ด PDF417 ไม่ใช่ QR หรือ Code128 +- `XDimension.Pixels` ควบคุมความละเอียดของแต่ละโมดูลสีดำหรือสีขาวขนาดเล็ก +- ส่วน **วิธีตั้งค่าคอลัมน์** มีผลโดยตรงต่อรูปร่างของ **ภาพบาร์โค้ด PDF417** +- `Truncate = true` จะตัดแถวว่างที่ไม่จำเป็นออก ทำให้ได้ลุค “กระชับ” ที่สแกนเนอร์หลายตัวชื่นชอบ + +--- + +## ขั้นตอนที่ 3: เจาะลึก – ทำความเข้าใจคอลัมน์และการตัดแถว + +### วิธีตั้งค่าคอลัมน์ + +PDF417 จัดข้อมูลในเมทริกซ์ของ *แถว* × *คอลัมน์* ไลบรารีตั้งค่าเริ่มต้นที่ 5 คอลัมน์ ซึ่งเหมาะกับกรณีส่วนใหญ่ อย่างไรก็ตาม คุณอาจต้องการบาร์โค้ดที่แคบลงเพื่อใส่ในป้าย หรือกว้างขึ้นเพื่อเพิ่มความน่าเชื่อถือของการสแกน คุณสมบัติดังนี้: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +รับค่าตั้งแต่ **1** ถึง **30** (ขีดจำกัดที่แน่นอนขึ้นอยู่กับความยาวข้อมูล) ต่อไปนี้คือชีตสรุปอย่างรวดเร็ว: + +| คอลัมน์ | ความกว้างโดยประมาณ (มม.) | เมื่อควรใช้ | +|---------|---------------------------|-------------| +| 1‑3 | แคบมาก | ป้ายเล็ก, พื้นที่จำกัด | +| 4‑6 | มาตรฐาน | ใบเสร็จส่วนใหญ่, ตั๋ว | +| 7‑10 | กว้างขึ้น | ข้อมูลความหนาแน่นสูง, ความอ่านง่ายที่ดีขึ้น | + +### Truncate (โหมดกระชับ) + +การตั้งค่า `Truncate = true` บอกตัวเข้ารหัสให้ตัดแถวว่างที่ไม่จำเป็นออกจากด้านล่าง ผลลัพธ์คือ **ภาพบาร์โค้ด PDF417 แบบกระชับ** ที่ใช้พื้นที่น้อยที่สุดแต่ยังคงบรรจุข้อมูลทั้งหมด หากคุณเจอข้อผิดพลาด “บาร์โค้ดใหญ่เกินป้าย” ให้สลับค่าสถานะนี้ + +--- + +## ขั้นตอนที่ 4: รันแอปและตรวจสอบผลลัพธ์ + +คอมไพล์และรัน: + +```bash +dotnet run +``` + +คุณควรเห็นข้อความในคอนโซลยืนยันตำแหน่งการบันทึก ไปที่โฟลเดอร์และเปิด `CompactPdf417.png` ภาพจะมีลักษณะประมาณนี้: + +![Generated PDF417 barcode image](./CompactPdf417.png "Generated PDF417 barcode image – compact PNG created by Aspose.BarCode") + +*ข้อความแทนภาพ:* **Generated PDF417 barcode image** – ไฟล์ PNG กระชับที่สร้างโดยโค้ดในบทเรียน + +หากสแกนเนอร์ของคุณอ่านได้สำเร็จ ยินดีด้วย—คุณได้ **สร้างบาร์โค้ด PDF417** อย่างสำเร็จและเข้าใจ **วิธีตั้งค่าคอลัมน์** เพื่อให้ได้ **ภาพบาร์โค้ด PDF417** ที่เรียบร้อย + +--- + +## ขั้นตอนที่ 5: ปัญหาที่พบบ่อยและวิธีแก้ + +| อาการ | สาเหตุที่เป็นไปได้ | วิธีแก้อย่างรวดเร็ว | +|-------|-------------------|----------------------| +| บาร์โค้ดดูเบลอ | `XDimension.Pixels` ต่ำเกินไป (เช่น 1) | เพิ่มเป็น 2‑3 พิกเซลเพื่อให้ภาพคมชัด | +| สแกนเนอร์อ่านไม่ได้ | คอลัมน์มากเกินไปสำหรับข้อมูลที่มี | ลด `Columns` หรือเปิด `Truncate` | +| รูปแบบไฟล์ผิด | บันทึกด้วย `BarCodeImageFormat.Jpeg` โดยบังเอิญ | ใช้ `BarCodeImageFormat.Png` เพื่อผลลัพธ์ไม่มีการสูญเสีย | +| เกิดข้อยกเว้น `ArgumentOutOfRangeException` | จำนวนคอลัมน์เกินช่วงที่อนุญาต | รักษาคอลัมน์ระหว่าง 1‑30 และตรวจสอบให้ข้อมูลพอดี | + +--- + +## ขั้นตอนที่ 6: ไปต่อ – ปรับสีและเพิ่มข้อความ + +หากต้องการให้บาร์โค้ดสอดคล้องกับสีแบรนด์ของคุณ สามารถปรับสีพื้นหน้าและพื้นหลังได้: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +หรือเพิ่มข้อความที่มนุษย์อ่านได้ใต้บาร์โค้ด: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +ส่วนเหล่านี้เป็นตัวเลือกเสริม แต่แสดงให้เห็นว่ากระบวนการ **สร้างบาร์โค้ด PDF417** มีความยืดหยุ่นแค่ไหน + +--- + +## สรุป + +เราได้เดินผ่านตัวอย่างครบวงจรที่ **สร้างบาร์โค้ด PDF417** ด้วย Aspose.BarCode, อธิบาย **วิธีตั้งค่าคอลัมน์** เพื่อควบคุมขนาดของบาร์โค้ด, และบันทึกผลลัพธ์เป็น **ภาพบาร์โค้ด PDF417** ที่คมชัดในรูปแบบ PNG โค้ดเป็นอิสระ, ทำงานกับ .NET 6+ และสามารถนำไปใช้ในโปรเจกต์ใดก็ได้โดยไม่ยุ่งยาก + +ต่อไปคุณอาจลองเข้ารหัสข้อมูลขนาดใหญ่ (เช่น JSON), ทดลองรูปแบบไฟล์ภาพต่าง ๆ, หรือรวมตัวสร้างบาร์โค้ดเข้ากับ Web API ที่ให้บริการบาร์โค้ดตามคำขอ ความเป็นไปได้ไม่มีที่สิ้นสุด และคุณก็มีพื้นฐานที่มั่นคงแล้วสำหรับการต่อยอด + +ขอให้สนุกกับการเขียนโค้ด และขอให้บาร์โค้ดของคุณสแกนได้สำเร็จตั้งแต่ครั้งแรก! + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมตัวอย่างโค้ดที่ทำงานได้เต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโปรเจกต์ของคุณ + +- [วิธีสร้างบาร์โค้ด – PDF417 แบบกระชับด้วย Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [วิธีสร้างภาพบาร์โค้ดใน Java ด้วย Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [สร้างบาร์โค้ด Java – ตั้งค่าความละเอียดภาพด้วย Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/thai/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..57ca0868b --- /dev/null +++ b/barcode/thai/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,200 @@ +--- +category: general +date: 2026-07-15 +description: สร้างบาร์โค้ด PDF417 อย่างรวดเร็วด้วย C# เรียนรู้วิธีสร้างบาร์โค้ดจากข้อความ + ปรับขนาดบาร์โค้ด และตั้งค่าขนาดบาร์โค้ดตามต้องการในเวลาไม่กี่นาที. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: th +lastmod: 2026-07-15 +og_description: สร้างบาร์โค้ด PDF417 ด้วย C# อย่างรวดเร็ว คู่มือนี้แสดงวิธีสร้างบาร์โค้ดจากข้อความ + ปรับขนาดบาร์โค้ด และกำหนดมิติของบาร์โค้ดตามต้องการ +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: สร้างบาร์โค้ด PDF417 ด้วย C# – คู่มือการเขียนโปรแกรมเต็มรูปแบบ +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: สร้างบาร์โค้ด PDF417 ด้วย C# – คู่มือแบบครบขั้นตอน +url: /th/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างบาร์โค้ด PDF417 ด้วย C# – คู่มือขั้นตอนเต็ม + +เคยต้อง **สร้างบาร์โค้ด PDF417** แต่ไม่แน่ใจว่าจะปรับตั้งค่าอะไรบ้างหรือไม่? คุณไม่ได้เป็นคนเดียว—นักพัฒนาหลายคนเจออุปสรรคเดียวกันเมื่อลองเล่นกับบาร์โค้ด 2‑D ครั้งแรก ข่าวดีคือ? ด้วยไม่กี่บรรทัดของ C# คุณก็สามารถแปลงสตริงใด ๆ ให้เป็นภาพ PDF417 ที่สแกนได้ ควบคุมขนาดได้อย่างแม่นยำ และแม้กระทั่งกำหนดรูปแบบคอลัมน์‑แถวแบบกำหนดเองได้ + +ในบทเรียนนี้เราจะอธิบายวิธี **สร้างบาร์โค้ดจากข้อความ**, ปรับขนาดบาร์โค้ด, และตั้งค่าขนาดบาร์โค้ดแบบกำหนดเอง — ทั้งหมดโดยใช้ไลบรารี Aspose.BarCode ที่ได้รับความนิยม เมื่อจบคุณจะมีตัวอย่างพร้อมรันที่สามารถใส่ลงในโปรเจกต์ .NET ใดก็ได้ + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## สิ่งที่คุณจะสร้าง + +- บาร์โค้ด PDF417 ที่เข้ารหัสสตริง `Åspóse.Barcóde©` +- การควบคุมมิติ X‑dimension (ความกว้างพิกเซลของแต่ละโมดูล) อย่างแม่นยำ +- รูปแบบกำหนดเอง 4 คอลัมน์และ 9 แถว +- ไฟล์ PNG ที่บันทึกลงดิสก์ + +ไม่มีบริการภายนอก ไม่มีเทคนิควิเศษ—แค่โค้ด C# ธรรมดาที่คุณสามารถคอมไพล์ได้ทันที + +## ข้อกำหนดเบื้องต้น + +- .NET 6.0 หรือใหม่กว่า (โค้ดนี้ทำงานบน .NET Framework 4.8 ด้วย) +- Visual Studio 2022 หรือ IDE ใด ๆ ที่รองรับ C# +- Aspose.BarCode for .NET (รุ่นทดลองหรือแบบลิขสิทธิ์) ติดตั้งผ่าน NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +เท่านี้—เมื่อแพ็กเกจถูกอ้างอิงแล้วคุณก็พร้อมเริ่มทำงาน + +## ขั้นตอนที่ 1 – สร้างบาร์โค้ด PDF417 ด้วยข้อมูลข้อความ + +สิ่งแรกที่ต้องมีคืออินสแตนซ์ของ `BarcodeGenerator` ที่ระบุว่าเรากำลังใช้สัญลักษณ์ PDF417 และข้อความที่ต้องการเข้ารหัส + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **ทำไมเรื่องนี้ถึงสำคัญ:** +> `EncodeTypes.Pdf417` บอกไลบรารีให้ใช้รูปแบบ PDF417 2‑D ส่วนอาร์กิวเมนต์ที่สองคือข้อมูล **generate barcode from text** ที่คุณใส่เข้าไป จะกลายเป็นข้อมูลที่บันทึกในเมทริกซ์ของบาร์โค้ด + +## ขั้นตอนที่ 2 – ปรับขนาดบาร์โค้ด (X‑Dimension) + +ถ้าคุณเคยพิมพ์บาร์โค้ดที่ดูเล็กเกินไปบนใบเสร็จ คุณคงเคยเจอปัญหาเครื่องสแกนไม่อ่านได้ `XDimension` ควบคุมความกว้างของโมดูลเดียว (สี่เหลี่ยมสีดำหรือสีขาวที่เล็กที่สุด) ในหน่วยพิกเซล + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **เคล็ดลับ:** +> ค่า 2 px ทำงานได้ดีในหลายกรณีที่แสดงบนหน้าจอ สำหรับการพิมพ์ความละเอียดสูงคุณอาจเพิ่มเป็น 3 หรือ 4 px ได้ แต่ต้องจำไว้ว่า X‑dimension ที่ใหญ่ขึ้นจะทำให้ภาพโดยรวมใหญ่ขึ้นด้วย + +## ขั้นตอนที่ 3 – ตั้งค่าขนาดบาร์โค้ดแบบกำหนดเอง (คอลัมน์ & แถว) + +PDF417 อนุญาตให้คุณกำหนดจำนวนคอลัมน์และแถวที่บาร์โค้ดจะใช้ นี่คือจุดที่ **custom barcode dimensions** เข้ามามีบทบาท การเปลี่ยนค่าต่าง ๆ สามารถช่วยให้บาร์โค้ดพอดีกับพื้นที่ UI ที่แคบหรือให้ตรงกับขนาดฉลากที่ต้องการ + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **เกิดอะไรขึ้นเบื้องหลัง?** +> ไลบรารีจะกระจายข้อมูลที่เข้ารหัสไปยังกริดที่กำหนด จำนวนคอลัมน์น้อยหมายถึงบาร์โค้ดที่สูงขึ้น; แถวมากหมายถึงบาร์โค้ดที่สั้นลง ปรับตัวเลขจนกว่าจะได้สมดุลที่เหมาะกับแอปของคุณ + +## ขั้นตอนที่ 4 – บันทึกภาพบาร์โค้ด + +เมื่อกำหนดค่าทั้งหมดแล้ว เราก็สั่งให้เจเนอเรเตอร์เขียนไฟล์ PNG ลงดิสก์ PNG เป็นรูปแบบ lossless จึงรักษาความคมของโมดูลได้อย่างเต็มที่ + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +เมื่อคุณรันโปรแกรม คุณควรจะเห็นไฟล์ที่ `C:\Barcodes\CustomLayout.png` ซึ่งมีลักษณะคล้ายกับภาพหน้าจอด้านบน การสแกนด้วยเครื่องอ่านที่รองรับ PDF417 จะคืนค่าข้อความเดิม `Åspóse.Barcóde©` + +## ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นโปรแกรมทั้งหมดที่คุณสามารถคัดลอก‑วางลงในแอปคอนโซลได้ รวมถึงการใช้ `using` ทั้งหมดและการจัดการข้อผิดพลาดที่คุณคาดหวังในโค้ดระดับผลิต + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +รันโค้ดแล้วจะพิมพ์: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…และสร้างไฟล์ PNG ที่เปิดได้ในโปรแกรมดูรูปภาพใดก็ได้ หากสแกนด้วยแอปบนมือถือ (เช่น “Barcode Scanner” บน iOS/Android) ข้อความที่ถอดรหัสจะต้องเป็น **Åspóse.Barcóde©** อย่างตรงกัน + +## คำถามที่พบบ่อย & กรณีขอบ + +| Question | Answer | +|----------|--------| +| **Can I use a different image format?** | Yes—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, or `Svg` are all supported. Just change the second argument of `Save`. | +| **What if my text contains Unicode characters?** | Aspose.BarCode fully supports UTF‑8, so the example with `Å` and `©` works out‑of‑the‑box. | +| **How do I change the error‑correction level?** | Use `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (levels 0‑8). Higher levels increase redundancy but also size. | +| **I need a transparent background—can I do that?** | Set `generator.Parameters.Barcode.Image.TransparentBackground = true;` before saving. | +| **Is there a way to embed the barcode directly into a PDF?** | Absolutely. Replace the `Save` call with `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` and you’ll get a one‑page PDF containing the barcode. | + +## สรุป + +คุณได้เรียนรู้วิธี **generate PDF417 barcode** ด้วย C# จากสตริงใดก็ได้, **adjust barcode size**, และใช้ **custom barcode dimensions** เพื่อให้พอดีกับการออกแบบของคุณ กระบวนการสี่ขั้นตอน—initialize, size, layout, save—ครอบคลุมการทำงานหลักสำหรับสถานการณ์บาร์โค้ด 2‑D ส่วนใหญ่ + +ต่อไปคุณจะลองสลับ `EncodeTypes.Pdf417` เป็น `EncodeTypes.QR` หรือ `EncodeTypes.Code128` เพื่อดูว่า API ปรับตัวอย่างไร ทดลองเปลี่ยนค่า `XDimension`, ปรับเมทริกซ์คอลัมน์/แถว, หรือฝังภาพลงในรายงาน PDF ความเป็นไปได้แทบไม่มีที่สิ้นสุด และตอนนี้คุณมีพื้นฐานที่มั่นคงเพื่อต่อยอด + +มีคำถามเพิ่มเติมหรือค้นพบเทคนิคเจ๋ง ๆ ขณะเล่นกับ PDF417? แสดงความคิดเห็นด้านล่าง—มาร่วมสนทนากันต่อไป ขอให้สนุกกับการเขียนโค้ด! + +## สิ่งที่คุณควรเรียนต่อไป + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคในคู่มือนี้ แต่ละแหล่งรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการทำงานทางเลือกในโปรเจกต์ของคุณ + +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Generate DataMatrix Barcode – Pro Guide with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/thai/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..75a26c8bf --- /dev/null +++ b/barcode/thai/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,311 @@ +--- +category: general +date: 2026-07-15 +description: วิธีอ่านบาร์โค้ด PDF417 ด้วย C# และอ่านบาร์โค้ดหลายรายการจากภาพเดียว + เรียนรู้การอ่านภาพบาร์โค้ดด้วย C# พร้อมโค้ดละเอียดและเคล็ดลับ +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: th +lastmod: 2026-07-15 +og_description: วิธีอ่านบาร์โค้ด PDF417 ด้วย C# อย่างรวดเร็ว คู่มือนี้จะแสดงวิธีอ่านบาร์โค้ดหลายรายการจากภาพเดียวและถอดรหัสคุณสมบัติแต่ละอย่าง. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: วิธีอ่าน PDF417 ด้วย C# – ตัวอย่างโค้ดเต็มและคำอธิบาย +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: วิธีอ่าน PDF417 ใน C# – คู่มือขั้นตอนเต็มรูปแบบ +url: /th/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีอ่าน PDF417 ใน C# – คู่มือขั้นตอนเต็ม + +เคยสงสัย **how to read PDF417** จากภาพโดยใช้ C# หรือไม่? คุณไม่ได้เป็นคนเดียว นักพัฒนาส่วนใหญ่มักเจออุปสรรคเมื่อจำเป็นต้องดึงฟิลด์ Macro‑PDF417 ที่ขยายจากเอกสารสแกน ข่าวดีคือ? ด้วยเพียงไม่กี่บรรทัดของโค้ด คุณสามารถถอดรหัส PDF417, อ่านบาร์โค้ดหลายรายการในรูปเดียวกัน, และดึงคุณสมบัติที่ซ่อนอยู่ทั้งหมดที่สเปคกำหนด + +ในบทแนะนำนี้ เราจะพาคุณผ่านตัวอย่างจริงที่แสดง **how to read PDF417**, วิธี **read multiple barcodes** จากไฟล์เดียว, และเหตุผลว่าทำไมโค้ด **read barcode image C#** มีลักษณะเช่นนั้น สุดท้ายคุณจะได้แอปคอนโซลที่พร้อมรันและพิมพ์ข้อมูลทุกส่วนที่คุณอาจต้องการ—File ID, Segment ID, Checksum, Timestamps, ตามที่คุณต้องการ + +## ข้อกำหนดเบื้องต้น + +* .NET 6.0 SDK หรือรุ่นที่ใหม่กว่า (โค้ดทำงานได้กับ .NET Core และ .NET Framework ด้วยเช่นกัน). +* Visual Studio 2022 (หรือเครื่องมือแก้ไขใด ๆ ที่คุณชอบ). +* แพคเกจ NuGet **Aspose.BarCode for .NET** – นี่คือไลบรารีที่ทำการแยกวิเคราะห์ PDF417 จริง ๆ. +* ภาพตัวอย่างที่มีบาร์โค้ด Macro‑PDF417 (เช่น `ExtPDF417Meta.png`). + +ไม่ต้องกำหนดค่าเพิ่มเติม; ไลบรารีมาพร้อมกับตัวถอดรหัสทั้งหมดที่คุณต้องการ. + +## ขั้นตอนที่ 1: ติดตั้ง Aspose.BarCode + +เปิดโฟลเดอร์โปรเจกต์ของคุณในเทอร์มินัลและรัน: + +```bash +dotnet add package Aspose.BarCode +``` + +คำสั่งนั้นจะดึงเวอร์ชันเสถียรล่าสุด (ณ กรกฎาคม 2026 คือ 23.12). หากคุณต้องการใช้ Package Manager Console ภายใน Visual Studio ให้ใช้: + +```powershell +Install-Package Aspose.BarCode +``` + +> **เคล็ดลับ:** ล็อกเวอร์ชัน (`23.12.0`) ในไฟล์ `.csproj` ของคุณเพื่อหลีกเลี่ยงการเปลี่ยนแปลงที่ทำให้โค้ดเสียหายโดยไม่ได้ตั้งใจในภายหลัง. + +## ขั้นตอนที่ 2: สร้างโครงสร้างแอปคอนโซล + +สร้างโปรเจกต์คอนโซลใหม่หากคุณยังไม่มี: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +แทนที่ไฟล์ `Program.cs` ที่สร้างอัตโนมัติด้วยโค้ดด้านล่าง เราจะอธิบายแต่ละบล็อกในส่วนต่อไป + +## ขั้นตอนที่ 3: เขียนโค้ด “How to Read PDF417” เต็มรูปแบบ + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### ทำไมโค้ดนี้ถึงทำงาน + +* **`BarCodeReader`** คือคลาสหลักที่สตรีมภาพ, ตรวจจับบาร์โค้ด, และคืนคอลเลกชันของอ็อบเจกต์ `BarCodeResult`. +* การส่ง **`DecodeType.MacroPdf417`** บอกไลบรารีให้จัดการ Macro‑PDF417 อย่างพิเศษ; มันยังคงคืนสัญลักษณ์ PDF417 ธรรมดา, ซึ่งตอบสนองความต้องการ **read multiple barcodes**. +* อ็อบเจกต์ **`Extended.Pdf417.MacroPdf417`** เก็บฟิลด์เลือกทั้งหมดที่กำหนดโดยมาตรฐาน ISO/IEC 15438 – ที่นี่คุณจะได้ `FileID`, `SegmentID`, `Checksum` เป็นต้น. +* บล็อก `using` รับประกันว่าทรัพยากรเนทีฟจะถูกปล่อย, ป้องกันการรั่วของหน่วยความจำในบริการที่ทำงานเป็นเวลานาน. + +## ขั้นตอนที่ 4: รันแอปพลิเคชันและตรวจสอบผลลัพธ์ + +จากเทอร์มินัล: + +```bash +dotnet run +``` + +คุณควรเห็นผลลัพธ์คล้ายกับ: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +หากภาพมีบาร์โค้ดมากกว่าหนึ่งรายการ, ลูปจะพิมพ์เส้นแบ่ง (`----------------------------------------`) และดำเนินการต่อกับผลลัพธ์ถัดไป—ตรงกับสิ่งที่ **read multiple barcodes** ทำงานในทางปฏิบัติ. + +## คำถามทั่วไป & กรณีขอบ + +### ถ้าภาพมีสัญลักษณ์ Macro‑PDF417 และ PDF417 ปกติพร้อมกันล่ะ? + +การเรียก `BarCodeReader` เดียวกันจะคืนค่าทั้งสอง คุณสามารถแยกแยะได้โดยตรวจสอบ `result.CodeType` (`MacroPdf417` กับ `Pdf417`). คุณสมบัติเพิ่มเติมจะเป็น `null` สำหรับ PDF417 ธรรมดา, ดังนั้นการตรวจสอบ `if (macro != null)` จะป้องกัน `NullReferenceException`. + +### บาร์โค้ดของฉันถูกหมุนหรือเอียง—รีดเดอร์จะทำงานต่อหรือไม่? + +Aspose.BarCode มีการชดเชยการหมุนและบิดเบือนในตัว หากบาร์โค้ดมีความกว้างอย่างน้อย 30 % ของความกว้างภาพ ตัวถอดรหัสมักจะสำเร็จ สำหรับกรณีสุดโต่งคุณสามารถเปิด `reader.Options.AllowInvertedBarcodes = true;` ก่อนเรียก `ReadBarCodes()`. + +### ฉันจะจัดการกับชุดภาพจำนวนมากอย่างไร? + +ห่อหุ้มตรรกะการอ่านในลูป `foreach (var file in Directory.GetFiles(folder, "*.png"))`. รูปแบบ `using` รับประกันว่าทรัพยากรเนทีฟของแต่ละภาพจะถูกปล่อยก่อนการวนรอบถัดไป, ทำให้การใช้หน่วยความจำน้อยลง. + +## รายการซอร์สโค้ดเต็ม (พร้อมคัดลอก‑วาง) + +ด้านล่างเป็นโปรแกรมทั้งหมดในบล็อกเดียวเพื่อคัดลอก‑วางอย่างรวดเร็ว ไม่ต้องพึ่งพาไลบรารีเพิ่มเติม—เพียงแพคเกจ NuGet ของ Aspose.BarCode. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## สรุป – สิ่งที่เราได้เรียนรู้ + +* **How to read PDF417** ด้วย Aspose.BarCode ใน C#. +* ขั้นตอนที่แน่นอนเพื่อ **read multiple barcodes** จากภาพเดียว. +* วิธี **read barcode image C#** และดึงข้อมูล Macro‑PDF417 ทุกฟิลด์. +* เคล็ดลับสำหรับการหมุน, การประมวลผลเป็นชุด, และการจัดการข้อมูลขยายที่หายไป. + +## ขั้นตอนต่อไป & หัวข้อที่เกี่ยวข้อง + +* **Encode PDF417** – สร้างบาร์โค้ด Macro‑PDF417 ของคุณเองด้วย `BarCodeBuilder`. +* **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – ใช้คลาส `BarCodeReader` เดียวกัน. +* **Integrate with ASP.NET Core** – เปิดเผย endpoint เว็บที่รับภาพอัปโหลดและคืนค่า JSON พร้อมฟิลด์ที่ถอดรหัส. + +อย่าลังเลที่จะทดลอง: เปลี่ยนเส้นทางภาพ, ใส่ PDF417 ธรรมดาในโฟลเดอร์เดียวกัน, หรือปรับค่า `DecodeType` เพื่อดูว่าไลบรารีทำงานอย่างไร ยิ่งคุณลองมากเท่าไหร่ คุณก็จะยิ่งคุ้นเคยกับสถานการณ์ **read barcode image C#** มากขึ้น. + +มีภาพที่ยากต่อการถอดรหัสหรือไม่? แสดงความคิดเห็นด้านล่างหรือเปิด issue ในรีโพ GitHub ของโปรเจกต์ตัวอย่าง ขอให้สนุกกับการเขียนโค้ด! + +## สิ่งที่คุณควรเรียนต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดซึ่งต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานครบถ้วนพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ 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/thai/net/one-dimensional-barcode-types/_index.md b/barcode/thai/net/one-dimensional-barcode-types/_index.md index dcd2c96bb..ba61a751c 100644 --- a/barcode/thai/net/one-dimensional-barcode-types/_index.md +++ b/barcode/thai/net/one-dimensional-barcode-types/_index.md @@ -24,7 +24,7 @@ url: /th/net/one-dimensional-barcode-types/ ## การกำหนดค่ารหัส 128 - ก่อนอื่นมาดำดิ่งกันก่อน**Code 128**บาร์โค้ดประเภทอเนกประสงค์นี้สามารถเข้ารหัสข้อมูลได้หลากหลาย ทำให้เป็นบาร์โค้ดยอดนิยมในหมู่นักพัฒนา ด้วย Aspose.BarCode คุณจะพบกับกระบวนการบูรณาการที่ราบรื่น ทำตามคำแนะนำทีละขั้นตอนของเราเพื่อเริ่มต้น + ก่อนแรกมาดำดิ่งกันก่อน**Code 128**บาร์โค้ดประเภทอเนกประสงค์นี้สามารถเข้ารหัสข้อมูลได้หลากหลาย ทำให้เป็นบาร์โค้ดยอดนิยมในหมู่นักพัฒนา ด้วย Aspose.BarCode คุณจะพบกับกระบวนการบูรณาการที่ราบรื่น ทำตามคำแนะนำทีละขั้นตอนของเราเพื่อเริ่มต้น ## การกำหนดค่ารหัส 39 @@ -78,6 +78,8 @@ url: /th/net/one-dimensional-barcode-types/ เรียนรู้วิธีจัดการกับข้อยกเว้นในขณะที่สร้างบาร์โค้ดหนึ่งมิติโดยใช้ Aspose.BarCode สำหรับ .NET คำแนะนำทีละขั้นตอนนี้ช่วยให้มั่นใจได้ถึงโซลูชันบาร์โค้ดที่ทนทานต่อข้อผิดพลาด เริ่มตอนนี้เลย! ### [การกำหนดค่าอัตราส่วนกว้าง-แคบหนึ่งมิติ](./one-dimensional-wide-narrow-ratio-configuration/) สร้างบาร์โค้ดแบบกำหนดเองได้อย่างง่ายดายด้วย Aspose.BarCode สำหรับ .NET คำแนะนำทีละขั้นตอนสำหรับการกำหนดค่าอัตราส่วนกว้าง-แคบหนึ่งมิติ +### [สร้างบาร์โค้ดจากข้อความโดยใช้ Aspose.BarCode – คู่มือ C#](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +เรียนรู้วิธีสร้างบาร์โค้ดจากข้อความใน C# ด้วย Aspose.BarCode อย่างง่ายและรวดเร็ว ## บทสรุป @@ -89,4 +91,4 @@ url: /th/net/one-dimensional-barcode-types/ {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/thai/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..5f68406f8 --- /dev/null +++ b/barcode/thai/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-07-15 +description: สร้างบาร์โค้ดจากข้อความโดยใช้ Aspose.BarCode ใน C# เรียนรู้วิธีเปลี่ยนจำนวนคอลัมน์ + บันทึกภาพบาร์โค้ด และสร้างโซลูชันบาร์โค้ดของ Aspose อย่างรวดเร็ว. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: th +lastmod: 2026-07-15 +og_description: สร้างบาร์โค้ดจากข้อความโดยใช้ Aspose.BarCode คู่มือนี้แสดงวิธีเปลี่ยนจำนวนคอลัมน์ + บันทึกภาพบาร์โค้ด และสร้างบาร์โค้ดด้วย Aspose เพียงไม่กี่บรรทัดของโค้ด +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: สร้างบาร์โค้ดจากข้อความด้วย Aspose.BarCode – คู่มือสั้น C# +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: สร้างบาร์โค้ดจากข้อความโดยใช้ Aspose.BarCode – คู่มือ C# +url: /th/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างบาร์โค้ดจากข้อความโดยใช้ Aspose.BarCode – คู่มือ C# + +การสร้างบาร์โค้ดจากข้อความโดยใช้ Aspose.BarCode นั้นง่ายกว่าที่คิด ในบทแนะนำนี้เราจะอธิบาย **วิธีสร้างบาร์โค้ด**, ปรับการจัดวางคอลัมน์, และสุดท้าย **บันทึกภาพบาร์โค้ด** เป็นไฟล์ PNG ไม่ว่าคุณจะกำลังสร้างระบบตั๋ว, เครื่องพิมพ์ป้ายคลังสินค้า, หรือแค่ทดลองใช้โค้ดสไตล์ QR ขั้นตอนต่อไปนี้จะช่วยให้คุณทำได้อย่างรวดเร็ว + +## สิ่งที่คุณจะได้เรียนรู้ + +- สร้างบาร์โค้ดจากสตริง Unicode ใดก็ได้ (ใช่, แม้แต่ “Åspóse.Barcóde©” ก็ทำงาน) +- ปรับ **จำนวนคอลัมน์** สำหรับ MicroPdf417 เพื่อให้เหมาะกับป้ายแคบหรือกว้าง +- เก็บผลลัพธ์ลงดิสก์ด้วยรูปแบบภาพที่เหมาะสม +- เคล็ดลับการจัดการอักขระพิเศษและข้อผิดพลาดทั่วไปเมื่อ **สร้างบาร์โค้ด Aspose** + +ไม่มีเครื่องมือภายนอก, ไม่มีการแฮ็กผ่านคอมมานด์ไลน์—แค่ C# ธรรมดาและไลบรารี Aspose.BarCode + +## ข้อกำหนดเบื้องต้น + +ก่อนที่เราจะเริ่ม, ตรวจสอบให้แน่ใจว่าคุณมี: + +1. **.NET 6.0** หรือใหม่กว่า (โค้ดนี้ทำงานบน .NET Framework 4.7+ ด้วย) +2. **ลิขสิทธิ์** ของ Aspose.BarCode, หรือคุณสามารถเริ่มต้นด้วยรุ่นทดลองฟรี +3. โฟลเดอร์ที่สามารถเขียนได้ – เราจะเรียกมันว่า `YOUR_DIRECTORY` ในตัวอย่าง + +หากคุณขาดอย่างใดอย่างหนึ่ง, ให้ดาวน์โหลดแพ็กเกจ NuGet ตอนนี้: + +```bash +dotnet add package Aspose.BarCode +``` + +เท่านี้—ไม่ต้องคัดลอก DLL เพิ่มเติมด้วยตนเอง + +## ขั้นตอนที่ 1 – ตั้งค่าโปรเจกต์และนำเข้า + +แรกเริ่มให้สร้างแอปคอนโซล (หรือวางโค้ดนี้ลงในโปรเจกต์ C# ใดก็ได้) ส่วนสำคัญคือการนำเข้า namespace ที่ถูกต้อง: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +ทำไมต้องใช้ `using` เหล่านี้? `BarcodeGenerator` อยู่ใน `Aspose.BarCode.Generation` ส่วน enum `BarCodeImageFormat` อยู่ใน `Aspose.BarCode` การจัดการ import ให้เป็นระเบียบทำให้โค้ดต่อมาดูเหมือนภาษาอังกฤษธรรมดา + +## ขั้นตอนที่ 2 – สร้าง Barcode Generator (วิธีสร้างบาร์โค้ด) + +ตอนนี้เราจะ **สร้างบาร์โค้ดจากข้อความ** จริง ๆ enum `EncodeTypes` บอก Aspose ว่าจะใช้ symbology ใด; เราเลือก `MicroPdf417` เพราะมันจัดการสตริงยาวในกริดที่กะทัดรัด + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +สังเกตว่าข้อความมีอักขระที่มีเครื่องหมายสำเนียงและสัญลักษณ์ลิขสิทธิ์ Aspose.BarCode จะเข้ารหัส Unicode อัตโนมัติ ไม่ต้องทำการประมวลผลล่วงหน้า + +## ขั้นตอนที่ 3 – ปรับแต่งลักษณะ (วิธีเปลี่ยนจำนวนคอลัมน์) + +MicroPdf417 ให้คุณควบคุมจำนวนคอลัมน์ ซึ่งส่งผลโดยตรงต่อความกว้างของบาร์โค้ด การจัดวางที่กระชับเหมาะกับป้ายแคบ; การจัดวางที่กว้างขึ้นช่วยให้อ่านง่ายบนการพิมพ์ขนาดใหญ่ + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +ทำไมต้องใช้โมดูล 2 พิกเซล? เพราะให้ภาพคมชัดโดยไม่ทำให้ไฟล์ใหญ่เกินไป คุณสามารถทดลองค่า 1‑4 ได้ตามต้องการ หากต้องการจำนวนคอลัมน์อื่น เพียงเปลี่ยน property `Columns`; Aspose จะคำนวณ layout ใหม่อัตโนมัติ + +## ขั้นตอนที่ 4 – บันทึกภาพบาร์โค้ด (บันทึกภาพบาร์โค้ด) + +เมื่อกำหนดค่า generator เรียบร้อยแล้ว เราพร้อม **บันทึกภาพบาร์โค้ด** เมธอด `Save` รับพาธไฟล์และ enum รูปแบบภาพ PNG เป็น loss‑less ทำให้บาร์โค้ดคมชัดแม้หลังจากสเกล + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +เคล็ดลับสั้น: ใช้พาธแบบ absolute หรือให้แน่ใจว่า working directory เป็นที่ที่คุณคาดหวัง; มิฉะนั้นไฟล์อาจถูกสร้างในโฟลเดอร์ bin และคุณอาจไม่พบไฟล์นั้น + +## ตัวอย่างทำงานเต็มรูปแบบ + +รวมทุกขั้นตอนเข้าด้วยกัน นี่คือโปรแกรมที่พร้อมคัดลอก‑วางลงใน `Program.cs` แล้วรันได้: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**ผลลัพธ์ที่คาดหวัง** (คอนโซล): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +และถ้าคุณเปิด `MicroPdf417.png` คุณจะเห็นบาร์โค้ด MicroPdf417 ที่คมชัดซึ่งเข้ารหัสสตริงเดิมพร้อมอักขระพิเศษที่ใส่เข้าไป + +## คำถามทั่วไป & กรณีขอบ + +### ถ้าข้อความของฉันยาวเกินความจุเริ่มต้นจะทำอย่างไร? + +MicroPdf417 จะสลับไปใช้ layout แบบหลายแถวอัตโนมัติเมื่อข้อมูลเกินจำนวนสูงสุดต่อแถว คุณยังคงควบคุมจำนวนคอลัมน์ได้, แต่ไลบรารีอาจเพิ่มแถวเพิ่มเติมโดยอัตโนมัติ ไม่ต้องเขียนโค้ดเพิ่ม—แค่ตรวจสอบขนาดภาพที่ได้ + +### จะเปลี่ยนรูปแบบภาพเป็น JPEG หรือ BMP ได้อย่างไร? + +เปลี่ยน `BarCodeImageFormat.Png` เป็น `BarCodeImageFormat.Jpeg` (หรือ `Bmp`) โปรดจำว่า JPEG มีการบีบอัดซึ่งอาจทำให้เกิด artefacts ส่งผลต่อความแม่นยำของการสแกน PNG ยังคงเป็นค่าเริ่มต้นที่ปลอดภัยที่สุด + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### ฉันเห็นลายน้ำในผลลัพธ์ มีอะไรผิดหรือไม่? + +นั่นคือเวอร์ชันทดลองของ Aspose.BarCode เพื่อ **สร้างบาร์โค้ด Aspose** โดยไม่มีลายน้ำ ให้โหลดไฟล์ลิขสิทธิ์ที่ถูกต้องตามที่แสดงในบรรทัดคอมเมนต์ของขั้นตอน 2 + +### ฉันสามารถสร้าง symbology อื่นได้หรือไม่ (QR, Code128, ฯลฯ)? + +ได้เลย เพียงเปลี่ยน `EncodeTypes.MicroPdf417` เป็นค่าอื่นจาก enum `EncodeTypes` เช่น `EncodeTypes.QR` หรือ `EncodeTypes.Code128` ส่วนโค้ดที่เหลือไม่ต้องเปลี่ยน ทำให้วิธีนี้นำกลับมาใช้ใหม่ได้ง่าย + +## เคล็ดลับระดับมืออาชีพสำหรับการสร้างบาร์โค้ดในสภาพการผลิต + +- **แคช generator** หากต้องสร้างบาร์โค้ดหลายรายการด้วยการตั้งค่าเดียวกัน; จะลดภาระการสร้างอ็อบเจกต์ +- **ตรวจสอบความถูกต้องของสตริง** ตามข้อจำกัดความยาวของ symbology ที่เลือก (Aspose จะโยน `ArgumentException` หากยาวเกิน) +- **ใช้ `using`** หรือเรียก `Dispose` กับ generator เมื่อเสร็จ เพื่อปลดปล่อยทรัพยากร native ทันที +- **ตั้งค่า DPI** ผ่าน `generator.Parameters.ImageResolution.DpiX/DpiY` หากต้องการพิมพ์ความละเอียดสูงสำหรับป้ายขนาดใหญ่ + +## สรุป + +ตอนนี้คุณรู้ **วิธีสร้างบาร์โค้ดจากข้อความ** ด้วย Aspose.BarCode, **วิธีเปลี่ยนจำนวนคอลัมน์**, และ **วิธีบันทึกภาพบาร์โค้ด** เป็น PNG ตัวอย่างเต็มที่ทำงานได้แสดงให้เห็นโค้ดที่สะอาดและพร้อมใช้งานในสภาพการผลิต + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคในคู่มือนี้ แต่ละแหล่งรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอน‑ต่อ‑ขั้นตอน เพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการทำงานทางเลือกในโปรเจกต์ของคุณเอง + +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Generate barcode image – Code 93 with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/turkish/net/compact-pdf417-encoding/_index.md index ea67f016b..dfce39db5 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. +### [C#'ta PDF417 Barkod Meta Verisi Oluşturma – Tam Adım‑Adım Kılavuz](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +C# ile PDF417 barkoduna meta veri eklemeyi adım adım öğrenin. + +### [C#'ta PDF417 Barkod Oluşturma – Tam Kılavuz](./generate-pdf417-barcode-in-c-complete-guide/) +C# ile PDF417 barkodunu baştan sona oluşturmayı adım adım öğrenin. + +### [C#'ta PDF417 Barkod Oluşturma – Tam Adım‑Adım Kılavuz](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +C# kullanarak PDF417 barkodunu sıfırdan oluşturmayı ayrıntılı adımlarla öğrenin. + +### [C#'ta PDF417 Okuma – Tam Adım‑Adım Kılavuz](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) +C# kullanarak PDF417 barkodlarını okuma sürecini adım adım öğrenin. + ## 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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/turkish/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..08e3d496a --- /dev/null +++ b/barcode/turkish/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-07-15 +description: Aspose.BarCode kullanarak C#'de PDF417 barkod meta verilerini oluşturun. + Macro PDF417 ayarlarını öğrenin, PNG olarak kaydedin ve Unicode metni işleyin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: tr +lastmod: 2026-07-15 +og_description: Aspose.BarCode ile C#'ta PDF417 barkod meta verilerini oluşturun. + Bu kılavuz, dosya kimliği, zaman damgaları ve daha fazlasını eklemek için ihtiyacınız + olan tüm ayarları gösterir. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: C#'ta PDF417 Barkod Meta Verilerini Oluşturma – Tam Programlama Rehberi +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: C#'ta PDF417 Barkod Metaverisini Oluşturma – Tam Adım Adım Rehber +url: /tr/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta PDF417 Barkod Metaverisini Oluşturma – Tam Adım‑Adım Kılavuz + +C#'ta **PDF417 barkod metaverisini oluşturmanız** gerektiğinde, hangi özellikleri ayarlamanız gerektiğinden emin olmadınız mı? Tek başınıza değilsiniz—geliştiriciler genellikle dosya kimlikleri, segment sayıları veya özel zaman damgaları gibi özellikler gerektiğinde takılıp kalıyor. + +İyi haber şu ki Aspose.BarCode bunu çocuk oyuncağı haline getiriyor. Bu öğreticide **Macro PDF417** için bir `BarcodeGenerator` oluşturacağız, tüm önemli metaverileri ekleyeceğiz ve sonucu PNG görüntüsü olarak kaydedeceğiz. Sonunda, herhangi bir tedarik zinciri ya da belge yönetim sistemi için hazır, tam özellikli bir barkodunuz olacak. + +## Bu Kılavuzda Neler Ele Alınıyor + +1. Aspose.BarCode NuGet paketini kurma. +2. **Macro PDF417** için bir `BarcodeGenerator` başlatma. +3. Her faydalı **barkod metaveri alanını** doldurma (dosya kimliği, segment kimliği, kontrol toplamı vb.). +4. Barkodu diske kaydetme ve çıktıyı doğrulama. + +Macro PDF417 hakkında önceden deneyim gerekmez—sadece temel C# bilgisi ve güncel bir .NET çalışma zamanı yeterlidir. + +Neden umursamalısınız? Zengin metaveriyi doğrudan bir barkoda gömmek, alttaki tarayıcıların bütün dosya transferlerini doğrulamasını, eksik segmentleri tespit etmesini veya otomatik iş akışlarını tetiklemesini sağlar. Başka bir deyişle, ayrı bir veritabanı sorgulamasına gerek kalmadan **güçlü, kendini tanımlayan veri** elde edersiniz. + +## Önkoşullar + +- .NET 6.0 veya daha yenisi (kod .NET Framework 4.7+ üzerinde de çalışır). +- Visual Studio 2022 (veya tercih ettiğiniz herhangi bir IDE). +- **Aspose.BarCode for .NET** NuGet paketi (ücretsiz deneme mevcut). + +Paketi aşağıdaki komutla kurabilirsiniz: + +```bash +dotnet add package Aspose.BarCode +``` + +Artık temel hazırlıklar tamam, gerçek uygulamaya dalalım. + +## Adım 1: Macro PDF417 için BarcodeGenerator'ı Başlatma + +İlk olarak **Macro PDF417** için yapılandırılmış bir `BarcodeGenerator` örneğine ihtiyacımız var. Bu, Aspose.BarCode'a hangi kodlama algoritmasını kullanacağını söyler ve insan‑okunur metni besleyebileceğimiz bir yer sağlar. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Neden önemli:** `EncodeTypes.MacroPdf417` genişletilmiş PDF417 modunu etkinleştirir; bu mod dosya kimlikleri ve segment numaraları gibi metaverileri destekler. Örnek metin Unicode karakterleri (`Å`, `ó`, `©`) içerir ve jeneratörün ASCII dışı girdileri sorunsuz işlediğini gösterir. + +## Adım 2: Temel Barkod Görünümünü Tanımlama + +Metaveri eklemeye başlamadan önce barkodun mikroskobik bir nokta olmaması için birkaç görsel parametre ayarlamalıyız. `XDimension` modül genişliğini kontrol eder, `Columns` ise genel şekli etkiler. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **İpucu:** `2` piksel genişlik ekran görüntüsü ve çoğu yazıcı için iyidir. Daha yüksek çözünürlüklü bir baskı gerekiyorsa `3` veya `4` olarak artırabilirsiniz. + +## Adım 3: Macro PDF417 Metaveri Alanlarını Doldurma + +Şimdi öğretinin kalbi geliyor—**barkod metaveri alanlarını** ekleme. Her özellik Macro PDF417 spesifikasyonunun bir segmentine doğrudan karşılık gelir. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Her Özelliğin Ne İşe Yaradığı + +| Özellik | Amaç | Tipik Değer | +|----------|------|-------------| +| **MacroPdf417FileID** | Tüm dosya seti için evrensel benzersiz tanımlayıcı. | `12345678` | +| **MacroPdf417SegmentID** | Mevcut segmentin indeksi (`0`'dan başlar). | `12` | +| **MacroPdf417SegmentsCount** | Dosya için beklenen toplam segment sayısı. | `20` | +| **MacroPdf417FileName** | İnsan tarafından okunabilir ad, genellikle orijinal dosya adı. | `"file01"` | +| **MacroPdf417Checksum** | Hata tespiti için 16‑bit CCITT kontrol toplamı. | `1234` | +| **MacroPdf417FileSize** | Orijinal dosyanın bayt cinsinden boyutu. | `400000` | +| **MacroPdf417TimeStamp** | Dosyanın oluşturulma zamanı. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Alıcıyı gösteren isteğe bağlı alan. | `"street"` | +| **MacroPdf417Sender** | Kaynak sistemi gösteren isteğe bağlı alan. | `"aspose"` | +| **MacroPdf417Terminator** | Tarayıcıya bu segmentin son olduğunu belirten bayrak. | `Pdf417MacroTerminator.Set` | + +> **Neden ihtiyacınız var:** Macro PDF417'yi anlayan tarayıcılar çok‑segmentli bir dosyayı yeniden birleştirebilir, kontrol toplamı ile bütünlüğü doğrulayabilir ve zaman damgasına göre eski verileri reddedebilir. Böylece ayrı bir manifest dosyasına gerek kalmaz. + +## Adım 4: Barkod Görüntüsünü Kaydetme + +Tüm parametreler ayarlandığında sadece `Save` metodunu çağırmamız yeterli. Örnek, belirttiğiniz bir klasöre PNG dosyası yazar. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Köşe durumu:** Barkodu daha sonra bir PDF'ye gömmeyi planlıyorsanız `BarCodeImageFormat.Jpeg` ya da `Pdf` tercih edebilirsiniz. PNG kayıpsız detay korur; doğrulama için kullanışlıdır. + +## Tam Çalışan Örnek + +Her şeyi bir araya getirdiğimizde, konsol uygulamasına kopyalayıp yapıştırabileceğiniz tam program aşağıdadır: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Beklenen Çıktı + +Program çalıştırıldığında çalıştırılabilir dosyanın klasöründe **ExtPDF417Meta.png** adlı bir dosya oluşur. Herhangi bir görüntüleyiciyle açtığınızda yoğun, yüksek kontrastlı bir PDF417 barkodu görürsünüz. Macro PDF417 destekli bir barkod okuyucu ile taradığınızda, ayarladığımız metaveri değerleri geri döner—dosya kimliği `12345678`, segment `12` / `20` vb. + +## Yaygın Sorular ve Tuzaklar + +- **Barkod bulanık çıkarsa ne yapmalı?** `XDimension.Pixels` değerini artırın veya daha yüksek çözünürlüklü bir görüntü formatına geçin. +- **Her metaveri alanını ayarlamam gerekiyor mu?** Hayır. Yalnızca aşağı akış sisteminizin gerektirdiği alanlar zorunludur. Kullanılmayan alanlar varsayılan değerlerinde kalabilir. +- **Çok‑segmentli bir dosyayı otomatik olarak oluşturabilir miyim?** Evet—veri üzerinde döngü kurarak `MacroPdf417SegmentID` değerini artırın ve her segment için ayrı bir barkod oluşturun. `MacroPdf417FileID` değerinin tüm segmentlerde tutarlı kalmasına dikkat edin. +- **Unicode destekleniyor mu?** Kesinlikle. Örnek metin `Å`, `ó` ve `©` karakterlerini içeriyor ve Aspose.BarCode'un UTF‑8'i kutudan çıkar çıkmaz işlediğini gösteriyor. + +## Sonraki Adımlar: Temelin Ötesine Geçmek + +Artık **PDF417 barkod metaverisini oluşturmayı** bildiğinize göre aşağıdaki konuları keşfedebilirsiniz: + +- **Barkodları PDF'lere gömme** `Aspose.Pdf` kullanarak uçtan uca belge oluşturma. +- **Metaveriyi geri okuma** `BarcodeReader` ile taramaları programlı olarak doğrulama. +- **Renkleri özelleştirme** (ön plan/arka plan) marka amaçları için. +- **Veritabanı entegrasyonu** `FileID` veya `Timestamp` gibi alanları otomatik doldurmak için. + +Bu konular, **macro pdf417**, **aspose barcode c#**, **barcode metadata fields** ve **c# barcode generation** gibi ikincil anahtar kelimelerimizle de bağlantılıdır; böylece öğrenmeye devam etmeniz için bolca materyal bulacaksınız. + +## Sonuç + +C#'ta **PDF417 barkod metaverisini oluşturma** sürecini adım adım gösteren, üretim ortamına hazır bir örnek sunduk. Aspose.BarCode'u kurmaktan, `BarcodeGenerator`'ı başlatmaya, ilgili **barkod metaveri alanlarını** doldurmaya ve net bir PNG kaydetmeye kadar tüm aşamalar basit bir şekilde gerçekleşir. + +Deneyin, değerleri değiştirin ve tarayıcıların tepkisini izleyin. Macro PDF417'nin esnekliği sayesinde, tek bir taranabilir görüntü içinde bir alt sistemin ihtiyaç duyduğu her şeyi gömebilirsiniz. İyi kodlamalar, barkodlarınız daima hatasız olsun! + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanarak yakından ilgili konuları kapsar. Her kaynak, adım adım açıklamalar ve tam çalışan kod örnekleri içerir; böylece API özelliklerini daha iyi kavrayabilir ve projelerinizde alternatif yaklaşımlar deneyebilirsiniz. + +- [Barkod Nasıl Oluşturulur – Aspose.BarCode ile Kompakt PDF417](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [java barkod kütüphanesi – Aspose kullanarak PDF'ye barkod ekleme](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [Bir Barkod Nasıl Oluşturulur – Aspose.BarCode ile Kompakt PDF417](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/turkish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..595459d6d --- /dev/null +++ b/barcode/turkish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: PDF417 barkodunu hızlı bir şekilde oluşturun ve C#'ta kompakt bir PDF417 + barkod görüntüsü için sütunları nasıl ayarlayacağınızı öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: tr +lastmod: 2026-07-15 +og_description: Aspose.BarCode ile PDF417 barkod oluşturun ve sıkışık bir PDF417 barkod + görüntüsü oluşturmak için sütunları nasıl ayarlayacağınızı öğrenin. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: C#'ta PDF417 Barkod Oluşturma – Adım Adım Rehber +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: C#'te PDF417 Barkod Oluşturma – Tam Rehber +url: /tr/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#’ta PDF417 Barkod Oluşturma – Tam Kılavuz + +Hiç .NET projesinde **PDF417 barkod oluşturma** ihtiyacı duydunuz ama nereden başlayacağınızı bilemediniz mi? Yalnız değilsiniz. Birçok kurumsal uygulamada—örneğin biniş kartı yazıcıları, envanter etiketleri veya mobil biletleme—PDF417, çok fazla veriyi küçük bir görsel alana sığdıran iş gücüdür. + +Şöyle ki: Aspose.BarCode kütüphanesi tüm süreci neredeyse ağrısız hâle getiriyor ve **sütunların nasıl ayarlanacağını** kontrol edebiliyorsunuz, böylece barkod mümkün olduğunca kompakt oluyor. Bu öğreticinin sonunda, **PDF417 barkod görüntüsü** olarak kullanıma hazır bir PNG dosyanız olacak; bunu herhangi bir UI, e‑posta ya da baskı işine ekleyebileceksiniz. + +## Öğrenecekleriniz + +- PDF417 barkod üreten tam işlevsel bir C# konsol uygulaması. +- *X‑Dimension* (modül boyutu) nedir ve neden önemli olduğu. +- **Sütunların nasıl ayarlanacağını** adım adım açıklayan talimatlar. +- Sonucu anında doğrulamak için kaydedilmiş bir `PNG` dosyası. +- Yaygın hatalar (ör. okunamayan barkodlar, yanlış görüntü formatı) için ipuçları. + +> **Önkoşullar** – .NET 6+ SDK, Visual Studio 2022 (ya da tercih ettiğiniz herhangi bir editör) ve `Aspose.BarCode` NuGet referansı. Başka bir şey gerekmez. + +--- + +## Adım 1: Aspose.BarCode NuGet Paketini Yükleyin + +PDF417 barkod **oluşturmak** için kütüphanenin projede bulunması gerekir. + +```bash +dotnet add package Aspose.BarCode +``` + +Bu tek satır, `BarcodeGenerator`, `EncodeTypes` ve `BarCodeImageFormat` enum’u gibi ihtiyacınız olacak tüm tipleri projeye ekler. + +> **Pro ipucu:** .NET Framework hedefliyorsanız, Package Manager Console içinde klasik `Install-Package Aspose.BarCode` PowerShell komutunu kullanın. + +--- + +## Adım 2: Minimal Bir Konsol Uygulaması Oluşturun + +Sadece bir barkod üreten ufak bir program oluşturalım. Yeni bir klasör açın, `dotnet new console` komutunu çalıştırın ve otomatik oluşturulan `Program.cs` dosyasını aşağıdaki kodla değiştirin. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Neden önemli:** +- `EncodeTypes.Pdf417` kütüphaneye PDF417 barkod istediğimizi söyler, QR ya da Code128 değil. +- `XDimension.Pixels` her bir küçük siyah ya da beyaz modülün çözünürlüğünü kontrol eder. +- **Sütunların nasıl ayarlanacağını** belirten blok, **PDF417 barkod görüntüsü**nün şeklini doğrudan etkiler. +- `Truncate = true` gereksiz boş satırları atar ve birçok tarayıcının sevdiği “kompakt” görünümü verir. + +--- + +## Adım 3: Daha Derine İnmek – Sütunları ve Kısaltmayı Anlamak + +### Sütunların Nasıl Ayarlanacağını + +PDF417, veriyi *satır* × *sütun* matrisinde düzenler. Kütüphane varsayılan olarak 5 sütun kullanır; bu çoğu senaryoda işe yarar. Ancak bir etikete sığdırmak için daha dar ya da tarama güvenilirliğini artırmak için daha geniş bir barkod gerekebilir. Kullanılacak özellik: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +**1** ile **30** arasında değer alır (tam sınır veri uzunluğuna bağlıdır). İşte hızlı bir özet: + +| Sütunlar | Yaklaşık Genişlik (mm) | Ne Zaman Kullanılır | +|----------|-----------------------|----------------------| +| 1‑3 | Çok dar | Küçük etiket, sınırlı alan | +| 4‑6 | Standart | Çoğu fiş, bilet | +| 7‑10 | Daha geniş | Yüksek yoğunluklu veri, daha iyi okunabilirlik | + +### Kısaltma (Compact Mode) + +`Truncate = true` ayarı, kodlayıcıya alt kısımdaki gereksiz boş satırları kesmesini söyler. Sonuç, **kompakt PDF417 barkod görüntüsü** olur; tüm veri aynı kalırken alan en aza indirilir. “Barkod etiket için çok büyük” hatası alırsanız bu bayrağı değiştirin. + +--- + +## Adım 4: Uygulamayı Çalıştırın ve Çıktıyı Doğrulayın + +Derleyin ve çalıştırın: + +```bash +dotnet run +``` + +Konsolda kaydetme konumunu belirten bir mesaj görmelisiniz. Klasöre gidin ve `CompactPdf417.png` dosyasını açın. Görüntü aşağıdaki gibi görünecek: + +![Generated PDF417 barcode image](./CompactPdf417.png "Generated PDF417 barcode image – compact PNG created by Aspose.BarCode") + +*Resim alt metni:* **Generated PDF417 barcode image** – öğretici kodu tarafından üretilen kompakt bir PNG dosyası. + +Tarayıcınız bu barkodu okuyabiliyorsa, tebrikler—başarıyla **PDF417 barkod oluşturmuş** ve düzenli bir **PDF417 barkod görüntüsü** için **sütunların nasıl ayarlanacağını** öğrenmiş oldunuz. + +--- + +## Adım 5: Yaygın Hatalar ve Çözüm Yolları + +| Semptom | Muhtemel Neden | Hızlı Çözüm | +|----------|----------------|-------------| +| Barkod bulanık görünüyor | `XDimension.Pixels` çok düşük (ör. 1) | Daha net bir görüntü için 2‑3 piksele yükseltin. | +| Tarayıcı okuyamıyor | Veri için çok fazla sütun | `Columns` değerini azaltın ya da `Truncate`’ı etkinleştirin. | +| Yanlış dosya formatı | Yanlışlıkla `BarCodeImageFormat.Jpeg` ile kaydedildi | Kayıpsız sonuçlar için `BarCodeImageFormat.Png` kullanın. | +| `ArgumentOutOfRangeException` hatası | Sütun sayısı izin verilen aralığın dışına çıktı | Sütunları 1‑30 arasında tutun ve verinin sığdığından emin olun. | + +--- + +## Adım 6: İleri Seviye – Renk Özelleştirme ve Metin Ekleme + +Barkodun marka renk paletine uymasını istiyorsanız, ön ve arka plan renklerini şu şekilde ayarlayabilirsiniz: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Ya da barkodun altına insan tarafından okunabilir bir metin ekleyin: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Bu eklemeler isteğe bağlıdır, ancak **PDF417 barkod oluşturma** iş akışının ne kadar esnek olabileceğini gösterir. + +--- + +## Sonuç + +Aspose.BarCode kullanarak **PDF417 barkod oluşturma** sürecini baştan sona gösterdik, **sütunların nasıl ayarlanacağını** açıklayarak barkod boyutlarını kontrol ettik ve sonucu net bir **PDF417 barkod görüntüsü** olarak PNG formatında kaydettik. Kod bağımsızdır, .NET 6+ ile çalışır ve mevcut projelere minimum çabayla entegre edilebilir. + +Sırada ne var? Daha büyük yükleri (ör. JSON payload) kodlamayı deneyin, farklı görüntü formatlarıyla oynayın ya da barkodları talep üzerine sunan bir web API’si oluşturun. Ufkunuz geniş, ve artık sağlam bir temele sahipsiniz. + +Keyifli kodlamalar, ve barkodlarınızın ilk denemede taranmasını dileriz! + +## Bir Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanan ve ilgili konuları derinlemesine ele alan örnekler içerir. Her kaynak, tam çalışan kod örnekleri ve adım adım açıklamalar sunar, böylece ek API özelliklerini öğrenebilir ve projelerinizde alternatif uygulama yaklaşımlarını keşfedebilirsiniz. + +- [How to Create Barcode – Compact PDF417 with Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/turkish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..e13c4ff62 --- /dev/null +++ b/barcode/turkish/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,201 @@ +--- +category: general +date: 2026-07-15 +description: C# ile PDF417 barkodunu hızlıca oluşturun. Metinden barkod üretmeyi, + barkod boyutunu ayarlamayı ve dakikalar içinde özel barkod boyutları belirlemeyi + öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: tr +lastmod: 2026-07-15 +og_description: C#'de PDF417 barkodu anında oluşturun. Bu kılavuz, metinden barkod + oluşturmayı, barkod boyutunu ayarlamayı ve özel barkod boyutları uygulamayı gösterir. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: C#'ta PDF417 Barkod Oluşturma – Tam Programlama Öğreticisi +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: C# ile PDF417 Barkod Oluşturma – Tam Adım Adım Rehber +url: /tr/net/compact-pdf417-encoding/generate-pdf417-barcode-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#'ta PDF417 Barkod Oluşturma – Tam Adım‑Adım Kılavuz + +Hiç **PDF417 barkod oluşturma** ihtiyacı duydunuz ama hangi ayarları değiştirmeniz gerektiğinden emin değildiniz? Sadece siz değilsiniz—birçok geliştirici 2‑D barkodlarla ilk kez çalıştıklarında aynı duvara çarpar. İyi haber? Birkaç C# satırıyla herhangi bir dizeyi taranabilir bir PDF417 görüntüsüne dönüştürebilir, tam boyutunu kontrol edebilir ve hatta özel bir sütun‑satır düzeni tanımlayabilirsiniz. + +Bu öğreticide, **metinden barkod oluşturma**, barkod boyutunu ayarlama ve özel barkod boyutlarını belirleme konularını popüler Aspose.BarCode kütüphanesini kullanarak adım adım inceleyeceğiz. Sonunda, herhangi bir .NET projesine ekleyebileceğiniz çalıştırmaya hazır bir örnek elde edeceksiniz. + +![Generate PDF417 barcode example](https://example.com/og-image.png "Generate PDF417 barcode example") + +## Ne Oluşturacaksınız + +- `Åspóse.Barcóde©` dizesini kodlayan bir PDF417 barkod. +- X‑dimension (her modülün piksel genişliği) üzerinde hassas kontrol. +- 4 sütun ve 9 satırdan oluşan özel bir düzen. +- Diske kaydedilen bir PNG dosyası. + +Harici hizmetler yok, sihirli değnek hileleri yok—sadece şu anda derleyebileceğiniz sade C# kodu. + +## Ön Koşullar + +- .NET 6.0 veya daha yenisi (kod .NET Framework 4.8'de de çalışır). +- Visual Studio 2022 veya C# destekleyen herhangi bir IDE. +- Aspose.BarCode for .NET (ücretsiz deneme veya lisanslı sürüm). NuGet üzerinden kurun: + +```bash +dotnet add package Aspose.BarCode +``` + +Hepsi bu—paket referans alındıktan sonra hazırsınız. + +## Adım 1 – Metin Verisiyle PDF417 Barkod Oluşturma + +İlk olarak ihtiyacımız olan, PDF417 sembolünü kullandığımızı ve kodlamak istediğimiz tam metni bilen bir `BarcodeGenerator` örneğidir. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Neden önemli:** +> `EncodeTypes.Pdf417` kütüphaneye PDF417 2‑D formatını kullanmasını söyler, ikinci argüman ise **metinden barkod oluşturma** yüküdür. Buraya gönderdiğiniz her şey barkod matrisinde saklanan veri olur. + +## Adım 2 – Barkod Boyutunu Ayarlama (X‑Dimension) + +Eğer bir fişte çok küçük görünen bir barkod bastıysanız, tarayıcının bunu kaçırmasının hayal kırıklığını biliyorsunuz. `XDimension` özelliği, tek bir modülün (en küçük siyah veya beyaz kare) piksel cinsinden genişliğini kontrol eder. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Pro ipucu:** +> 2 px değeri çoğu ekran görüntüsü senaryosu için iyidir. Yüksek çözünürlüklü baskılar için bunu 3 veya 4 px'e çıkarabilirsiniz. Ancak daha büyük X‑dimension değerlerinin toplam görüntü boyutunu artırdığını unutmayın. + +## Adım 3 – Özel Barkod Boyutlarını Ayarlama (Sütunlar ve Satırlar) + +PDF417, barkodun kaç sütun ve satır kaplayacağını belirlemenize izin verir. İşte **özel barkod boyutları** burada devreye girer. Bu değerleri değiştirmek, barkodu dar bir UI alanına sığdırmanıza veya belirli bir etiket boyutuna uymasına yardımcı olabilir. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Arka planda ne oluyor?** +> Kütüphane, kodlanmış veriyi belirtilen ızgara üzerine yeniden dağıtır. Daha az sütun daha uzun barkodlar, daha fazla satır ise daha kısa barkodlar anlamına gelir. Sayılarla oynayın ve görsel denge uygulamanız için doğru hissettiğiniz bir düzen elde edene kadar ayarlayın. + +## Adım 4 – Barkod Görüntüsünü Kaydetme + +Şimdi her şeyi yapılandırdığımıza göre, jeneratörden bir PNG dosyası yazmasını istiyoruz. PNG kayıpsızdır, bu yüzden modüllerin netliği korunur. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Programı çalıştırdığınızda, `C:\Barcodes\CustomLayout.png` konumunda yukarıdaki ekran görüntüsüne benzer bir dosya görmelisiniz. Herhangi bir PDF417‑uyumlu okuyucu ile tarandığında, orijinal `Åspóse.Barcóde©` dizesi dönecektir. + +## Tam Çalışan Örnek + +Aşağıda, bir konsol uygulamasına kopyalayıp yapıştırabileceğiniz tam program yer alıyor. Üretim kodunda bekleyeceğiniz tüm using yönergeleri ve hata yönetimini içerir. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Beklenen Çıktı + +Kodu çalıştırdığınızda şu çıktı verir: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…ve herhangi bir görüntüleyicide açılabilecek bir PNG oluşturur. Mobil bir uygulama (ör. iOS/Android'de “Barcode Scanner”) ile taradığınızda, çözülen metin tam olarak **Åspóse.Barcóde©** olmalıdır. + +## Sık Sorulan Sorular & Kenar Durumları + +| Soru | Cevap | +|------|-------| +| **Farklı bir görüntü formatı kullanabilir miyim?** | Evet—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` veya `Svg` hepsi desteklenir. Sadece `Save` metodunun ikinci argümanını değiştirin. | +| **Metnim Unicode karakterler içeriyorsa ne olur?** | Aspose.BarCode tam olarak UTF‑8'i destekler, bu yüzden `Å` ve `©` içeren örnek sorunsuz çalışır. | +| **Hata düzeltme seviyesini nasıl değiştiririm?** | `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` kullanın (seviyeler 0‑8). Daha yüksek seviyeler daha fazla yedeklilik ekler ama aynı zamanda boyutu da artırır. | +| **Şeffaf arka plan gerekiyor—bunu yapabilir miyim?** | Kaydetmeden önce `generator.Parameters.Barcode.Image.TransparentBackground = true;` ayarlayın. | +| **Barkodu doğrudan bir PDF'e gömmenin bir yolu var mı?** | Kesinlikle. `Save` çağrısını `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` ile değiştirin ve barkodu içeren tek sayfalık bir PDF elde edersiniz. | + +## Sonuç + +Artık herhangi bir dizeden C#'ta **PDF417 barkod oluşturma**, **barkod boyutunu ayarlama** ve **özel barkod boyutlarını** uygulayarak düzen ihtiyaçlarınıza uydurmayı biliyorsunuz. Dört adımlı akış—başlatma, boyutlandırma, düzen, kaydetme—çoğu 2‑D barkod senaryosu için temel iş akışını kapsar. + +Sırada ne var? `EncodeTypes.Pdf417` yerine `EncodeTypes.QR` ya da `EncodeTypes.Code128` deneyerek API'nin nasıl uyum sağladığını görün. Farklı `XDimension` değerleriyle deneyler yapın, sütun/satır matrisini oynayın veya görüntüyü bir PDF raporuna gömün. Olanaklar neredeyse sınırsızdır ve artık üzerine inşa edebileceğiniz sağlam bir temele sahipsiniz. + +Daha fazla sorunuz mu var, ya da PDF417 ile oynarken akıllı bir püf noktası mı keşfettiniz? Aşağıya bir yorum bırakın—sohbeti sürdürelim. Kodlamanın tadını çıkarı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 kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak adım adım açıklamalı tam çalışan kod örnekleri içerir. + +- [Aspose.BarCode for .NET kullanarak özel en‑boy oranı ile Aztec barkod oluşturma](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Barkod Oluşturma - Tek Boyutlu Barkod Türleri](/barcode/english/net/one-dimensional-barcode-types/) +- [DataMatrix Barkod Oluşturma – Aspose.BarCode ile Profesyonel Kılavuz](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/turkish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..8bded4215 --- /dev/null +++ b/barcode/turkish/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,314 @@ +--- +category: general +date: 2026-07-15 +description: C#'ta PDF417 barkodunu nasıl okursunuz ve bir görüntüden birden fazla + barkodu nasıl okursunuz. Detaylı kod ve ipuçlarıyla C#'ta barkod görüntüsü okumayı + öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: tr +lastmod: 2026-07-15 +og_description: C#'ta PDF417 barkodunu hızlı bir şekilde nasıl okuyabilirsiniz. Bu + kılavuz, tek bir görüntüden birden fazla barkodu nasıl okuyacağınızı ve her bir + özelliği nasıl çözeceğinizi gösterir. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: C#'ta PDF417 Nasıl Okunur – Tam Kod Örneği ve Açıklama +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: C#'ta PDF417 Nasıl Okunur – Tam Adım Adım Kılavuz +url: /tr/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF417'yi C#'ta Nasıl Okuyabilirsiniz – Tam Adım‑Adım Kılavuz + +C# kullanarak bir görüntüden **PDF417'yi nasıl okuyacağınızı** hiç merak ettiniz mi? Tek başınıza değilsiniz. Çoğu geliştirici, taranmış bir belgeden genişletilmiş Macro‑PDF417 alanlarını çıkarmaya çalışırken bir duvara çarpar. İyi haber? Sadece birkaç satır kodla bir PDF417'yi çözebilir, aynı resimde birden fazla barkodu okuyabilir ve spesifikasyonun sunduğu tüm gizli özellikleri yakalayabilirsiniz. + +Bu öğreticide, **PDF417'yi nasıl okuyacağınızı** gösteren gerçek bir örnek üzerinden ilerleyecek, tek bir dosyadan **birden fazla barkodu nasıl okuyacağınızı** ve **read barcode image C#** kodunun neden böyle göründüğünü açıklayacağız. Sonunda, ihtiyacınız olabilecek her bilgiyi—dosya kimliği, segment kimliği, kontrol toplamı, zaman damgaları vb.—yazdıran çalıştırmaya hazır bir konsol uygulamanız olacak. + +## Önkoşullar + +* .NET 6.0 SDK veya daha yenisi (kod .NET Core ve .NET Framework ile de çalışır). +* Visual Studio 2022 (veya tercih ettiğiniz herhangi bir editör). +* **Aspose.BarCode for .NET** NuGet paketi – bu, PDF417'yi gerçekten ayrıştıran kütüphanedir. +* Macro‑PDF417 barkodu içeren bir örnek görüntü (örneğin `ExtPDF417Meta.png`). + +Ek bir yapılandırma gerekmez; kütüphane ihtiyacınız olan tüm çözücüleri içerir. + +## Adım 1: Aspose.BarCode'u Yükleyin + +Proje klasörünüzü bir terminalde açın ve şu komutu çalıştırın: + +```bash +dotnet add package Aspose.BarCode +``` + +Bu komut en son kararlı sürümü çeker (Temmuz 2026 itibarıyla 23.12). Visual Studio içindeki Package Manager Console'u tercih ediyorsanız, şu komutu kullanın: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Pro ipucu:** `.csproj` dosyanızda sürümü (`23.12.0`) kilitleyerek ileride oluşabilecek istenmeyen kırılma değişikliklerinden kaçının. + +## Adım 2: Bir Konsol Uygulaması Taslağı Oluşturun + +Henüz bir tane yoksa yeni bir konsol projesi oluşturun: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Otomatik oluşturulan `Program.cs` dosyasını aşağıdaki kodla değiştirin. Her bloğu sonraki bölümlerde açıklayacağız. + +## Adım 3: Tam “PDF417'yi Nasıl Okuyacağız” Kodunu Yazın + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Bu Kod Neden Çalışıyor + +* **`BarCodeReader`** görüntüyü akıtan, barkodları algılayan ve `BarCodeResult` nesnelerinden oluşan bir koleksiyon döndüren temel sınıftır. +* **`DecodeType.MacroPdf417`** geçmek, kütüphaneye Macro‑PDF417'yi özel olarak ele almasını söyler; yine de düz PDF417 sembollerini döndürür, bu da **read multiple barcodes** gereksinimini karşılar. +* **`Extended.Pdf417.MacroPdf417`** nesnesi, ISO/IEC 15438 standardı tarafından tanımlanan tüm isteğe bağlı alanları tutar – burada `FileID`, `SegmentID`, `Checksum` vb. elde edersiniz. +* `using` bloğu, yerel kaynakların serbest bırakılmasını garanti eder ve uzun süre çalışan hizmetlerde bellek sızıntılarını önler. + +## Adım 4: Uygulamayı Çalıştırın ve Çıktıyı Doğrulayın + +Terminalden: + +```bash +dotnet run +``` + +Şuna benzer bir çıktı görmelisiniz: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Görüntü birden fazla barkod içeriyorsa, döngü bir ayırıcı satır (`----------------------------------------`) yazdırır ve bir sonraki sonuçla devam eder—tam olarak **read multiple barcodes**'ın pratikte nasıl göründüğüdür. + +## Yaygın Sorular ve Kenar Durumları + +### Görüntü hem Macro‑PDF417 hem de normal PDF417 sembolleri içeriyorsa ne olur? + +Aynı `BarCodeReader` çağrısı her ikisini de döndürür. `result.CodeType` (`MacroPdf417` vs `Pdf417`) kontrol ederek ayırt edebilirsiniz. Genişletilmiş özellikler, düz bir PDF417 için `null` olur, bu yüzden `if (macro != null)` kontrolü bir `NullReferenceException` oluşmasını önler. + +### Barkodum döndürülmüş veya eğik—okuyucu hâlâ çalışır mı? + +Aspose.BarCode, yerleşik döndürme ve bozulma telafisi içerir. Barkod, görüntünün genişliğinin en az %30'u kadar olduğunda, çözücü genellikle başarılı olur. Aşırı durumlar için `ReadBarCodes()` çağırmadan önce `reader.Options.AllowInvertedBarcodes = true;` özelliğini etkinleştirebilirsiniz. + +### Büyük miktarda görüntüyü nasıl işleyebilirim? + +Okuma mantığını bir `foreach (var file in Directory.GetFiles(folder, "*.png"))` döngüsü içinde sarın. `using` deseni, bir sonraki yinelemeye geçmeden önce her görüntünün yerel kaynaklarının serbest bırakılmasını sağlar ve bellek kullanımını düşük tutar. + +## Tam Kaynak Listesi (Kopyala‑Yapıştır Hazır) + +Aşağıda, hızlı kopyala‑yapıştır için tek bir blokta tüm program yer almaktadır. Gizli bağımlılık yok—sadece Aspose.BarCode NuGet paketi. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Özet – Neler Kaptık + +* **Aspose.BarCode** kullanarak C#'ta **PDF417'yi nasıl okuyacağınızı**. +* Tek bir görüntüden **birden fazla barkodu nasıl okuyacağınızı** gösteren tam adımlar. +* **read barcode image C#** kodu ile her Macro‑PDF417 alanını nasıl çıkaracağınızı. +* Döndürme, toplu işleme ve eksik genişletilmiş verileri ele alma ipuçları. + +## Sonraki Adımlar ve İlgili Konular + +* **Encode PDF417** – `BarCodeBuilder` ile kendi Macro‑PDF417 barkodlarınızı oluşturun. +* **Read other 2‑D symbologies** – aynı `BarCodeReader` sınıfını kullanarak QR, DataMatrix, Aztec okuyun. +* **Integrate with ASP.NET Core** – yüklenen bir görüntüyü kabul eden ve çözülen alanları JSON olarak dönen bir web uç noktası oluşturun. + +Denemekten çekinmeyin: görüntü yolunu değiştirin, aynı klasöre düz bir PDF417 koyun veya `DecodeType` bayraklarını ayarlayarak kütüphanenin nasıl davrandığını görün. Ne kadar çok denerseniz, **read barcode image C#** senaryolarında o kadar rahat olursunuz. + +Çözülmesi zor bir görüntünüz mü var? Aşağıya yorum bırakın veya örnek projenin GitHub deposunda bir issue açın. İyi kodlamalar! + +## 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 kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak adım adım açıklamalı tam çalışan kod örnekleri içerir. + +- [DataMatrix Barkodlarını Aspose.BarCode for .NET ile Nasıl Okuyabilirsiniz](/barcode/english/net/datamatrix-barcode-reading/) +- [Kompakt PDF417 Barkodu – Aspose.BarCode ile Nasıl Oluşturulur](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [DataMatrix Barkodu C# ile Okuma – DataMatrix Modunu (Otomatik) Oluşturma](/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/one-dimensional-barcode-types/_index.md b/barcode/turkish/net/one-dimensional-barcode-types/_index.md index e88a66604..e924dfa09 100644 --- a/barcode/turkish/net/one-dimensional-barcode-types/_index.md +++ b/barcode/turkish/net/one-dimensional-barcode-types/_index.md @@ -28,7 +28,7 @@ Tek boyutlu barkodlar, veri kodlamanın temelidir ve bilgiyi depolamanın basit ## Kod 39 Yapılandırması - Eğer üretmeniz gerekiyorsa**Code 39** barkodlar, Aspose.BarCode yanınızda. Bu barkod türü endüstriyelden sağlık hizmetlerine kadar çeşitli uygulamalarda yaygın olarak kullanılmaktadır. Geliştiriciler sorunsuz bir kurulum için adım adım kılavuzumuza güvenebilirler. + Eğer üretmeniz gerekiyorsa**Code 39** barkodlar, Aspose.BarCode yanınızda. Bu barkod türü endüstriyetten sağlık hizmetlerine kadar çeşitli uygulamalarda yaygın olarak kullanılmaktadır. Geliştiriciler sorunsuz bir kurulum için adım adım kılavuzumuza güvenebilirler. ## Kod 93 Yapılandırması @@ -78,6 +78,8 @@ Aspose.BarCode for .NET ile .NET'te barkod oluşturmayı öğrenin. Bu kapsamlı Aspose.BarCode for .NET'i kullanarak tek boyutlu barkodlar oluştururken istisnaları nasıl ele alacağınızı öğrenin. Bu adım adım kılavuz, hataya dayanıklı barkod çözümleri sağlar. Şimdi başla! ### [Tek Boyutlu Geniş-Dar Oranlı Yapılandırma](./one-dimensional-wide-narrow-ratio-configuration/) Aspose.BarCode for .NET ile özelleştirilmiş barkodları kolayca oluşturun. Tek boyutlu geniş-dar oranlı yapılandırma için adım adım kılavuz. +### [Metinden Barkod Oluşturma – Aspose.BarCode ile C# Kılavuzu](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Aspose.BarCode kullanarak C# ile metinden barkod oluşturmayı öğrenin. Adım adım kılavuzumuzla kolayca başlayın. ## Çözüm @@ -89,4 +91,4 @@ Bu makaleyle yalnızca çeşitli tek boyutlu barkod türleri hakkında bilgi edi {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/turkish/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..13b8cb5c6 --- /dev/null +++ b/barcode/turkish/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-07-15 +description: C#'ta Aspose.BarCode kullanarak metinden barkod oluşturun. Sütun sayısını + nasıl değiştireceğinizi, barkod görüntüsünü nasıl kaydedeceğinizi öğrenin ve barkod + Aspose çözümlerini hızlı bir şekilde oluşturun. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: tr +lastmod: 2026-07-15 +og_description: Aspose.BarCode kullanarak metinden barkod oluşturun. Bu kılavuz, sütun + sayısını nasıl değiştireceğinizi, barkod görüntüsünü nasıl kaydedeceğinizi ve birkaç + satır kodla Aspose barkodu nasıl oluşturacağınızı gösterir. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Aspose.BarCode ile metinden barkod oluşturma – Hızlı C# Kılavuzu +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Aspose.BarCode kullanarak metinden barkod oluşturma – C# Rehberi +url: /tr/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Metinden barkod oluşturma Aspose.BarCode – C# Kılavuzu + +Aspose.BarCode kullanarak metinden barkod oluşturmak şaşırtıcı derecede basittir. Bu öğreticide **barkod nasıl oluşturulur** adımını, sütun düzenini ayarlamayı ve sonunda **barkod görüntüsünü** PNG dosyası olarak kaydetmeyi göstereceğiz. Biletleme sistemi, depo etiket yazıcısı oluşturuyor ya da sadece QR‑stil kodlarla deneme yapıyor olun, aşağıdaki adımlar sizi hızlıca hedefe ulaştıracak. + +## Öğrenecekleriniz + +- Herhangi bir Unicode dizesinden barkod oluşturun (evet, “Åspóse.Barcóde©” bile çalışır). +- **column count** değerini MicroPdf417 için dar ya da geniş etiketlere uyacak şekilde ayarlayın. +- Sonucu uygun görüntü formatı ile diske kaydedin. +- **create barcode Aspose** çözümleri oluştururken özel karakterlerle başa çıkma ve yaygın tuzaklar için ipuçları. + +Harici araçlar yok, komut satırı hileleri yok—sadece saf C# ve Aspose.BarCode kütüphanesi. + +## Önkoşullar + +Before we dive in, make sure you have: + +1. **.NET 6.0** veya daha yeni bir sürümün yüklü olduğundan emin olun (kod .NET Framework 4.7+ üzerinde de çalışır). +2. Aspose.BarCode için bir **lisans**, ya da ücretsiz deneme sürümüyle başlayabilirsiniz. +3. Yazma izniniz olan bir klasör – örneklerde `YOUR_DIRECTORY` olarak adlandıracağız. + +Eğer bunlardan herhangi birine sahip değilseniz, hemen NuGet paketini alın: + +```bash +dotnet add package Aspose.BarCode +``` + +Hepsi bu kadar—manuel olarak kopyalamanız gereken ekstra DLL yok. + +## Adım 1 – Projeyi ve İçe Aktarmaları Ayarlama + +İlk olarak bir console uygulaması oluşturun (veya kodu herhangi bir C# projesine ekleyin). Önemli kısım doğru ad alanlarını (namespaces) eklemektir: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Bu using ifadeleri neden gerekli? `BarcodeGenerator` `Aspose.BarCode.Generation` içinde, `BarCodeImageFormat` enumu ise `Aspose.BarCode` içinde bulunur. İçe aktarmaları düzenli tutmak, sonraki kodun sade İngilizce gibi okunmasını sağlar. + +## Adım 2 – Barkod Üreteci Oluşturma (barkod nasıl oluşturulur) + +Şimdi gerçekten **metinden barkod oluşturuyoruz**. `EncodeTypes` enumu Aspose'a hangi sembolojiyi kullanacağını söyler; burada uzun dizeleri kompakt bir ızgara içinde işlediği için `MicroPdf417` seçiyoruz. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Dizgenin aksanlı karakterler ve bir telif hakkı simgesi içerdiğine dikkat edin. Aspose.BarCode Unicode'u otomatik olarak kodlar, bu yüzden metni önceden işlemek zorunda değilsiniz. + +## Adım 3 – Görünümü İnce Ayarlama (sütun sayısını nasıl değiştirirsiniz) + +MicroPdf417, sütun sayısını kontrol etmenizi sağlar; bu doğrudan barkodun genişliğini etkiler. Daha sıkı bir düzen dar etiketler için harikadır; daha geniş bir düzen büyük baskılarda okunabilirliği artırır. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Neden 2 piksel modüller? Dosya boyutunu şişirmeden net bir görüntü sağlar. Denemekten çekinmeyin—1 ile 4 arasındaki değerler genellikle iyi çalışır. Farklı bir sütun sayısına ihtiyacınız olursa, sadece `Columns` özelliğini değiştirin; Aspose düzeni otomatik olarak yeniden hesaplar. + +## Adım 4 – Barkod Görüntüsünü Kaydetme (barkod görüntüsü kaydetme) + +Üreteç yapılandırıldıktan sonra **barkod görüntüsünü kaydetmeye** hazırız. `Save` metodu bir dosya yolu ve bir görüntü formatı enumu alır. PNG kayıpsızdır, bu yüzden barkod ölçeklendirme sonrası da net kalır. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Kısa bir ipucu: her zaman mutlak bir yol kullanın ya da çalışma dizininin beklediğiniz gibi olduğundan emin olun; aksi takdirde dosya bin klasörüne düşebilir ve neden bulamadığınızı merak edebilirsiniz. + +## Tam Çalışan Örnek + +Hepsini bir araya getirerek, `Program.cs` içine kopyalayıp çalıştırabileceğiniz bağımsız bir program burada: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Beklenen çıktı** (konsol): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +Ve `MicroPdf417.png` dosyasını açtığınızda, orijinal dizgeyi, içinde beslediğimiz özel karakterlerle birlikte kodlayan net bir MicroPdf417 barkodu göreceksiniz. + +## Yaygın Sorular ve Kenar Durumları + +### Metnim varsayılan kapasiteden daha uzun olursa ne olur? + +Veri satır başına maksimumu aştığında MicroPdf417 otomatik olarak çok‑satırlı bir düzene geçer. Hâlâ sütun sayısını kontrol edebilirsiniz, ancak kütüphane arka planda ekstra satırlar ekleyebilir. Ek bir kod gerekmez—sadece ortaya çıkan görüntü boyutlarına dikkat edin. + +### Görüntü formatını JPEG veya BMP olarak nasıl değiştiririm? + +`BarCodeImageFormat.Png` yerine `BarCodeImageFormat.Jpeg` (veya `Bmp`) kullanın. JPEG sıkıştırma artefaktları ekler, bu da tarama güvenilirliğini etkileyebilir. PNG en güvenli varsayılandır. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Çıktıda bir watermark (filigran) görüyorum—ne yanlış? + +Bu, Aspose.BarCode'un değerlendirme sürümüdür. Watermark olmadan **create barcode Aspose** yapmak için, Adım 2'deki yorum satırında gösterildiği gibi geçerli bir lisans dosyası yükleyin. + +### Başka sembolojiler (QR, Code128, vb.) üretebilir miyim? + +Kesinlikle. `EncodeTypes.MicroPdf417` yerine `EncodeTypes` enumundan başka bir değer, örneğin `EncodeTypes.QR` ya da `EncodeTypes.Code128` koyun. Kodun geri kalanı aynı kalır, bu da yaklaşımı çok yeniden kullanılabilir kılar. + +## Üretim‑Hazır Barkod Oluşturma için Profesyonel İpuçları + +- **Cache the generator** aynı ayarlarla çok sayıda barkod oluşturuyorsanız; nesne oluşturma maliyetini azaltır. +- **Validate the input string** seçilen sembolojiye özgü uzunluk kısıtlamaları için (çok uzun olursa Aspose `ArgumentException` fırlatır). +- **Use `using` statements** veya işiniz bittiğinde `Dispose` ederek üreteci serbest bırakın, böylece yerel kaynaklar hızlıca temizlenir. +- **Set DPI** büyük etiketler için yüksek çözünürlüklü baskıya ihtiyacınız varsa `generator.Parameters.ImageResolution.DpiX/DpiY` ile ayarlayın. + +## Sonuç + +Artık Aspose.BarCode ile **metinden barkod nasıl oluşturulur**, **sütun sayısı nasıl değiştirilir** ve PNG olarak **barkod görüntüsü nasıl kaydedilir** konularını tam olarak biliyorsunuz. Yukarıdaki eksiksiz, çalıştırılabilir örnek temiz ve üretim‑hazır bir + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanan 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. + +- [Barkod Nasıl Oluşturulur – Code 39 Konfigürasyonu Aspose.BarCode ile](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Barkod Görüntüsü Oluşturma – Code 93 Aspose.BarCode ile](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [DataMatrix Barkodları (ECC 200) Nasıl Oluşturulur Aspose.BarCode for .NET ile](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/_index.md b/barcode/vietnamese/net/compact-pdf417-encoding/_index.md index 8c0240726..faf667b36 100644 --- a/barcode/vietnamese/net/compact-pdf417-encoding/_index.md +++ b/barcode/vietnamese/net/compact-pdf417-encoding/_index.md @@ -85,6 +85,18 @@ Ngoài các kiến thức cơ bản, dưới đây là một số mẹo thực t ### [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. +### [Tạo siêu dữ liệu mã vạch PDF417 trong C# – Hướng dẫn chi tiết từng bước](./create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/) +Hướng dẫn chi tiết cách tạo và quản lý siêu dữ liệu cho mã vạch PDF417 bằng C# với Aspose.BarCode. + +### [Tạo mã vạch PDF417 trong C# – Hướng dẫn đầy đủ](./generate-pdf417-barcode-in-c-complete-guide/) +Hướng dẫn chi tiết cách tạo mã vạch PDF417 bằng C# với Aspose.BarCode, bao gồm các bước cấu hình và ví dụ mã nguồn. + +### [Tạo mã vạch PDF417 trong C# – Hướng dẫn chi tiết từng bước](./generate-pdf417-barcode-in-c-complete-step-by-step-guide/) +Hướng dẫn toàn diện tạo mã vạch PDF417 bằng C# với Aspose.BarCode, bao gồm các bước cấu hình chi tiết và ví dụ mã nguồn. + +### [Cách Đọc PDF417 trong C# – Hướng Dẫn Chi Tiết Từng Bước](./how-to-read-pdf417-in-c-complete-step-by-step-guide/) +Hướng dẫn chi tiết cách đọc mã vạch PDF417 bằng C# với Aspose.BarCode, bao gồm các bước cấu hình và ví dụ mã nguồn. + ## Câu hỏi thường gặp **Q: Dung lượng tối đa tôi có thể lưu trữ trong một mã vạch Compact PDF417 là bao nhiêu?** @@ -111,4 +123,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/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md b/barcode/vietnamese/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md new file mode 100644 index 000000000..339cd6911 --- /dev/null +++ b/barcode/vietnamese/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-07-15 +description: Tạo metadata mã vạch PDF417 trong C# bằng Aspose.BarCode. Tìm hiểu cài + đặt Macro PDF417, lưu dưới dạng PNG và xử lý văn bản Unicode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create pdf417 barcode metadata +- macro pdf417 +- aspose barcode c# +- barcode metadata fields +- c# barcode generation +language: vi +lastmod: 2026-07-15 +og_description: Tạo siêu dữ liệu mã vạch PDF417 trong C# với Aspose.BarCode. Hướng + dẫn này cho thấy mọi cài đặt bạn cần để nhúng ID tệp, dấu thời gian và nhiều hơn + nữa. +og_image_alt: Screenshot of a generated PDF417 barcode containing metadata fields +og_title: Tạo siêu dữ liệu mã vạch PDF417 trong C# – Hướng dẫn lập trình chi tiết +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + headline: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: Create PDF417 barcode metadata in C# using Aspose.BarCode. Learn Macro + PDF417 settings, save as PNG, and handle Unicode text. + name: Create PDF417 Barcode Metadata in C# – Complete Step‑by‑Step Guide + steps: + - name: Setting up the Aspose.BarCode NuGet package. + text: Setting up the Aspose.BarCode NuGet package. + - name: Initializing a `BarcodeGenerator` for **Macro PDF417**. + text: Initializing a `BarcodeGenerator` for **Macro PDF417**. + - name: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + text: Populating every useful **barcode metadata field** (file ID, segment ID, + checksum, etc.). + - name: Saving the barcode to disk and verifying the output. + text: Saving the barcode to disk and verifying the output. + type: HowTo +- questions: + - answer: Increase `XDimension.Pixels` or switch to a higher‑resolution image format. + question: What if the barcode looks blurry? + - answer: No. Only the fields required by your downstream system are mandatory. + Unused fields can stay at their defaults. + question: Do I need to set every metadata field? + - answer: Yes—loop over the data, increment `MacroPdf417SegmentID`, and generate + a separate barcode for each segment. Remember to keep `MacroPdf417FileID` consistent + across all segments. + question: Can I generate a multi‑segment file automatically? + - answer: Absolutely. The sample text contains `Å`, `ó`, and `©`, showing that Aspose.BarCode + handles UTF‑8 out of the box. + question: Is Unicode supported? + type: FAQPage +tags: +- barcode +- csharp +- aspose +- pdf417 +title: Tạo siêu dữ liệu mã vạch PDF417 trong C# – Hướng dẫn chi tiết từng bước +url: /vi/net/compact-pdf417-encoding/create-pdf417-barcode-metadata-in-c-complete-step-by-step-gu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo siêu dữ liệu mã vạch PDF417 trong C# – Hướng dẫn chi tiết từng bước + +Bạn đã bao giờ cần **tạo siêu dữ liệu mã vạch PDF417** trong C# nhưng không biết phải điều chỉnh thuộc tính nào? Bạn không phải là người duy nhất—các nhà phát triển thường gặp khó khăn khi đặc tả yêu cầu các thông tin như ID tệp, số lượng đoạn, hoặc dấu thời gian tùy chỉnh. + +Tin tốt là Aspose.BarCode biến việc này thành chuyện đơn giản. Trong tutorial này chúng ta sẽ khởi tạo một `BarcodeGenerator` cho **Macro PDF417**, thêm vào tất cả các siêu dữ liệu quan trọng, và lưu kết quả dưới dạng ảnh PNG. Khi kết thúc, bạn sẽ có một mã vạch đầy đủ tính năng, sẵn sàng cho bất kỳ hệ thống chuỗi cung ứng hay quản lý tài liệu nào. + +## Nội dung hướng dẫn + +Chúng ta sẽ đi qua: + +1. Cài đặt gói NuGet Aspose.BarCode. +2. Khởi tạo `BarcodeGenerator` cho **Macro PDF417**. +3. Điền vào mọi **trường siêu dữ liệu mã vạch** hữu ích (file ID, segment ID, checksum, …). +4. Lưu mã vạch ra đĩa và kiểm tra kết quả. + +Không cần kinh nghiệm trước về Macro PDF417—chỉ cần kiến thức cơ bản về C# và môi trường .NET mới nhất. + +Tại sao bạn nên quan tâm? Nhúng siêu dữ liệu phong phú trực tiếp vào mã vạch cho phép các máy quét phía sau xác thực toàn bộ quá trình truyền tệp, phát hiện các đoạn bị thiếu, hoặc thậm chí kích hoạt các quy trình tự động. Nói cách khác, bạn có **dữ liệu tự mô tả, mạnh mẽ** mà không cần tra cứu cơ sở dữ liệu riêng. + +## Yêu cầu trước + +- .NET 6.0 hoặc mới hơn (mã cũng chạy trên .NET Framework 4.7+). +- Visual Studio 2022 (hoặc bất kỳ IDE nào bạn thích). +- Gói **Aspose.BarCode for .NET** từ NuGet (có bản dùng thử miễn phí). + +Bạn có thể cài đặt gói bằng lệnh sau: + +```bash +dotnet add package Aspose.BarCode +``` + +Bây giờ đã có nền tảng, chúng ta cùng đi vào phần thực thi. + +## Bước 1: Khởi tạo BarcodeGenerator cho Macro PDF417 + +Điều đầu tiên cần làm là tạo một thể hiện `BarcodeGenerator` được cấu hình cho **Macro PDF417**. Điều này thông báo cho Aspose.BarCode thuật toán mã hoá nào sẽ dùng và cung cấp nơi để đưa văn bản có thể đọc được bởi con người. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using System; + +// Step 1: Create a BarcodeGenerator for Macro PDF417 with the desired text +using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) +{ + // The rest of the steps will go inside this using block. +} +``` + +> **Tại sao lại quan trọng:** `EncodeTypes.MacroPdf417` kích hoạt chế độ PDF417 mở rộng, hỗ trợ siêu dữ liệu như file ID và số đoạn. Văn bản mẫu chứa các ký tự Unicode (`Å`, `ó`, `©`) để chứng minh trình tạo có thể xử lý đầu vào không phải ASCII một cách mượt mà. + +## Bước 2: Định nghĩa giao diện cơ bản của mã vạch + +Trước khi bắt đầu thêm siêu dữ liệu, chúng ta nên thiết lập một vài tham số hiển thị để mã vạch không quá nhỏ. `XDimension` điều khiển độ rộng mô-đun, trong khi `Columns` ảnh hưởng đến hình dạng tổng thể. + +```csharp +// Step 2: Define basic barcode appearance +generator.Parameters.Barcode.XDimension.Pixels = 2; // module width +generator.Parameters.Barcode.Pdf417.Columns = 5; // number of columns +``` + +> **Mẹo chuyên nghiệp:** Độ rộng pixel `2` thường phù hợp cho hiển thị trên màn hình và hầu hết máy in. Nếu bạn cần in ở độ phân giải cao hơn, tăng lên `3` hoặc `4`. + +## Bước 3: Điền các trường siêu dữ liệu Macro PDF417 + +Bây giờ là phần cốt lõi của tutorial—thêm **các trường siêu dữ liệu mã vạch**. Mỗi thuộc tính tương ứng trực tiếp với một đoạn trong đặc tả Macro PDF417. + +```csharp +// Step 3: Set Macro PDF417 metadata +generator.Parameters.Barcode.Pdf417.MacroPdf417FileID = 12345678; // Unique file identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentID = 12; // Current segment number +generator.Parameters.Barcode.Pdf417.MacroPdf417SegmentsCount = 20; // Total number of segments +generator.Parameters.Barcode.Pdf417.MacroPdf417FileName = "file01"; // Logical file name +generator.Parameters.Barcode.Pdf417.MacroPdf417Checksum = 1234; // CCITT‑16 checksum +generator.Parameters.Barcode.Pdf417.MacroPdf417FileSize = 400000; // File size in bytes +generator.Parameters.Barcode.Pdf417.MacroPdf417TimeStamp = new DateTime(2019, 11, 1); +generator.Parameters.Barcode.Pdf417.MacroPdf417Addressee = "street"; // Intended recipient +generator.Parameters.Barcode.Pdf417.MacroPdf417Sender = "aspose"; // Sender identifier +generator.Parameters.Barcode.Pdf417.MacroPdf417Terminator = Pdf417MacroTerminator.Set; +``` + +### Giải thích từng thuộc tính + +| Thuộc tính | Mục đích | Giá trị điển hình | +|------------|----------|-------------------| +| **MacroPdf417FileID** | Định danh duy nhất toàn cầu cho toàn bộ tập tin. | `12345678` | +| **MacroPdf417SegmentID** | Chỉ số của đoạn hiện tại (bắt đầu từ `0`). | `12` | +| **MacroPdf417SegmentsCount** | Tổng số đoạn dự kiến cho tệp. | `20` | +| **MacroPdf417FileName** | Tên có thể đọc được, thường là tên tệp gốc. | `"file01"` | +| **MacroPdf417Checksum** | Kiểm tra CRC 16‑bit CCITT để phát hiện lỗi. | `1234` | +| **MacroPdf417FileSize** | Kích thước tệp gốc tính bằng byte. | `400000` | +| **MacroPdf417TimeStamp** | Thời điểm tệp được tạo. | `new DateTime(2019,11,1)` | +| **MacroPdf417Addressee** | Trường tùy chọn chỉ người nhận. | `"street"` | +| **MacroPdf417Sender** | Trường tùy chọn chỉ hệ thống gửi. | `"aspose"` | +| **MacroPdf417Terminator** | Cờ báo cho máy quét biết đây là đoạn cuối cùng. | `Pdf417MacroTerminator.Set` | + +> **Tại sao bạn cần chúng:** Các máy quét hiểu Macro PDF417 có thể ghép lại tệp đa đoạn, xác thực tính toàn vẹn bằng checksum, và thậm chí từ chối dữ liệu cũ dựa trên dấu thời gian. Điều này loại bỏ nhu cầu một file manifest riêng. + +## Bước 4: Lưu ảnh mã vạch + +Khi mọi tham số đã được thiết lập, chỉ cần gọi `Save`. Ví dụ dưới đây ghi file PNG vào thư mục bạn chỉ định. + +```csharp +// Step 4: Save the barcode image +generator.Save("YOUR_DIRECTORY/ExtPDF417Meta.png", BarCodeImageFormat.Png); +``` + +> **Trường hợp đặc biệt:** Nếu bạn dự định nhúng mã vạch vào PDF sau này, có thể dùng `BarCodeImageFormat.Jpeg` hoặc `Pdf`. PNG giữ chi tiết không mất mát, rất hữu ích cho việc kiểm chứng. + +## Ví dụ hoàn chỉnh + +Kết hợp tất cả lại, đây là chương trình đầy đủ mà bạn có thể sao chép‑dán vào một ứng dụng console: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Create a BarcodeGenerator for Macro PDF417 with Unicode text + using (BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.MacroPdf417, "Åspóse.Barcóde©")) + { + // Basic appearance + generator.Parameters.Barcode.XDimension.Pixels = 2; + generator.Parameters.Barcode.Pdf417.Columns = 5; + + // Macro PDF417 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; + 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; + + // Save as PNG + generator.Save("ExtPDF417Meta.png", BarCodeImageFormat.Png); + } + + Console.WriteLine("Macro PDF417 barcode with metadata saved successfully."); + } +} +``` + +### Kết quả mong đợi + +Chạy chương trình sẽ tạo một file có tên **ExtPDF417Meta.png** trong thư mục chứa executable. Mở nó bằng bất kỳ trình xem ảnh nào và bạn sẽ thấy một mã vạch PDF417 dày đặc, độ tương phản cao. Nếu quét bằng máy đọc hỗ trợ Macro PDF417, máy sẽ trả về các giá trị siêu dữ liệu chúng ta đã đặt—file ID `12345678`, đoạn `12` trong `20`, v.v. + +## Câu hỏi thường gặp & Những lỗi thường gặp + +- **Mã vạch bị mờ?** Tăng `XDimension.Pixels` hoặc chuyển sang định dạng ảnh có độ phân giải cao hơn. +- **Có bắt buộc phải đặt mọi trường siêu dữ liệu không?** Không. Chỉ cần các trường mà hệ thống phía dưới yêu cầu. Các trường không dùng có thể để mặc định. +- **Có thể tự động tạo tệp đa đoạn không?** Có—lặp qua dữ liệu, tăng `MacroPdf417SegmentID`, và tạo một mã vạch riêng cho mỗi đoạn. Đừng quên giữ `MacroPdf417FileID` giống nhau cho tất cả các đoạn. +- **Unicode có được hỗ trợ không?** Hoàn toàn có. Văn bản mẫu chứa `Å`, `ó`, và `©`, chứng tỏ Aspose.BarCode xử lý UTF‑8 ngay từ đầu. + +## Bước tiếp theo: Vượt ra ngoài những kiến thức cơ bản + +Sau khi đã biết cách **tạo siêu dữ liệu mã vạch PDF417**, bạn có thể khám phá: + +- **Nhúng mã vạch vào PDF** bằng `Aspose.Pdf` để tạo tài liệu đầu cuối. +- **Đọc lại siêu dữ liệu** bằng `BarcodeReader` để xác thực quét một cách lập trình. +- **Tùy chỉnh màu sắc** (foreground/background) để phù hợp thương hiệu. +- **Kết nối với cơ sở dữ liệu** để tự động điền các trường như `FileID` hoặc `Timestamp`. + +Tất cả các chủ đề này liên quan tới các từ khóa phụ—**macro pdf417**, **aspose barcode c#**, **barcode metadata fields**, và **c# barcode generation**—vì vậy bạn sẽ tìm thấy rất nhiều tài liệu để tiếp tục học hỏi. + +## Kết luận + +Chúng ta vừa đi qua một ví dụ hoàn chỉnh, sẵn sàng cho môi trường sản xuất, về cách **tạo siêu dữ liệu mã vạch PDF417** trong C#. Từ việc cài đặt Aspose.BarCode, khởi tạo `BarcodeGenerator`, điền mọi **trường siêu dữ liệu mã vạch** liên quan, đến cuối cùng là lưu ảnh PNG sắc nét, quy trình trở nên đơn giản khi bạn biết đúng thuộc tính cần dùng. + +Hãy thử, điều chỉnh các giá trị và quan sát phản hồi của máy quét. Khả năng mở rộng của Macro PDF417 cho phép bạn nhúng mọi thông tin hệ thống phía dưới cần—trong một hình ảnh có thể quét được. Chúc bạn lập trình vui vẻ và mã vạch luôn không lỗi! + +## Bạn nên học gì tiếp theo? + +Các tutorial dưới đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã trình bày trong hướng dẫn này. Mỗi tài nguyên đều bao gồm mã mẫu đầy đủ và giải thích từng bước để giúp bạn làm chủ các tính năng API khác 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 – Compact PDF417 với Aspose.BarCode](/barcode/english/net/compact-pdf417-encoding/compact-pdf417-basic-configuration/) +- [Thư viện mã vạch java – Thêm mã vạch vào PDF bằng Aspose](/barcode/english/java/barcode-basics/adding-barcode-to-pdf-document/) +- [So erstellen Sie einen Barcode – Kompaktes PDF417 mit Aspose.BarCode](/barcode/german/net/compact-pdf417-encoding/compact-pdf417-basic-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-pdf417-barcode-in-c-complete-guide/_index.md b/barcode/vietnamese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md new file mode 100644 index 000000000..f53e47518 --- /dev/null +++ b/barcode/vietnamese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-07-15 +description: Tạo mã vạch PDF417 nhanh chóng và học cách thiết lập số cột cho hình + ảnh mã vạch PDF417 gọn gàng trong C#. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- how to set columns +- pdf417 barcode image +- Aspose.BarCode PDF417 +- C# barcode generation +- compact PDF417 +language: vi +lastmod: 2026-07-15 +og_description: Tạo mã vạch PDF417 bằng Aspose.BarCode và học cách thiết lập các cột + để tạo hình ảnh mã vạch PDF417 gọn nhẹ. +og_image_alt: Screenshot of a compact PDF417 barcode saved as PNG +og_title: Tạo mã vạch PDF417 trong C# – Hướng dẫn từng bước +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly and learn how to set columns for a + compact PDF417 barcode image in C#. + headline: Generate PDF417 Barcode in C# – Complete Guide + type: TechArticle +tags: +- barcode +- C# +- PDF417 +title: Tạo mã vạch PDF417 bằng C# – Hướng dẫn toàn diện +url: /vi/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo PDF417 Barcode trong C# – Hướng dẫn đầy đủ + +Bạn đã bao giờ cần **generate PDF417 barcode** trong một dự án .NET nhưng không biết bắt đầu từ đâu chưa? Bạn không phải là người duy nhất. Trong nhiều ứng dụng doanh nghiệp—như máy in thẻ lên máy bay, nhãn kho, hoặc vé di động—PDF417 là công cụ chính, cho phép nén nhiều dữ liệu vào một không gian hình ảnh nhỏ. + +Điều quan trọng là: thư viện Aspose.BarCode làm cho toàn bộ quá trình gần như không gây khó khăn, và bạn thậm chí có thể kiểm soát **how to set columns** để mã vạch trở nên gọn gàng nhất có thể. Khi kết thúc hướng dẫn này, bạn sẽ có một hình ảnh PNG sẵn sàng sử dụng của **PDF417 barcode image** mà bạn có thể chèn vào bất kỳ giao diện UI, email, hay công việc in nào. + +## Những gì bạn sẽ nhận được + +- Một ứng dụng console C# hoạt động đầy đủ, tạo ra PDF417 barcode. +- Hiểu rõ về *X‑Dimension* (kích thước mô-đun) và lý do nó quan trọng. +- Hướng dẫn từng bước về **how to set columns** để tạo mã vạch chặt hơn. +- Một tệp `PNG` đã lưu mà bạn có thể mở ngay để xác minh kết quả. +- Mẹo khắc phục các vấn đề thường gặp (ví dụ: mã vạch không đọc được, định dạng hình ảnh sai). + +> **Prerequisites** – .NET 6+ SDK, Visual Studio 2022 (hoặc bất kỳ trình soạn thảo nào bạn thích), và một tham chiếu NuGet tới `Aspose.BarCode`. Không cần gì khác. + +--- + +## Bước 1: Cài đặt gói NuGet Aspose.BarCode + +Trước khi chúng ta có thể *generate PDF417 barcode*, thư viện phải có trong dự án. + +```bash +dotnet add package Aspose.BarCode +``` + +Dòng lệnh duy nhất này sẽ kéo về tất cả các kiểu bạn cần, bao gồm `BarcodeGenerator`, `EncodeTypes`, và enum `BarCodeImageFormat`. + +> **Pro tip:** Nếu bạn nhắm tới .NET Framework thay vì .NET 6, hãy sử dụng lệnh PowerShell cổ điển `Install-Package Aspose.BarCode` trong Package Manager Console. + +--- + +## Bước 2: Tạo một ứng dụng console tối thiểu + +Hãy tạo một chương trình nhỏ chỉ thực hiện việc tạo mã vạch. Mở một thư mục mới, chạy `dotnet new console`, sau đó thay thế tệp `Program.cs` được tự động tạo bằng đoạn mã dưới đây. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace Pdf417Demo +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Define the data you want to encode. + string data = "SampleBarcode©"; + + // 2️⃣ Instantiate the generator for PDF417. + BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.Pdf417, data); + + // 3️⃣ Set the size of a single barcode module (pixel dimension). + // This is the “X‑Dimension” – smaller values yield a finer image. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 4️⃣ **How to set columns** – configure the matrix layout. + // Fewer columns = taller barcode; more columns = wider barcode. + generator.Parameters.Barcode.Pdf417.Columns = 3; // 👈 primary levers + generator.Parameters.Barcode.Pdf417.Truncate = true; // compact mode + + // 5️⃣ Choose where the PNG will be saved. + string outputPath = @"./CompactPdf417.png"; + + // 6️⃣ Save the generated barcode as a PNG image. + generator.Save(outputPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode saved to {outputPath}"); + } + } +} +``` + +**Why this matters:** +- `EncodeTypes.Pdf417` cho thư viện biết chúng ta muốn một PDF417 barcode, không phải QR hay Code128. +- `XDimension.Pixels` kiểm soát độ phân giải của mỗi mô-đun đen hoặc trắng nhỏ. +- Khối **how to set columns** ảnh hưởng trực tiếp đến hình dạng của **PDF417 barcode image**. +- `Truncate = true` loại bỏ bất kỳ hàng trống không cần thiết nào, mang lại giao diện “compact” mà nhiều máy quét yêu thích. + +--- + +## Bước 3: Đi sâu hơn – Hiểu về Cột và Cắt ngắn + +### Cách thiết lập Cột + +PDF417 sắp xếp dữ liệu trong một ma trận *rows* × *columns*. Thư viện mặc định là 5 cột, phù hợp với hầu hết các trường hợp. Tuy nhiên, bạn có thể cần một mã vạch hẹp hơn để vừa nhãn hoặc rộng hơn để cải thiện độ tin cậy khi quét. Thuộc tính: + +```csharp +generator.Parameters.Barcode.Pdf417.Columns = ; +``` + +chấp nhận các giá trị từ **1** đến **30** (giới hạn chính xác phụ thuộc vào độ dài dữ liệu). Dưới đây là bảng nhanh: + +| Cột | Chiều rộng ước tính (mm) | Khi nào dùng | +|-----|---------------------------|--------------| +| 1‑3 | Rất hẹp | Nhãn nhỏ, không gian hạn chế | +| 4‑6 | Tiêu chuẩn | Hầu hết biên lai, vé | +| 7‑10| Rộng hơn | Dữ liệu mật độ cao, độ đọc tốt hơn | + +### Truncate (Chế độ Compact) + +Cài đặt `Truncate = true` yêu cầu bộ mã hoá cắt bỏ bất kỳ hàng trống không cần thiết nào ở dưới cùng. Kết quả là một **compact PDF417 barcode image** chiếm diện tích nhỏ nhất có thể trong khi vẫn chứa toàn bộ dữ liệu. Nếu bạn gặp lỗi “barcode too big for label”, hãy bật/tắt cờ này. + +--- + +## Bước 4: Chạy ứng dụng và xác minh đầu ra + +Compile and execute: + +```bash +dotnet run +``` + +Bạn sẽ thấy thông báo trên console xác nhận vị trí lưu. Điều hướng tới thư mục và mở `CompactPdf417.png`. Hình ảnh sẽ trông giống như sau: + +![Hình ảnh mã vạch PDF417 đã tạo](./CompactPdf417.png "Hình ảnh mã vạch PDF417 đã tạo – PNG compact được tạo bởi Aspose.BarCode") + +*Văn bản thay thế hình ảnh:* **Generated PDF417 barcode image** – một tệp PNG compact được tạo bởi mã hướng dẫn. + +Nếu máy quét của bạn có thể đọc được, chúc mừng—bạn đã thành công **generate PDF417 barcode** và nắm vững **how to set columns** để tạo một **PDF417 barcode image** gọn gàng. + +--- + +## Bước 5: Những lỗi thường gặp & Cách khắc phục + +| Triệu chứng | Nguyên nhân có thể | Cách khắc phục nhanh | +|-------------|--------------------|----------------------| +| Mã vạch bị mờ | `XDimension.Pixels` quá thấp (ví dụ: 1) | Tăng lên 2‑3 pixel để có hình ảnh rõ hơn. | +| Máy quét không đọc được | Quá nhiều cột cho dữ liệu hiện tại | Giảm `Columns` hoặc bật `Truncate`. | +| Định dạng tệp sai | Lưu bằng `BarCodeImageFormat.Jpeg` nhầm | Sử dụng `BarCodeImageFormat.Png` để có kết quả không mất dữ liệu. | +| Ngoại lệ `ArgumentOutOfRangeException` | Số cột vượt quá phạm vi cho phép | Giữ cột trong khoảng 1‑30 và đảm bảo dữ liệu phù hợp. | + +--- + +## Bước 6: Tiếp tục – Tùy chỉnh màu sắc và thêm văn bản + +Nếu bạn muốn mã vạch phù hợp với bảng màu thương hiệu, bạn có thể điều chỉnh màu nền và màu chữ: + +```csharp +generator.Parameters.Barcode.BarcodeColor = System.Drawing.Color.DarkBlue; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +``` + +Hoặc chồng văn bản có thể đọc được của con người dưới mã vạch: + +```csharp +generator.Parameters.Barcode.CodeText = data; // shows the raw string +generator.Parameters.Barcode.CodeLocation = CodeLocation.Below; +``` + +Những bổ sung này là tùy chọn, nhưng chúng minh họa cách linh hoạt của quy trình **generate PDF417 barcode**. + +--- + +## Kết luận + +Chúng tôi đã trình bày một ví dụ hoàn chỉnh, từ đầu đến cuối về **generate PDF417 barcode** bằng Aspose.BarCode, giải thích **how to set columns** để kiểm soát kích thước của mã vạch, và lưu kết quả dưới dạng **PDF417 barcode image** sắc nét ở định dạng PNG. Mã nguồn độc lập, hoạt động với .NET 6+, và có thể được chèn vào bất kỳ dự án hiện có nào mà không gặp rắc rối. + +Tiếp theo gì? Hãy thử mã hoá các tải trọng lớn hơn (ví dụ: payload JSON), thử nghiệm các định dạng hình ảnh khác nhau, hoặc tích hợp trình tạo vào một web API cung cấp mã vạch theo yêu cầu. Không có giới hạn, và bạn đã có nền tảng vững chắc để phát triển. + +Chúc lập trình vui vẻ, và hy vọng mã vạch của bạn luôn được quét thành công ngay lần đầu! + +## 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ẽ, 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 bao gồm các ví dụ mã hoạt động đầy đủ 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 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 hình ảnh mã vạch trong Java với Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Tạo mã vạch Java – Đặt độ phân giải hình ảnh với Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + +{{< /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-complete-step-by-step-guide/_index.md b/barcode/vietnamese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..3bbcc60c7 --- /dev/null +++ b/barcode/vietnamese/net/compact-pdf417-encoding/generate-pdf417-barcode-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-07-15 +description: Tạo mã vạch PDF417 nhanh chóng với C#. Tìm hiểu cách tạo mã vạch từ văn + bản, điều chỉnh kích thước mã vạch và thiết lập kích thước tùy chỉnh cho mã vạch + trong vài phút. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate pdf417 barcode +- generate barcode from text +- adjust barcode size +- custom barcode dimensions +language: vi +lastmod: 2026-07-15 +og_description: Tạo mã vạch PDF417 trong C# ngay lập tức. Hướng dẫn này chỉ cách tạo + mã vạch từ văn bản, điều chỉnh kích thước mã vạch và áp dụng kích thước tùy chỉnh + cho mã vạch. +og_image_alt: Screenshot of a PDF417 barcode generated with custom dimensions using + C# code +og_title: Tạo mã vạch PDF417 trong C# – Hướng dẫn lập trình đầy đủ +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate PDF417 barcode quickly with C#. Learn how to generate barcode + from text, adjust barcode size, and set custom barcode dimensions in minutes. + headline: Generate PDF417 Barcode in C# – Complete Step‑by‑Step Guide + type: TechArticle +tags: +- barcode +- pdf417 +- csharp +title: Tạo mã vạch PDF417 trong C# – Hướng dẫn chi tiết từng bước +url: /vi/net/compact-pdf417-encoding/generate-pdf417-barcode-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 PDF417 trong C# – Hướng dẫn chi tiết từng bước + +Bạn đã bao giờ cần **tạo mã vạch PDF417** nhưng không chắc nên điều chỉnh thiết lập nào? Bạn không phải là người duy nhất—nhiều nhà phát triển gặp cùng một rào cản khi lần đầu làm việc với mã vạch 2‑D. Tin tốt là gì? Chỉ với vài dòng C# bạn có thể biến bất kỳ chuỗi nào thành một hình ảnh PDF417 có thể quét được, kiểm soát kích thước chính xác, và thậm chí định nghĩa bố cục cột‑hàng tùy chỉnh. + +Trong hướng dẫn này, chúng ta sẽ đi qua cách **tạo mã vạch từ văn bản**, điều chỉnh kích thước mã vạch, và thiết lập kích thước mã vạch tùy chỉnh — tất cả đều sử dụng thư viện Aspose.BarCode phổ biến. Khi hoàn thành, bạn sẽ có một mẫu sẵn sàng chạy mà bạn có thể đưa vào bất kỳ dự án .NET nào. + +![Ví dụ tạo mã vạch PDF417](https://example.com/og-image.png "Ví dụ tạo mã vạch PDF417") + +## Những gì bạn sẽ xây dựng + +- Một mã vạch PDF417 mã hoá chuỗi `Åspóse.Barcóde©`. +- Kiểm soát chính xác kích thước X (độ rộng pixel của mỗi mô-đun). +- Bố cục tùy chỉnh 4 cột và 9 hàng. +- Tệp PNG được lưu vào đĩa. + +Không có dịch vụ bên ngoài, không có thủ thuật ma thuật—chỉ là mã C# thuần túy mà bạn có thể biên dịch ngay bây giờ. + +## Yêu cầu trước + +- .NET 6.0 trở lên (mã cũng hoạt động trên .NET Framework 4.8). +- Visual Studio 2022 hoặc bất kỳ IDE nào hỗ trợ C#. +- Aspose.BarCode for .NET (bản dùng thử miễn phí hoặc phiên bản có giấy phép). Cài đặt qua NuGet: + +```bash +dotnet add package Aspose.BarCode +``` + +Xong—khi gói đã được tham chiếu, bạn đã sẵn sàng. + +## Bước 1 – Tạo mã vạch PDF417 với dữ liệu văn bản + +Điều đầu tiên chúng ta cần là một thể hiện của `BarcodeGenerator` biết rằng chúng ta đang làm việc với ký hiệu PDF417 và chuỗi văn bản cần mã hoá. + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +// Step 1: Initialize the barcode generator with PDF417 symbology and the data to encode +BarcodeGenerator barcodeGenerator = new BarcodeGenerator(EncodeTypes.Pdf417, "Åspóse.Barcóde©"); +``` + +> **Tại sao lại quan trọng:** +> `EncodeTypes.Pdf417` báo cho thư viện sử dụng định dạng PDF417 2‑D, trong khi đối số thứ hai là **tải dữ liệu để tạo mã vạch từ văn bản**. Bất kỳ gì bạn truyền vào đây sẽ trở thành dữ liệu được lưu trong ma trận mã vạch. + +## Bước 2 – Điều chỉnh kích thước mã vạch (X‑Dimension) + +Nếu bạn từng in một mã vạch quá nhỏ trên biên lai, bạn sẽ hiểu sự bực bội khi máy quét không nhận ra. Thuộc tính `XDimension` điều khiển độ rộng của một mô-đun duy nhất (ô đen hoặc trắng nhỏ nhất) tính bằng pixel. + +```csharp +// Step 2: Set the module (X) dimension in pixels to control barcode size +barcodeGenerator.Parameters.Barcode.XDimension.Pixels = 2; // 2 px per module +``` + +> **Mẹo chuyên nghiệp:** +> Giá trị 2 px hoạt động tốt cho hầu hết các kịch bản hiển thị trên màn hình. Đối với in ấn độ phân giải cao, bạn có thể tăng lên 3 hoặc 4 px. Chỉ cần nhớ rằng kích thước X lớn hơn sẽ làm tăng tổng kích thước hình ảnh. + +## Bước 3 – Đặt kích thước mã vạch tùy chỉnh (Cột & Hàng) + +PDF417 cho phép bạn chỉ định số cột và hàng mà mã vạch sẽ chiếm. Đây là nơi **kích thước mã vạch tùy chỉnh** phát huy tác dụng. Thay đổi các giá trị này có thể giúp bạn vừa mã vạch vào không gian UI chật hẹp hoặc đáp ứng kích thước nhãn cụ thể. + +```csharp +// Step 3: Define the layout of the PDF417 barcode: number of columns and rows +barcodeGenerator.Parameters.Barcode.Pdf417.Columns = 4; // 4 columns +barcodeGenerator.Parameters.Barcode.Pdf417.Rows = 9; // 9 rows +``` + +> **Điều gì đang diễn ra phía sau?** +> Thư viện phân phối lại dữ liệu đã mã hoá trên lưới được chỉ định. Ít cột hơn đồng nghĩa với mã vạch cao hơn; nhiều hàng hơn làm chúng ngắn hơn. Thử nghiệm các con số cho đến khi cân bằng hình ảnh phù hợp với ứng dụng của bạn. + +## Bước 4 – Lưu hình ảnh mã vạch + +Khi mọi thứ đã được cấu hình, chúng ta chỉ cần yêu cầu trình tạo ghi ra tệp PNG. PNG là định dạng không mất dữ liệu, vì vậy độ sắc nét của các mô-đun vẫn được giữ nguyên. + +```csharp +// Step 4: Save the generated barcode as a PNG image +barcodeGenerator.Save(@"C:\Barcodes\CustomLayout.png", BarCodeImageFormat.Png); +``` + +Khi chạy chương trình, bạn sẽ thấy một tệp tại `C:\Barcodes\CustomLayout.png` trông giống như ảnh chụp màn hình ở trên. Quét nó bằng bất kỳ trình đọc PDF417 nào sẽ trả về chuỗi gốc `Åspóse.Barcóde©`. + +## Ví dụ hoàn chỉnh hoạt động + +Dưới đây là chương trình đầy đủ mà bạn có thể sao chép‑dán vào một ứng dụng console. Nó bao gồm tất cả các chỉ thị `using` và xử lý lỗi mà bạn mong đợi trong mã sản xuất. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + try + { + // 1️⃣ Initialize generator with PDF417 symbology and text + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.Pdf417, + "Åspóse.Barcóde©"); + + // 2️⃣ Adjust X‑dimension to control overall size + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Apply custom layout: 4 columns × 9 rows + generator.Parameters.Barcode.Pdf417.Columns = 4; + generator.Parameters.Barcode.Pdf417.Rows = 9; + + // 4️⃣ Save as PNG + string outPath = @"C:\Barcodes\CustomLayout.png"; + generator.Save(outPath, BarCodeImageFormat.Png); + + Console.WriteLine($"✅ Barcode generated successfully → {outPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"❌ Error: {ex.Message}"); + } + } +} +``` + +### Kết quả mong đợi + +Chạy mã sẽ in ra: + +``` +✅ Barcode generated successfully → C:\Barcodes\CustomLayout.png +``` + +…và tạo một tệp PNG có thể mở bằng bất kỳ trình xem ảnh nào. Nếu bạn quét nó bằng một ứng dụng di động (ví dụ, “Barcode Scanner” trên iOS/Android), văn bản giải mã sẽ chính xác là **Åspóse.Barcóde©**. + +## Câu hỏi thường gặp & Trường hợp đặc biệt + +| Câu hỏi | Trả lời | +|----------|--------| +| **Tôi có thể dùng định dạng ảnh khác không?** | Có—`BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, hoặc `Svg` đều được hỗ trợ. Chỉ cần thay đổi đối số thứ hai của `Save`. | +| **Nếu văn bản của tôi chứa ký tự Unicode thì sao?** | Aspose.BarCode hỗ trợ đầy đủ UTF‑8, vì vậy ví dụ với `Å` và `©` hoạt động ngay mà không cần cấu hình thêm. | +| **Làm sao thay đổi mức độ sửa lỗi?** | Dùng `generator.Parameters.Barcode.Pdf417.ErrorCorrectionLevel = Pdf417ErrorCorrectionLevel.Level5;` (các mức từ 0‑8). Mức cao hơn tăng độ dư thừa nhưng cũng làm tăng kích thước. | +| **Tôi cần nền trong suốt—có thể thực hiện không?** | Đặt `generator.Parameters.Barcode.Image.TransparentBackground = true;` trước khi lưu. | +| **Có cách nhúng mã vạch trực tiếp vào PDF không?** | Chắc chắn. Thay lời gọi `Save` bằng `generator.Save("output.pdf", BarCodeImageFormat.Pdf);` và bạn sẽ nhận được một tệp PDF một trang chứa mã vạch. | + +## Kết luận + +Bây giờ bạn đã biết cách **tạo mã vạch PDF417** trong C# từ bất kỳ chuỗi nào, **điều chỉnh kích thước mã vạch**, và áp dụng **kích thước mã vạch tùy chỉnh** để phù hợp với bố cục của mình. Quy trình bốn bước—khởi tạo, kích thước, bố cục, lưu—bao quát luồng công việc cốt lõi cho hầu hết các kịch bản mã vạch 2‑D. + +Tiếp theo bạn sẽ làm gì? Hãy thử thay `EncodeTypes.Pdf417` bằng `EncodeTypes.QR` hoặc `EncodeTypes.Code128` để xem API thích nghi như thế nào. Thử nghiệm các giá trị `XDimension` khác nhau, chơi với ma trận cột/hàng, hoặc nhúng hình ảnh vào báo cáo PDF. Khả năng là gần như vô hạn, và giờ bạn đã có nền tảng vững chắc để phát triển. + +Có câu hỏi nào khác, hoặc đã khám phá được mẹo hay khi làm việc với PDF417? Hãy để lại bình luận bên dưới—cùng nhau tiếp tục thảo luận. Chúc bạn lập trình vui vẻ! + + +## Bạn nên học gì tiếp theo? + + +Các hướng dẫn sau đây đề cập đến các chủ đề liên quan chặt chẽ, 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 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. + +- [Cách tạo mã vạch Aztec với tỷ lệ khung hình tùy chỉnh bằng Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Cách tạo mã vạch – Các loại mã vạch một chiều](/barcode/english/net/one-dimensional-barcode-types/) +- [Tạo mã vạch DataMatrix – Hướng dẫn chuyên sâu với Aspose.BarCode](/barcode/english/net/datamatrix-barcode-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/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md b/barcode/vietnamese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md new file mode 100644 index 000000000..2082289ce --- /dev/null +++ b/barcode/vietnamese/net/compact-pdf417-encoding/how-to-read-pdf417-in-c-complete-step-by-step-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-07-15 +description: Cách đọc mã vạch PDF417 trong C# và đọc nhiều mã vạch từ một hình ảnh. + Học cách đọc hình ảnh mã vạch bằng C# với mã chi tiết và các mẹo. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to read pdf417 +- read multiple barcodes +- read barcode image c# +- Aspose.BarCode PDF417 +- C# barcode decoding +language: vi +lastmod: 2026-07-15 +og_description: Cách đọc mã vạch PDF417 trong C# nhanh chóng. Hướng dẫn này cho bạn + biết cách đọc nhiều mã vạch từ một hình ảnh duy nhất và giải mã từng thuộc tính. +og_image_alt: Screenshot of C# console output displaying PDF417 barcode details +og_title: Cách Đọc PDF417 trong C# – Mẫu Mã Đầy Đủ & Giải Thích +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + headline: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + type: TechArticle +- description: How to read PDF417 barcode in C# and read multiple barcodes from an + image. Learn to read barcode image C# with detailed code and tips. + name: How to Read PDF417 in C# – Complete Step‑by‑Step Guide + steps: + - name: Why This Code Works + text: '* **`BarCodeReader`** is the core class that streams the image, detects + barcodes, and returns a collection of `BarCodeResult` objects. * Passing **`DecodeType.MacroPdf417`** + tells the library to treat Macro‑PDF417 specially; it still returns plain PDF417 + symbols, which satisfies the **read multiple ' + - name: What if the image has both Macro‑PDF417 and regular PDF417 symbols? + text: The same `BarCodeReader` call will return both. You can differentiate them + by checking `result.CodeType` (`MacroPdf417` vs `Pdf417`). The extended properties + will be `null` for a plain PDF417, so the `if (macro != null)` guard prevents + a `NullReferenceException`. + - name: My barcode is rotated or skewed—will the reader still work? + text: Aspose.BarCode includes built‑in rotation and distortion compensation. As + long as the barcode is at least 30 % of the image width, the decoder will usually + succeed. For extreme cases you can enable `reader.Options.AllowInvertedBarcodes + = true;` before calling `ReadBarCodes()`. + - name: How do I handle large batches of images? + text: Wrap the reading logic in a `foreach (var file in Directory.GetFiles(folder, + "*.png"))` loop. The `using` pattern ensures each image’s native resources are + freed before the next iteration, keeping memory usage low. + type: HowTo +tags: +- C# +- barcode +- PDF417 +- Aspose +title: Cách đọc PDF417 trong C# – Hướng dẫn chi tiết từng bước +url: /vi/net/compact-pdf417-encoding/how-to-read-pdf417-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ách Đọc PDF417 trong C# – Hướng Dẫn Bước‑đầu Đầy Đủ + +Bạn đã bao giờ tự hỏi **cách đọc PDF417** từ một hình ảnh bằng C# chưa? Bạn không phải là người duy nhất. Hầu hết các nhà phát triển gặp khó khăn khi cần trích xuất các trường Macro‑PDF417 mở rộng từ một tài liệu đã quét. Tin tốt là gì? Chỉ với vài dòng mã, bạn có thể giải mã PDF417, đọc nhiều mã vạch trong cùng một hình ảnh, và lấy mọi thuộc tính ẩn mà đặc tả cung cấp. + +Trong hướng dẫn này, chúng ta sẽ đi qua một ví dụ thực tế cho thấy **cách đọc PDF417**, cách **đọc nhiều mã vạch** từ một tệp duy nhất, và tại sao mã **read barcode image C#** trông như vậy. Khi kết thúc, bạn sẽ có một ứng dụng console sẵn sàng chạy, in ra mọi thông tin bạn có thể cần—ID tệp, ID đoạn, checksum, dấu thời gian, v.v. + +## Yêu Cầu Trước + +* .NET 6.0 SDK hoặc phiên bản mới hơn (mã hoạt động với .NET Core và .NET Framework cũng được). +* Visual Studio 2022 (hoặc bất kỳ trình soạn thảo nào bạn thích). +* Gói NuGet **Aspose.BarCode for .NET** – đây là thư viện thực sự phân tích PDF417. +* Một hình ảnh mẫu chứa mã vạch Macro‑PDF417 (ví dụ `ExtPDF417Meta.png`). + +Không cần cấu hình bổ sung; thư viện đã đi kèm với tất cả các bộ giải mã cần thiết. + +## Bước 1: Cài Đặt Aspose.BarCode + +Mở thư mục dự án của bạn trong terminal và chạy: + +```bash +dotnet add package Aspose.BarCode +``` + +Lệnh đó tải phiên bản ổn định mới nhất (tính đến tháng 7 2026 là 23.12). Nếu bạn thích Package Manager Console trong Visual Studio, hãy dùng: + +```powershell +Install-Package Aspose.BarCode +``` + +> **Mẹo chuyên nghiệp:** khóa phiên bản (`23.12.0`) trong file `.csproj` của bạn để tránh các thay đổi gây lỗi không mong muốn sau này. + +## Bước 2: Tạo Khung Ứng Dụng Console + +Tạo một dự án console mới nếu bạn chưa có: + +```bash +dotnet new console -n Pdf417ReaderDemo +cd Pdf417ReaderDemo +``` + +Thay thế file `Program.cs` được tạo tự động bằng đoạn mã dưới đây. Chúng tôi sẽ giải thích từng khối trong các phần tiếp theo. + +## Bước 3: Viết Toàn Bộ Mã “Cách Đọc PDF417” + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + // ----------------------------------------------------------------- + // 1️⃣ Set the path to the image that contains one or more PDF417 codes + // ----------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + // ----------------------------------------------------------------- + // 2️⃣ Initialise the BarCodeReader for MacroPdf417 decoding + // ----------------------------------------------------------------- + // The DecodeType flag tells Aspose to look specifically for Macro‑PDF417, + // but it will also pick up plain PDF417 symbols that happen to be in the + // same image – perfect for the “read multiple barcodes” scenario. + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + // ----------------------------------------------------------------- + // 3️⃣ Iterate over every barcode found in the image + // ----------------------------------------------------------------- + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + // ------------------------------------------------------------- + // 4️⃣ Basic barcode information – works for any barcode type + // ------------------------------------------------------------- + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + // ------------------------------------------------------------- + // 5️⃣ Macro‑PDF417 extended properties (the real reason you’re here) + // ------------------------------------------------------------- + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); // visual separator + } + } + + // ----------------------------------------------------------------- + // 6️⃣ Keep the console window open when running from VS + // ----------------------------------------------------------------- + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Tại Sao Mã Này Hoạt Động + +* **`BarCodeReader`** là lớp cốt lõi chịu việc truyền luồng ảnh, phát hiện mã vạch và trả về một tập hợp các đối tượng `BarCodeResult`. +* Việc truyền **`DecodeType.MacroPdf417`** cho thư viện biết xử lý Macro‑PDF417 đặc biệt; nó vẫn trả về các ký hiệu PDF417 thông thường, đáp ứng yêu cầu **read multiple barcodes**. +* Đối tượng **`Extended.Pdf417.MacroPdf417`** chứa mọi trường tùy chọn được định nghĩa trong tiêu chuẩn ISO/IEC 15438 – ở đây bạn sẽ nhận được `FileID`, `SegmentID`, `Checksum`, v.v. +* Khối `using` đảm bảo các tài nguyên gốc được giải phóng, ngăn ngừa rò rỉ bộ nhớ trong các dịch vụ chạy lâu. + +## Bước 4: Chạy Ứng Dụng và Xác Nhận Kết Quả + +Từ terminal: + +```bash +dotnet run +``` + +Bạn sẽ thấy một kết quả tương tự: + +``` +Code Type : MacroPdf417 +Code Text : 1234567890... +File ID : 12 +Segment ID : 1 +Segments Count : 3 +File Name : invoice2024.pdf +Checksum : 9A3F +File Size : 245760 +Time Stamp : 2024-11-02T14:23:00Z +Addressee : Acme Corp +Sender : Logistics Dept +Terminator : 1 +---------------------------------------- +Done. Press any key to exit... +``` + +Nếu hình ảnh chứa nhiều hơn một mã vạch, vòng lặp sẽ in ra một dòng phân cách (`----------------------------------------`) và tiếp tục với kết quả tiếp theo—đúng như cách **read multiple barcodes** hoạt động trong thực tế. + +## Các Câu Hỏi Thường Gặp & Trường Hợp Đặc Biệt + +### Nếu hình ảnh có cả ký hiệu Macro‑PDF417 và PDF417 thông thường thì sao? + +Cùng một lời gọi `BarCodeReader` sẽ trả về cả hai. Bạn có thể phân biệt chúng bằng cách kiểm tra `result.CodeType` (`MacroPdf417` so với `Pdf417`). Các thuộc tính mở rộng sẽ là `null` đối với PDF417 thông thường, vì vậy điều kiện `if (macro != null)` ngăn ngừa `NullReferenceException`. + +### Mã vạch của tôi bị quay hoặc lệch—đọc vẫn hoạt động không? + +Aspose.BarCode bao gồm khả năng bù trừ quay và biến dạng tích hợp. Miễn là mã vạch chiếm ít nhất 30 % chiều rộng ảnh, bộ giải mã thường sẽ thành công. Đối với các trường hợp cực đoan, bạn có thể bật `reader.Options.AllowInvertedBarcodes = true;` trước khi gọi `ReadBarCodes()`. + +### Làm thế nào để xử lý một lượng lớn ảnh? + +Bao bọc logic đọc trong một vòng lặp `foreach (var file in Directory.GetFiles(folder, "*.png"))`. Mẫu `using` đảm bảo tài nguyên gốc của mỗi ảnh được giải phóng trước vòng lặp tiếp theo, giữ mức sử dụng bộ nhớ thấp. + +## Danh Sách Mã Nguồn Đầy Đủ (Sẵn Sàng Sao Chép‑Dán) + +Dưới đây là toàn bộ chương trình trong một khối duy nhất để sao chép‑dán nhanh. Không có phụ thuộc ẩn—chỉ cần gói NuGet Aspose.BarCode. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeRecognition; + +namespace Pdf417ReaderDemo +{ + class Program + { + static void Main(string[] args) + { + string imagePath = @"YOUR_DIRECTORY/ExtPDF417Meta.png"; + + using (BarCodeReader reader = new BarCodeReader(imagePath, DecodeType.MacroPdf417)) + { + foreach (BarCodeResult result in reader.ReadBarCodes()) + { + Console.WriteLine($"Code Type : {result.CodeTypeName}"); + Console.WriteLine($"Code Text : {result.CodeText}"); + + var macro = result.Extended?.Pdf417?.MacroPdf417; + if (macro != null) + { + Console.WriteLine($"File ID : {macro.FileID}"); + Console.WriteLine($"Segment ID : {macro.SegmentID}"); + Console.WriteLine($"Segments Count : {macro.SegmentsCount}"); + Console.WriteLine($"File Name : {macro.FileName}"); + Console.WriteLine($"Checksum : {macro.Checksum}"); + Console.WriteLine($"File Size : {macro.FileSize}"); + Console.WriteLine($"Time Stamp : {macro.TimeStamp}"); + Console.WriteLine($"Addressee : {macro.Addressee}"); + Console.WriteLine($"Sender : {macro.Sender}"); + Console.WriteLine($"Terminator : {macro.Terminator}"); + } + else + { + Console.WriteLine("No Macro‑PDF417 extended data found for this barcode."); + } + + Console.WriteLine(new string('-', 40)); + } + } + + Console.WriteLine("Done. Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +## Tóm Tắt – Những Điều Chúng Ta Đã Bao Quát + +- **Cách đọc PDF417** bằng Aspose.BarCode trong C#. +- Các bước chính xác để **đọc nhiều mã vạch** từ một hình ảnh duy nhất. +- Cách **read barcode image C#** và trích xuất mọi trường Macro‑PDF417. +- Mẹo về quay, xử lý batch, và xử lý dữ liệu mở rộng bị thiếu. + +## Các Bước Tiếp Theo & Chủ Đề Liên Quan + +- **Encode PDF417** – tạo các mã vạch Macro‑PDF417 của riêng bạn bằng `BarCodeBuilder`. +- **Read other 2‑D symbologies** – QR, DataMatrix, Aztec – sử dụng cùng lớp `BarCodeReader`. +- **Integrate with ASP.NET Core** – cung cấp một endpoint web nhận ảnh tải lên và trả về JSON với các trường đã giải mã. + +Bạn có thể thoải mái thử nghiệm: thay đổi đường dẫn ảnh, đặt một PDF417 thông thường vào cùng thư mục, hoặc điều chỉnh các cờ `DecodeType` để xem thư viện hoạt động như thế nào. Càng thực hành, bạn sẽ càng thoải mái với các kịch bản **read barcode image C#**. + +Có ảnh khó giải mã? Để lại bình luận bên dưới hoặc mở một issue trên repo GitHub của dự án mẫu. Chúc lập trình vui vẻ! + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây bao quát các chủ đề liên quan chặt chẽ, 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 bao gồm các ví dụ mã đầy đủ, hoạt động 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. + +- [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 diff --git a/barcode/vietnamese/net/one-dimensional-barcode-types/_index.md b/barcode/vietnamese/net/one-dimensional-barcode-types/_index.md index e62a15ca4..933558b4f 100644 --- a/barcode/vietnamese/net/one-dimensional-barcode-types/_index.md +++ b/barcode/vietnamese/net/one-dimensional-barcode-types/_index.md @@ -78,6 +78,8 @@ tìm hiểu cách tạo mã vạch trong .NET bằng Aspose.BarCode cho .NET. H Tìm hiểu cách xử lý các trường hợp ngoại lệ trong khi tạo mã vạch một chiều bằng Aspose.BarCode cho .NET. Hướng dẫn từng bước này đảm bảo các giải pháp mã vạch có khả năng chịu lỗi. Bắt đầu ngay bây giờ! ### [Cấu hình tỷ lệ rộng-hẹp một chiều](./one-dimensional-wide-narrow-ratio-configuration/) Tạo mã vạch tùy chỉnh dễ dàng với Aspose.BarCode cho .NET. Hướng dẫn từng bước cho cấu hình tỷ lệ rộng-hẹp một chiều. +### [Tạo mã vạch từ văn bản bằng Aspose.BarCode – Hướng dẫn C#](./generate-barcode-from-text-using-aspose-barcode-c-guide/) +Hướng dẫn tạo mã vạch từ chuỗi văn bản trong C# bằng Aspose.BarCode, bao gồm các bước cấu hình và ví dụ thực tế. ## Phần kết luận @@ -89,4 +91,4 @@ Với bài viết này, bạn không chỉ có được kiến thức về các {{< /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/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md b/barcode/vietnamese/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md new file mode 100644 index 000000000..609c00a4a --- /dev/null +++ b/barcode/vietnamese/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-guide/_index.md @@ -0,0 +1,240 @@ +--- +category: general +date: 2026-07-15 +description: Tạo mã vạch từ văn bản bằng Aspose.BarCode trong C#. Tìm hiểu cách thay + đổi số cột, lưu hình ảnh mã vạch và tạo các giải pháp mã vạch Aspose nhanh chóng. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- generate barcode from text +- how to generate barcode +- how to change column count +- save barcode image +- create barcode aspose +language: vi +lastmod: 2026-07-15 +og_description: Tạo mã vạch từ văn bản bằng Aspose.BarCode. Hướng dẫn này cho thấy + cách thay đổi số cột, lưu hình ảnh mã vạch và tạo mã vạch Aspose chỉ trong vài dòng + mã. +og_image_alt: Generate barcode from text example – MicroPdf417 PNG output +og_title: Tạo mã vạch từ văn bản bằng Aspose.BarCode – Hướng dẫn nhanh C# +schemas: +- author: Aspose + dateModified: '2026-07-15' + description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + headline: Generate barcode from text using Aspose.BarCode – C# Guide + type: TechArticle +- description: Generate barcode from text using Aspose.BarCode in C#. Learn how to + change column count, save barcode image, and create barcode Aspose solutions fast. + name: Generate barcode from text using Aspose.BarCode – C# Guide + steps: + - name: What if my text is longer than the default capacity? + text: MicroPdf417 automatically switches to a multi‑row layout when the data exceeds + the maximum per row. You can still control the column count, but the library + may add extra rows behind the scenes. No extra code needed—just keep an eye + on the resulting image dimensions. + - name: How do I change the image format to JPEG or BMP? + text: Replace `BarCodeImageFormat.Png` with `BarCodeImageFormat.Jpeg` (or `Bmp`). + Remember that JPEG introduces compression artifacts, which can affect scanning + reliability. PNG is the safest default. + - name: I’m seeing a watermark in the output—what’s wrong? + text: That’s the evaluation version of Aspose.BarCode. To **create barcode Aspose** + without watermarks, load a valid license file as shown in the commented line + of Step 2. + - name: Can I generate other symbologies (QR, Code128, etc.)? + text: Absolutely. Just swap `EncodeTypes.MicroPdf417` with any other value from + the `EncodeTypes` enum, e.g., `EncodeTypes.QR` or `EncodeTypes.Code128`. The + rest of the code stays the same, which makes the approach highly reusable. + type: HowTo +tags: +- barcode +- Aspose +- C# +- image-processing +title: Tạo mã vạch từ văn bản bằng Aspose.BarCode – Hướng dẫn C# +url: /vi/net/one-dimensional-barcode-types/generate-barcode-from-text-using-aspose-barcode-c-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 bằng Aspose.BarCode – Hướng dẫn C# + +Việc tạo mã vạch từ văn bản bằng Aspose.BarCode thật bất ngờ đơn giản. Trong hướng dẫn này, chúng ta sẽ đi qua **cách tạo mã vạch**, điều chỉnh bố cục cột, và cuối cùng **lưu hình ảnh mã vạch** dưới dạng tệp PNG. Dù bạn đang xây dựng hệ thống bán vé, máy in nhãn kho, hay chỉ đang thử nghiệm các mã kiểu QR, các bước dưới đây sẽ giúp bạn nhanh chóng đạt được mục tiêu. + +## Những gì bạn sẽ học + +- Tạo mã vạch từ bất kỳ chuỗi Unicode nào (đúng vậy, ngay cả “Åspóse.Barcóde©” cũng hoạt động). +- Điều chỉnh **số cột** cho MicroPdf417 để phù hợp với nhãn hẹp hoặc rộng. +- Lưu kết quả vào đĩa với định dạng ảnh phù hợp. +- Mẹo xử lý ký tự đặc biệt và các lỗi thường gặp khi bạn **tạo mã vạch Aspose** giải pháp. + +Không cần công cụ bên ngoài, không cần hack dòng lệnh—chỉ cần C# thuần và thư viện Aspose.BarCode. + +## Yêu cầu trước + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +1. **.NET 6.0** hoặc phiên bản mới hơn đã được cài đặt (mã cũng hoạt động trên .NET Framework 4.7+). +2. Một **giấy phép** cho Aspose.BarCode, hoặc bạn có thể bắt đầu với phiên bản đánh giá miễn phí. +3. Một thư mục bạn có thể ghi vào – chúng tôi sẽ gọi nó là `YOUR_DIRECTORY` trong các ví dụ. + +Nếu bạn thiếu bất kỳ mục nào trong số này, hãy tải gói NuGet ngay: + +```bash +dotnet add package Aspose.BarCode +``` + +Xong rồi—không cần sao chép DLL bổ sung thủ công. + +## Bước 1 – Thiết lập dự án và các import + +Đầu tiên, tạo một ứng dụng console (hoặc chèn mã vào bất kỳ dự án C# nào). Phần quan trọng là nhập các namespace đúng: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; +using Aspose.BarCode.BarCodeImageFormat; // for the image format enum +``` + +Tại sao lại cần các câu lệnh using này? `BarcodeGenerator` nằm trong `Aspose.BarCode.Generation`, trong khi enum `BarCodeImageFormat` nằm trong `Aspose.BarCode`. Giữ các import gọn gàng giúp mã sau này đọc như tiếng Anh thuần. + +## Bước 2 – Tạo Barcode Generator (cách tạo mã vạch) + +Bây giờ chúng ta thực sự **tạo mã vạch từ văn bản**. Enum `EncodeTypes` cho Aspose biết sẽ sử dụng ký hiệu nào; ở đây chúng ta chọn `MicroPdf417` vì nó xử lý các chuỗi dài trong lưới gọn gàng. + +```csharp +// Step 2: Create a barcode generator for MicroPdf417 with the desired text +var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + +// Optional: If you have a license, load it now to avoid the evaluation watermark +// generator.License = new License(); // generator.License.SetLicense("Aspose.Total.NET.lic"); +``` + +Lưu ý chuỗi chứa các ký tự có dấu và ký hiệu bản quyền. Aspose.BarCode tự động mã hoá Unicode, vì vậy bạn không cần tiền xử lý văn bản. + +## Bước 3 – Tinh chỉnh giao diện (cách thay đổi số cột) + +MicroPdf417 cho phép bạn kiểm soát số cột, điều này ảnh hưởng trực tiếp đến chiều rộng của mã vạch. Bố cục chặt hơn rất phù hợp cho nhãn hẹp; bố cục rộng hơn cải thiện khả năng đọc trên các bản in lớn. + +```csharp +// Step 3: Set the X‑dimension (module width) to 2 pixels for finer resolution +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Step 3b: Define the number of columns for the PDF417 layout (e.g., 4 columns) +generator.Parameters.Barcode.Pdf417.Columns = 4; // <-- how to change column count +``` + +Tại sao lại dùng mô-đun 2 pixel? Nó tạo ra hình ảnh sắc nét mà không làm tăng kích thước tệp. Bạn có thể thử nghiệm—giá trị từ 1 đến 4 thường hoạt động tốt. Nếu cần số cột khác, chỉ cần thay đổi thuộc tính `Columns`; Aspose sẽ tự động tính lại bố cục. + +## Bước 4 – Lưu hình ảnh mã vạch (save barcode image) + +Với generator đã được cấu hình, chúng ta sẵn sàng **lưu hình ảnh mã vạch**. Phương thức `Save` nhận một đường dẫn tệp và một enum định dạng ảnh. PNG là không mất dữ liệu, vì vậy mã vạch vẫn giữ độ sắc nét ngay cả khi phóng to. + +```csharp +// Step 4: Save the generated barcode as a PNG image +string outputPath = @"YOUR_DIRECTORY\MicroPdf417.png"; +generator.Save(outputPath, BarCodeImageFormat.Png); +Console.WriteLine($"Barcode saved to {outputPath}"); +``` + +Mẹo nhanh: luôn sử dụng đường dẫn tuyệt đối hoặc đảm bảo thư mục làm việc là như bạn mong đợi; nếu không tệp có thể bị lưu vào thư mục bin và bạn sẽ thắc mắc tại sao không tìm thấy nó. + +## Ví dụ hoàn chỉnh hoạt động + +Kết hợp tất cả lại, đây là một chương trình tự chứa mà bạn có thể sao chép‑dán vào `Program.cs` và chạy: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create the generator with Unicode text + var generator = new BarcodeGenerator(EncodeTypes.MicroPdf417, "Åspóse.Barcóde©"); + + // 2️⃣ Adjust visual parameters + generator.Parameters.Barcode.XDimension.Pixels = 2; // finer modules + generator.Parameters.Barcode.Pdf417.Columns = 4; // how to change column count + + // 3️⃣ Choose output location + string outputPath = @"C:\Temp\MicroPdf417.png"; + + try + { + // 4️⃣ Persist the image (save barcode image) + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"✅ Barcode generated and saved to: {outputPath}"); + } + catch (Exception ex) + { + // Pro tip: handle I/O errors gracefully + Console.Error.WriteLine($"❌ Failed to save barcode: {ex.Message}"); + } + } + } +} +``` + +**Kết quả mong đợi** (console): + +``` +✅ Barcode generated and saved to: C:\Temp\MicroPdf417.png +``` + +Và nếu bạn mở `MicroPdf417.png`, bạn sẽ thấy một mã vạch MicroPdf417 sắc nét mã hoá chuỗi gốc, bao gồm cả các ký tự đặc biệt mà chúng ta đã cung cấp. + +## Câu hỏi thường gặp & Trường hợp đặc biệt + +### Nếu văn bản của tôi dài hơn dung lượng mặc định thì sao? + +MicroPdf417 tự động chuyển sang bố cục đa hàng khi dữ liệu vượt quá tối đa mỗi hàng. Bạn vẫn có thể kiểm soát số cột, nhưng thư viện có thể thêm các hàng phụ. Không cần mã bổ sung—chỉ cần chú ý đến kích thước ảnh kết quả. + +### Làm sao để thay đổi định dạng ảnh sang JPEG hoặc BMP? + +Thay `BarCodeImageFormat.Png` bằng `BarCodeImageFormat.Jpeg` (hoặc `Bmp`). Hãy nhớ JPEG tạo ra các artefact nén, có thể ảnh hưởng đến độ tin cậy khi quét. PNG là mặc định an toàn nhất. + +```csharp +generator.Save(outputPath, BarCodeImageFormat.Jpeg); +``` + +### Tôi thấy watermark trong kết quả—có vấn đề gì? + +Đó là phiên bản đánh giá của Aspose.BarCode. Để **tạo mã vạch Aspose** không có watermark, tải tệp giấy phép hợp lệ như được hiển thị trong dòng comment của Bước 2. + +### Tôi có thể tạo các ký hiệu khác (QR, Code128, v.v.) không? + +Chắc chắn. Chỉ cần thay `EncodeTypes.MicroPdf417` bằng bất kỳ giá trị nào khác trong enum `EncodeTypes`, ví dụ `EncodeTypes.QR` hoặc `EncodeTypes.Code128`. Phần còn lại của mã vẫn giữ nguyên, giúp cách tiếp cận này rất tái sử dụng. + +## Mẹo chuyên nghiệp cho việc tạo mã vạch sẵn sàng cho sản xuất + +- **Cache generator** nếu bạn tạo nhiều mã vạch với cùng cài đặt; nó giảm tải tạo đối tượng. +- **Xác thực chuỗi đầu vào** cho các giới hạn độ dài riêng của ký hiệu đã chọn (Aspose sẽ ném `ArgumentException` nếu quá dài). +- **Sử dụng câu lệnh `using`** hoặc `Dispose` generator khi hoàn thành để giải phóng tài nguyên gốc kịp thời. +- **Đặt DPI** qua `generator.Parameters.ImageResolution.DpiX/DpiY` nếu bạn cần in độ phân giải cao cho nhãn lớn. + +## Kết luận + +Bạn giờ đã biết chính xác **cách tạo mã vạch từ văn bản** với Aspose.BarCode, cách **thay đổi số cột**, và cách đúng để **lưu hình ảnh mã vạch** dưới dạng PNG. Ví dụ hoàn chỉnh, có thể chạy được ở trên minh họa một cách sạch sẽ, sẵn sàng cho sản xuất + +## 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 đã 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 tạo mã vạch – Cấu hình Code 39 với Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-configuration/) +- [Tạo hình ảnh mã vạch – Code 93 với Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-93-configuration/) +- [Cách tạo mã DataMatrix (ECC 200) với Aspose.BarCode cho .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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