diff --git a/barcode/arabic/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/arabic/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..a0a4a004d --- /dev/null +++ b/barcode/arabic/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-07-18 +description: مثال على مولد الباركود يوضح كيفية ضبط الأبعاد وإنشاء صورة باركود DataBar + Stacked Omni‑Directional باستخدام C#. تعلم أنواع ترميز الباركود بسرعة. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: ar +lastmod: 2026-07-18 +og_description: يُرشدك مثال مولد الباركود إلى كيفية ضبط الأبعاد، اختيار أنواع ترميز + الباركود، وإنشاء مشاريع صور الباركود بلغة C# بأقل قدر من الشيفرة. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: مثال على مولد الباركود – إنشاء صورة DataBar سريع في C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: مثال على مولد الباركود – إنشاء صورة DataBar باستخدام C# +url: /ar/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# مثال مولد الباركود – إنشاء صورة DataBar باستخدام C# + +هل احتجت يوماً إلى **مثال مولد باركود** يطبع باركود حقيقي دون أن تجعلك تشعر بالإحباط؟ لست وحدك. يواجه معظم المطورين صعوبة عندما يحاولون معرفة **كيفية ضبط الأبعاد** لباركود DataBar Stacked Omni‑Directional، خاصةً عندما تكون الوثائق مغطاة بطبقات من المصطلحات التقنية. + +في هذا الدرس سنستعرض برنامج C# كامل جاهز للتنفيذ يوضح **كيفية إنشاء صور databar**، يختار **أنواع ترميز الباركود** المناسبة، وأخيراً **إنشاء ملفات صورة باركود c#** يمكنك إدراجها في أي مشروع. لا إطالة—فقط الكود الذي يمكنك نسخه‑لصقه، بالإضافة إلى شرح كل سطر. + +## ما ستحتاجه + +- **.NET 6** (أو أي نسخة حديثة من .NET) – الـ API الذي نستخدمه يستهدف .NET Standard، لذا يعمل أيضاً على .NET Framework. +- **Aspose.BarCode for .NET** – المكتبة التي توفر `BarcodeGenerator`. يمكنك الحصول عليها من NuGet باستخدام `Install-Package Aspose.BarCode`. +- **بيئة تطوير C#** – Visual Studio، Rider، أو VS Code تكفي. +- مجلد على القرص حيث سيتم حفظ ملفات PNG (يقوم الكود بإنشاء `DatabarAspectRatio15.png` و `DatabarAspectRatio30.png`). + +هل لديك كل ذلك؟ رائع—لنبدأ. + +## مثال مولد الباركود – تهيئة المولد + +أولاً: نحتاج إلى كائن `BarcodeGenerator` مُعد لرمز **DataBar Stacked Omni‑Directional**. هذا هو **نوع ترميز الباركود** الذي سنعمل معه. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **لماذا هذا مهم:** `EncodeTypes.DatabarStackedOmniDirectional` يخبر Aspose بالرمز المحدد الذي يجب رسمه. إذا اخترت النوع الخاطئ، لن يتعرف القارئ على الباركود مهما كان الشكل جذاباً. + +## كيفية ضبط الأبعاد للباركود + +قابلية قراءة الباركود تعتمد على **بعد X** (عرض أصغر شريط). في معظم الحالات قيمة 2 بكسل تكفي، لكن يمكنك تعديلها لتناسب الطابعة أو الشاشة الخاصة بك. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **نصيحة محترف:** إذا تساءلت يوماً **كيفية ضبط الأبعاد** لعائلة باركود أخرى، فإن سلسلة الخصائص نفسها (`Parameters.Barcode.XDimension`) تنطبق—فقط غير قيمة `Pixels`. + +## كيفية إنشاء باركود DataBar Stacked Omni‑Directional + +الآن بعد أن أصبح المولد جاهزاً، سنلعب بخاصية **نسبة الأبعاد**. هذه الخاصية تتحكم في العلاقة بين الارتفاع والعرض للـ DataBar، مما يتيح لك إنتاج رمز قصير ومربع أو طويل ورفيع. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **ما الذي يحدث؟** `AspectRatio = 15` يطلب من المحرك جعل الأشرطة أطول بـ 15 مرة من عرضها. يتم حفظ ملف PNG الناتج بجوار الملف التنفيذي. + +## إنشاء صورة باركود C# – تغيير نسبة الأبعاد + +لنعرض المرونة بتغيير النسبة إلى 30 وحفظ ملف ثاني. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +عند تشغيل البرنامج ستحصل على ملفين PNG: + +| الملف | نسبة الأبعاد | الحجم التقريبي | +|------|--------------|----------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +افتحهما بأي عارض صور—يجب أن ترى رموز DataBar نظيفة وقابلة للمسح. + +## نظرة عامة على أنواع ترميز الباركود (اختياري لكنه مفيد) + +إذا كنت مهتماً بأنواع **barcode encode types** الأخرى التي تدعمها Aspose، إليك ورقة مرجعية سريعة: + +| تعداد EncodeTypes | الوصف | +|------------------|-------| +| `EncodeTypes.Code128` | أحرف وأرقام عالية الكثافة | +| `EncodeTypes.QR` | رمز مصفوفة ثنائي الأبعاد | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar للبيع بالتجزئة | +| `EncodeTypes.DatabarStackedOmniDirectional` | **تركيزنا** – مضغوط، متعدد الاتجاهات | + +معرفة الـ enum الصحيح يوفر عليك الكثير من التجربة والخطأ عند الانتقال بين المشاريع. + +## الأخطاء الشائعة وكيفية تجنبها + +- **عدم وجود حزمة NuGet** – لن يتم تجميع الكود بدون `Aspose.BarCode`. نفّذ `dotnet add package Aspose.BarCode` أولاً. +- **مسار ملف غير صحيح** – إذا استخدمت مسارًا مطلقًا، تأكد من الشرطتين المائلتين (`\\`) على نظام Windows. المسارات النسبية (كما هو موضح) تجعل المشروع أكثر قابلية للنقل. +- **نسبة أبعاد مفرطة** – النسب فوق 50 قد تجعل الباركود طويلًا جدًا بالنسبة للماسحات التقليدية. ابقَ في نطاق 15‑30 لمعظم الاستخدامات. + +## الكود الكامل (جاهز للنسخ‑اللصق) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +شغّل البرنامج (`dotnet run` أو اضغط **F5** في Visual Studio) وسترى رسالة في وحدة التحكم تؤكد أن الملفات تم حفظها على القرص. + +![مثال مخرجات مولد الباركود يظهر باركود DataBar بنسبة أبعاد 15](placeholder/path/to/image.png){: .align-center alt="مثال مخرجات مولد الباركود يظهر باركود DataBar بنسبة أبعاد 15"} + +## الخلاصة + +لقد أنجزنا الآن **مثال مولد باركود** يوضح **كيفية ضبط الأبعاد**، يختار **أنواع ترميز الباركود** الصحيحة، وأخيراً **إنشاء ملفات صورة باركود c#** يمكنك دمجها في أي مشروع. الكود صغير، المفاهيم واضحة، وأصبحت الآن تمتلك أساسًا قويًا لتوسيع الحل—ربما بإضافة تسميات نصية، تدوير الصورة، أو الانتقال إلى رموز أخرى. + +### ما التالي؟ + +- جرّب **أبعاد X مختلفة** لترى كيف تتغير تحمل الماسح. +- جرب أنواع **EncodeTypes** أخرى مثل `Code128` أو `QR` لتوسيع أدواتك. +- أتمتة إنشاء دفعات: كرّر على ملف CSV يحتوي على معرفات منتجات وأنشئ PNG لكل منها. + +إذا واجهت أي مشكلة، اترك تعليقًا أدناه أو راجع وثائق Aspose.BarCode—فهي مليئة بأمثلة تكمل ما قدمناه هنا. + +برمجة سعيدة، ولتُمسح باركوداتك دائمًا من المرة الأولى! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة كود كاملة مع شروحات خطوة‑بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية إنشاء باركود - أنواع الباركود أحادية الأبعاد](/barcode/english/net/one-dimensional-barcode-types/) +- [إنشاء صورة باركود C# – مثال GS1 DataMatrix](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [كيفية إنشاء باركود 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/arabic/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/arabic/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..d98f19c71 --- /dev/null +++ b/barcode/arabic/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,278 @@ +--- +category: general +date: 2026-07-18 +description: أنشئ باركود Planet بسرعة باستخدام C#. تعلم كيفية إنشاء الأشرطة المملوءة + والفارغة، ضبط البُعد X، وحفظ صور PNG – كل ذلك في دليل واحد. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: ar +lastmod: 2026-07-18 +og_description: إنشاء باركود كوكب على الفور. يوضح لك هذا الدليل كيفية ضبط البُعد X، + والتبديل بين الشرائط المملوءة والفارغة، وتصدير ملفات PNG باستخدام Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: إنشاء باركود كوكب في C# – دليل برمجة كامل +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: إنشاء باركود كوكب في C# – دليل كامل خطوة بخطوة +url: /ar/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء باركود Planet في C# – دليل خطوة بخطوة كامل + +هل احتجت يوماً إلى **إنشاء باركود planet** ولكنك لم تكن متأكدًا من الخصائص التي يجب تعديلها؟ لست وحدك. يواجه العديد من المطورين صعوبة عندما لا تكون الأعمدة المملوءة الافتراضية هي ما يتطلبه المعيار، أو عندما يجب أن يتطابق عرض العمود مع DPI الطابعة. + +في هذا الدرس ستتعلم بالضبط كيفية **إنشاء باركود planet** باستخدام مكتبة Aspose.BarCode، وكيفية التحكم في **بكسلات XDimension**، وكيفية التبديل بين **الأعمدة المملوءة** و**الأعمدة الفارغة** دون الحاجة إلى إعادة كتابة أي كود. في النهاية ستحصل على ملفي PNG—أحدهما بأعمدة صلبة والآخر بأعمدة مجوفة—جاهزين لأي نظام بريدي يتطلب رموز Planet. + +## المتطلبات المسبقة + +- .NET 6.0 أو أحدث (الكود يعمل أيضاً على .NET Framework 4.7 +) +- حزمة NuGet Aspose.BarCode for .NET (`Install-Package Aspose.BarCode`) +- معرفة أساسية بلغة C# (سترى لاحقًا لماذا نستخدم عبارات `using`) +- مجلد قابل للكتابة على القرص حيث سيتم حفظ ملفات PNG + +إذا كان لديك كل ذلك، يمكننا القفز مباشرة إلى التنفيذ. + +## الخطوة 1 – إعداد المشروع وإضافة المكتبة + +أولاً، أنشئ تطبيق console جديد (أو أي مشروع C#) وأضف مرجع مكتبة **مولد باركود Planet**. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **نصيحة احترافية:** في Visual Studio، انقر بزر الماوس الأيمن على المشروع → *Manage NuGet Packages* → ابحث عن **Aspose.BarCode** وانقر *Install*. سيمنحك ذلك الوصول إلى `BarcodeGenerator` وجميع **معلمات BarcodeGenerator** التي ستحتاجها. + +## الخطوة 2 – تهيئة مولد باركود Planet + +الآن نقوم فعليًا **بإنشاء مولد باركود planet** وإعطائه البيانات التي نريد ترميزها (`"123456"` في هذا المثال). يحدد تعداد `EncodeTypes.Planet` للمكتبة أي رموز يجب استخدامها. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **لماذا هذا مهم:** علم `EncodeTypes.Planet` يطبق تلقائيًا خوارزمية التحقق من الصحة وقواعد التخطيط الصحيحة لباركود Planet البريدي، لذا لا تحتاج إلى حسابها يدويًا. + +## الخطوة 3 – ضبط X‑Dimension (عرض العمود) + +معظم الطابعات تتوقع أن يكون كل عمود بعدد محدد من البكسلات. هنا نضبط **بكسلات XDimension** إلى `4`، وهو قيمة شائعة لطابعات الحرارة بدقة 203 dpi. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **حالة حافة:** إذا كنت تستهدف طابعة بدقة 300 dpi، قد تحتاج إلى `3` أو `5` بكسل بدلاً من ذلك. عدّل هذه القيمة بناءً على وثائق جهازك. + +## الخطوة 4 – حفظ نسخة الأعمدة المملوءة + +بشكل افتراضي يولد المولد **أعمدة مملوءة** (مستطيلات سوداء صلبة). لنكتبها إلى القرص: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +استبدل `YOUR_DIRECTORY` بمسار مطلق أو نسبي يمكن لتطبيقك الكتابة فيه. بعد تنفيذ هذا السطر ستجد ملف PNG يبدو كباركود Planet التقليدي—مثالي للاختبار مع ماسح البريد. + +## الخطوة 5 – التبديل إلى الأعمدة الفارغة + +أحيانًا تتطلب خدمات البريد نمط “الأعمدة الفارغة”، حيث تُنقش الأعمدة على خلفية بيضاء بدلاً من أن تُلون بالأسود. المكتبة توفر مفتاحًا بسيطًا لهذا: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +ضبط `FilledBars` إلى `false` يخبر المُرَسِّم بعكس منطق تعبئة الأعمدة. لا حاجة لإنشاء كائن `BarcodeGenerator` جديد؛ نكتفي بتعديل **معلمات BarcodeGenerator** الحالية. + +## الخطوة 6 – حفظ نسخة الأعمدة الفارغة + +أخيرًا، صدّر الصورة الثانية: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +الآن لديك ملفي PNG مميزين، كل منهما يلتزم بمتطلبات بصرية مختلفة. + +## مثال كامل يعمل + +بدمج جميع الأجزاء معًا، إليك البرنامج الكامل جاهز للنسخ واللصق: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**الناتج المتوقع** (على وحدة التحكم): + +``` +Both Planet barcode images have been generated successfully. +``` + +وفي `C:\Barcodes\` ستجد: + +- `PostalPlanetFilledBars.png` – أعمدة سوداء صلبة +- `PostalPlanetEmptyBars.png` – أعمدة بيضاء مع حدود سوداء + +افتحهما بأي عارض صور؛ يجب أن يتطابق كلاهما مع مواصفات Planet. + +## أسئلة شائعة ونصائح + +### “هل يمكنني تغيير تنسيق الصورة؟” + +بالطبع. طريقة `Save` تقبل `BarCodeImageFormat.Jpeg`، `Bmp`، `Gif`، إلخ. ما عليك سوى استبدال `BarCodeImageFormat.Png` بالتنسيق الذي تفضله. + +### “ماذا لو احتجت إلى ارتفاع باركود مختلف؟” + +استخدم `planetBarcode.Parameters.Barcode.BarHeight` (بالنقاط) لزيادة أو تقليل الحجم العمودي. مثال: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “هل يمكن إضافة تسمية قابلة للقراءة البشرية؟” + +نعم. عيّن الخاصية `CodeText` على `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “هل يجب إغلاق المولد؟” + +كائن `BarcodeGenerator` ينفّذ `IDisposable`. ضعّه داخل كتلة `using` إذا كنت تنشئ العديد من الباركودات داخل حلقة: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “ماذا عن معالجة الأخطاء؟” + +احط استدعاءات `Save` بكتلة `try…catch` لالتقاط `IOException` (مشكلات القرص) أو `ArgumentException` (معلمات غير صالحة). مثال: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## ملخص + +غطّينا كل ما تحتاجه لإنشاء صور **باركود planet** في C#: + +1. تهيئة **مولد باركود Planet** بالبيانات الخاصة بك. +2. ضبط **بكسلات XDimension** لتتناسب مع مواصفات الطابعة. +3. حفظ PNG بأعمدة مملوءة. +4. تبديل `FilledBars` لإنتاج **أعمدة فارغة**. +5. حفظ PNG الثاني. + +من هنا يمكنك استكشاف المزيد من **معلمات BarcodeGenerator**، تجربة رموز أخرى (`EncodeTypes.Postnet`، `EncodeTypes.Code128`، إلخ)، أو دمج الصور في سير عمل البريد. + +--- + +**هل أنت مستعد للخطوة التالية؟** جرّب إضافة رمز QR إلى نفس المستند، أو توليد دفعة من باركودات Planet من قائمة CSV باستخدام حلقة `foreach`. واجهة Aspose.BarCode API مرنة بما يكفي للتعامل مع عمليات الدفعات، الألوان المخصصة، وحتى إخراج SVG قائم على المتجهات. + +إذا واجهت أي صعوبات، اترك تعليقًا أدناه أو راجع الوثائق الرسمية لـ Aspose.BarCode للحصول على شروحات أعمق للميزات المتقدمة. برمجة سعيدة! + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة شفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [Create Barcode with Aspose - Set X & Y Dimensions in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/arabic/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..c2fcb788e --- /dev/null +++ b/barcode/arabic/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-07-18 +description: إنشاء رمز شريطي RM4SCC في C# بسرعة؛ تعلم كيفية ضبط ارتفاع الرمز الشريطي + وإنشاء رمز Planet بأبعاد مخصصة. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: ar +lastmod: 2026-07-18 +og_description: إنشاء رمز شريطي RM4SCC في C# واكتشاف كيفية ضبط ارتفاع الرمز الشريطي. + كما يمكنك الاطلاع على كيفية إنشاء رمز شريطي Planet باستخدام نفس المكتبة. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: إنشاء رمز شريطي RM4SCC في C# – ضبط الارتفاع المخصص بسرعة +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: إنشاء باركود RM4SCC في C# – دليل كامل لضبط الارتفاع +url: /ar/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء باركود RM4SCC في C# – دليل كامل لتعيين الارتفاع + +هل احتجت يومًا إلى **إنشاء باركود RM4SCC** في تطبيق .NET لكنك لم تكن متأكدًا من كيفية التحكم في حجمه؟ لست وحدك. سواءً كنت تبني نظامًا للبريد أو لوحة تحكم لوجستية، فإن الحصول على الارتفاع المناسب للباركود يمكن أن يكون الفارق بين عملية مسح ناجحة وفاشلة. + +في هذا الدرس سنستعرض العملية بالكامل: من تثبيت المكتبة، إلى **إنشاء باركود Planet** كمثال جانبي، وأخيرًا إلى **كيفية تعيين ارتفاع الباركود** لكلا النوعين. في النهاية ستحصل على تطبيق كونسول جاهز للتشغيل ينتج ملفات PNG بالأبعاد الدقيقة التي تحتاجها. + +--- + +## ما ستحتاجه + +- **.NET 6 SDK** (أو أي نسخة حديثة من .NET) – الشيفرة تعمل أيضًا على .NET Framework، لكن .NET 6 هو الخيار المثالي. +- **Aspose.BarCode for .NET** حزمة NuGet – هذه هي المكتبة التي توفر الفئة `BarcodeGenerator`. +- معرفة أساسية بـ C# – سنجعل الصياغة صديقة للمبتدئين. +- بيئة تطوير متكاملة أو محرر نصوص (Visual Studio، VS Code، Rider—اختر ما يناسبك). + +> **نصيحة احترافية:** إذا كنت تستخدم خط أنابيب CI/CD، أضف إشارة NuGet في ملف `.csproj` حتى لا ينسى البناء الاعتماد. + +## الخطوة 1: إعداد المشروع + +افتح الطرفية وأنشئ مشروع كونسول جديد: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +هذا كل شيء—مشروعك الآن يَشير إلى المكتبة التي تشغّل كل ما يلي. + +### إضافة توجيهات الـ Using + +افتح `Program.cs` والصق التالي في الأعلى: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +## الخطوة 2: تعريف طريقة مساعدة لحفظ الصور + +لتجنب تكرار منطق الحفظ نفسه، سنغلفه في طريقة صغيرة. هذا أيضًا يوضح **كيفية تعيين ارتفاع الباركود** لاحقًا. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **لماذا هذا مهم:** تركيز منطق الحفظ يعني أنك تحتاج لتغيير الصيغة أو المجلد في مكان واحد فقط إذا تغيرت المتطلبات. + +## الخطوة 3: إنشاء باركود Planet (جزء “إنشاء باركود planet”) + +قبل الغوص في تفاصيل RM4SCC، لننشئ **باركود Planet**. هذا يمنحك فحصًا بصريًا سريعًا للتأكد من أن المكتبة تعمل. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**الناتج المتوقع:** يظهر ملفان PNG في مجلد `output`—أحدهما بارتفاع محسوب تلقائيًا من المكتبة، والآخر بارتفاع 100 بكسل بالضبط. + +## الخطوة 4: إنشاء باركود RM4SCC – الهدف الأساسي + +الآن نأتي إلى نجمة العرض: **إنشاء باركود RM4SCC**. RM4SCC هو رمز البريد الملكي رباعي الحالة، يُستخدم على نطاق واسع في نظام البريد بالمملكة المتحدة. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**ما ستراه:** +- `RM4SCCDefault.png` – المكتبة تقرر ارتفاعًا مريحًا بناءً على بعد X. +- `RM4SCCHeight100.png` – باركود واضح بارتفاع 100 بكسل جاهز للطباعة على الظرف. + +> **لماذا ضبط الارتفاع؟** بعض طابعات الملصقات تتطلب ارتفاعًا أدنى للخطوط لضمان مسح موثوق. من خلال تثبيت الارتفاع تضمن التوافق عبر الأجهزة. + +## الخطوة 5: فهم إعدادات الارتفاع (الإجابة على سؤال “كيفية تعيين ارتفاع الباركود”) + +كلا المثالين Planet و RM4SCC يستخدمان الخاصية نفسها: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** هو كائن `BarHeight` يجمع عدة وحدات قياس (بكسل، مليمتر، بوصة). +- **`.Pixels`** هي الوحدة الأكثر مباشرة للإخراج الموجه للشاشة، لكن يمكنك أيضًا استخدام `.Millimeters` أو `.Inches` إذا كنت تستهدف وسائط الطباعة. + +### الحالات الخاصة والنصائح + +| الحالة | النهج الموصى به | +|-----------|----------------------| +| **بعد X صغير جدًا (مثلاً 1 بكسل)** | زيادة `BarHeight` للحفاظ على قابلية قراءة الباركود. | +| **الطباعة على طابعات ملصقات عالية الدقة** | استخدام `.Millimeters` للحصول على حجم مستقل عن الجهاز. | +| **أنواع باركود مختلطة في صورة واحدة** | تعيين `BarHeight` *بعد* `XDimension` لكل مولد لتجنب الوراثة غير المقصودة. | +| **بيانات ديناميكية (مثل أكواد يدخلها المستخدم)** | غلف إنشاء المولد في طريقة تقبل معلمات `code` و `height`. | + +## الخطوة 6: مثال كامل يعمل + +فيما يلي برنامج واحد مستقل يمكنك نسخه ولصقه في `Program.cs`. يتضمن كل شيء من إعداد المشروع إلى حفظ الصور. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +شغّله باستخدام: + +```bash +dotnet run +``` + +يجب أن ترى مخرجات الكونسول التي تؤكد حفظ كل ملف، ومجلد `output` سيحتوي على أربعة ملفات PNG بأسماء مطابقة لما هو موضح أعلاه. + +## الخلاصة + +أنت الآن تعرف **كيفية إنشاء باركود RM4SCC** في C# والتحكم في أبعاده ببضع تعيينات للخصائص. كما غطينا **إنشاء باركود planet** كفحص سريع، واستكشفنا تفاصيل **كيفية تعيين ارتفاع الباركود** لمختلف سيناريوهات الطباعة. + +الخطوة التالية؟ جرّب استبدال تعداد `EncodeTypes` بسمبوليات أخرى (Code128، QR، DataMatrix) وجرب `BarHeight` بالمليمترات لطابعات عالية الدقة. إذا كنت بحاجة لتضمين الباركود في PDF، اجمع Aspose.BarCode مع Aspose.PDF—مجموعة قوية أخرى. + +هل لديك أسئلة أو تريد مشاركة تعديلاتك؟ اترك تعليقًا أدناه، وبرمجة سعيدة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة شاملة للكود مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية إنشاء باركود Aztec بنسبة عرض مخصصة باستخدام Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [كيفية إنشاء منطقة هادئة للباركود ITF-14 باستخدام Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [كيفية إنشاء منطقة هادئة للباركود Code 16K باستخدام Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/arabic/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..2661c92d9 --- /dev/null +++ b/barcode/arabic/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-07-18 +description: تعلم كيفية إنشاء صور الباركود باستخدام مولد باركود .net وتغيير ارتفاع + الباركود بسهولة لرموز GS1‑Databar Omni‑Directional. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: ar +lastmod: 2026-07-18 +og_description: يتيح لك مولد الباركود .net إنشاء صور الباركود بسرعة. يوضح هذا الدليل + كيفية إنشاء الباركود، وضبط ارتفاع الخط، وحفظ ملفات PNG. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: تغيير ارتفاع الباركود باستخدام مولد الباركود .net +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET مولد الباركود – تغيير ارتفاع الباركود +url: /ar/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – تغيير ارتفاع الباركود + +هل تساءلت يومًا **كيف تولد صور الباركود** دون الحاجة إلى التعامل مع عشرات الأدوات الخارجية؟ في عالم .NET هناك طريقة نظيفة بشكل مفاجئ للقيام بذلك، والقطعة الأساسية هي **.net barcode generator**. ببضع أسطر فقط من C# يمكنك إنشاء رمز GS1‑Databar Omni‑Directional، تعديل ارتفاع الخطوط، وحفظ النتيجة كملف PNG. + +إذا كنت تبني نظام جرد، أو طابعة ملصقات شحن، أو أي تطبيق يحتاج إلى رمز يمكن مسحه ضوئيًا، سيوفر لك هذا الدرس الانتقال من الصفر إلى باركود يعمل في دقائق. سنستعرض الكود الكامل، نشرح لماذا كل إعداد مهم، ونظهر لك كيفية **تغيير ارتفاع الباركود** دون خرق المواصفات. + +## ما ستحتاجه + +- .NET 6.0 أو أحدث (تعمل الواجهة البرمجية بنفس الطريقة على .NET Framework 4.7+) +- إشارة إلى مكتبة الباركود (مثلاً Aspose.BarCode for .NET – تُستخدم نفس الفئات في العديد من الحزم التجارية) +- بيئة تطوير (Visual Studio، Rider، أو VS Code مع امتداد C#) +- مجلد لديك صلاحية كتابة فيه – سيحفظ الدرس ملفات PNG هناك + +هذا كل شيء. لا توجد حزم NuGet إضافية بخلاف مكتبة الباركود نفسها. + +## استخدام .net barcode generator لتغيير ارتفاع الباركود + +فيما يلي **برنامج كونسول كامل وقابل للتنفيذ**. الصقه في مشروع C# جديد، عدل مجلد الإخراج، واضغط F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### لماذا كل سطر مهم + +| Line | Reason | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | يقوم بإنشاء **.net barcode generator** مع الرموز المطلوبة وبيانات الحمولة. يحدد تعداد `EncodeTypes.DatabarOmniDirectional` للمكتبة استخدام تنسيق GS1‑Databar Omni‑Directional. | +| `XDimension.Pixels = 2;` | بعد X هو عرض أرفع شريط. ضبطه على *2 بكسل* يمنح صورة واضحة على معظم الشاشات مع الحفاظ على حجم الملف منخفضًا. | +| `BarHeight.Pixels = 30;` | هذه هي خطوة **تغيير ارتفاع الباركود** التي تحدد ارتفاع كل شريط. ارتفاع 30 بكسل يُعد قيمة افتراضية جيدة للملصقات الصغيرة. | +| `generator.Save(...);` | يحفظ الباركود في ملف PNG. PNG غير مضغوط، مما يعني أن الماسحات الضوئية ترى النمط الدقيق الذي تم توليده. | +| `BarHeight.Pixels = 60;` | هنا نقوم **بتغيير ارتفاع الباركود** مرة أخرى—هذه المرة إلى 60 بكسل. تقوم المكتبة بإعادة رسم الرمز تلقائيًا بالأبعاد الجديدة عند استدعاء `Save` للمرة الثانية. | +| `Console.WriteLine(...);` | يقدم لك رد فعل سريع يُظهر أن العملية انتهت دون إلقاء استثناء. | + +> **نصيحة احترافية:** إذا كنت تحتاج إلى إخراج بدقة أعلى للطباعة، استبدل `BarCodeImageFormat.Png` بـ `BarCodeImageFormat.Tiff` وزد قيمة الخاصية `Resolution` (مثال: `generator.Parameters.ImageResolution = 300;`). سيظل ارتفاع الخط محفوظًا، فقط سيتم عرضه بدقة DPI أعلى. + +## كيفية توليد صور الباركود بإعدادات مختلفة + +المقتطف أعلاه يغطي الأساسيات، لكن السيناريوهات الواقعية غالبًا ما تتطلب تعديلات إضافية: + +### ضبط بعد X للطباعة الكبيرة +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +زيادة بعد X تجعل الباركود بأكمله أكبر دون تعديل البيانات المشفرة. هذا مفيد عند الطباعة على ملصقات كبيرة. + +### تبديل صيغ الإخراج +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG يتوسع بلا حدود، وهو مثالي للماسحات الضوئية المستندة إلى الويب التي تحتاج إلى رسومات متجهة واضحة. + +### إضافة نص قابل للقراءة البشرية +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +تفعيل `CodeTextVisible` يضيف البيانات الخام أسفل الباركود، وهو مفيد للتحقق أثناء الاختبار. + +## المشكلات الشائعة عند **تغيير ارتفاع الباركود** + +1. **الارتفاع صغير جدًا** – بعض الماسحات الضوئية تتطلب ارتفاعًا أدنى للخط (غالبًا 10 مم بوحدات فعلية). إذا ضبطت `BarHeight.Pixels` منخفضًا جدًا، قد تكون الصورة المولدة غير قابلة للقراءة على ماسح حقيقي. اختبر دائمًا مع الأجهزة المستهدفة. +2. **عدم توافق بعد X والارتفاع** – ارتفاع شريط كبير مع بعد X صغير قد يبدو مشوهًا وقد يسبب أخطاء في فك الترميز. استهدف نسبة متوازنة (تقريبًا 3:1 إلى 5:1) ما لم تحدد المواصفات غير ذلك. +3. **نسيان إعادة ضبط المعلمات** – يحتفظ المولد بالحالة بين عمليات الحفظ. إذا غيرت `BarHeight` لصورة واحدة ثم أعدت استخدام نفس المثيل لباركود آخر، سيظل الارتفاع السابق قائمًا. إما أعد ضبط الخاصية أو أنشئ `BarcodeGenerator` جديد لكل باركود مميز. + +## مثال كامل من البداية إلى النهاية (بما في ذلك تثبيت NuGet) + +إذا كنت تبدأ من الصفر، اتبع هذه الخطوات لتشغيل المشروع: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +استبدل ملف `Program.cs` الذي تم إنشاؤه تلقائيًا بالكتلة البرمجية المعروضة سابقًا، **تذكر استبدال `YOUR_DIRECTORY`** بشيء مثل `Path.Combine(Environment.CurrentDirectory, "output")`. ثم: + +```bash +dotnet run +``` + +يجب أن ترى ملفين PNG في مجلد `output`: + +- `DatabarBarHeight30Pixels.png` – باركود بارتفاع 30 بكسل مدمج. +- `DatabarBarHeight60Pixels.png` – نسخة بارتفاع 60 بكسل أطول. + +ستبدو الصورتان متشابهتين، لكن الصورة الثانية ستحوي أشرطة أطول بشكل ملحوظ، مما يسهل قراءتها بواسطة الماسحات ذات الدقة المنخفضة. + +![Barcode height example](/images/barcode-height.png){alt="مخرجات .net barcode generator تظهر ارتفاعات أشرطة مختلفة"} + +## ملخص وخطوات قادمة + +لقد غطينا كيفية **توليد صور الباركود** باستخدام **.net barcode generator**، وضبطنا خاصية **تغيير ارتفاع الباركود**، وحفظنا النتائج بصيغة PNG. النقاط الرئيسية هي: + +- إنشاء المولد باستخدام `EncodeTypes` الصحيح. +- التحكم في الحجم البصري عبر `XDimension` و `BarHeight`. +- استدعاء `Save` بعد كل تعديل لحفظ صورة جديدة. +- تعديل الدقة، الصيغة, + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية توليد باركود Aztec بنسبة عرض مخصصة باستخدام Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [كيفية إنشاء نص شفرة موسعة لdotcode باستخدام Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-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/chinese/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/chinese/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..1a5b80ec0 --- /dev/null +++ b/barcode/chinese/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-07-18 +description: 条形码生成器示例,展示如何设置尺寸并在 C# 中生成 DataBar Stacked Omni‑Directional 条码图像。快速了解条码编码类型。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: zh +lastmod: 2026-07-18 +og_description: 条形码生成器示例向您展示如何设置尺寸、选择条形码编码类型,并使用最少的代码创建条形码图像的 C# 项目。 +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: 条形码生成器示例 – 使用 C# 快速创建 DataBar 图像 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: 条码生成器示例 – 使用 C# 构建 DataBar 图像 +url: /zh/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 条形码生成器示例 – 在 C# 中构建 DataBar 图像 + +有没有需要一个**条形码生成器示例**,能够真正生成可用的条形码而不让你抓狂?你并不孤单。大多数开发者在尝试弄清楚**如何设置尺寸**以生成 DataBar Stacked Omni‑Directional 条形码时会卡住,尤其是当文档被大量行话埋得很深时。 + +在本教程中,我们将逐步演示一个完整、可直接运行的 C# 程序,展示**如何生成 databar** 图像,选择正确的**条形码编码类型**,并最终**创建 barcode image c#** 文件,您可以将其嵌入任何项目。没有冗余——只提供可复制粘贴的代码,并解释每一行的原理。 + +## 您需要的环境 + +- **.NET 6**(或任何近期的 .NET 版本)——我们使用的 API 面向 .NET Standard,因此在 .NET Framework 上也可运行。 +- **Aspose.BarCode for .NET**——提供 `BarcodeGenerator` 的库。您可以通过 `Install-Package Aspose.BarCode` 从 NuGet 获取。 +- 一个**C# IDE**——Visual Studio、Rider 或 VS Code 都可以。 +- 磁盘上的一个文件夹,用于保存 PNG 文件(代码会生成 `DatabarAspectRatio15.png` 和 `DatabarAspectRatio30.png`)。 + +准备好了吗?很好——让我们开始吧。 + +## 条形码生成器示例 – 初始化生成器 + +首先,我们需要一个配置为 **DataBar Stacked Omni‑Directional** 符号的 `BarcodeGenerator` 实例。这就是我们将使用的**条形码编码类型**。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **为什么这很重要:** `EncodeTypes.DatabarStackedOmniDirectional` 明确告知 Aspose 渲染哪种符号。如果选择错误的类型,扫描仪无论图像多漂亮都无法识别条形码。 + +## 如何为条形码设置尺寸 + +条形码的可读性取决于其**X‑dimension**(最窄条的宽度)。大多数情况下 2 像素的值足够,但您可以根据打印机或屏幕进行微调。 + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **专业提示:** 如果您想了解**如何为其他条形码系列设置尺寸**,同样的属性链 (`Parameters.Barcode.XDimension`) 适用——只需更改 `Pixels` 的数值。 + +## 如何生成 DataBar Stacked Omni‑Directional 条形码 + +生成器准备好后,我们将使用 **aspect ratio** 属性。它控制 DataBar 的高宽比,让您可以生成短而方形或高而窄的符号。 + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **发生了什么?** `AspectRatio = 15` 告诉引擎将条的高度设为宽度的 15 倍。生成的 PNG 会保存在可执行文件旁边。 + +## 创建条形码图像 C# – 更改宽高比 + +让我们通过将比例改为 30 并保存第二个文件来验证其灵活性。 + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +运行程序后,您将得到两个 PNG 文件: + +| 文件 | 宽高比 | 大约尺寸 | +|------|--------|----------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +在任意图像查看器中打开它们——您应该能看到清晰、可扫描的 DataBar 符号。 + +## 条形码编码类型概览(可选但实用) + +如果您想了解 Aspose 支持的其他**条形码编码类型**,这里有一个快速速查表: + +| EncodeTypes Enum | 描述 | +|------------------|------| +| `EncodeTypes.Code128` | 高密度字母数字 | +| `EncodeTypes.QR` | 二维矩阵码 | +| `EncodeTypes.DatabarExpanded` | 零售用 GS1 DataBar | +| `EncodeTypes.DatabarStackedOmniDirectional` | **我们的重点** – 紧凑、全方向 | + +## 常见陷阱及避免方法 + +- **缺少 NuGet 包** – 没有 `Aspose.BarCode` 代码无法编译。请先运行 `dotnet add package Aspose.BarCode`。 +- **错误的文件路径** – 如果使用绝对路径,请检查 Windows 上的反斜杠 (`\\`)。如示例所示的相对路径更具可移植性。 +- **宽高比过于极端** – 超过 50 的比例会使条形码对普通扫描仪来说过高。大多数情况下请保持在 15‑30 之间。 + +## 完整源代码(可直接复制粘贴) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +运行程序(`dotnet run` 或在 Visual Studio 中按 **F5**)后,您会在控制台看到确认文件已生成的消息。 + +![条形码生成器示例输出,显示宽高比为 15 的 DataBar 条形码](placeholder/path/to/image.png){: .align-center alt="条形码生成器示例输出,显示宽高比为 15 的 DataBar 条形码"} + +## 总结 + +我们刚刚完成了一个**条形码生成器示例**,演示了**如何设置尺寸**,选择正确的**条形码编码类型**,并最终**创建 barcode image c#** 文件,可嵌入任何地方。代码简洁,概念清晰,您现在拥有了扩展此方案的坚实基础——比如添加文字说明、旋转图像或切换到其他符号。 + +### 接下来做什么? + +- 尝试不同的 **X‑dimension**,观察扫描仪容差的变化。 +- 尝试其他 **EncodeTypes** 如 `Code128` 或 `QR`,丰富您的工具箱。 +- 自动化批量生成:遍历包含产品 ID 的 CSV,为每个生成 PNG。 + +如果遇到问题,请在下方留言或查阅 Aspose.BarCode 文档——其中包含大量与本教程相辅相成的示例。 + +祝编码愉快,愿您的条形码总能一次成功扫描! + +## 接下来应该学习什么? + +以下教程涵盖与本指南紧密相关的主题,基于本教程展示的技术进行扩展。每个资源都包含完整的可运行代码示例和逐步说明,帮助您掌握更多 API 功能并在项目中探索替代实现方案。 + +- [如何生成条形码 - 一维条形码类型](/barcode/english/net/one-dimensional-barcode-types/) +- [创建条形码图像 C# – GS1 DataMatrix 示例](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [如何使用 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/chinese/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/chinese/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..dd043fc2e --- /dev/null +++ b/barcode/chinese/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-07-18 +description: 使用 C# 快速创建 Planet 条码。学习如何生成实心和空白条、设置 X 维度并保存 PNG 图像——全部在一个教程中。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: zh +lastmod: 2026-07-18 +og_description: 即时创建 Planet 条形码。本指南展示如何设置 X 维度、在实心条和空心条之间切换,以及使用 Aspose.BarCode 导出 + PNG 文件。 +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: 在 C# 中创建 Planet 条形码 – 完整编程演练 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: 在 C# 中创建 Planet 条形码 – 完整逐步指南 +url: /zh/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 C# 创建 Planet 条形码 – 完整分步指南 + +是否曾需要**create planet barcode**图像,但不确定该调整哪些属性?您并不孤单。许多开发者在默认的实心条不符合规范,或条宽必须匹配打印机 DPI 时会遇到障碍。 + +在本教程中,您将学习如何使用 Aspose.BarCode 库**create planet barcode**文件,如何控制 **XDimension pixels**,以及如何在 **filled bars** 与 **empty bars** 之间切换而无需重写代码。完成后,您将拥有两个 PNG 文件——一个实心条,一个空心条——可供任何需要 Planet 符号的邮政系统使用。 + +## 前置条件 + +- .NET 6.0 或更高(代码同样适用于 .NET Framework 4.7 +) +- Aspose.BarCode for .NET NuGet 包(`Install-Package Aspose.BarCode`) +- 基本的 C# 知识(稍后您会了解为何使用 `using` 语句) +- 一个可写入的磁盘文件夹,用于保存 PNG + +如果您已经具备上述条件,我们可以直接进入实现步骤。 + +## 第一步 – 设置项目并添加库 + +首先,创建一个新的控制台应用(或任何 C# 项目),并引用 **Planet barcode generator** 库。 + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro tip:** 在 Visual Studio 中,右键单击项目 → *Manage NuGet Packages* → 搜索 **Aspose.BarCode** 并点击 *Install*。这将为您提供 `BarcodeGenerator` 以及所有需要的 **BarcodeGenerator parameters**。 + +## 第二步 – 初始化 Planet 条形码生成器 + +现在我们实际**create planet barcode**生成器实例,并将要编码的数据(本例中为 `"123456"`)传入。`EncodeTypes.Planet` 枚举告诉库使用哪种符号。 + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Why this matters:** `EncodeTypes.Planet` 标志会自动应用 Planet 邮政条码的正确校验和布局规则,您无需手动计算。 + +## 第三步 – 配置 X‑Dimension(条宽) + +大多数打印机期望每根条的像素数固定。这里我们将 **XDimension pixels** 设置为 `4`,这是 203 dpi 热敏打印机的常见值。 + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Edge case:** 如果目标是 300 dpi 打印机,可能需要 `3` 或 `5` 像素。请根据设备文档调整此值。 + +## 第四步 – 保存实心条版本 + +默认情况下,生成器会产生 **filled bars**(实心黑色矩形)。让我们将其写入磁盘: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +将 `YOUR_DIRECTORY` 替换为应用程序可以写入的绝对或相对路径。运行此行后,您会得到一个看起来像经典 Planet 条码的 PNG 文件——非常适合在邮政扫描仪上进行测试。 + +## 第五步 – 切换为空心条 + +有时邮政服务要求使用“empty bars”样式,即条是从白色背景中挖空而不是涂黑。库提供了一个简单的开关: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +将 `FilledBars` 设置为 `false` 可让渲染器反转条的填充逻辑。无需创建新的 `BarcodeGenerator` 实例,只需调整现有的 **BarcodeGenerator parameters** 即可。 + +## 第六步 – 保存空心条版本 + +最后,导出第二张图像: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +现在您拥有两张不同的 PNG 文件,每个都满足不同的视觉需求。 + +## 完整工作示例 + +将所有部分组合在一起,以下是完整的、可直接复制粘贴的程序: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Expected output**(在控制台上): + +``` +Both Planet barcode images have been generated successfully. +``` + +在 `C:\Barcodes\` 中您会看到: + +- `PostalPlanetFilledBars.png` – 实心黑色条 +- `PostalPlanetEmptyBars.png` – 白色条并带有黑色轮廓 + +使用任意图像查看器打开它们;它们都应符合 Planet 规范。 + +## 常见问题与技巧 + +### “我可以更改图像格式吗?” + +当然可以。`Save` 方法接受 `BarCodeImageFormat.Jpeg`、`Bmp`、`Gif` 等。只需将 `BarCodeImageFormat.Png` 替换为您想要的格式即可。 + +### “如果我需要不同的条码高度怎么办?” + +使用 `planetBarcode.Parameters.Barcode.BarHeight`(单位为点)来增大或减小垂直尺寸。例如: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “有没有办法添加可读的文字说明?” + +可以。设置 `planetBarcode.Parameters.Caption` 上的 `CodeText` 属性: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “我需要释放生成器吗?” + +`BarcodeGenerator` 实现了 `IDisposable`。如果在循环中创建大量条码,请将其放在 `using` 块中: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “错误处理该怎么做?” + +将 `Save` 调用包裹在 `try…catch` 块中,以捕获 `IOException`(磁盘问题)或 `ArgumentException`(参数无效)。示例: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## 小结 + +我们已经覆盖了在 C# 中**create planet barcode**图像所需的全部内容: + +1. 使用您的数据初始化 **Planet barcode generator**。 +2. 调整 **XDimension pixels** 以匹配打印机规格。 +3. 保存实心条 PNG。 +4. 切换 `FilledBars` 以生成 **empty bars**。 +5. 保存第二个 PNG。 + +从这里您可以进一步探索更多 **BarcodeGenerator parameters**,尝试其他符号(`EncodeTypes.Postnet`、`EncodeTypes.Code128` 等),或将图像集成到邮件工作流中。 + +--- + +**Ready for the next step?** 尝试在同一文档中添加 QR 码,或使用 `foreach` 循环从 CSV 列表批量生成 Planet 条码。Aspose.BarCode API 足够灵活,能够处理批量操作、自定义颜色,甚至基于向量的 SVG 输出。 + +如果遇到任何问题,请在下方留言或查阅官方 Aspose.BarCode 文档,深入了解高级功能。祝编码愉快! + +## 接下来该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助您在项目中进一步掌握 API 功能并探索替代实现方式。每个资源都提供完整的可运行代码示例和逐步解释。 + +- [使用 Aspose 创建条形码 - 在 Java 中设置 X 与 Y 维度](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [如何在 Java 中使用 Aspose.BarCode 创建 code128 条形码图像](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [如何在 Java 中创建 code128 条码并设置条高](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/chinese/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..a7eeffcac --- /dev/null +++ b/barcode/chinese/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-07-18 +description: 在 C# 中快速创建 RM4SCC 条码;了解如何设置条码高度,并生成具有自定义尺寸的 Planet 条码。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: zh +lastmod: 2026-07-18 +og_description: 在 C# 中创建 RM4SCC 条形码并了解如何设置条形码高度。还可以查看如何使用同一库生成 Planet 条形码。 +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: 在 C# 中创建 RM4SCC 条码 – 快速设置自定义高度 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: 在 C# 中创建 RM4SCC 条码 – 设置高度的完整指南 +url: /zh/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中创建 RM4SCC 条码 – 设置高度的完整指南 + +是否曾经需要在 .NET 应用中 **创建 RM4SCC 条码**,但不确定如何控制其尺寸?你并不孤单。无论是构建邮件系统还是物流仪表板,正确的条码高度可能决定扫描成功与否的差别。 + +在本教程中,我们将完整演示整个过程:从安装库,到 **生成 Planet 条码** 作为并列示例,最后到 **如何设置条码高度**(适用于两种条码类型)。完成后,你将拥有一个可直接运行的控制台应用,能够输出具有精确尺寸的 PNG 文件。 + +--- + +## 您需要的条件 + +- **.NET 6 SDK**(或任何近期的 .NET 版本)– 代码同样适用于 .NET Framework,但 .NET 6 是最佳选择。 +- **Aspose.BarCode for .NET** NuGet 包 – 该库提供 `BarcodeGenerator` 类。 +- 适度的 C# 知识 – 我们将保持语法对初学者友好。 +- 一个 IDE 或文本编辑器(Visual Studio、VS Code、Rider——任选其一)。 + +> **专业提示:** 如果你在 CI/CD 流水线中,建议在 `.csproj` 中添加 NuGet 引用,这样构建永远不会忘记此依赖。 + +--- + +## 第一步:设置项目 + +打开终端并创建一个新的控制台项目: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +就这样——你的项目现在已经引用了驱动后续所有功能的库。 + +### 添加 Using 指令 + +打开 `Program.cs` 并在顶部粘贴以下内容: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +这些命名空间让我们能够访问 `BarcodeGenerator` 以及后面将使用的图像格式枚举。 + +--- + +## 第二步:定义用于保存图像的辅助方法 + +为了避免重复相同的保存逻辑,我们将其封装在一个小方法中。这也演示了 **如何设置条码高度**。 + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **为什么这很重要:** 将保存逻辑集中管理后,如果需求变化,只需在一个位置修改格式或文件夹即可。 + +--- + +## 第三步:生成 Planet 条码(“生成 Planet 条码”部分) + +在深入 RM4SCC 细节之前,先生成一个 **Planet 条码**。这可以快速检查库是否正常工作。 + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**预期输出:** `output` 文件夹中会出现两个 PNG 文件——一个使用库自动计算的高度,另一个高度恰好为 100 px。 + +--- + +## 第四步:创建 RM4SCC 条码 – 主要目标 + +现在来实现本教程的明星:**创建 RM4SCC 条码**。RM4SCC 是 Royal Mail 4‑State Code,广泛用于英国邮政系统。 + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**你会看到:** +- `RM4SCCDefault.png` – 库根据 X‑dimension 自动决定一个舒适的高度。 +- `RM4SCCHeight100.png` – 高度为 100 像素的清晰条码,适合在信封上打印。 + +> **为什么要设置高度?** 某些标签打印机要求最小条码高度以确保可靠扫描。固定高度即可保证在各种设备上的合规性。 + +--- + +## 第五步:理解高度设置(回答“如何设置条码高度”) + +Planet 和 RM4SCC 示例均使用相同的属性: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** 是一个 `BarHeight` 对象,封装了多种测量单位(像素、毫米、英寸)。 +- **`.Pixels`** 是最直接的屏幕输出单位,但如果面向打印介质,也可以使用 `.Millimeters` 或 `.Inches`。 + +### 边缘情况与技巧 + +| 场景 | 推荐做法 | +|-----------|----------------------| +| **非常小的 X‑dimension(例如 1 px)** | 增大 `BarHeight` 以保持条码可读性。 | +| **在高分辨率标签打印机上打印** | 使用 `.Millimeters` 实现设备无关的尺寸。 | +| **在同一图像中混合多种条码类型** | 对每个生成器在设置 `XDimension` 后再设置 `BarHeight`,避免意外继承。 | +| **动态数据(例如用户输入的代码)** | 将生成器创建封装在接受 `code` 和 `height` 参数的方法中。 | + +--- + +## 第六步:完整工作示例 + +下面是一段完整、独立的程序代码,可直接复制粘贴到 `Program.cs` 中。它涵盖了从项目设置到图像保存的全部步骤。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +运行它: + +```bash +dotnet run +``` + +你应该会在控制台看到每个文件保存的确认信息,`output` 文件夹中将包含四个 PNG,名称与上文所示相匹配。 + +--- + +## 结论 + +现在你已经掌握了在 C# 中 **创建 RM4SCC 条码** 并通过几行属性赋值来控制其尺寸。我们还演示了 **生成 Planet 条码** 作为快速检查,并深入探讨了 **如何设置条码高度** 在不同打印场景下的细微差别。 + +接下来可以尝试将 `EncodeTypes` 枚举换成其他符号(Code128、QR、DataMatrix),并在高分辨率打印机上使用毫米单位的 `BarHeight` 进行实验。如果需要将条码嵌入 PDF,可将 Aspose.BarCode 与 Aspose.PDF 组合使用——同样强大。 + +有问题或想分享自己的改进?在下方留言吧,祝编码愉快! + +## 接下来您应该学习什么? + +以下教程涵盖了与本指南技术紧密相关的主题,帮助你在项目中进一步掌握 API 功能并探索替代实现方案。每篇资源均提供完整可运行的代码示例和逐步说明。 + +- [如何使用 Aspose.BarCode for .NET 生成具有自定义宽高比的 Aztec 条码](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [如何使用 Aspose.BarCode for .NET 为 ITF-14 创建条码静区](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [如何使用 Aspose.BarCode for .NET 为 Code 16K 创建条码静区](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/chinese/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..d583388ca --- /dev/null +++ b/barcode/chinese/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-07-18 +description: 了解如何使用 .net 条码生成器生成条码图像,并轻松更改 GS1‑Databar 全向符号的条码高度。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: zh +lastmod: 2026-07-18 +og_description: .NET 条形码生成器让您快速创建条形码图像。本指南展示如何生成条形码、调整条码高度以及保存 PNG 文件。 +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: 使用 .net 条码生成器更改条码高度 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET 条形码生成器 – 更改条形码高度 +url: /zh/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – 更改条码高度 + +是否曾想过 **如何生成条码** 图像而不需要使用大量第三方工具?在 .NET 世界中,有一种出乎意料的简洁方式来实现,而关键就在于 **.net barcode generator**。只需几行 C# 代码,就能生成 GS1‑Databar Omni‑Directional 符号,调整条码高度,并将结果保存为 PNG 文件。 + +如果你正在构建库存系统、运单标签打印机,或任何需要可扫描代码的应用,本教程将在几分钟内帮助你从零实现可用的条码。我们将逐步讲解完整代码,说明每个设置为何重要,并展示如何 **更改条码高度** 而不破坏规范。 + +## 所需条件 + +- .NET 6.0 或更高版本(API 在 .NET Framework 4.7+ 上表现相同) +- 条码库的引用(例如 Aspose.BarCode for .NET —— 许多商业套件使用相同的类) +- 开发环境(Visual Studio、Rider,或带有 C# 扩展的 VS Code) +- 一个拥有写入权限的文件夹 —— 本教程会将 PNG 文件保存到该文件夹 + +仅此而已。除条码库本身外,无需额外的 NuGet 包。 + +## 使用 .net barcode generator 更改条码高度 + +下面是一个 **完整、可运行的控制台程序**。将其粘贴到新的 C# 项目中,调整输出文件夹路径,然后按 F5 运行。 + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### 为什么每行代码都很重要 + +| 行 | 原因 | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | 实例化 **.net barcode generator**,并指定所需的符号类型和数据负载。`EncodeTypes.DatabarOmniDirectional` 枚举告诉库使用 GS1‑Databar Omni‑Directional 格式。 | +| `XDimension.Pixels = 2;` | X‑dimension 是最细条的宽度。设置为 *2 像素* 可在大多数显示器上生成清晰图像,同时保持文件体积小。 | +| `BarHeight.Pixels = 30;` | 这一步 **更改条码高度**,决定每根条的高度。30 像素的高度是小标签的良好默认值。 | +| `generator.Save(...);` | 将条码持久化为 PNG 文件。PNG 为无损格式,意味着扫描器看到的正是你生成的精确图案。 | +| `BarHeight.Pixels = 60;` | 此处再次 **更改条码高度**——这次设为 60 像素。调用第二次 `Save` 时,库会自动使用新尺寸重新渲染符号。 | +| `Console.WriteLine(...);` | 快速反馈,表明过程已完成且未抛出异常。 | + +> **小技巧:** 如果需要更高分辨率的打印输出,可将 `BarCodeImageFormat.Png` 换成 `BarCodeImageFormat.Tiff` 并提升 `Resolution` 属性(例如 `generator.Parameters.ImageResolution = 300;`)。条码高度仍会被遵循,只是以更细的 DPI 渲染。 + +## 使用不同设置生成条码图像 + +上面的代码片段涵盖了基础,但实际场景常常需要额外的微调: + +### 为大幅面打印调整 X‑dimension +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +增加 X‑dimension 会在不改变编码数据的前提下放大整个条码。打印大标签时非常实用。 + +### 切换输出格式 +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG 可无限缩放,适合需要清晰矢量图的网页扫描器。 + +### 添加可读文本 +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +启用 `CodeTextVisible` 会在条码下方附加原始数据,便于测试时进行人工核对。 + +## 常见陷阱——在 **更改条码高度** 时 + +1. **高度过小** —— 某些扫描器要求最小条码高度(通常为 10 mm 实际尺寸)。如果 `BarHeight.Pixels` 设置得太低,生成的图像在真实扫描器上可能无法读取。务必使用目标硬件进行测试。 +2. **X‑dimension 与高度不匹配** —— 极高的条码高度配合极小的 X‑dimension 会显得拉伸,可能导致解码错误。除非规范另有说明,否则建议保持大致 3:1 到 5:1 的比例。 +3. **忘记重置参数** —— 生成器在多次保存之间会保留状态。如果为一张图像更改了 `BarHeight`,随后在同一实例上生成另一张条码,之前的高度会被保留。要么重置属性,要么为每个不同的条码实例化新的 `BarcodeGenerator`。 + +## 完整端到端示例(含 NuGet 安装) + +如果从零开始,请按以下步骤搭建项目: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +将自动生成的 `Program.cs` 替换为前面展示的代码块,**记得将 `YOUR_DIRECTORY` 替换为类似 `Path.Combine(Environment.CurrentDirectory, "output")` 的路径**。然后: + +```bash +dotnet run +``` + +你应该会在 `output` 文件夹中看到两个 PNG 文件: + +- `DatabarBarHeight30Pixels.png` —— 紧凑的 30 像素高条码。 +- `DatabarBarHeight60Pixels.png` —— 更高的 60 像素版本。 + +两张图像看起来相似,但第二张的条更长,低分辨率扫描器更容易读取。 + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator 输出显示不同的条码高度"} + +## 小结与后续 + +我们已经介绍了如何使用 **.net barcode generator** **生成条码** 图像,微调 **更改条码高度** 属性,并以 PNG 格式保存结果。关键要点如下: + +- 使用正确的 `EncodeTypes` 实例化生成器。 +- 通过 `XDimension` 与 `BarHeight` 控制视觉尺寸。 +- 每次更改后调用 `Save` 以生成新图像。 +- 如有需要,可调整分辨率、格式等。 + +## 接下来该学习什么? + +以下教程涵盖了与本指南技术紧密相关的主题,帮助你进一步掌握 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 create dotcode extended codetext with Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-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/czech/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/czech/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..2fca44345 --- /dev/null +++ b/barcode/czech/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-07-18 +description: Příklad generátoru čárových kódů, který ukazuje, jak nastavit rozměry + a vygenerovat obrázek čárového kódu DataBar Stacked Omni‑Directional v C#. Rychle + se naučte typy kódování čárových kódů. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: cs +lastmod: 2026-07-18 +og_description: Příklad generátoru čárových kódů vás provede nastavením rozměrů, výběrem + typů kódování čárových kódů a vytvořením projektů C# pro obrázek čárového kódu s + minimálním kódem. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Příklad generátoru čárových kódů – rychlé vytvoření DataBar obrázku v C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Příklad generátoru čárových kódů – Vytvořte DataBar obrázek v C# +url: /cs/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Příklad generátoru čárových kódů – Vytvoření DataBar obrázku v C# + +Už jste někdy potřebovali **barcode generator example**, který skutečně vygeneruje reálný čárový kód, aniž by vám to roztrhávalo vlasy? Nejste sami. Většina vývojářů narazí na problém, když se snaží zjistit **how to set dimensions** pro DataBar Stacked Omni‑Directional čárový kód, zejména když je dokumentace ukryta pod vrstvou žargonu. + +V tomto tutoriálu projdeme kompletní, připravený C# program, který ukazuje **how to generate databar** obrázky, vybírá správné **barcode encode types** a nakonec **create barcode image c#** soubory, které můžete vložit do libovolného projektu. Žádné zbytečnosti – jen kód, který můžete zkopírovat‑vložit, a vysvětlení za každým řádkem. + +## Co budete potřebovat + +- **.NET 6** (nebo jakákoli novější verze .NET) – API, které používáme, cílí na .NET Standard, takže funguje i na .NET Framework. +- **Aspose.BarCode for .NET** – knihovna, která poskytuje `BarcodeGenerator`. Získáte ji z NuGet pomocí `Install-Package Aspose.BarCode`. +- **C# IDE** – Visual Studio, Rider nebo VS Code budou stačit. +- Složku na disku, kam se uloží PNG soubory (kód vytvoří `DatabarAspectRatio15.png` a `DatabarAspectRatio30.png`). + +Máte vše připravené? Skvěle – pojďme na to. + +## Barcode Generator Example – Inicializace generátoru + +Nejprve potřebujeme instanci `BarcodeGenerator` nakonfigurovanou pro **DataBar Stacked Omni‑Directional** symbologii. Toto je **barcode encode type**, se kterým budeme pracovat. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Proč je to důležité:** `EncodeTypes.DatabarStackedOmniDirectional` říká Aspose přesně, kterou symbologii má vykreslit. Pokud vyberete špatný typ, skener čárový kód nerozpozná, ať už je obrázek jakkoli pěkný. + +## Jak nastavit rozměry čárového kódu + +Čitelnost čárového kódu závisí na jeho **X‑dimension** (šířka nejúzkého pruhu). Ve většině případů hodnota 2 pixely funguje dobře, ale můžete ji upravit podle vašeho tiskárny nebo obrazovky. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Tip:** Pokud se někdy zamyslíte **how to set dimensions** pro jinou rodinu čárových kódů, použije se stejný řetězec vlastností (`Parameters.Barcode.XDimension`) – stačí změnit hodnotu `Pixels`. + +## Jak vygenerovat DataBar Stacked Omni‑Directional čárový kód + +Nyní, když je generátor připraven, pohráváme si s vlastností **aspect ratio**. Ta řídí poměr výšky k šířce DataBaru a umožňuje vám vytvořit krátký, čtvercový symbol nebo vysoký, úzký. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Co se děje?** `AspectRatio = 15` říká enginu, aby udělal pruhy 15‑krát vyšší než široké. Výsledný PNG se uloží vedle spustitelného souboru. + +## Create Barcode Image C# – Změna poměru stran + +Pojďme dokázat flexibilitu tím, že poměr změníme na 30 a uložíme druhý soubor. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +Po spuštění programu získáte dva PNG soubory: + +| Soubor | Poměr stran | Přibližná velikost | +|--------|-------------|--------------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Otevřete je v libovolném prohlížeči obrázků – měli byste vidět čisté, skenovatelné DataBar symboly. + +## Přehled Barcode Encode Types (Volitelné, ale užitečné) + +Pokud vás zajímají další **barcode encode types**, které Aspose podporuje, tady je rychlý cheat‑sheet: + +| Enum EncodeTypes | Popis | +|------------------|-------| +| `EncodeTypes.Code128` | **Vysoká hustota alfanumerických znaků** | +| `EncodeTypes.QR` | 2‑D maticový kód | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar pro maloobchod | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Náš fokus** – kompaktní, všesměrový | + +Znalost správného enumu vám ušetří spoustu pokusů a omylů při přechodu mezi projekty. + +## Časté úskalí a jak se jim vyhnout + +- **Chybějící NuGet balíček** – Kód se neskompiluje bez `Aspose.BarCode`. Nejprve spusťte `dotnet add package Aspose.BarCode`. +- **Špatná cesta k souboru** – Pokud používáte absolutní cestu, zkontrolujte zpětná lomítka (`\\`) ve Windows. Relativní cesty (jak jsou ukázány) udržují projekt přenosný. +- **Příliš extrémní poměr stran** – Poměry nad 50 mohou udělat čárový kód příliš vysoký pro běžné skenery. Držte se 15‑30 pro většinu případů. + +## Kompletní zdrojový kód (připravený ke kopírování) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Spusťte program (`dotnet run` nebo stiskněte **F5** ve Visual Studiu) a v konzoli uvidíte zprávu potvrzující, že soubory jsou na disku. + +![Příklad výstupu generátoru čárových kódů zobrazující DataBar čárový kód s poměrem stran 15](placeholder/path/to/image.png){: .align-center alt="Příklad výstupu generátoru čárových kódů zobrazující DataBar čárový kód s poměrem stran 15"} + +## Závěr + +Právě jsme dokončili **barcode generator example**, který demonstruje **how to set dimensions**, vybírá správné **barcode encode types** a nakonec **create barcode image c#** soubory, které můžete vložit kamkoli. Kód je malý, koncepty jsou naprosto jasné a nyní máte pevný základ pro rozšíření řešení – třeba přidání textových popisků, otáčení obrázku nebo přechod na jinou symbologii. + +### Co dál? + +- Experimentujte s **různými X‑dimension** a sledujte, jak se mění tolerance skeneru. +- Vyzkoušejte jiné **EncodeTypes** jako `Code128` nebo `QR` a rozšiřte si nástrojovou sadu. +- Automatizujte hromadné generování: projděte CSV soubor s ID produktů a vytvořte PNG pro každý z nich. + +Pokud narazíte na problém, zanechte komentář níže nebo si projděte dokumentaci Aspose.BarCode – je plná příkladů, které doplňují to, co jsme zde probírali. + +Šťastné kódování a ať vaše čárové kódy vždy skenují na 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 podrobnými vysvětleními, aby vám pomohly zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vašich projektech. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/czech/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/czech/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..c6f670d30 --- /dev/null +++ b/barcode/czech/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-07-18 +description: Rychle vytvořte čárový kód Planet pomocí C#. Naučte se generovat plné + i prázdné pruhy, nastavit X‑rozměr a uložit PNG obrázky – vše v jednom tutoriálu. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: cs +lastmod: 2026-07-18 +og_description: Vytvořte čárový kód Planet okamžitě. Tento průvodce ukazuje, jak nastavit + X‑rozměr, přepínat mezi vyplněnými a prázdnými pruhy a exportovat PNG soubory pomocí + Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Vytvořte Planet Barcode v C# – Kompletní programovací průvodce +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Vytvořte Planet Barcode v C# – Kompletní krok‑za‑krokem průvodce +url: /cs/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření Planet čárového kódu v C# – Kompletní průvodce krok za krokem + +Už jste někdy potřebovali **vytvořit planet čárový kód** obrázky, ale nebyli jste si jisti, které vlastnosti upravit? Nejste v tom sami. Mnoho vývojářů narazí na problém, když výchozí plně vyplněné pruhy nesplňují požadavky specifikace, nebo když šířka pruhu musí odpovídat DPI tiskárny. + +V tomto tutoriálu se přesně naučíte, jak **vytvořit planet čárový kód** soubory pomocí knihovny Aspose.BarCode, jak ovládat **XDimension pixely** a jak přepínat mezi **vyplněnými pruhy** a **prázdnými pruhy** bez přepisování kódu. Na konci budete mít dva PNG soubory — jeden s plnými pruhy a jeden s dutými pruhy — připravené pro jakýkoli poštovní systém, který očekává symbologii Planet. + +## Požadavky + +- .NET 6.0 nebo novější (kód funguje také na .NET Framework 4.7 +) +- Aspose.BarCode pro .NET NuGet balíček (`Install-Package Aspose.BarCode`) +- Základní znalost C# (později uvidíte, proč používáme `using` příkazy) +- Zapisovatelná složka na disku, kam budou PNG soubory uloženy + +Pokud máte vše připravené, můžeme rovnou přejít k implementaci. + +## Krok 1 – Nastavení projektu a přidání knihovny + +Nejprve vytvořte novou konzolovou aplikaci (nebo jakýkoli C# projekt) a odkazujte na knihovnu **Planet barcode generator**. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Tip:** Ve Visual Studiu klikněte pravým tlačítkem na projekt → *Manage NuGet Packages* → vyhledejte **Aspose.BarCode** a klikněte na *Install*. Tím získáte přístup k `BarcodeGenerator` a všem **BarcodeGenerator parametrům**, které budete potřebovat. + +## Krok 2 – Inicializace Planet čárového kódu + +Nyní skutečně **vytvoříme planet čárový kód** generátor a předáme mu data, která chceme zakódovat (`"123456"` v tomto příkladu). Enum `EncodeTypes.Planet` říká knihovně, kterou symbologii použít. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Proč je to důležité:** Příznak `EncodeTypes.Planet` automaticky použije správný kontrolní součet a pravidla rozložení pro planetární poštovní čárový kód, takže je nemusíte počítat ručně. + +## Krok 3 – Nastavení X‑Dimension (šířka pruhu) + +Většina tiskáren očekává, že každý pruh bude mít konkrétní počet pixelů. Zde nastavíme **XDimension pixely** na `4`, což je běžná hodnota pro 203 dpi termální tiskárny. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Hraniční případ:** Pokud cílíte na 300 dpi tiskárnu, možná budete potřebovat `3` nebo `5` pixelů. Hodnotu upravte podle dokumentace vašeho zařízení. + +## Krok 4 – Uložení verze s vyplněnými pruhy + +Ve výchozím nastavení generátor vytváří **vyplněné pruhy** (plné černé obdélníky). Uložme je na disk: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Nahraďte `YOUR_DIRECTORY` absolutní nebo relativní cestou, do které může vaše aplikace zapisovat. Po spuštění tohoto řádku najdete PNG soubor, který vypadá jako klasický Planet čárový kód — ideální pro testování na poštovním skeneru. + +## Krok 5 – Přepnutí na prázdné pruhy + +Některé poštovní služby vyžadují styl „prázdných pruhů“, kde jsou pruhy vyřezány z bílého pozadí místo aby byly černě natřeny. Knihovna poskytuje jednoduchý přepínač: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Nastavení `FilledBars` na `false` říká rendereru, aby invertoval logiku vyplnění pruhu. Není potřeba vytvářet novou instanci `BarcodeGenerator`; stačí upravit existující **BarcodeGenerator parametry**. + +## Krok 6 – Uložení verze s prázdnými pruhy + +Nakonec exportujte druhý obrázek: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Nyní máte dva odlišné PNG soubory, každý splňující jiný vizuální požadavek. + +## Kompletní funkční příklad + +Sestavením všech částí získáte kompletní program připravený ke zkopírování a vložení: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Očekávaný výstup** (v konzoli): + +``` +Both Planet barcode images have been generated successfully. +``` + +A ve složce `C:\Barcodes\` uvidíte: + +- `PostalPlanetFilledBars.png` – plné černé pruhy +- `PostalPlanetEmptyBars.png` – bílé pruhy s černými obrysy + +Otevřete je v libovolném prohlížeči obrázků; oba by měly odpovídat specifikaci Planet. + +## Často kladené otázky a tipy + +### „Mohu změnit formát obrázku?“ + +Samozřejmě. Metoda `Save` přijímá `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` atd. Stačí nahradit `BarCodeImageFormat.Png` požadovaným formátem. + +### „Co když potřebuji jinou výšku čárového kódu?“ + +Použijte `planetBarcode.Parameters.Barcode.BarHeight` (v bodech) pro zvýšení nebo snížení vertikální velikosti. Například: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### „Existuje způsob, jak přidat čitelný popisek?“ + +Ano. Nastavte vlastnost `CodeText` na `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### „Musím generátor uvolnit?“ + +`BarcodeGenerator` implementuje `IDisposable`. Zabalte jej do `using` bloku, pokud vytváříte mnoho čárových kódů v cyklu: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### „Jak řešit chyby?“ + +Obalte volání `Save` do `try…catch` bloku, abyste zachytili `IOException` (problémy s diskem) nebo `ArgumentException` (neplatné parametry). Příklad: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Shrnutí + +Probrali jsme vše, co potřebujete k **vytvoření planet čárového kódu** v C#: + +1. Inicializujte **Planet barcode generator** s vašimi daty. +2. Upravit **XDimension pixely** podle specifikací tiskárny. +3. Uložte PNG s **vyplněnými pruhy**. +4. Přepněte `FilledBars` pro vytvoření **prázdných pruhů**. +5. Uložte druhý PNG. + +Odtud můžete zkoumat další **BarcodeGenerator parametry**, experimentovat s jinými symbologiemi (`EncodeTypes.Postnet`, `EncodeTypes.Code128` atd.) nebo integrovat obrázky do poštovního workflow. + +--- + +**Připravený na další krok?** Zkuste přidat QR kód do stejného dokumentu nebo vygenerovat dávku Planet čárových kódů ze seznamu CSV pomocí smyčky `foreach`. API Aspose.BarCode je dostatečně flexibilní pro hromadné operace, vlastní barvy i vektorový výstup SVG. + +Pokud narazíte na problémy, zanechte komentář níže nebo si prostudujte oficiální dokumentaci Aspose.BarCode pro podrobnější informace o pokročilých funkcích. Šť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í přístupy ve vlastních projektech. + +- [Create Barcode with Aspose - Set X & Y Dimensions in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/czech/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..bf327e419 --- /dev/null +++ b/barcode/czech/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-07-18 +description: Vytvořte rychle čárový kód RM4SCC v C#; naučte se nastavit výšku čárového + kódu a také generovat Planet čárový kód s vlastními rozměry. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: cs +lastmod: 2026-07-18 +og_description: Vytvořte čárový kód RM4SCC v C# a zjistěte, jak nastavit výšku čárového + kódu. Také se podívejte, jak vygenerovat čárový kód Planet pomocí stejné knihovny. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Vytvořte čárový kód RM4SCC v C# – rychle nastavte vlastní výšku +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Vytvořte čárový kód RM4SCC v C# – Kompletní průvodce nastavením výšky +url: /cs/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření čárového kódu RM4SCC v C# – Kompletní průvodce nastavením výšky + +Už jste někdy potřebovali **vytvořit čárový kód RM4SCC** v .NET aplikaci, ale nebyli jste si jisti, jak ovládat jeho velikost? Nejste v tom sami. Ať už budujete poštovní systém nebo logistický dashboard, správná výška čárového kódu může být rozdílem mezi úspěšným skenováním a selháním. + +V tomto tutoriálu projdeme celý proces: od instalace knihovny, přes **vytvoření Planet čárového kódu** jako příklad vedle sebe, až po **jak nastavit výšku čárového kódu** pro oba typy čárových kódů. Na konci budete mít připravenou konzolovou aplikaci, která vygeneruje PNG soubory s přesnými rozměry, které potřebujete. + +--- + +## Co budete potřebovat + +- **.NET 6 SDK** (nebo jakákoli recentní verze .NET) – kód funguje i na .NET Framework, ale .NET 6 je ideální volba. +- **Aspose.BarCode for .NET** NuGet balíček – tato knihovna poskytuje třídu `BarcodeGenerator`. +- Skromné znalosti C# – syntaxe bude přátelská pro začátečníky. +- IDE nebo textový editor (Visual Studio, VS Code, Rider — vyberte si podle libosti). + +> **Tip:** Pokud používáte CI/CD pipeline, přidejte odkaz na NuGet do vašeho `.csproj`, aby build nikdy nezapomněl na závislost. + +## Krok 1: Nastavení projektu + +Otevřete terminál a vytvořte nový konzolový projekt: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +A to je vše — váš projekt nyní odkazuje na knihovnu, která pohání vše, co následuje. + +### Přidání using direktiv + +Otevřete `Program.cs` a na začátek vložte následující: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +## Krok 2: Definice pomocné metody pro ukládání obrázků + +Abychom se vyhnuli opakování stejné logiky ukládání, zabalíme ji do malé metody. Tím také ukážeme **jak nastavit výšku čárového kódu** později. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Proč je to důležité:** Centralizace logiky ukládání znamená, že pokud se požadavky změní, stačí změnit formát nebo složku na jednom místě. + +## Krok 3: Vytvoření Planet čárového kódu (část „vytvořit planet čárový kód“) + +Než se ponoříme do specifik RM4SCC, vytvořme **Planet čárový kód**. To vám poskytne rychlou vizuální kontrolu, že knihovna funguje. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Očekávaný výstup:** V adresáři `output` se objeví dva PNG soubory — jeden s automaticky vypočtenou výškou knihovny, druhý přesně 100 px vysoký. + +## Krok 4: Vytvoření RM4SCC čárového kódu — hlavní cíl + +Nyní hvězda představení: **vytvořit RM4SCC čárový kód**. RM4SCC je Royal Mail 4‑State Code, široce používaný v poštovním systému Velké Británie. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**Co uvidíte:** +- `RM4SCCDefault.png` — knihovna určí pohodlnou výšku na základě X‑dimenze. +- `RM4SCCHeight100.png` — ostrý 100‑pixelový čárový kód připravený k tisku na obálky. + +> **Proč nastavit výšku?** Některé tiskárny štítků vyžadují minimální výšku čáry pro spolehlivé skenování. Nastavením pevné výšky zaručíte soulad napříč zařízeními. + +## Krok 5: Porozumění nastavení výšky (odpověď na „jak nastavit výšku čárového kódu“) + +Oba příklady, Planet i RM4SCC, používají stejnou vlastnost: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** je objekt `BarHeight`, který seskupuje několik měrných jednotek (pixely, milimetry, palce). +- **`.Pixels`** je nejjednodušší jednotka pro výstup zaměřený na obrazovku, ale můžete také použít `.Millimeters` nebo `.Inches`, pokud cílíte na tisková média. + +### Okrajové případy a tipy + +| Situace | Doporučený přístup | +|-----------|----------------------| +| **Velmi malá X‑dimenze (např. 1 px)** | Zvyšte `BarHeight`, aby byl čárový kód čitelný. | +| **Tisk na vysoce rozlišených tiskárnách štítků** | Použijte `.Millimeters` pro nezávislé měřítko na zařízení. | +| **Smíšené typy čárových kódů v jednom obrázku** | Nastavte `BarHeight` *po* `XDimension` pro každý generátor, aby nedošlo k nechtěnému dědění. | +| **Dynamická data (např. kódy zadané uživatelem)** | Zabalte vytvoření generátoru do metody, která přijímá parametry `code` a `height`. | + +## Krok 6: Kompletní funkční příklad + +Níže je jeden samostatný program, který můžete zkopírovat a vložit do `Program.cs`. Obsahuje vše od nastavení projektu až po ukládání obrázků. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Spusťte jej pomocí: + +```bash +dotnet run +``` + +Měli byste vidět výstup v konzoli potvrzující uložení každého souboru a adresář `output` bude obsahovat čtyři PNG soubory odpovídající výše uvedeným názvům. + +## Závěr + +Nyní víte **jak vytvořit RM4SCC čárový kód** v C# a ovládat jeho rozměry pomocí několika přiřazení vlastností. Také jsme pokryli **vytvoření Planet čárového kódu** jako rychlou kontrolu a prozkoumali nuance **jak nastavit výšku čárového kódu** pro různé tiskové scénáře. + +Další kroky? Zkuste vyměnit enum `EncodeTypes` za jiné symbologie (Code128, QR, DataMatrix) a experimentujte s `BarHeight` v milimetrech pro vysoce rozlišené tiskárny. Pokud potřebujete vložit čárový kód do PDF, spojte Aspose.BarCode s Aspose.PDF — další výkonnou kombinaci. + +Máte otázky nebo chcete sdílet své úpravy? Zanechte komentář níže a šťastné programová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, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci 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 vytvořit tichou zónu čárového kódu pro ITF-14 pomocí Aspose.BarCode pro .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Jak vytvořit tichou zónu čárového kódu pro Code 16K pomocí Aspose.BarCode pro .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/czech/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..73b9703e9 --- /dev/null +++ b/barcode/czech/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-07-18 +description: Naučte se, jak generovat obrázky čárových kódů pomocí .net generátoru + čárových kódů a snadno měnit výšku čárového kódu pro symboly GS1‑Databar Omni‑Directional. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: cs +lastmod: 2026-07-18 +og_description: .NET generátor čárových kódů vám umožní rychle vytvořit obrázky čárových + kódů. Tento návod ukazuje, jak generovat čárový kód, nastavit výšku čáry a uložit + soubory PNG. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Změňte výšku čárového kódu pomocí .NET generátoru čárových kódů +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET generátor čárových kódů – změna výšky čárového kódu +url: /cs/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – změna výšky čárového kódu + +Už jste se někdy zamýšleli **jak generovat čárový kód** obrázky bez používání desítek nástrojů třetích stran? Ve světě .NET existuje překvapivě jednoduchý způsob, jak to udělat, a klíčovým prvkem je **.net barcode generator**. Pouhými několika řádky C# můžete vytvořit symbol GS1‑Databar Omni‑Directional, upravit výšku čáry a uložit výsledek do souboru PNG. + +Pokud vytváříte inventární systém, tiskárnu štítků pro dopravu nebo jakoukoli aplikaci, která potřebuje skenovatelný kód, tento tutoriál vás během několika minut provede od nuly až po fungující čárový kód. Projdeme kompletní kód, vysvětlíme, proč každé nastavení má význam, a ukážeme vám, jak **změnit výšku čárového kódu** bez porušení specifikace. + +## Co budete potřebovat + +- .NET 6.0 nebo novější (API funguje stejně na .NET Framework 4.7+) +- Odkaz na knihovnu čárových kódů (například Aspose.BarCode for .NET – stejné třídy používá mnoho komerčních balíčků) +- Vývojové prostředí (Visual Studio, Rider nebo VS Code s rozšířením C#) +- Složka, do které máte oprávnění zapisovat – tutoriál tam uloží soubory PNG + +To je vše. Žádné další NuGet balíčky kromě samotné knihovny čárových kódů. + +## Použití .net barcode generator k změně výšky čárového kódu + +Níže je **kompletní, spustitelný konzolový program**. Vložte jej do nového C# projektu, upravte výstupní složku a stiskněte F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Proč je každý řádek důležitý + +| Line | Reason | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Vytvoří **.net barcode generator** s požadovanou symbologií a datovým nákladem. Výčtový typ `EncodeTypes.DatabarOmniDirectional` říká knihovně, aby použila formát GS1‑Databar Omni‑Directional. | +| `XDimension.Pixels = 2;` | X‑dimenze je šířka nejtenčí čáry. Nastavením na *2 pixely* získáte ostrý obrázek na většině monitorů a zároveň udržíte malou velikost souboru. | +| `BarHeight.Pixels = 30;` | Toto je krok **změny výšky čárového kódu**, který určuje, jak vysoká bude každá čára. Výška 30 pixelů je dobrá výchozí hodnota pro malé štítky. | +| `generator.Save(...);` | Uloží čárový kód do souboru PNG. PNG je bezztrátový formát, což znamená, že skenery vidí přesně ten vzor, který jste vygenerovali. | +| `BarHeight.Pixels = 60;` | Zde **měníme výšku čárového kódu** znovu – tentokrát na 60 pixelů. Knihovna automaticky znovu vykreslí symbol s novým rozměrem, když zavoláte `Save` podruhé. | +| `Console.WriteLine(...);` | Poskytne vám rychlou zpětnou vazbu, že proces byl dokončen bez vyhození výjimky. | + +> **Tip:** Pokud potřebujete výstup s vyšším rozlišením pro tisk, přepněte `BarCodeImageFormat.Png` na `BarCodeImageFormat.Tiff` a zvýšte vlastnost `Resolution` (např. `generator.Parameters.ImageResolution = 300;`). Výška čáry bude i nadále respektována, jen bude vykreslena s jemnějším DPI. + +## Jak generovat obrázky čárových kódů s různými nastaveními + +Ukázka výše pokrývá základy, ale reálné scénáře často vyžadují další úpravy: + +### Úprava X‑dimenze pro větší výtisky +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Zvýšení X‑dimenze zvětší celý čárový kód, aniž by změnilo kódovaná data. To je užitečné při tisku na velké štítky. + +### Přepínání výstupních formátů +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG se škáluje nekonečně, což je ideální pro webové skenery, které potřebují ostré vektory. + +### Přidání lidsky čitelného textu +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Povolení `CodeTextVisible` přidá surová data pod čárový kód, což je užitečné pro ověření během testování. + +## Časté úskalí při **změně výšky čárového kódu** + +1. **Výška příliš malá** – Některé skenery vyžadují minimální výšku čáry (často 10 mm v reálných jednotkách). Pokud nastavíte `BarHeight.Pixels` příliš nízko, může být vygenerovaný obrázek nečitelné pro skutečný scanner. Vždy testujte s vaším cílovým hardwarem. +2. **Nesoulad X‑dimenze a výšky** – Velká výška čáry spojená s malou X‑dimenzí může vypadat nataženě a může způsobit chyby při dekódování. Usilujte o vyvážený poměr (přibližně 3:1 až 5:1), pokud specifikace neuvádí jinak. +3. **Zapomenutí resetovat parametry** – Generátor si uchovává stav mezi ukládáními. Pokud změníte `BarHeight` pro jeden obrázek a poté znovu použijete stejnou instanci pro jiný čárový kód, předchozí výška zůstane. Buď resetujte vlastnost, nebo vytvořte novou `BarcodeGenerator` pro každý odlišný čárový kód. + +## Kompletní end‑to‑end příklad (včetně instalace NuGet) + +Pokud začínáte od nuly, postupujte podle těchto kroků, abyste projekt spustili: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Nahraďte automaticky vygenerovaný `Program.cs` kódem uvedeným výše, **nezapomeňte nahradit `YOUR_DIRECTORY`** něčím jako `Path.Combine(Environment.CurrentDirectory, "output")`. Poté: + +```bash +dotnet run +``` + +V adresáři `output` byste měli vidět dva soubory PNG: + +- `DatabarBarHeight30Pixels.png` – kompaktní čárový kód vysoký 30 pixelů. +- `DatabarBarHeight60Pixels.png` – vyšší verze s výškou 60 pixelů. + +Oba obrázky budou vypadat podobně, ale druhý bude mít výrazně delší čáry, což usnadní čtení skenerům s nízkým rozlišením. + +![Příklad výšky čárového kódu](/images/barcode-height.png){alt=".net barcode generator výstup zobrazující různé výšky čar"} + +## Shrnutí a další kroky + +Probrali jsme, jak **generovat čárový kód** obrázky pomocí **.net barcode generator**, doladili vlastnost **změny výšky čárového kódu** a uložili výsledky ve formátu PNG. Hlavní body jsou: + +- Vytvořte generátor s správným `EncodeTypes`. +- Ovládejte vizuální velikost pomocí `XDimension` a `BarHeight`. +- Po každé změně zavolejte `Save`, aby se uložil nový obrázek. +- Upravte rozlišení, formát, + +## 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í přístupy k implementaci ve vašich projektech. + +- [Jak generovat Aztec čárový kód s vlastním poměrem stran pomocí Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Jak vytvořit rozšířený kódový text pro dotcode pomocí Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Jak generovat DataMatrix čárové kódy (ECC 200) pomocí 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/dutch/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/dutch/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..0066e42da --- /dev/null +++ b/barcode/dutch/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-07-18 +description: Barcodegenerator‑voorbeeld dat laat zien hoe je afmetingen instelt en + een DataBar Stacked Omni‑Directional barcode‑afbeelding genereert in C#. Leer barcode‑encodeertypen + snel. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: nl +lastmod: 2026-07-18 +og_description: Barcodegenerator‑voorbeeld leidt je stap voor stap door het instellen + van afmetingen, het kiezen van barcode‑encodeertypen en het maken van barcode‑afbeeldingsprojecten + in C# met minimale code. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Barcode Generator Voorbeeld – Snelle DataBar-afbeeldingscreatie in C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Barcode Generator Voorbeeld – Maak DataBar-afbeelding in C# +url: /nl/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode Generator-voorbeeld – DataBar-afbeelding maken in C# + +Heb je ooit een **barcode generator voorbeeld** nodig gehad dat echt een werkelijke barcode maakt zonder dat je je haar uittrekt? Je bent niet de enige. De meeste ontwikkelaars lopen tegen een muur aan wanneer ze proberen **hoe de afmetingen in te stellen** voor een DataBar Stacked Omni‑Directional barcode, vooral omdat de documentatie begraven ligt onder lagen jargon. + +In deze tutorial lopen we stap voor stap door een compleet, kant‑klaar C#‑programma dat laat zien **hoe je databar**‑afbeeldingen genereert, de juiste **barcode encode types** kiest, en uiteindelijk **barcode image c#**‑bestanden maakt die je in elk project kunt gebruiken. Geen poespas—alleen de code die je kunt copy‑pasten, plus de reden achter elke regel. + +## Wat je nodig hebt + +- **.NET 6** (of een recente .NET‑versie) – de API die we gebruiken richt zich op .NET Standard, dus hij werkt ook op .NET Framework. +- **Aspose.BarCode for .NET** – de bibliotheek die `BarcodeGenerator` levert. Je kunt hem via NuGet halen met `Install-Package Aspose.BarCode`. +- Een **C#‑IDE** – Visual Studio, Rider of VS Code volstaat. +- Een map op schijf waar de PNG‑bestanden worden opgeslagen (de code maakt `DatabarAspectRatio15.png` en `DatabarAspectRatio30.png` aan). + +Heb je alles? Geweldig—laten we beginnen. + +## Barcode Generator-voorbeeld – Initialiseer de Generator + +Allereerst hebben we een instantie van `BarcodeGenerator` nodig die is geconfigureerd voor de **DataBar Stacked Omni‑Directional** symbologie. Dit is het **barcode encode type** waarmee we gaan werken. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Waarom dit belangrijk is:** `EncodeTypes.DatabarStackedOmniDirectional` vertelt Aspose precies welke symbologie moet worden gerenderd. Als je het verkeerde type kiest, zal de scanner de barcode niet herkennen, hoe mooi de afbeelding er ook uitziet. + +## Hoe de afmetingen voor de barcode in te stellen + +De leesbaarheid van een barcode hangt af van de **X‑dimension** (de breedte van de smalste balk). In de meeste gevallen werkt een waarde van 2 pixels prima, maar je kunt dit aanpassen aan je printer of scherm. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Pro tip:** Als je je ooit afvraagt **hoe je de afmetingen instelt** voor een andere barcode‑familie, geldt dezelfde eigenschapsketen (`Parameters.Barcode.XDimension`)—verander alleen de `Pixels`‑waarde. + +## Hoe een DataBar Stacked Omni‑Directional barcode te genereren + +Nu de generator klaar is, gaan we spelen met de **aspect ratio**‑eigenschap. Deze bepaalt de hoogte‑tot‑breedte‑verhouding van de DataBar, zodat je een kort, vierkant symbool of een lang, smal symbool kunt maken. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Wat gebeurt er?** `AspectRatio = 15` vertelt de engine om de balken 15 keer hoger te maken dan ze breed zijn. De resulterende PNG wordt opgeslagen naast je uitvoerbare bestand. + +## Create Barcode Image C# – De aspect ratio wijzigen + +Laten we de flexibiliteit bewijzen door de ratio naar 30 te veranderen en een tweede bestand op te slaan. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +Wanneer je het programma uitvoert, krijg je twee PNG‑bestanden: + +| Bestand | Aspect Ratio | Geschatte grootte | +|---------|--------------|-------------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Open ze in een willekeurige afbeeldingsviewer—je zou schone, scanbare DataBar‑symbolen moeten zien. + +## Overzicht van Barcode Encode Types (Optioneel maar Handig) + +Als je nieuwsgierig bent naar andere **barcode encode types** die door Aspose worden ondersteund, hier een snelle cheat‑sheet: + +| EncodeTypes Enum | Beschrijving | +|------------------|--------------| +| `EncodeTypes.Code128` | Hoge‑dichtheid alfanumeriek | +| `EncodeTypes.QR` | 2‑D matrixcode | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar voor retail | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Onze focus** – compact, omnidirectioneel | + +De juiste enum kennen bespaart je veel trial‑and‑error wanneer je van project wisselt. + +## Veelvoorkomende valkuilen & hoe ze te vermijden + +- **Ontbrekend NuGet‑pakket** – De code compileert niet zonder `Aspose.BarCode`. Voer eerst `dotnet add package Aspose.BarCode` uit. +- **Verkeerd bestandspad** – Als je een absoluut pad gebruikt, controleer dan de backslashes (`\\`) op Windows. Relatieve paden (zoals hier) houden het draagbaar. +- **Aspect ratio te extreem** – Ratio’s boven 50 kunnen de barcode te hoog maken voor typische scanners. Houd je aan 15‑30 voor de meeste scenario’s. + +## Volledige broncode (Klaar om te copy‑pasten) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Voer het programma uit (`dotnet run` of druk op **F5** in Visual Studio) en je ziet een console‑bericht dat bevestigt dat de bestanden op schijf staan. + +![Barcode generator example output showing DataBar barcode with aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Voorbeeldoutput van barcode generator met DataBar barcode en aspect ratio 15"} + +## Afronding + +We hebben zojuist een **barcode generator voorbeeld** voltooid dat laat zien **hoe je de afmetingen instelt**, het juiste **barcode encode type** kiest, en uiteindelijk **barcode image c#**‑bestanden maakt die je overal kunt inbedden. De code is klein, de concepten zijn glashelder, en je hebt nu een solide basis om de oplossing uit te breiden—misschien door tekstbijschriften toe te voegen, de afbeelding te roteren, of over te schakelen naar een andere symbologie. + +### Wat is de volgende stap? + +- Experimenteer met **verschillende X‑dimensions** om te zien hoe de toleranties van scanners veranderen. +- Probeer andere **EncodeTypes** zoals `Code128` of `QR` om je gereedschapskist uit te breiden. +- Automatiseer batch‑generatie: loop over een CSV met product‑ID’s en genereer een PNG voor elk. + +Als je tegen een probleem aanloopt, laat dan een reactie achter of raadpleeg de Aspose.BarCode‑documentatie—die zit boordevol voorbeelden die aansluiten bij wat we hier behandeld hebben. + +Happy coding, 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 stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/dutch/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/dutch/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..7e3b3ac39 --- /dev/null +++ b/barcode/dutch/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-07-18 +description: Maak snel een Planet‑barcode met C#. Leer hoe je gevulde en lege staven + genereert, de X‑dimensie instelt en PNG‑afbeeldingen opslaat – allemaal in één tutorial. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: nl +lastmod: 2026-07-18 +og_description: Maak direct een Planet‑barcode. Deze gids laat zien hoe je de X‑dimensie + instelt, schakelt tussen gevulde en lege staven, en PNG‑bestanden exporteert met + Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Maak Planet Barcode in C# – Complete programmeerhandleiding +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Maak Planet Barcode in C# – Volledige stap‑voor‑stap gids +url: /nl/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maak Planet Barcode in C# – Volledige Stapsgewijze Gids + +Heb je ooit **planet barcode** afbeeldingen moeten maken maar wist je niet welke eigenschappen je moest aanpassen? Je bent niet de enige. Veel ontwikkelaars lopen tegen een muur wanneer de standaard gevulde strepen niet voldoen aan de specificatie, of wanneer de breedte van de strepen moet overeenkomen met de DPI van een printer. + +In deze tutorial leer je precies hoe je **planet barcode** bestanden maakt met de Aspose.BarCode‑bibliotheek, hoe je de **XDimension‑pixels** kunt regelen, en hoe je kunt schakelen tussen **gevulde strepen** en **lege strepen** zonder enige code opnieuw te schrijven. Aan het einde heb je twee PNG‑bestanden — een met massieve strepen en een met holle strepen — klaar voor elk postsysteem dat de Planet‑symbologie verwacht. + +## Vereisten + +- .NET 6.0 of later (de code werkt ook op .NET Framework 4.7 +) +- Aspose.BarCode for .NET NuGet‑pakket (`Install-Package Aspose.BarCode`) +- Basiskennis van C# (je ziet later waarom we `using`‑statements gebruiken) +- Een schrijfbare map op schijf waar de PNG‑bestanden worden opgeslagen + +Als je dit hebt, kunnen we meteen naar de implementatie gaan. + +## Stap 1 – Zet het project op en voeg de bibliotheek toe + +Eerst maak je een nieuwe console‑app (of elk C#‑project) en verwijs je naar de **Planet barcode‑generator**‑bibliotheek. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro tip:** In Visual Studio klik je met de rechtermuisknop op het project → *Manage NuGet Packages* → zoek naar **Aspose.BarCode** en klik op *Install*. Hiermee krijg je toegang tot `BarcodeGenerator` en alle **BarcodeGenerator‑parameters** die je nodig hebt. + +## Stap 2 – Initialiseert de Planet Barcode Generator + +Nu maken we daadwerkelijk een **planet barcode**‑generator‑instantie en voeren we de gegevens in die we willen coderen (`"123456"` in dit voorbeeld). De `EncodeTypes.Planet`‑enum vertelt de bibliotheek welke symbologie gebruikt moet worden. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Waarom dit belangrijk is:** De `EncodeTypes.Planet`‑vlag past automatisch de juiste checksum‑ en layoutrichtlijnen toe voor de Planet‑postbarcode, zodat je ze niet handmatig hoeft te berekenen. + +## Stap 3 – Configureer X‑Dimension (Balkbreedte) + +De meeste printers verwachten dat elke balk een specifiek aantal pixels heeft. Hier stellen we de **XDimension‑pixels** in op `4`, een veelvoorkomende waarde voor 203 dpi thermische printers. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Randgeval:** Als je een 300 dpi‑printer target, heb je mogelijk `3` of `5` pixels nodig. Pas deze waarde aan op basis van de documentatie van je apparaat. + +## Stap 4 – Sla de Filled‑Bar‑versie op + +Standaard genereert de generator **gevulde strepen** (massieve zwarte rechthoeken). Laten we die naar schijf schrijven: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Vervang `YOUR_DIRECTORY` door een absoluut of relatief pad waar je app naar kan schrijven. Nadat deze regel is uitgevoerd, vind je een PNG‑bestand dat eruitziet als een klassieke Planet‑barcode — perfect voor testen met een postscanner. + +## Stap 5 – Schakel over naar lege strepen + +Soms vereisen postdiensten de “lege strepen”‑stijl, waarbij de strepen uit een witte achtergrond worden uitgesneden in plaats van zwart te worden geschilderd. De bibliotheek biedt een eenvoudige schakelaar: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Door `FilledBars` op `false` te zetten, vertel je de renderer de vullogica om te keren. Je hoeft geen nieuwe `BarcodeGenerator`‑instantie te maken; we passen gewoon de bestaande **BarcodeGenerator‑parameters** aan. + +## Stap 6 – Sla de Empty‑Bar‑versie op + +Tot slot exporteer je de tweede afbeelding: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Nu heb je twee afzonderlijke PNG‑bestanden, elk voldaan aan een andere visuele eis. + +## Volledig werkend voorbeeld + +Alle stukjes bij elkaar, hier is het complete, kant‑en‑klaar‑te‑kopiëren programma: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Verwachte uitvoer** (op de console): + +``` +Both Planet barcode images have been generated successfully. +``` + +En in `C:\Barcodes\` zie je: + +- `PostalPlanetFilledBars.png` – massieve zwarte strepen +- `PostalPlanetEmptyBars.png` – witte strepen met zwarte omtrek + +Open ze in een willekeurige afbeeldingsviewer; beide zouden moeten voldoen aan de Planet‑specificatie. + +## Veelgestelde vragen & Tips + +### “Kan ik het afbeeldingsformaat wijzigen?” + +Zeker. De `Save`‑methode accepteert `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, enz. Vervang simpelweg `BarCodeImageFormat.Png` door het gewenste formaat. + +### “Wat als ik een andere barcode‑hoogte nodig heb?” + +Gebruik `planetBarcode.Parameters.Barcode.BarHeight` (in points) om de verticale grootte te vergroten of te verkleinen. Bijvoorbeeld: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “Is er een manier om een mens‑leesbare bijschrift toe te voegen?” + +Ja. Stel de `CodeText`‑eigenschap in op `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “Moet ik de generator vrijgeven?” + +`BarcodeGenerator` implementeert `IDisposable`. Plaats het in een `using`‑block als je veel barcodes in een lus maakt: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “Hoe zit het met foutafhandeling?” + +Omring de `Save`‑aanroepen met een `try…catch`‑blok om `IOException` (schijffouten) of `ArgumentException` (ongeldige parameters) af te vangen. Voorbeeld: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Samenvatting + +We hebben alles behandeld wat je nodig hebt om **planet barcode** afbeeldingen in C# te **maken**: + +1. Initialiseert de **Planet barcode‑generator** met je gegevens. +2. Pas **XDimension‑pixels** aan om aan de printerspecificaties te voldoen. +3. Sla een **gevulde strepen** PNG op. +4. Schakel `FilledBars` om **lege strepen** te produceren. +5. Sla de tweede PNG op. + +Vanaf hier kun je meer **BarcodeGenerator‑parameters** verkennen, experimenteren met andere symbologieën (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, enz.), of de afbeeldingen integreren in een verzendworkflow. + +--- + +**Klaar voor de volgende stap?** Probeer een QR‑code toe te voegen aan hetzelfde document, of genereer een batch Planet‑barcodes vanuit een CSV‑lijst met een `foreach`‑lus. De Aspose.BarCode‑API is flexibel genoeg voor bulk‑operaties, aangepaste kleuren en zelfs vector‑gebaseerde SVG‑output. + +Als je ergens vastloopt, laat dan een reactie achter of raadpleeg de officiële Aspose.BarCode‑documentatie voor diepere duiken in geavanceerde functies. Veel programmeerplezier! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids zijn 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. + +- [Barcode maken met Aspose - X‑ en Y‑dimensies instellen in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [Hoe code128 barcode‑afbeeldingen te maken in Java met Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [Hoe code128 barcode in Java te maken en de balkhoogte in te stellen](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/dutch/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..b02c19c31 --- /dev/null +++ b/barcode/dutch/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-07-18 +description: Maak snel een RM4SCC‑barcode in C#; leer hoe je de barcodehoogte instelt + en genereer ook een Planet‑barcode met aangepaste afmetingen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: nl +lastmod: 2026-07-18 +og_description: Maak een RM4SCC‑barcode in C# en ontdek hoe je de barcodehoogte instelt. + Bekijk ook hoe je een Planet‑barcode genereert met dezelfde bibliotheek. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Maak RM4SCC-barcode in C# – Stel aangepaste hoogte snel in +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Maak RM4SCC-barcode in C# – Volledige gids voor het instellen van de hoogte +url: /nl/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maak RM4SCC-barcode in C# – Volledige gids om hoogte in te stellen + +Heb je ooit een **RM4SCC barcode** moeten maken in een .NET‑app, maar wist je niet hoe je de grootte kunt regelen? Je bent niet de enige. Of je nu een postverwerkingssysteem of een logistiek dashboard bouwt, de juiste barcode‑hoogte kan het verschil maken tussen een scan die werkt en een die faalt. + +In deze tutorial lopen we het volledige proces door: van het installeren van de bibliotheek, tot het **genereren van een Planet barcode** als voorbeeld naast elkaar, en uiteindelijk **hoe je de barcode‑hoogte instelt** voor beide barcode‑typen. Aan het einde heb je een kant‑klaar console‑programma dat PNG‑bestanden genereert met precies de afmetingen die je nodig hebt. + +--- + +## Wat je nodig hebt + +- **.NET 6 SDK** (of een recente .NET‑versie) – de code werkt ook op .NET Framework, maar .NET 6 is de ideale keuze. +- **Aspose.BarCode for .NET** NuGet‑pakket – dit is de bibliotheek die de `BarcodeGenerator`‑klasse levert. +- Een bescheiden hoeveelheid C#‑kennis – we houden de syntax beginnersvriendelijk. +- Een IDE of teksteditor (Visual Studio, VS Code, Rider—kies wat je wilt). + +> **Pro tip:** Als je een CI/CD‑pipeline gebruikt, voeg dan de NuGet‑referentie toe in je `.csproj` zodat de build nooit de afhankelijkheid vergeet. + +--- + +## Stap 1: Het project opzetten + +Open een terminal en maak een nieuw console‑project aan: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +Dat is alles—je project verwijst nu naar de bibliotheek die alles aandrijft wat volgt. + +### Voeg de using‑directives toe + +Open `Program.cs` en plak het volgende bovenaan: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +Deze namespaces geven ons toegang tot `BarcodeGenerator` en de image‑format‑enum die we later gaan gebruiken. + +--- + +## Stap 2: Definieer een hulpmethode voor het opslaan van afbeeldingen + +Om te voorkomen dat we dezelfde opslaalogica herhalen, verpakken we die in een kleine methode. Dit laat ook zien **hoe je de barcode‑hoogte instelt** later. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Waarom dit belangrijk is:** Het centraliseren van de opslaalogica betekent dat je het formaat of de map slechts op één plek hoeft aan te passen als de eisen veranderen. + +--- + +## Stap 3: Genereer een Planet‑barcode (het “generate planet barcode”‑deel) + +Voordat we de RM4SCC‑details induiken, laten we een **Planet barcode** maken. Dit geeft je een snelle visuele controle dat de bibliotheek werkt. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Verwachte output:** Twee PNG‑bestanden verschijnen in de map `output`—een met de automatisch berekende hoogte van de bibliotheek, en een precies 100 px hoog. + +--- + +## Stap 4: Maak RM4SCC‑barcode – Hoofddoel + +Nu het sterpunt van de show: **maak RM4SCC barcode**. RM4SCC is de Royal Mail 4‑State Code, veelgebruikt in het Britse postensysteem. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**Wat je zult zien:** +- `RM4SCCDefault.png` – de bibliotheek kiest een comfortabele hoogte op basis van de X‑dimensie. +- `RM4SCCHeight100.png` – een scherpe barcode van 100 pixel hoog, klaar om op enveloppen te worden afgedrukt. + +> **Waarom de hoogte instellen?** Sommige labelprinters vereisen een minimale balkhoogte voor betrouwbare scanning. Door de hoogte vast te zetten, garandeer je naleving op alle apparaten. + +--- + +## Stap 5: Inzicht in de hoogte‑instellingen (Antwoord op “how to set barcode height”) + +Zowel de Planet‑ als de RM4SCC‑voorbeelden gebruiken dezelfde eigenschap: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** is een `BarHeight`‑object dat verschillende meeteenheden groepeert (pixels, millimeters, inches). +- **`.Pixels`** is de meest eenvoudige eenheid voor scherm‑gerichte output, maar je kunt ook `.Millimeters` of `.Inches` gebruiken als je voor printmedia richt. + +### Randgevallen & Tips + +| Situatie | Aanbevolen aanpak | +|-----------|-------------------| +| **Zeer kleine X‑dimensie (bijv. 1 px)** | Verhoog `BarHeight` om de barcode leesbaar te houden. | +| **Afdrukken op high‑resolution labelprinters** | Gebruik `.Millimeters` voor apparaat‑onafhankelijke afmetingen. | +| **Gemengde barcode‑typen in één afbeelding** | Stel `BarHeight` *na* `XDimension` in voor elke generator om onbedoelde overerving te voorkomen. | +| **Dynamische data (bijv. door de gebruiker ingevoerde codes)** | Verpak de generatorcreatie in een methode die `code` en `height` parameters accepteert. | + +--- + +## Stap 6: Volledig werkend voorbeeld + +Hieronder vind je een enkel, zelfstandig programma dat je kunt kopiëren‑plakken in `Program.cs`. Het bevat alles van projectopzet tot het opslaan van de afbeeldingen. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Voer het uit met: + +```bash +dotnet run +``` + +Je zou de console‑output moeten zien die bevestigt dat elk bestand is opgeslagen, en de map `output` zal vier PNG‑bestanden bevatten met de hierboven getoonde namen. + +--- + +## Conclusie + +Je weet nu **hoe je een RM4SCC barcode maakt** in C# en de afmetingen regelt met slechts een paar eigenschaps‑toewijzingen. We hebben ook **Planet barcode genereren** behandeld als snelle controle, en de nuances van **hoe je de barcode‑hoogte instelt** voor verschillende afdrukscenario’s verkend. + +Volgende stappen? Probeer de `EncodeTypes`‑enum te vervangen door andere symbologieën (Code128, QR, DataMatrix) en experimenteer met `BarHeight` in millimeters voor high‑resolution printers. Als je de barcode in een PDF wilt embedden, combineer dan Aspose.BarCode met Aspose.PDF—een andere krachtige combinatie. + +Heb je vragen of wil je je eigen tweaks delen? Laat een reactie achter hieronder, en happy coding! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids zijn gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe een Aztec‑barcode genereren met aangepaste beeldverhouding met Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Hoe een barcode‑quiet‑zone maken voor ITF-14 met Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Hoe een barcode‑quiet‑zone maken voor Code 16K met Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/dutch/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..5ee57a88d --- /dev/null +++ b/barcode/dutch/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-07-18 +description: Leer hoe u barcode‑afbeeldingen kunt genereren met een .net barcode‑generator + en eenvoudig de barcodehoogte kunt aanpassen voor GS1‑Databar Omni‑Directional‑symbolen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: nl +lastmod: 2026-07-18 +og_description: .net barcode generator laat je snel barcode‑afbeeldingen maken. Deze + gids laat zien hoe je een barcode genereert, de balkhoogte aanpast en PNG‑bestanden + opslaat. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Pas de barcodehoogte aan met .net barcodegenerator +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET barcodegenerator – barcodehoogte wijzigen +url: /nl/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – barcodehoogte wijzigen + +Heb je je ooit afgevraagd **hoe je barcode** afbeeldingen kunt genereren zonder een tiental externe tools te jongleren? In de .NET-wereld is er een verrassend eenvoudige manier om dit te doen, en het belangrijkste onderdeel is de **.net barcode generator**. Met slechts een paar regels C# kun je een GS1‑Databar Omni‑Directional symbool maken, de balkhoogte aanpassen en het resultaat opslaan als een PNG‑bestand. + +Als je een voorraadbeheersysteem, een verzendetikettenprinter of een andere app bouwt die een scanbare code nodig heeft, brengt deze tutorial je in enkele minuten van nul naar een werkende barcode. We lopen de volledige code stap voor stap door, leggen uit waarom elke instelling belangrijk is, en laten zien hoe je de **barcodehoogte wijzigt** zonder de specificatie te breken. + +## Wat je nodig hebt + +- .NET 6.0 of later (the API works the same on .NET Framework 4.7+) +- Een referentie naar de barcode‑bibliotheek (bijvoorbeeld, Aspose.BarCode for .NET – dezelfde klassen worden gebruikt door veel commerciële kits) +- Een ontwikkelomgeving (Visual Studio, Rider, of VS Code met de C#‑extensie) +- Een map waarin je schrijfrechten hebt – de tutorial slaat daar PNG‑bestanden op + +Dat is alles. Geen extra NuGet‑pakketten naast de barcode‑bibliotheek zelf. + +## De .net barcode generator gebruiken om de barcodehoogte te wijzigen + +Hieronder staat een **volledig, uitvoerbaar console‑programma**. Plak het in een nieuw C#‑project, pas de uitvoermap aan, en druk op F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Waarom elke regel belangrijk is + +| Line | Reason | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Instantieert de **.net barcode generator** met de gewenste symbologie en gegevenspayload. De `EncodeTypes.DatabarOmniDirectional`‑enum geeft de bibliotheek aan om het GS1‑Databar Omni‑Directional‑formaat te gebruiken. | +| `XDimension.Pixels = 2;` | De X‑dimensie is de breedte van de dunste balk. Instellen op *2 pixels* levert een scherp beeld op de meeste monitoren en houdt de bestandsgrootte klein. | +| `BarHeight.Pixels = 30;` | Dit is de **barcodehoogte wijzigen** stap die bepaalt hoe hoog elke balk wordt. Een hoogte van 30 pixels is een goede standaard voor kleine etiketten. | +| `generator.Save(...);` | Slaat de barcode op als een PNG‑bestand. PNG is verliesvrij, wat betekent dat scanners het exacte patroon zien dat je hebt gegenereerd. | +| `BarHeight.Pixels = 60;` | Hier **wijzigen we de barcodehoogte** opnieuw—dit keer naar 60 pixels. De bibliotheek rendert het symbool automatisch opnieuw met de nieuwe afmeting wanneer je `Save` een tweede keer aanroept. | +| `Console.WriteLine(...);` | Geeft je snelle feedback dat het proces is voltooid zonder een uitzondering te werpen. | + +> **Pro tip:** Als je een hogere resolutie‑output nodig hebt voor afdrukken, schakel `BarCodeImageFormat.Png` over naar `BarCodeImageFormat.Tiff` en verhoog de `Resolution`‑eigenschap (bijv. `generator.Parameters.ImageResolution = 300;`). De balkhoogte blijft gerespecteerd, alleen gerenderd met een fijnere DPI. + +## Hoe barcode‑afbeeldingen te genereren met verschillende instellingen + +De bovenstaande code behandelt de basis, maar real‑world scenario's vereisen vaak extra aanpassingen: + +### X‑dimensie aanpassen voor grotere afdrukken +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Het verhogen van de X‑dimensie maakt de hele barcode groter zonder de gecodeerde data te wijzigen. Dit is handig bij het afdrukken op grote etiketten. + +### Uitvoerformaten wisselen +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG schaalt oneindig, wat perfect is voor web‑gebaseerde scanners die scherpe vectoren nodig hebben. + +### Menselijk leesbare tekst toevoegen +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Het inschakelen van `CodeTextVisible` voegt de ruwe data onder de barcode toe, handig voor verificatie tijdens het testen. + +## Veelvoorkomende valkuilen wanneer je **barcodehoogte wijzigt** + +1. **Hoogte te klein** – Sommige scanners vereisen een minimale balkhoogte (vaak 10 mm in fysieke eenheden). Als je `BarHeight.Pixels` te laag instelt, kan de gegenereerde afbeelding onleesbaar zijn voor een echte scanner. Test altijd met je doelhardware. +2. **Niet‑overeenkomende X‑dimensie en hoogte** – Een enorme balkhoogte gecombineerd met een kleine X‑dimensie kan er uitgerekt uitzien en kan decodeerfouten veroorzaken. Streef naar een gebalanceerde verhouding (ongeveer 3:1 tot 5:1) tenzij de specificatie iets anders aangeeft. +3. **Vergeten parameters te resetten** – De generator behoudt de staat tussen opslagen. Als je `BarHeight` voor één afbeelding wijzigt en vervolgens dezelfde instantie opnieuw gebruikt voor een andere barcode, blijft de vorige hoogte behouden. Reset de eigenschap of maak een nieuwe `BarcodeGenerator` aan voor elke afzonderlijke barcode. + +## Volledig end‑to‑end voorbeeld (inclusief NuGet‑installatie) + +Als je vanaf nul begint, volg dan deze stappen om het project werkend te krijgen: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Vervang de automatisch gegenereerde `Program.cs` door het eerder getoonde code‑blok, **vergeet niet `YOUR_DIRECTORY`** te vervangen door iets als `Path.Combine(Environment.CurrentDirectory, "output")`. Vervolgens: + +```bash +dotnet run +``` + +Je zou twee PNG‑bestanden in de `output`‑map moeten zien: + +- `DatabarBarHeight30Pixels.png` – een compacte barcode van 30 pixels hoog. +- `DatabarBarHeight60Pixels.png` – een hogere versie van 60 pixels. + +Beide afbeeldingen zien er vergelijkbaar uit, maar de tweede heeft merkbaar langere balken, waardoor het makkelijker is voor scanners met lage resolutie om te lezen. + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator output die verschillende balkhoogtes toont"} + +## Samenvatting & volgende stappen + +We hebben behandeld hoe je **barcode** afbeeldingen kunt **genereren** met een **.net barcode generator**, de **barcodehoogte wijzigen** eigenschap fijn afgesteld, en de resultaten opgeslagen in PNG‑formaat. De belangrijkste punten zijn: + +- Instantieer de generator met de juiste `EncodeTypes`. +- Regel de visuele grootte via `XDimension` en `BarHeight`. +- Roep `Save` aan na elke wijziging om een nieuwe afbeelding op te slaan. +- Pas resolutie, formaat, ... + +## 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 aspectratio met Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Hoe een dotcode met uitgebreide codetext te maken met Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Hoe DataMatrix barcodes (ECC 200) te genereren met 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/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/english/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..b30f4a0db --- /dev/null +++ b/barcode/english/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-07-18 +description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: en +lastmod: 2026-07-18 +og_description: Barcode generator example walks you through how to set dimensions, + choose barcode encode types, and create barcode image C# projects with minimal code. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Barcode Generator Example – Quick DataBar Image Creation in C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Barcode Generator Example – Build DataBar Image in C# +url: /python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode Generator Example – Build DataBar Image in C# + +Ever needed a **barcode generator example** that actually prints a real‑world barcode without pulling your hair out? You’re not alone. Most developers hit a wall when they try to figure out **how to set dimensions** for a DataBar Stacked Omni‑Directional barcode, especially when the documentation is buried under layers of jargon. + +In this tutorial we’ll walk through a complete, ready‑to‑run C# program that shows **how to generate databar** images, picks the right **barcode encode types**, and finally **create barcode image c#** files you can drop into any project. No fluff—just the code you can copy‑paste, plus the reasoning behind every line. + +## What You’ll Need + +- **.NET 6** (or any recent .NET version) – the API we use targets .NET Standard, so it works on .NET Framework too. +- **Aspose.BarCode for .NET** – the library that provides `BarcodeGenerator`. You can grab it from NuGet with `Install-Package Aspose.BarCode`. +- A **C# IDE** – Visual Studio, Rider, or VS Code will do. +- A folder on disk where the PNG files will be saved (the code creates `DatabarAspectRatio15.png` and `DatabarAspectRatio30.png`). + +Got all that? Great—let’s dive in. + +## Barcode Generator Example – Initialize the Generator + +First things first: we need an instance of `BarcodeGenerator` configured for the **DataBar Stacked Omni‑Directional** symbology. This is the **barcode encode type** we’ll be working with. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Why this matters:** `EncodeTypes.DatabarStackedOmniDirectional` tells Aspose exactly which symbology to render. If you pick the wrong type, the scanner won’t recognize the barcode, no matter how pretty the image looks. + +## How to Set Dimensions for the Barcode + +A barcode’s readability hinges on its **X‑dimension** (the width of the narrowest bar). In most cases a value of 2 pixels works fine, but you can tweak it to suit your printer or screen. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Pro tip:** If you ever wonder **how to set dimensions** for a different barcode family, the same property chain (`Parameters.Barcode.XDimension`) applies—just change the `Pixels` value. + +## How to Generate DataBar Stacked Omni‑Directional Barcode + +Now that the generator is ready, we’ll play with the **aspect ratio** property. This controls the height‑to‑width relationship of the DataBar, letting you produce a short, squarish symbol or a tall, narrow one. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **What’s happening?** `AspectRatio = 15` tells the engine to make the bars 15 times taller than they are wide. The resulting PNG is saved right next to your executable. + +## Create Barcode Image C# – Changing the Aspect Ratio + +Let’s prove the flexibility by swapping the ratio to 30 and saving a second file. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +When you run the program, you’ll end up with two PNG files: + +| File | Aspect Ratio | Approx. Size | +|------|--------------|--------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Open them in any image viewer—you should see clean, scannable DataBar symbols. + +## Barcode Encode Types Overview (Optional but Handy) + +If you’re curious about other **barcode encode types** supported by Aspose, here’s a quick cheat‑sheet: + +| EncodeTypes Enum | Description | +|------------------|-------------| +| `EncodeTypes.Code128` | High‑density alphanumeric | +| `EncodeTypes.QR` | 2‑D matrix code | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar for retail | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Our focus** – compact, omnidirectional | + +Knowing the right enum saves you from a lot of trial‑and‑error when you switch projects. + +## Common Pitfalls & How to Avoid Them + +- **Missing NuGet package** – The code won’t compile without `Aspose.BarCode`. Run `dotnet add package Aspose.BarCode` first. +- **Wrong file path** – If you use an absolute path, double‑check the backslashes (`\\`) on Windows. Relative paths (as shown) keep things portable. +- **Aspect ratio too extreme** – Ratios above 50 can make the barcode too tall for typical scanners. Stick to 15‑30 for most use‑cases. + +## Full Source Code (Copy‑Paste Ready) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Run the program (`dotnet run` or press **F5** in Visual Studio) and you’ll see the console message confirming the files are on disk. + +![Barcode generator example output showing DataBar barcode with aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Barcode generator example output showing DataBar barcode with aspect ratio 15"} + +## Wrapping Up + +We’ve just completed a **barcode generator example** that demonstrates **how to set dimensions**, picks the correct **barcode encode types**, and finally **create barcode image c#** files you can embed anywhere. The code is tiny, the concepts are crystal‑clear, and you now have a solid foundation for extending the solution—maybe adding text captions, rotating the image, or switching to a different symbology. + +### What’s Next? + +- Experiment with **different X‑dimensions** to see how scanner tolerance changes. +- Try other **EncodeTypes** like `Code128` or `QR` to broaden your toolkit. +- Automate batch generation: loop over a CSV of product IDs and spit out a PNG for each. + +If you hit a snag, drop a comment below or check the Aspose.BarCode documentation—it's packed with examples that complement what we covered here. + +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 Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/python-java/general/barcode-generator-example-build-databar-image-in-c/og-image.png b/barcode/english/python-java/general/barcode-generator-example-build-databar-image-in-c/og-image.png new file mode 100644 index 000000000..be91c58cf Binary files /dev/null and b/barcode/english/python-java/general/barcode-generator-example-build-databar-image-in-c/og-image.png differ diff --git a/barcode/english/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/english/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..db07fe10d --- /dev/null +++ b/barcode/english/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-07-18 +description: Create Planet barcode quickly with C#. Learn how to generate filled and + empty bars, set X‑dimension, and save PNG images – all in one tutorial. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: en +lastmod: 2026-07-18 +og_description: Create Planet barcode instantly. This guide shows you how to set X‑dimension, + switch between filled and empty bars, and export PNG files with Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Create Planet Barcode in C# – Complete Programming Walkthrough +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Create Planet Barcode in C# – Full Step‑by‑Step Guide +url: /python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create Planet Barcode in C# – Full Step‑by‑Step Guide + +Ever needed to **create planet barcode** images but weren’t sure which properties to tweak? You're not alone. Many developers hit a wall when the default filled bars aren’t what the spec demands, or when the bar width must match a printer’s DPI. + +In this tutorial you’ll learn exactly how to **create planet barcode** files using the Aspose.BarCode library, how to control the **XDimension pixels**, and how to switch between **filled bars** and **empty bars** without rewriting any code. By the end you’ll have two PNG files—one with solid bars and one with hollow bars—ready for any postal system that expects the Planet symbology. + +## Prerequisites + +- .NET 6.0 or later (the code works on .NET Framework 4.7 + as well) +- Aspose.BarCode for .NET NuGet package (`Install-Package Aspose.BarCode`) +- Basic C# knowledge (you’ll see why we use `using` statements later) +- A writable folder on disk where the PNGs will be saved + +If you’ve got these, we can jump straight into the implementation. + +## Step 1 – Set Up the Project and Add the Library + +First, create a new console app (or any C# project) and reference the **Planet barcode generator** library. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro tip:** In Visual Studio, right‑click the project → *Manage NuGet Packages* → search for **Aspose.BarCode** and click *Install*. This gives you access to `BarcodeGenerator` and all the **BarcodeGenerator parameters** you’ll need. + +## Step 2 – Initialise the Planet Barcode Generator + +Now we actually **create planet barcode** generator instance and feed it the data we want to encode (`"123456"` in this example). The `EncodeTypes.Planet` enum tells the library which symbology to use. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Why this matters:** The `EncodeTypes.Planet` flag automatically applies the correct checksum and layout rules for the Planet postal barcode, so you don’t have to calculate them manually. + +## Step 3 – Configure X‑Dimension (Bar Width) + +Most printers expect each bar to be a specific number of pixels. Here we set the **XDimension pixels** to `4`, which is a common value for 203 dpi thermal printers. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Edge case:** If you’re targeting a 300 dpi printer, you might need `3` or `5` pixels instead. Adjust this value based on your device’s documentation. + +## Step 4 – Save the Filled‑Bar Version + +By default the generator produces **filled bars** (solid black rectangles). Let’s write that to disk: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Replace `YOUR_DIRECTORY` with an absolute or relative path that your app can write to. After this line runs you’ll find a PNG file that looks like a classic Planet barcode—perfect for testing against a postal scanner. + +## Step 5 – Switch to Empty Bars + +Sometimes postal services require the “empty bars” style, where the bars are carved out of a white background instead of painted black. The library exposes a simple switch: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Setting `FilledBars` to `false` tells the renderer to invert the bar fill logic. No need to create a new `BarcodeGenerator` instance; we just tweak the existing **BarcodeGenerator parameters**. + +## Step 6 – Save the Empty‑Bar Version + +Finally, export the second image: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Now you have two distinct PNG files, each adhering to a different visual requirement. + +## Full Working Example + +Putting all the pieces together, here’s the complete, copy‑and‑paste‑ready program: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Expected output** (on the console): + +``` +Both Planet barcode images have been generated successfully. +``` + +And in `C:\Barcodes\` you’ll see: + +- `PostalPlanetFilledBars.png` – solid black bars +- `PostalPlanetEmptyBars.png` – white bars with black outlines + +Open them in any image viewer; they should both comply with the Planet specification. + +## Common Questions & Tips + +### “Can I change the image format?” + +Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + +### “What if I need a different barcode height?” + +Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase or decrease the vertical size. For example: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “Is there a way to add a human‑readable caption?” + +Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “Do I need to dispose the generator?” + +The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block if you’re creating many barcodes in a loop: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “What about error handling?” + +Enclose the `Save` calls in a `try…catch` block to capture `IOException` (disk issues) or `ArgumentException` (invalid parameters). Example: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Recap + +We’ve covered everything you need to **create planet barcode** images in C#: + +1. Initialise the **Planet barcode generator** with your data. +2. Adjust **XDimension pixels** to match printer specs. +3. Save a **filled bars** PNG. +4. Toggle `FilledBars` to produce **empty bars**. +5. Save the second PNG. + +From here you can explore more **BarcodeGenerator parameters**, experiment with other symbologies (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, etc.), or integrate the images into a mailing workflow. + +--- + +**Ready for the next step?** Try adding a QR code to the same document, or generate a batch of Planet barcodes from a CSV list using a `foreach` loop. The Aspose.BarCode API is flexible enough to handle bulk operations, custom colors, and even vector‑based SVG output. + +If you hit any snags, drop a comment below or check the official Aspose.BarCode documentation for deeper dives into advanced features. 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. + +- [Create Barcode with Aspose - Set X & Y Dimensions in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/og-image.png b/barcode/english/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/og-image.png new file mode 100644 index 000000000..f01a71440 Binary files /dev/null and b/barcode/english/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/og-image.png differ diff --git a/barcode/english/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/english/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..37ddb8304 --- /dev/null +++ b/barcode/english/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,274 @@ +--- +category: general +date: 2026-07-18 +description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: en +lastmod: 2026-07-18 +og_description: Create RM4SCC barcode in C# and discover how to set barcode height. + Also see how to generate Planet barcode with the same library. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Create RM4SCC Barcode in C# – Set Custom Height Fast +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Create RM4SCC Barcode in C# – Full Guide to Set Height +url: /python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create RM4SCC Barcode in C# – Full Guide to Set Height + +Ever needed to **create RM4SCC barcode** in a .NET app but weren’t sure how to control its size? You’re not alone. Whether you’re building a mailing system or a logistics dashboard, getting the right barcode height can be the difference between a scan that works and one that fails. + +In this tutorial we’ll walk through the entire process: from installing the library, to **generate Planet barcode** as a side‑by‑side example, and finally to **how to set barcode height** for both barcode types. By the end you’ll have a ready‑to‑run console app that spits out PNG files with the exact dimensions you need. + +--- + +## What You’ll Need + +- **.NET 6 SDK** (or any recent .NET version) – the code works on .NET Framework too, but .NET 6 is the sweet spot. +- **Aspose.BarCode for .NET** NuGet package – this is the library that provides the `BarcodeGenerator` class. +- A modest amount of C# knowledge – we’ll keep the syntax beginner‑friendly. +- An IDE or text editor (Visual Studio, VS Code, Rider—pick your poison). + +> **Pro tip:** If you’re on a CI/CD pipeline, add the NuGet reference in your `.csproj` so the build never forgets the dependency. + +--- + +## Step 1: Set Up the Project + +Open a terminal and create a new console project: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +That’s it—your project now references the library that powers everything that follows. + +### Add the Using Directives + +Open `Program.cs` and paste the following at the top: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +These namespaces give us access to `BarcodeGenerator` and the image format enum we’ll use later. + +--- + +## Step 2: Define a Helper Method for Saving Images + +To avoid repeating the same save logic, we’ll wrap it in a tiny method. This also demonstrates **how to set barcode height** later on. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Why this matters:** Centralising the save logic means you only have to change the format or folder in one place if requirements shift. + +--- + +## Step 3: Generate a Planet Barcode (the “generate planet barcode” part) + +Before we dive into the RM4SCC specifics, let’s spin up a **Planet barcode**. This gives you a quick visual sanity check that the library is working. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Expected output:** Two PNG files appear in the `output` folder—one with the library’s auto‑calculated height, the other exactly 100 px tall. + +--- + +## Step 4: Create RM4SCC Barcode – Primary Goal + +Now for the star of the show: **create RM4SCC barcode**. RM4SCC is the Royal Mail 4‑State Code, widely used in the UK postal system. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**What you’ll see:** +- `RM4SCCDefault.png` – the library decides a comfortable height based on the X‑dimension. +- `RM4SCCHeight100.png` – a crisp 100‑pixel tall barcode ready for printing on envelopes. + +> **Why set the height?** Some label printers demand a minimum bar height for reliable scanning. By fixing the height you guarantee compliance across devices. + +--- + +## Step 5: Understanding the Height Settings (Answering “how to set barcode height”) + +Both the Planet and RM4SCC examples use the same property: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** is a `BarHeight` object that groups several measurement units (pixels, millimetres, inches). +- **`.Pixels`** is the most straightforward unit for screen‑oriented output, but you can also use `.Millimeters` or `.Inches` if you’re targeting print media. + +### Edge Cases & Tips + +| Situation | Recommended Approach | +|-----------|----------------------| +| **Very small X‑dimension (e.g., 1 px)** | Increase `BarHeight` to keep the barcode readable. | +| **Printing on high‑resolution label printers** | Use `.Millimeters` for device‑independent sizing. | +| **Mixed barcode types in one image** | Set `BarHeight` *after* `XDimension` for each generator to avoid accidental inheritance. | +| **Dynamic data (e.g., user‑entered codes)** | Wrap the generator creation in a method that accepts `code` and `height` parameters. | + +--- + +## Step 6: Full Working Example + +Below is a single, self‑contained program you can copy‑paste into `Program.cs`. It includes everything from project setup to saving the images. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Run it with: + +```bash +dotnet run +``` + +You should see the console output confirming each file saved, and the `output` folder will contain four PNGs matching the names shown above. + +--- + +## Conclusion + +You now know **how to create RM4SCC barcode** in C# and control its dimensions with just a couple of property assignments. We also covered **generate planet barcode** as a quick sanity check, and explored the nuances of **how to set barcode height** for different printing scenarios. + +Next steps? Try swapping the `EncodeTypes` enum for other symbologies (Code128, QR, DataMatrix) and experiment with `BarHeight` in millimetres for high‑resolution printers. If you need to embed the barcode into a PDF, pair Aspose.BarCode with Aspose.PDF—another powerful combo. + +Got questions or want to share your own tweaks? Drop a comment below, and 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 Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [How to create barcode quiet zone for Code 16K using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/og-image.png b/barcode/english/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/og-image.png new file mode 100644 index 000000000..69df29355 Binary files /dev/null and b/barcode/english/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/og-image.png differ diff --git a/barcode/english/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/english/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..1a1d12cc9 --- /dev/null +++ b/barcode/english/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-07-18 +description: Learn how to generate barcode images with a .net barcode generator and + easily change barcode height for GS1‑Databar Omni‑Directional symbols. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: en +lastmod: 2026-07-18 +og_description: .net barcode generator lets you quickly create barcode images. This + guide shows how to generate barcode, adjust bar height, and save PNG files. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Change barcode height with .net barcode generator +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .net barcode generator – change barcode height +url: /python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – change barcode height + +Ever wondered **how to generate barcode** images without juggling a dozen third‑party tools? In the .NET world there’s a surprisingly clean way to do it, and the key piece is the **.net barcode generator**. With just a few lines of C# you can spin up a GS1‑Databar Omni‑Directional symbol, tweak the bar height, and dump the result to a PNG file. + +If you’re building an inventory system, a shipping label printer, or any app that needs a scannable code, this tutorial will get you from zero to a working barcode in minutes. We’ll walk through the complete code, explain why each setting matters, and show you how to **change barcode height** without breaking the spec. + +## What you’ll need + +- .NET 6.0 or later (the API works the same on .NET Framework 4.7+) +- A reference to the barcode library (for example, Aspose.BarCode for .NET – the same classes are used by many commercial kits) +- A development environment (Visual Studio, Rider, or VS Code with the C# extension) +- A folder where you have write permission – the tutorial will save PNG files there + +That’s it. No extra NuGet packages beyond the barcode library itself. + +## Using the .net barcode generator to change barcode height + +Below is a **complete, runnable console program**. Paste it into a new C# project, adjust the output folder, and hit F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Why each line matters + +| Line | Reason | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` enum tells the library to use the GS1‑Databar Omni‑Directional format. | +| `XDimension.Pixels = 2;` | The X‑dimension is the width of the thinnest bar. Setting it to *2 pixels* gives a crisp image on most monitors while keeping file size low. | +| `BarHeight.Pixels = 30;` | This is the **change barcode height** step that determines how tall each bar will be. A 30‑pixel height is a good default for small labels. | +| `generator.Save(...);` | Persists the barcode to a PNG file. PNG is loss‑less, which means scanners see the exact pattern you generated. | +| `BarHeight.Pixels = 60;` | Here we **change barcode height** again—this time to 60 pixels. The library automatically re‑renders the symbol with the new dimension when you call `Save` a second time. | +| `Console.WriteLine(...);` | Gives you quick feedback that the process finished without throwing an exception. | + +> **Pro tip:** If you need higher‑resolution output for printing, switch `BarCodeImageFormat.Png` to `BarCodeImageFormat.Tiff` and bump the `Resolution` property (e.g., `generator.Parameters.ImageResolution = 300;`). The bar height will still be respected, just rendered at a finer DPI. + +## How to generate barcode images with different settings + +The snippet above covers the basics, but real‑world scenarios often demand extra tweaks: + +### Adjusting the X‑dimension for larger prints +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Increasing the X‑dimension makes the whole barcode larger without altering the encoded data. This is handy when you print on large labels. + +### Switching output formats +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG scales infinitely, which is perfect for web‑based scanners that need crisp vectors. + +### Adding human‑readable text +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Enabling `CodeTextVisible` appends the raw data under the barcode, useful for verification during testing. + +## Common pitfalls when you **change barcode height** + +1. **Height too small** – Some scanners require a minimum bar height (often 10 mm in physical units). If you set `BarHeight.Pixels` too low, the generated image might be unreadable on a real scanner. Always test with your target hardware. +2. **Mismatched X‑dimension and height** – A huge bar height paired with a tiny X‑dimension can look stretched and may cause decoding errors. Aim for a balanced ratio (roughly 3:1 to 5:1) unless the spec says otherwise. +3. **Forgetting to reset parameters** – The generator keeps state between saves. If you change `BarHeight` for one image and then reuse the same instance for another barcode, the previous height will stick around. Either reset the property or instantiate a new `BarcodeGenerator` for each distinct barcode. + +## Full end‑to‑end example (including NuGet install) + +If you’re starting from scratch, follow these steps to get the project running: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Replace the autogenerated `Program.cs` with the code block shown earlier, **remember to replace `YOUR_DIRECTORY`** with something like `Path.Combine(Environment.CurrentDirectory, "output")`. Then: + +```bash +dotnet run +``` + +You should see two PNG files in the `output` folder: + +- `DatabarBarHeight30Pixels.png` – a compact 30‑pixel tall barcode. +- `DatabarBarHeight60Pixels.png` – a taller 60‑pixel version. + +Both images will look similar, but the second one will have noticeably longer bars, making it easier for low‑resolution scanners to read. + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator output showing different bar heights"} + +## Recap & next steps + +We’ve covered how to **generate barcode** images using a **.net barcode generator**, fine‑tuned the **change barcode height** property, and saved the results in PNG format. The key takeaways are: + +- Instantiate the generator with the correct `EncodeTypes`. +- Control visual size via `XDimension` and `BarHeight`. +- Call `Save` after each change to persist a new image. +- Adjust resolution, format, + + +## 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 create dotcode extended codetext with Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-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/python-java/general/net-barcode-generator-change-barcode-height/og-image.png b/barcode/english/python-java/general/net-barcode-generator-change-barcode-height/og-image.png new file mode 100644 index 000000000..65e315557 Binary files /dev/null and b/barcode/english/python-java/general/net-barcode-generator-change-barcode-height/og-image.png differ diff --git a/barcode/french/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/french/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..ff4c5e14f --- /dev/null +++ b/barcode/french/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-07-18 +description: Exemple de générateur de codes‑barres montrant comment définir les dimensions + et générer une image de code‑barres DataBar Stacked Omni‑Directional en C#. Apprenez + rapidement les types d’encodage de codes‑barres. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: fr +lastmod: 2026-07-18 +og_description: L'exemple de générateur de codes‑barres vous montre comment définir + les dimensions, choisir les types d’encodage et créer des projets d’images de codes‑barres + en C# avec un code minimal. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Exemple de générateur de code‑barres – Création rapide d’image DataBar en + C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Exemple de générateur de code-barres – Créez une image DataBar en C# +url: /fr/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Exemple de générateur de code‑barres – Créer une image DataBar en C# + +Vous avez déjà eu besoin d’un **exemple de générateur de code‑barres** qui crée réellement un code‑barres utilisable sans vous arracher les cheveux ? Vous n’êtes pas seul. La plupart des développeurs se heurtent à un mur lorsqu’ils essaient de déterminer **comment définir les dimensions** d’un code‑barres DataBar Stacked Omni‑Directional, surtout quand la documentation est enfouie sous des couches de jargon. + +Dans ce tutoriel, nous allons parcourir un programme C# complet, prêt à l’exécution, qui montre **comment générer des images databar**, sélectionne les bons **types d’encodage de code‑barres**, et enfin **crée des fichiers image de code‑barres c#** que vous pouvez intégrer à n’importe quel projet. Pas de blabla—juste le code à copier‑coller, plus le raisonnement derrière chaque ligne. + +## Ce dont vous avez besoin + +- **.NET 6** (ou toute version récente de .NET) – l’API que nous utilisons cible .NET Standard, elle fonctionne donc aussi sur .NET Framework. +- **Aspose.BarCode for .NET** – la bibliothèque qui fournit `BarcodeGenerator`. Vous pouvez l’obtenir via NuGet avec `Install-Package Aspose.BarCode`. +- Un **IDE C#** – Visual Studio, Rider ou VS Code feront l’affaire. +- Un dossier sur le disque où les fichiers PNG seront enregistrés (le code crée `DatabarAspectRatio15.png` et `DatabarAspectRatio30.png`). + +Tout est‑t‑il prêt ? Parfait—plongeons‑y. + +## Exemple de générateur de code‑barres – Initialiser le générateur + +Première étape : nous avons besoin d’une instance de `BarcodeGenerator` configurée pour la symbologie **DataBar Stacked Omni‑Directional**. C’est le **type d’encodage de code‑barres** avec lequel nous allons travailler. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Pourquoi c’est important :** `EncodeTypes.DatabarStackedOmniDirectional` indique à Aspose exactement quelle symbologie rendre. Si vous choisissez le mauvais type, le lecteur ne reconnaîtra pas le code‑barres, aussi joli soit l’image. + +## Comment définir les dimensions du code‑barres + +La lisibilité d’un code‑barres dépend de son **X‑dimension** (la largeur de la barre la plus étroite). Dans la plupart des cas, une valeur de 2 pixels suffit, mais vous pouvez l’ajuster selon votre imprimante ou votre écran. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Astuce pro :** Si vous vous demandez **comment définir les dimensions** pour une autre famille de codes‑barres, la même chaîne de propriétés (`Parameters.Barcode.XDimension`) s’applique—il suffit de changer la valeur `Pixels`. + +## Comment générer un code‑barres DataBar Stacked Omni‑Directional + +Maintenant que le générateur est prêt, nous allons jouer avec la propriété **aspect ratio**. Celle‑ci contrôle la relation hauteur‑largeur du DataBar, vous permettant de produire un symbole court et carré ou un symbole haut et étroit. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Que se passe‑t‑il ?** `AspectRatio = 15` indique au moteur de rendre les barres 15 fois plus hautes qu’elles ne sont larges. Le PNG résultant est enregistré juste à côté de votre exécutable. + +## Créer une image de code‑barres C# – Modifier le rapport d’aspect + +Prouvons la flexibilité en changeant le ratio à 30 et en enregistrant un deuxième fichier. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +Lorsque vous exécuterez le programme, vous obtiendrez deux fichiers PNG : + +| Fichier | Rapport d’aspect | Taille approximative | +|------|--------------|--------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Ouvrez‑les avec n’importe quel visualiseur d’images — vous devriez voir des symboles DataBar propres et lisibles. + +## Aperçu des types d’encodage de code‑barres (Optionnel mais pratique) + +Si vous êtes curieux des autres **types d’encodage de code‑barres** pris en charge par Aspose, voici une petite feuille de référence : + +| Enum EncodeTypes | Description | +|------------------|-------------| +| `EncodeTypes.Code128` | Alphanumérique haute densité | +| `EncodeTypes.QR` | Code matriciel 2‑D | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar pour le commerce de détail | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Notre focus** – compact, omnidirectionnel | + +Connaître le bon enum vous évite de nombreux essais‑erreurs lorsque vous changez de projet. + +## Pièges courants & comment les éviter + +- **Package NuGet manquant** – Le code ne compilera pas sans `Aspose.BarCode`. Exécutez d’abord `dotnet add package Aspose.BarCode`. +- **Chemin de fichier incorrect** – Si vous utilisez un chemin absolu, vérifiez les antislashs (`\\`) sous Windows. Les chemins relatifs (comme indiqué) restent portables. +- **Rapport d’aspect trop extrême** – Des ratios supérieurs à 50 peuvent rendre le code‑barres trop haut pour les lecteurs classiques. Restez entre 15 et 30 pour la plupart des cas d’usage. + +## Code source complet (prêt à copier‑coller) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Exécutez le programme (`dotnet run` ou appuyez sur **F5** dans Visual Studio) et vous verrez le message console confirmant que les fichiers sont bien sur le disque. + +![Barcode generator example output showing DataBar barcode with aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Exemple de sortie du générateur de code‑barres montrant le DataBar avec un rapport d’aspect de 15"} + +## Conclusion + +Nous venons de terminer un **exemple de générateur de code‑barres** qui montre **comment définir les dimensions**, sélectionne les bons **types d’encodage de code‑barres**, et enfin **crée des fichiers image de code‑barres c#** que vous pouvez intégrer où vous le souhaitez. Le code est minuscule, les concepts sont limpides, et vous disposez maintenant d’une base solide pour étendre la solution—peut‑être en ajoutant des légendes, en faisant pivoter l’image, ou en passant à une autre symbologie. + +### Et après ? + +- Expérimentez avec **différentes X‑dimensions** pour observer comment la tolérance du lecteur varie. +- Essayez d’autres **EncodeTypes** comme `Code128` ou `QR` pour élargir votre boîte à outils. +- Automatisez la génération en lot : bouclez sur un CSV d’identifiants produit et créez un PNG pour chacun. + +Si vous rencontrez un problème, laissez un commentaire ci‑dessous ou consultez la documentation Aspose.BarCode—elle regorge d’exemples qui complètent ce que nous avons vu ici. + +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 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 Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/french/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/french/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..c268ca4e8 --- /dev/null +++ b/barcode/french/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-07-18 +description: Créez rapidement le code‑barres Planet avec C#. Apprenez à générer des + barres pleines et vides, à définir la dimension X et à enregistrer des images PNG + – le tout dans un seul tutoriel. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: fr +lastmod: 2026-07-18 +og_description: Créez le code‑barcode Planet instantanément. Ce guide vous montre + comment définir la dimension X, basculer entre les barres pleines et vides, et exporter + des fichiers PNG avec Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Créer le code-barres Planète en C# – Guide complet de programmation +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Créer le code‑barres Planet en C# – Guide complet étape par étape +url: /fr/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer un code-barres Planet en C# – Guide complet étape par étape + +Vous avez déjà eu besoin de **créer un code-barres planet** images mais vous n'étiez pas sûr des propriétés à ajuster ? Vous n'êtes pas seul. De nombreux développeurs se heurtent à un mur lorsque les barres remplies par défaut ne correspondent pas aux exigences de la spécification, ou lorsque la largeur des barres doit correspondre au DPI d'une imprimante. + +Dans ce tutoriel, vous apprendrez exactement comment **créer des fichiers planet barcode** en utilisant la bibliothèque Aspose.BarCode, comment contrôler les **pixels XDimension**, et comment basculer entre les **barres remplies** et les **barres vides** sans réécrire de code. À la fin, vous disposerez de deux fichiers PNG — l'un avec des barres solides et l'autre avec des barres creuses — prêts pour tout système postal qui attend la symbologie Planet. + +## Prérequis + +- .NET 6.0 ou version ultérieure (le code fonctionne également sur .NET Framework 4.7 +) +- Package NuGet Aspose.BarCode pour .NET (`Install-Package Aspose.BarCode`) +- Connaissances de base en C# (vous verrez plus tard pourquoi nous utilisons les instructions `using`) +- Un dossier accessible en écriture sur le disque où les PNG seront enregistrés + +Si vous avez tout cela, nous pouvons passer directement à l'implémentation. + +## Étape 1 – Configurer le projet et ajouter la bibliothèque + +Tout d'abord, créez une nouvelle application console (ou tout projet C#) et référencez la bibliothèque **Planet barcode generator**. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Astuce pro :** Dans Visual Studio, faites un clic droit sur le projet → *Manage NuGet Packages* → recherchez **Aspose.BarCode** et cliquez sur *Install*. Cela vous donne accès à `BarcodeGenerator` et à tous les **paramètres BarcodeGenerator** dont vous avez besoin. + +## Étape 2 – Initialiser le générateur de code-barres Planet + +Nous allons maintenant réellement **créer le générateur de planet barcode** et lui fournir les données que nous voulons encoder (`"123456"` dans cet exemple). L'énumération `EncodeTypes.Planet` indique à la bibliothèque quelle symbologie utiliser. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Pourquoi c'est important :** Le drapeau `EncodeTypes.Planet` applique automatiquement le bon checksum et les règles de mise en page pour le code-barres postal Planet, vous n'avez donc pas besoin de les calculer manuellement. + +## Étape 3 – Configurer la X‑Dimension (largeur de la barre) + +La plupart des imprimantes attendent que chaque barre soit un nombre spécifique de pixels. Ici, nous définissons les **pixels XDimension** à `4`, ce qui est une valeur courante pour les imprimantes thermiques à 203 dpi. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Cas particulier :** Si vous ciblez une imprimante à 300 dpi, vous pourriez avoir besoin de `3` ou `5` pixels à la place. Ajustez cette valeur en fonction de la documentation de votre appareil. + +## Étape 4 – Enregistrer la version à barres remplies + +Par défaut, le générateur produit des **barres remplies** (rectangles noirs solides). Enregistrons cela sur le disque : + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Remplacez `YOUR_DIRECTORY` par un chemin absolu ou relatif auquel votre application peut écrire. Après l'exécution de cette ligne, vous trouverez un fichier PNG qui ressemble à un code-barres Planet classique — parfait pour tester avec un scanner postal. + +## Étape 5 – Passer aux barres vides + +Parfois, les services postaux exigent le style « barres vides », où les barres sont découpées dans un fond blanc au lieu d'être peintes en noir. La bibliothèque expose un commutateur simple : + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Définir `FilledBars` à `false` indique au rendu d'inverser la logique de remplissage des barres. Aucun besoin de créer une nouvelle instance `BarcodeGenerator` ; nous ajustons simplement les **paramètres BarcodeGenerator** existants. + +## Étape 6 – Enregistrer la version à barres vides + +Enfin, exportez la deuxième image : + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Vous avez maintenant deux fichiers PNG distincts, chacun répondant à une exigence visuelle différente. + +## Exemple complet fonctionnel + +En assemblant toutes les pièces, voici le programme complet, prêt à copier‑coller : + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Sortie attendue** (dans la console) : + +``` +Both Planet barcode images have been generated successfully. +``` + +Et dans `C:\Barcodes\` vous verrez : + +- `PostalPlanetFilledBars.png` – barres noires solides +- `PostalPlanetEmptyBars.png` – barres blanches avec contours noirs + +Ouvrez-les dans n'importe quel visualiseur d'images ; ils devraient tous deux être conformes à la spécification Planet. + +## Questions fréquentes & astuces + +### « Puis-je changer le format de l'image ? » + +Absolument. La méthode `Save` accepte `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, etc. Il suffit de remplacer `BarCodeImageFormat.Png` par le format souhaité. + +### « Et si j'ai besoin d'une hauteur de code-barres différente ? » + +Utilisez `planetBarcode.Parameters.Barcode.BarHeight` (en points) pour augmenter ou diminuer la taille verticale. Par exemple : + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### « Existe‑t‑il un moyen d'ajouter une légende lisible par l'homme ? » + +Oui. Définissez la propriété `CodeText` sur `planetBarcode.Parameters.Caption` : + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### « Dois‑je libérer le générateur ? » + +Le `BarcodeGenerator` implémente `IDisposable`. Enveloppez‑le dans un bloc `using` si vous créez de nombreux codes-barres dans une boucle : + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### « Et la gestion des erreurs ? » + +Encapsulez les appels `Save` dans un bloc `try…catch` pour capturer `IOException` (problèmes de disque) ou `ArgumentException` (paramètres invalides). Exemple : + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Récapitulatif + +Nous avons couvert tout ce dont vous avez besoin pour **créer des images planet barcode** en C# : + +1. Initialisez le **générateur de code-barres Planet** avec vos données. +2. Ajustez les **pixels XDimension** pour correspondre aux spécifications de l'imprimante. +3. Enregistrez un PNG avec des **barres remplies**. +4. Basculez `FilledBars` pour produire des **barres vides**. +5. Enregistrez le deuxième PNG. + +À partir de là, vous pouvez explorer davantage les **paramètres BarcodeGenerator**, expérimenter avec d'autres symbologies (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, etc.), ou intégrer les images dans un flux de travail postal. + +--- + +**Prêt pour l'étape suivante ?** Essayez d'ajouter un code QR au même document, ou générez un lot de codes-barres Planet à partir d'une liste CSV en utilisant une boucle `foreach`. L'API Aspose.BarCode est suffisamment flexible pour gérer des opérations en masse, des couleurs personnalisées, et même une sortie SVG vectorielle. + +Si vous rencontrez des problèmes, laissez un commentaire ci‑dessous ou consultez la documentation officielle d'Aspose.BarCode pour des approfondissements des fonctionnalités avancées. 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. + +- [Créer un code-barres avec Aspose - Définir les dimensions X & Y en Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [Comment créer des images de code128 en Java avec Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [Comment créer un code128 en Java et définir la hauteur des barres](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/french/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..4fc342c00 --- /dev/null +++ b/barcode/french/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-07-18 +description: Créez rapidement un code‑barres RM4SCC en C# ; apprenez à définir la + hauteur du code‑barres et générez également un code‑barres Planet avec des dimensions + personnalisées. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: fr +lastmod: 2026-07-18 +og_description: Créez un code‑barres RM4SCC en C# et découvrez comment définir la + hauteur du code‑barres. Découvrez également comment générer un code‑barres Planet + avec la même bibliothèque. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Créer un code‑barres RM4SCC en C# – Définir rapidement une hauteur personnalisée +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Créer un code‑barres RM4SCC en C# – Guide complet pour définir la hauteur +url: /fr/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer un code-barres RM4SCC en C# – Guide complet pour définir la hauteur + +Vous avez déjà eu besoin de **create RM4SCC barcode** dans une application .NET mais vous ne saviez pas comment contrôler sa taille ? Vous n'êtes pas seul. Que vous construisiez un système d'envoi de courriers ou un tableau de bord logistique, obtenir la bonne hauteur du code-barres peut faire la différence entre une lecture qui fonctionne et une qui échoue. + +Dans ce tutoriel, nous parcourrons l'ensemble du processus : de l'installation de la bibliothèque, à **generate Planet barcode** comme exemple côte à côte, et enfin à **how to set barcode height** pour les deux types de codes-barres. À la fin, vous disposerez d'une application console prête à l'emploi qui génère des fichiers PNG avec les dimensions exactes dont vous avez besoin. + +--- + +## Ce dont vous aurez besoin + +- **.NET 6 SDK** (ou toute version récente de .NET) – le code fonctionne également sur .NET Framework, mais .NET 6 est le meilleur choix. +- **Aspose.BarCode for .NET** package NuGet – c’est la bibliothèque qui fournit la classe `BarcodeGenerator`. +- Une connaissance modeste de C# – nous garderons la syntaxe accessible aux débutants. +- Un IDE ou un éditeur de texte (Visual Studio, VS Code, Rider—choisissez votre poison). + +> **Astuce pro :** Si vous utilisez un pipeline CI/CD, ajoutez la référence NuGet dans votre `.csproj` afin que la construction n'oublie jamais la dépendance. + +## Étape 1 : Configurer le projet + +Ouvrez un terminal et créez un nouveau projet console : + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +C’est tout — votre projet référence maintenant la bibliothèque qui alimente tout ce qui suit. + +### Ajouter les directives using + +Ouvrez `Program.cs` et collez ce qui suit en haut du fichier : + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +## Étape 2 : Définir une méthode d'aide pour enregistrer les images + +Pour éviter de répéter la même logique d'enregistrement, nous l'envelopperons dans une petite méthode. Cela montre également **how to set barcode height** plus tard. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Pourquoi c’est important :** Centraliser la logique d’enregistrement signifie que vous n’avez qu’à modifier le format ou le dossier à un seul endroit si les exigences changent. + +## Étape 3 : Générer un code-barres Planet (la partie « generate planet barcode ») + +Avant de plonger dans les spécificités du RM4SCC, créons un **Planet barcode**. Cela vous donne une vérification visuelle rapide que la bibliothèque fonctionne. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Résultat attendu :** Deux fichiers PNG apparaissent dans le dossier `output` — l’un avec la hauteur auto‑calculée par la bibliothèque, l’autre exactement de 100 px de haut. + +## Étape 4 : Créer un code-barres RM4SCC – Objectif principal + +Passons maintenant à la vedette du spectacle : **create RM4SCC barcode**. RM4SCC est le Royal Mail 4‑State Code, largement utilisé dans le système postal du Royaume-Uni. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**Ce que vous verrez :** +- `RM4SCCDefault.png` – la bibliothèque détermine une hauteur confortable en fonction de la dimension X. +- `RM4SCCHeight100.png` – un code-barres net de 100 pixels de haut, prêt à être imprimé sur des enveloppes. + +> **Pourquoi définir la hauteur ?** Certains imprimantes d’étiquettes exigent une hauteur minimale des barres pour une lecture fiable. En fixant la hauteur, vous garantissez la conformité sur tous les appareils. + +## Étape 5 : Comprendre les réglages de hauteur (Répondant à « how to set barcode height ») + +Les exemples Planet et RM4SCC utilisent la même propriété : + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** est un objet `BarHeight` qui regroupe plusieurs unités de mesure (pixels, millimètres, pouces). +- **`.Pixels`** est l’unité la plus simple pour une sortie orientée écran, mais vous pouvez également utiliser `.Millimeters` ou `.Inches` si vous ciblez les médias imprimés. + +### Cas limites & conseils + +| Situation | Approche recommandée | +|-----------|----------------------| +| **Très petite dimension X (par ex., 1 px)** | Augmentez `BarHeight` pour que le code-barres reste lisible. | +| **Impression sur des imprimantes d’étiquettes haute résolution** | Utilisez `.Millimeters` pour un dimensionnement indépendant du dispositif. | +| **Types de codes-barres mixtes dans une même image** | Définissez `BarHeight` *après* `XDimension` pour chaque générateur afin d'éviter une héritage accidentel. | +| **Données dynamiques (par ex., codes saisis par l'utilisateur)** | Enveloppez la création du générateur dans une méthode qui accepte les paramètres `code` et `height`. | + +## Étape 6 : Exemple complet fonctionnel + +Ci-dessous se trouve un programme autonome que vous pouvez copier‑coller dans `Program.cs`. Il comprend tout, de la configuration du projet à l’enregistrement des images. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Exécutez-le avec : + +```bash +dotnet run +``` + +Vous devriez voir la sortie console confirmant chaque fichier enregistré, et le dossier `output` contiendra quatre PNG correspondant aux noms affichés ci‑dessus. + +## Conclusion + +Vous savez maintenant **how to create RM4SCC barcode** en C# et contrôler ses dimensions avec seulement quelques affectations de propriétés. Nous avons également couvert **generate planet barcode** comme vérification rapide, et exploré les nuances de **how to set barcode height** pour différents scénarios d’impression. + +Prochaines étapes ? Essayez de remplacer l’énumération `EncodeTypes` par d’autres symbologies (Code128, QR, DataMatrix) et expérimentez `BarHeight` en millimètres pour les imprimantes haute résolution. Si vous devez intégrer le code-barres dans un PDF, associez Aspose.BarCode à Aspose.PDF — une autre combinaison puissante. + +Des questions ou envie de partager vos propres ajustements ? Laissez un commentaire ci‑dessous, et 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 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 générer un code-barres Aztec avec un rapport d’aspect personnalisé en utilisant Aspose.BarCode pour .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Comment créer une zone silencieuse de code-barres pour ITF-14 en utilisant Aspose.BarCode pour .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Comment créer une zone silencieuse de code-barres pour Code 16K en utilisant Aspose.BarCode pour .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/french/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..3f86874af --- /dev/null +++ b/barcode/french/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-07-18 +description: Apprenez à générer des images de codes-barres avec un générateur de codes-barres + .net et à modifier facilement la hauteur du code-barres pour les symboles GS1‑Databar + omnidirectionnels. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: fr +lastmod: 2026-07-18 +og_description: Le générateur de codes-barres .net vous permet de créer rapidement + des images de codes-barres. Ce guide montre comment générer un code-barres, ajuster + la hauteur des barres et enregistrer des fichiers PNG. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Modifier la hauteur du code‑barres avec le générateur de code‑barres .NET +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: Générateur de code‑barres .NET – modifier la hauteur du code‑barres +url: /fr/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – modifier la hauteur du code‑barres + +Vous êtes-vous déjà demandé **comment générer des images de code‑barres** sans jongler avec une douzaine d’outils tiers ? Dans l’univers .NET, il existe une méthode étonnamment simple, et l’élément clé est le **.net barcode generator**. En quelques lignes de C#, vous pouvez créer un symbole GS1‑Databar Omni‑Directional, ajuster la hauteur des barres et enregistrer le résultat dans un fichier PNG. + +Que vous construisiez un système d’inventaire, une imprimante d’étiquettes d’expédition, ou toute application nécessitant un code scannable, ce tutoriel vous fera passer de zéro à un code‑barres fonctionnel en quelques minutes. Nous passerons en revue le code complet, expliquerons pourquoi chaque paramètre est important, et vous montrerons comment **modifier la hauteur du code‑barres** sans enfreindre la spécification. + +## Ce dont vous avez besoin + +- .NET 6.0 ou ultérieur (l’API fonctionne de la même façon sur .NET Framework 4.7+) +- Une référence à la bibliothèque de code‑barres (par exemple, Aspose.BarCode for .NET – les mêmes classes sont utilisées par de nombreux kits commerciaux) +- Un environnement de développement (Visual Studio, Rider ou VS Code avec l’extension C#) +- Un dossier où vous avez les droits d’écriture – le tutoriel enregistrera les fichiers PNG dans ce répertoire + +C’est tout. Aucun package NuGet supplémentaire en dehors de la bibliothèque de code‑barres elle‑même. + +## Utiliser le .net barcode generator pour modifier la hauteur du code‑barres + +Voici un **programme console complet et exécutable**. Copiez‑le dans un nouveau projet C#, ajustez le dossier de sortie, puis appuyez sur F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Pourquoi chaque ligne est importante + +| Ligne | Raison | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Instancie le **.net barcode generator** avec la symbologie et les données souhaitées. L’énumération `EncodeTypes.DatabarOmniDirectional` indique à la bibliothèque d’utiliser le format GS1‑Databar Omni‑Directional. | +| `XDimension.Pixels = 2;` | La X‑dimension correspond à la largeur de la barre la plus fine. La régler à *2 pixels* donne une image nette sur la plupart des écrans tout en conservant une petite taille de fichier. | +| `BarHeight.Pixels = 30;` | C’est l’étape **modifier la hauteur du code‑barres** qui détermine la hauteur de chaque barre. Une hauteur de 30 pixels est une bonne valeur par défaut pour les petites étiquettes. | +| `generator.Save(...);` | Enregistre le code‑barres dans un fichier PNG. Le PNG est sans perte, ce qui signifie que les scanners voient exactement le motif généré. | +| `BarHeight.Pixels = 60;` | Ici nous **modifions à nouveau la hauteur du code‑barres** – cette fois à 60 pixels. La bibliothèque re‑rend automatiquement le symbole avec la nouvelle dimension lorsque vous appelez `Save` une seconde fois. | +| `Console.WriteLine(...);` | Vous donne un retour rapide indiquant que le processus s’est terminé sans lever d’exception. | + +> **Astuce :** Si vous avez besoin d’une sortie haute résolution pour l’impression, remplacez `BarCodeImageFormat.Png` par `BarCodeImageFormat.Tiff` et augmentez la propriété `Resolution` (par ex., `generator.Parameters.ImageResolution = 300;`). La hauteur des barres sera toujours respectée, simplement rendue à une résolution DPI plus fine. + +## Générer des images de code‑barres avec différents paramètres + +L’extrait ci‑dessus couvre les bases, mais les scénarios réels exigent souvent des ajustements supplémentaires : + +### Ajuster la X‑dimension pour des impressions plus grandes +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Augmenter la X‑dimension rend le code‑barres entier plus grand sans modifier les données encodées. C’est pratique lorsqu’on imprime sur de grandes étiquettes. + +### Changer de format de sortie +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +Le SVG s’adapte à l’infini, ce qui est parfait pour les scanners web qui nécessitent des vecteurs nets. + +### Ajouter du texte lisible par l’homme +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Activer `CodeTextVisible` ajoute les données brutes sous le code‑barres, utile pour la vérification lors des tests. + +## Pièges courants lors de la **modification de la hauteur du code‑barres** + +1. **Hauteur trop petite** – Certains scanners exigent une hauteur minimale de barre (souvent 10 mm en unités physiques). Si vous définissez `BarHeight.Pixels` trop bas, l’image générée peut être illisible par un scanner réel. Testez toujours avec le matériel cible. +2. **X‑dimension et hauteur incompatibles** – Une hauteur de barre très élevée associée à une X‑dimension minuscule peut donner un aspect étiré et provoquer des erreurs de décodage. Visez un ratio équilibré (environ 3 : 1 à 5 : 1) sauf indication contraire de la spécification. +3. **Oublier de réinitialiser les paramètres** – Le générateur conserve son état entre les sauvegardes. Si vous changez `BarHeight` pour une image puis réutilisez la même instance pour un autre code‑barres, la hauteur précédente restera en vigueur. Réinitialisez la propriété ou créez un nouveau `BarcodeGenerator` pour chaque code‑barres distinct. + +## Exemple complet de bout en bout (avec installation NuGet) + +Si vous partez de zéro, suivez ces étapes pour lancer le projet : + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Remplacez le `Program.cs` généré automatiquement par le bloc de code montré précédemment, **n’oubliez pas de remplacer `YOUR_DIRECTORY`** par quelque chose comme `Path.Combine(Environment.CurrentDirectory, "output")`. Ensuite : + +```bash +dotnet run +``` + +Vous devriez voir deux fichiers PNG dans le dossier `output` : + +- `DatabarBarHeight30Pixels.png` – un code‑barres compact de 30 pixels de hauteur. +- `DatabarBarHeight60Pixels.png` – une version de 60 pixels, plus haute. + +Les deux images se ressemblent, mais la seconde possède des barres visiblement plus longues, ce qui facilite la lecture par les scanners à basse résolution. + +![Barcode height example](/images/barcode-height.png){alt="Sortie du .net barcode generator montrant différentes hauteurs de barres"} + +## Récapitulatif & étapes suivantes + +Nous avons vu comment **générer des images de code‑barres** à l’aide d’un **.net barcode generator**, affiner la propriété **modifier la hauteur du code‑barres**, et enregistrer les résultats au format PNG. Les points clés sont : + +- Instancier le générateur avec le bon `EncodeTypes`. +- Contrôler la taille visuelle via `XDimension` et `BarHeight`. +- Appeler `Save` après chaque modification pour créer une nouvelle image. +- Ajuster la résolution, le format, + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants abordent 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 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 generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to create dotcode extended codetext with Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-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/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/german/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..f0b0e2306 --- /dev/null +++ b/barcode/german/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-07-18 +description: Barcode‑Generator‑Beispiel, das zeigt, wie man die Abmessungen festlegt + und ein DataBar Stacked Omni‑Directional‑Barcode‑Bild in C# erzeugt. Lernen Sie + Barcode‑Codierungstypen schnell. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: de +lastmod: 2026-07-18 +og_description: Das Barcode‑Generator‑Beispiel zeigt Ihnen, wie Sie Abmessungen festlegen, + Barcode‑Codierungstypen auswählen und Barcode‑Bild‑C#‑Projekte mit minimalem Code + erstellen. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Barcode-Generator-Beispiel – Schnelle DataBar-Bilderstellung in C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Barcode‑Generator‑Beispiel – DataBar‑Bild in C# erstellen +url: /de/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode-Generator-Beispiel – DataBar‑Bild in C# erstellen + +Haben Sie jemals ein **barcode generator example** gebraucht, das tatsächlich einen echten Barcode ausdruckt, ohne dass Ihnen die Haare ausfallen? Sie sind nicht allein. Die meisten Entwickler stoßen auf ein Problem, wenn sie versuchen herauszufinden, **how to set dimensions** für einen DataBar Stacked Omni‑Directional Barcode, besonders wenn die Dokumentation unter Schichten von Fachjargon vergraben ist. + +In diesem Tutorial gehen wir ein vollständiges, sofort ausführbares C#‑Programm durch, das zeigt, **how to generate databar**‑Bilder, die richtigen **barcode encode types** auswählt und schließlich **create barcode image c#**‑Dateien erstellt, die Sie in jedes Projekt einbinden können. Kein Schnickschnack – nur der Code, den Sie kopieren‑einfügen können, plus die Begründung hinter jeder Zeile. + +## Was Sie benötigen + +- **.NET 6** (oder jede aktuelle .NET‑Version) – die API, die wir verwenden, zielt auf .NET Standard, sodass sie auch unter .NET Framework funktioniert. +- **Aspose.BarCode for .NET** – die Bibliothek, die `BarcodeGenerator` bereitstellt. Sie können sie von NuGet mit `Install-Package Aspose.BarCode` holen. +- Ein **C# IDE** – Visual Studio, Rider oder VS Code reicht aus. +- Ein Ordner auf der Festplatte, in dem die PNG‑Dateien gespeichert werden (der Code erzeugt `DatabarAspectRatio15.png` und `DatabarAspectRatio30.png`). + +Alles bereit? Super – lassen Sie uns loslegen. + +## Barcode-Generator-Beispiel – Generator initialisieren + +Zuerst benötigen wir eine Instanz von `BarcodeGenerator`, die für die **DataBar Stacked Omni‑Directional**‑Symbologie konfiguriert ist. Das ist der **barcode encode type**, mit dem wir arbeiten werden. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Warum das wichtig ist:** `EncodeTypes.DatabarStackedOmniDirectional` teilt Aspose exakt mit, welche Symbologie gerendert werden soll. Wenn Sie den falschen Typ wählen, erkennt der Scanner den Barcode nicht, egal wie hübsch das Bild aussieht. + +## Wie man Dimensionen für den Barcode festlegt + +Die Lesbarkeit eines Barcodes hängt von seiner **X‑dimension** (der Breite des schmalsten Strichs) ab. In den meisten Fällen funktioniert ein Wert von 2 Pixeln gut, aber Sie können ihn an Ihren Drucker oder Bildschirm anpassen. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Profi‑Tipp:** Wenn Sie sich jemals fragen, **how to set dimensions** für eine andere Barcode‑Familie, gilt dieselbe Property‑Kette (`Parameters.Barcode.XDimension`) – ändern Sie einfach den `Pixels`‑Wert. + +## Wie man einen DataBar Stacked Omni‑Directional Barcode erzeugt + +Jetzt, wo der Generator bereit ist, spielen wir mit der **aspect ratio**‑Eigenschaft. Diese steuert das Höhen‑zu‑Breiten‑Verhältnis des DataBar und ermöglicht es Ihnen, ein kurzes, quadratisches Symbol oder ein hohes, schmales zu erzeugen. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Was passiert?** `AspectRatio = 15` weist die Engine an, die Striche 15 ‑mal höher zu machen, als sie breit sind. Das resultierende PNG wird direkt neben Ihrer ausführbaren Datei gespeichert. + +## Barcode‑Bild in C# erstellen – Aspect Ratio ändern + +Lassen Sie uns die Flexibilität beweisen, indem wir das Verhältnis auf 30 ändern und eine zweite Datei speichern. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +Wenn Sie das Programm ausführen, erhalten Sie zwei PNG‑Dateien: + +| Datei | Seitenverhältnis | Ungefähre Größe | +|------|------------------|-----------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Öffnen Sie sie in einem beliebigen Bildbetrachter – Sie sollten saubere, scanbare DataBar‑Symbole sehen. + +## Überblick über Barcode‑Encode‑Typen (Optional aber nützlich) + +Wenn Sie neugierig auf andere **barcode encode types** sind, die von Aspose unterstützt werden, hier ein kurzer Spickzettel: + +| EncodeTypes Enum | Beschreibung | +|------------------|--------------| +| `EncodeTypes.Code128` | High‑density alphanumeric | +| `EncodeTypes.QR` | 2‑D matrix code | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar for retail | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Our focus** – compact, omnidirectional | + +Das Wissen um das richtige Enum erspart Ihnen viel Ausprobieren, wenn Sie Projekte wechseln. + +## Häufige Fallstricke & wie man sie vermeidet + +- **Missing NuGet package** – Der Code kompiliert nicht ohne `Aspose.BarCode`. Führen Sie zuerst `dotnet add package Aspose.BarCode` aus. +- **Wrong file path** – Wenn Sie einen absoluten Pfad verwenden, prüfen Sie die Backslashes (`\\`) unter Windows. Relative Pfade (wie gezeigt) halten die Dinge portabel. +- **Aspect ratio too extreme** – Verhältnisse über 50 können den Barcode für typische Scanner zu hoch machen. Bleiben Sie für die meisten Anwendungsfälle bei 15‑30. + +## Vollständiger Quellcode (Kopier‑Einfüge‑bereit) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Führen Sie das Programm aus (`dotnet run` oder drücken Sie **F5** in Visual Studio) und Sie sehen die Konsolennachricht, die bestätigt, dass die Dateien auf der Festplatte liegen. + +![Barcode generator example output showing DataBar barcode with aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Barcode-Generator-Beispielausgabe, die DataBar-Barcode mit Seitenverhältnis 15 zeigt"} + +## Fazit + +Wir haben gerade ein **barcode generator example** abgeschlossen, das **how to set dimensions** demonstriert, die richtigen **barcode encode types** auswählt und schließlich **create barcode image c#**‑Dateien erzeugt, die Sie überall einbetten können. Der Code ist klein, die Konzepte sind kristallklar, und Sie haben nun eine solide Grundlage, um die Lösung zu erweitern – vielleicht Textbeschriftungen hinzuzufügen, das Bild zu drehen oder zu einer anderen Symbologie zu wechseln. + +### Was kommt als Nächstes? + +- Experimentieren Sie mit **different X‑dimensions**, um zu sehen, wie sich die Scanner‑Toleranz ändert. +- Probieren Sie andere **EncodeTypes** wie `Code128` oder `QR`, um Ihr Werkzeugset zu erweitern. +- Automatisieren Sie die Stapelgenerierung: Durchlaufen Sie eine CSV mit Produkt‑IDs und erzeugen Sie für jede ein PNG. + +Wenn Sie auf ein Problem stoßen, hinterlassen Sie unten einen Kommentar oder prüfen Sie die Aspose.BarCode‑Dokumentation – sie ist voll mit Beispielen, die das hier behandelte ergänzen. + +Viel Spaß beim Coden und möge Ihr Barcode immer beim ersten Versuch scannen! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige funktionierende 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 generiert – Ein‑dimensionaler Barcode‑Typen](/barcode/english/net/one-dimensional-barcode-types/) +- [Barcode‑Bild in C# erstellen – GS1 DataMatrix Beispiel](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [Wie man DataMatrix‑Barcodes (ECC 200) mit Aspose.BarCode für .NET generiert](/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/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/german/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..1c51c0743 --- /dev/null +++ b/barcode/german/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,282 @@ +--- +category: general +date: 2026-07-18 +description: Erstellen Sie Planet‑Barcodes schnell mit C#. Erfahren Sie, wie Sie gefüllte + und leere Balken erzeugen, die X‑Dimension einstellen und PNG‑Bilder speichern – + alles in einem Tutorial. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: de +lastmod: 2026-07-18 +og_description: Erstellen Sie sofort einen Planet-Barcode. Dieser Leitfaden zeigt + Ihnen, wie Sie die X‑Dimension einstellen, zwischen gefüllten und leeren Balken + wechseln und PNG‑Dateien mit Aspose.BarCode exportieren. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Planet-Barcode in C# erstellen – komplette Programmieranleitung +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Planet-Barcode in C# erstellen – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Planet‑Barcode in C# erstellen – Vollständige Schritt‑für‑Schritt‑Anleitung + +Haben Sie jemals **Planet‑Barcode**‑Bilder erstellen müssen, waren sich aber nicht sicher, welche Eigenschaften Sie anpassen sollten? Sie sind nicht allein. Viele Entwickler stoßen auf Probleme, wenn die standardmäßig gefüllten Balken nicht den Vorgaben der Spezifikation entsprechen oder wenn die Balkenbreite an die DPI eines Druckers angepasst werden muss. + +In diesem Tutorial erfahren Sie genau, wie Sie **Planet‑Barcode**‑Dateien mit der Aspose.BarCode‑Bibliothek erstellen, wie Sie die **XDimension‑Pixel** steuern und wie Sie zwischen **gefüllten Balken** und **leeren Balken** wechseln können, ohne Code neu zu schreiben. Am Ende haben Sie zwei PNG‑Dateien – eine mit soliden Balken und eine mit hohlen Balken – bereit für jedes Postsystem, das die Planet‑Symbolik erwartet. + +## Voraussetzungen + +- .NET 6.0 oder höher (der Code funktioniert auch unter .NET Framework 4.7 +) +- Aspose.BarCode für .NET NuGet‑Paket (`Install-Package Aspose.BarCode`) +- Grundkenntnisse in C# (Sie werden später sehen, warum wir `using`‑Anweisungen verwenden) +- Ein beschreibbarer Ordner auf der Festplatte, in dem die PNGs gespeichert werden + +Wenn Sie diese Voraussetzungen erfüllen, können wir direkt mit der Implementierung beginnen. + +## Schritt 1 – Projekt einrichten und Bibliothek hinzufügen + +Erstellen Sie zunächst eine neue Konsolen‑App (oder ein beliebiges C#‑Projekt) und binden Sie die **Planet‑Barcode‑Generator**‑Bibliothek ein. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro‑Tipp:** In Visual Studio klicken Sie mit der rechten Maustaste auf das Projekt → *Manage NuGet Packages* → suchen Sie nach **Aspose.BarCode** und klicken Sie auf *Install*. Damit erhalten Sie Zugriff auf `BarcodeGenerator` und alle **BarcodeGenerator‑Parameter**, die Sie benötigen. + +## Schritt 2 – Planet‑Barcode‑Generator initialisieren + +Jetzt erstellen wir tatsächlich eine **Planet‑Barcode**‑Generator‑Instanz und übergeben ihr die zu kodierenden Daten (`"123456"` in diesem Beispiel). Das `EncodeTypes.Planet`‑Enum teilt der Bibliothek mit, welche Symbolik verwendet werden soll. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Warum das wichtig ist:** Das Flag `EncodeTypes.Planet` wendet automatisch die korrekten Prüfziffer‑ und Layout‑Regeln für den Planet‑Post‑Barcode an, sodass Sie diese nicht manuell berechnen müssen. + +## Schritt 3 – X‑Dimension (Balkenbreite) konfigurieren + +Die meisten Drucker erwarten, dass jeder Balken eine bestimmte Anzahl von Pixeln hat. Hier setzen wir die **XDimension‑Pixel** auf `4`, ein gängiger Wert für 203 dpi Thermodrucker. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Randfall:** Wenn Sie einen 300 dpi‑Drucker ansteuern, benötigen Sie möglicherweise `3` oder `5` Pixel. Passen Sie diesen Wert anhand der Dokumentation Ihres Geräts an. + +## Schritt 4 – Gefüllte‑Balken‑Version speichern + +Standardmäßig erzeugt der Generator **gefüllte Balken** (solide schwarze Rechtecke). Schreiben wir das Ergebnis auf die Festplatte: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Ersetzen Sie `YOUR_DIRECTORY` durch einen absoluten oder relativen Pfad, in den Ihre Anwendung schreiben darf. Nach Ausführung dieser Zeile finden Sie eine PNG‑Datei, die wie ein klassischer Planet‑Barcode aussieht – perfekt zum Testen mit einem Postscanner. + +## Schritt 5 – Auf leere Balken umschalten + +Manchmal verlangen Postdienste den Stil „leere Balken“, bei dem die Balken aus einem weißen Hintergrund herausgeschnitten werden, anstatt schwarz gemalt zu sein. Die Bibliothek bietet dafür einen einfachen Schalter: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Durch Setzen von `FilledBars` auf `false` wird die Render‑Logik für die Balkenfüllung invertiert. Es ist nicht nötig, eine neue `BarcodeGenerator`‑Instanz zu erstellen; wir passen einfach die bestehenden **BarcodeGenerator‑Parameter** an. + +## Schritt 6 – Leere‑Balken‑Version speichern + +Zum Schluss exportieren wir das zweite Bild: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Jetzt besitzen Sie zwei unterschiedliche PNG‑Dateien, die jeweils einer anderen visuellen Anforderung entsprechen. + +## Vollständiges funktionierendes Beispiel + +Alle Teile zusammengefügt, hier das komplette, copy‑and‑paste‑bereite Programm: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Erwartete Konsolenausgabe**: + +``` +Both Planet barcode images have been generated successfully. +``` + +Und in `C:\Barcodes\` sehen Sie: + +- `PostalPlanetFilledBars.png` – solide schwarze Balken +- `PostalPlanetEmptyBars.png` – weiße Balken mit schwarzen Konturen + +Öffnen Sie sie in einem Bildbetrachter; beide sollten der Planet‑Spezifikation entsprechen. + +## Häufige Fragen & Tipps + +### „Kann ich das Bildformat ändern?“ + +Natürlich. Die `Save`‑Methode akzeptiert `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` usw. Ersetzen Sie einfach `BarCodeImageFormat.Png` durch das gewünschte Format. + +### „Was, wenn ich eine andere Barcode‑Höhe brauche?“ + +Verwenden Sie `planetBarcode.Parameters.Barcode.BarHeight` (in Punkten), um die vertikale Größe zu erhöhen oder zu verringern. Beispiel: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### „Gibt es eine Möglichkeit, eine lesbare Beschriftung hinzuzufügen?“ + +Ja. Setzen Sie die Eigenschaft `CodeText` auf `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### „Muss ich den Generator freigeben?“ + +Der `BarcodeGenerator` implementiert `IDisposable`. Packen Sie ihn in einen `using`‑Block, wenn Sie viele Barcodes in einer Schleife erzeugen: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### „Wie sieht die Fehlerbehandlung aus?“ + +Umgeben Sie die `Save`‑Aufrufe mit einem `try…catch`‑Block, um `IOException` (Festplattenprobleme) oder `ArgumentException` (ungültige Parameter) abzufangen. Beispiel: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Zusammenfassung + +Wir haben alles behandelt, was Sie benötigen, um **Planet‑Barcode**‑Bilder in C# zu **erstellen**: + +1. Initialisieren Sie den **Planet‑Barcode‑Generator** mit Ihren Daten. +2. Passen Sie die **XDimension‑Pixel** an die Druckerspezifikationen an. +3. Speichern Sie ein **gefülltes‑Balken**‑PNG. +4. Schalten Sie `FilledBars` um, um **leere Balken** zu erzeugen. +5. Speichern Sie das zweite PNG. + +Ab hier können Sie weitere **BarcodeGenerator‑Parameter** erkunden, mit anderen Symboliken experimentieren (`EncodeTypes.Postnet`, `EncodeTypes.Code128` usw.) oder die Bilder in einen Versand‑Workflow integrieren. + +--- + +**Bereit für den nächsten Schritt?** Versuchen Sie, dem selben Dokument einen QR‑Code hinzuzufügen, oder generieren Sie einen Batch von Planet‑Barcodes aus einer CSV‑Liste mittels einer `foreach`‑Schleife. Die Aspose.BarCode‑API ist flexibel genug für Bulk‑Operationen, benutzerdefinierte Farben und sogar vektorbasierte SVG‑Ausgabe. + +Wenn Sie auf Probleme stoßen, hinterlassen Sie einen Kommentar unten oder schauen Sie in die offizielle Aspose.BarCode‑Dokumentation für tiefere Einblicke in erweiterte Funktionen. 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‑Features zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Create Barcode with Aspose - Set X & Y Dimensions in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/german/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..93ede1cc0 --- /dev/null +++ b/barcode/german/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-07-18 +description: Erstellen Sie schnell einen RM4SCC‑Barcode in C#; erfahren Sie, wie Sie + die Barcode‑Höhe einstellen und zudem einen Planet‑Barcode mit benutzerdefinierten + Abmessungen erzeugen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: de +lastmod: 2026-07-18 +og_description: Erstellen Sie einen RM4SCC-Barcode in C# und erfahren Sie, wie Sie + die Barcode‑Höhe einstellen. Sehen Sie außerdem, wie Sie mit derselben Bibliothek + einen Planet‑Barcode erzeugen. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Erstelle RM4SCC-Barcode in C# – Benutzerdefinierte Höhe schnell festlegen +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Erstellen Sie einen RM4SCC-Barcode in C# – Vollständige Anleitung zum Festlegen + der Höhe +url: /de/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Erstellen Sie einen RM4SCC-Barcode in C# – Vollständige Anleitung zum Festlegen der Höhe + +Haben Sie jemals einen **RM4SCC-Barcode** in einer .NET‑App erstellen müssen, waren sich aber nicht sicher, wie Sie seine Größe steuern können? Sie sind nicht allein. Egal, ob Sie ein Mailing‑System oder ein Logistik‑Dashboard bauen, die richtige Barcode‑Höhe kann den Unterschied zwischen einem funktionierenden Scan und einem Fehlschlag ausmachen. + +In diesem Tutorial führen wir Sie durch den gesamten Prozess: von der Installation der Bibliothek über das **Erzeugen eines Planet‑Barcodes** als Nebeneinander‑Beispiel bis hin zu **wie man die Barcode‑Höhe** für beide Barcode‑Typen festlegt. Am Ende haben Sie eine sofort ausführbare Konsolen‑App, die PNG‑Dateien mit den exakt benötigten Abmessungen erzeugt. + +--- + +## Was Sie benötigen + +- **.NET 6 SDK** (oder jede aktuelle .NET‑Version) – der Code funktioniert auch unter .NET Framework, aber .NET 6 ist der optimale Punkt. +- **Aspose.BarCode for .NET** NuGet‑Paket – das ist die Bibliothek, die die Klasse `BarcodeGenerator` bereitstellt. +- Ein gewisses Grundwissen in C# – wir halten die Syntax einsteigerfreundlich. +- Eine IDE oder ein Text‑Editor (Visual Studio, VS Code, Rider — nach Belieben). + +> **Pro‑Tipp:** Wenn Sie in einer CI/CD‑Pipeline arbeiten, fügen Sie den NuGet‑Verweis in Ihrer `.csproj` hinzu, damit der Build die Abhängigkeit nie vergisst. + +--- + +## Schritt 1: Projekt einrichten + +Open a terminal and create a new console project: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +Das war's — Ihr Projekt verweist nun auf die Bibliothek, die alles Weitere antreibt. + +### Using‑Direktiven hinzufügen + +Open `Program.cs` and paste the following at the top: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +These namespaces give us access to `BarcodeGenerator` and the image format enum we’ll use later. + +--- + +## Schritt 2: Hilfsmethode zum Speichern von Bildern definieren + +To avoid repeating the same save logic, we’ll wrap it in a tiny method. This also demonstrates **how to set barcode height** later on. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Warum das wichtig ist:** Durch die Zentralisierung der Speicher‑Logik müssen Sie das Format oder den Ordner nur an einer Stelle ändern, falls sich Anforderungen ändern. + +--- + +## Schritt 3: Einen Planet‑Barcode erzeugen (der „generate planet barcode“-Teil) + +Before we dive into the RM4SCC specifics, let’s spin up a **Planet barcode**. This gives you a quick visual sanity check that the library is working. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Erwartete Ausgabe:** Zwei PNG‑Dateien erscheinen im Ordner `output` — eine mit der von der Bibliothek automatisch berechneten Höhe, die andere exakt 100 px hoch. + +--- + +## Schritt 4: RM4SCC‑Barcode erstellen — Hauptziel + +Now for the star of the show: **create RM4SCC barcode**. RM4SCC is the Royal Mail 4‑State Code, widely used in the UK postal system. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**Was Sie sehen werden:** +- `RM4SCCDefault.png` — die Bibliothek wählt eine angenehme Höhe basierend auf der X‑Dimension. +- `RM4SCCHeight100.png` — ein scharfer 100‑Pixel‑hoher Barcode, bereit zum Druck auf Umschlägen. + +> **Warum die Höhe festlegen?** Einige Etikettendrucker verlangen eine Mindestbalkenhöhe für zuverlässiges Scannen. Durch das Fixieren der Höhe stellen Sie die Konformität über alle Geräte hinweg sicher. + +--- + +## Schritt 5: Die Höheneinstellungen verstehen (Antwort auf „how to set barcode height“) + +Both the Planet and RM4SCC examples use the same property: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** ist ein `BarHeight`‑Objekt, das mehrere Maßeinheiten (Pixel, Millimeter, Inches) gruppiert. +- **`.Pixels`** ist die einfachste Einheit für bildschirmorientierte Ausgaben, Sie können aber auch `.Millimeters` oder `.Inches` verwenden, wenn Sie für Druckmedien ausgeben. + +### Randfälle & Tipps + +| Situation | Empfohlener Ansatz | +|-----------|----------------------| +| **Sehr kleine X‑Dimension (z. B. 1 px)** | Erhöhen Sie `BarHeight`, um den Barcode lesbar zu halten. | +| **Drucken auf hochauflösenden Etikettendruckern** | Verwenden Sie `.Millimeters` für geräteunabhängige Größen. | +| **Gemischte Barcode‑Typen in einem Bild** | Setzen Sie `BarHeight` *nach* `XDimension` für jeden Generator, um versehentliche Vererbung zu vermeiden. | +| **Dynamische Daten (z. B. benutzereingebene Codes)** | Packen Sie die Generator‑Erstellung in eine Methode, die Parameter `code` und `height` akzeptiert. | + +--- + +## Schritt 6: Vollständiges funktionierendes Beispiel + +Below is a single, self‑contained program you can copy‑paste into `Program.cs`. It includes everything from project setup to saving the images. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Run it with: + +```bash +dotnet run +``` + +Sie sollten die Konsolenausgabe sehen, die jede gespeicherte Datei bestätigt, und der Ordner `output` wird vier PNG‑Dateien enthalten, die den oben gezeigten Namen entsprechen. + +--- + +## Fazit + +Sie wissen jetzt, **wie man einen RM4SCC‑Barcode** in C# erstellt und seine Abmessungen mit nur wenigen Property‑Zuweisungen steuert. Wir haben außerdem **Planet‑Barcode erzeugen** als schnellen Plausibilitäts‑Check behandelt und die Nuancen von **wie man die Barcode‑Höhe** für verschiedene Druckszenarien untersucht. + +Nächste Schritte? Versuchen Sie, das `EncodeTypes`‑Enum gegen andere Symbologien (Code128, QR, DataMatrix) auszutauschen und experimentieren Sie mit `BarHeight` in Millimetern für Hochauflösungs‑Drucker. Wenn Sie den Barcode in ein PDF einbetten müssen, kombinieren Sie Aspose.BarCode mit Aspose.PDF — eine weitere leistungsstarke Kombination. + +Haben Sie Fragen oder möchten Sie eigene Anpassungen teilen? Hinterlassen Sie unten einen Kommentar und 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 einen Aztec‑Barcode mit benutzerdefiniertem Seitenverhältnis erzeugt mit Aspose.BarCode für .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Wie man eine Barcode‑Quiet‑Zone für ITF‑14 erstellt mit Aspose.BarCode für .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Wie man eine Barcode‑Quiet‑Zone für Code 16K erstellt mit Aspose.BarCode für .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/german/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..f507cfab6 --- /dev/null +++ b/barcode/german/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-07-18 +description: Erfahren Sie, wie Sie Barcode‑Bilder mit einem .NET‑Barcode‑Generator + erzeugen und die Barcode‑Höhe für GS1‑Databar Omni‑Directional‑Symbole einfach ändern + können. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: de +lastmod: 2026-07-18 +og_description: .net Barcode-Generator ermöglicht es Ihnen, schnell Barcode-Bilder + zu erstellen. Dieser Leitfaden zeigt, wie man Barcodes generiert, die Balkenhöhe + anpasst und PNG-Dateien speichert. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Barcode-Höhe mit .NET Barcode-Generator ändern +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET Barcode-Generator – Barcode-Höhe ändern +url: /de/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – Barcode-Höhe ändern + +Haben Sie sich jemals gefragt, **wie man Barcode**‑Bilder erzeugt, ohne ein Dutzend Drittanbieter‑Tools zu jonglieren? In der .NET‑Welt gibt es einen überraschend sauberen Weg, und das Schlüsselelement ist der **.net barcode generator**. Mit nur wenigen Zeilen C# können Sie ein GS1‑Databar Omni‑Directional‑Symbol erzeugen, die Balkenhöhe anpassen und das Ergebnis in eine PNG‑Datei schreiben. + +Wenn Sie ein Inventarsystem, einen Versandetikettendrucker oder irgendeine Anwendung bauen, die einen scannbaren Code benötigt, führt Sie dieses Tutorial in wenigen Minuten von Null zu einem funktionierenden Barcode. Wir gehen den vollständigen Code durch, erklären, warum jede Einstellung wichtig ist, und zeigen Ihnen, wie Sie **die Barcode-Höhe ändern** können, ohne die Spezifikation zu verletzen. + +## Was Sie benötigen + +- .NET 6.0 oder höher (die API funktioniert gleich auf .NET Framework 4.7+) +- Ein Verweis auf die Barcode‑Bibliothek (z. B. Aspose.BarCode for .NET – dieselben Klassen werden von vielen kommerziellen Kits verwendet) +- Eine Entwicklungsumgebung (Visual Studio, Rider oder VS Code mit der C#‑Erweiterung) +- Ein Ordner, in dem Sie Schreibrechte haben – das Tutorial speichert dort PNG‑Dateien + +Das war’s. Keine zusätzlichen NuGet‑Pakete außer der Barcode‑Bibliothek selbst. + +## Verwendung des .net barcode generator zum Ändern der Barcode-Höhe + +Unten finden Sie ein **vollständiges, ausführbares Konsolenprogramm**. Fügen Sie es in ein neues C#‑Projekt ein, passen Sie den Ausgabepfad an und drücken Sie F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Warum jede Zeile wichtig ist + +| Zeile | Grund | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Instanziiert den **.net barcode generator** mit der gewünschten Symbolik und Datenpayload. Das Enum `EncodeTypes.DatabarOmniDirectional` weist die Bibliothek an, das GS1‑Databar Omni‑Directional‑Format zu verwenden. | +| `XDimension.Pixels = 2;` | Die X‑Dimension ist die Breite des dünnsten Balkens. Das Setzen auf *2 Pixel* liefert ein scharfes Bild auf den meisten Monitoren und hält die Dateigröße gering. | +| `BarHeight.Pixels = 30;` | Dies ist der Schritt zum **Ändern der Barcode-Höhe**, der bestimmt, wie hoch jeder Balken ist. Eine Höhe von 30 Pixel ist ein guter Standard für kleine Etiketten. | +| `generator.Save(...);` | Speichert den Barcode in einer PNG‑Datei. PNG ist verlustfrei, was bedeutet, dass Scanner das exakt erzeugte Muster sehen. | +| `BarHeight.Pixels = 60;` | Hier **ändern wir die Barcode-Höhe** erneut – diesmal auf 60 Pixel. Die Bibliothek rendert das Symbol automatisch mit der neuen Dimension, wenn Sie `Save` ein zweites Mal aufrufen. | +| `Console.WriteLine(...);` | Gibt Ihnen eine schnelle Rückmeldung, dass der Vorgang ohne Ausnahme beendet wurde. | + +> **Pro Tipp:** Wenn Sie eine höher aufgelöste Ausgabe für den Druck benötigen, wechseln Sie `BarCodeImageFormat.Png` zu `BarCodeImageFormat.Tiff` und erhöhen Sie die `Resolution`‑Eigenschaft (z. B. `generator.Parameters.ImageResolution = 300;`). Die Balkenhöhe wird weiterhin berücksichtigt, nur mit feinerer DPI gerendert. + +## Wie man Barcode‑Bilder mit verschiedenen Einstellungen erzeugt + +Das obige Snippet deckt die Grundlagen ab, aber reale Szenarien erfordern oft zusätzliche Anpassungen: + +### Anpassen der X‑Dimension für größere Drucke +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Das Erhöhen der X‑Dimension vergrößert den gesamten Barcode, ohne die codierten Daten zu ändern. Das ist praktisch, wenn Sie auf großen Etiketten drucken. + +### Wechseln der Ausgabeformate +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG skaliert unendlich, was perfekt für webbasierte Scanner ist, die scharfe Vektoren benötigen. + +### Hinzufügen von menschenlesbarem Text +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Durch Aktivieren von `CodeTextVisible` wird der Rohdaten‑Text unter dem Barcode angehängt, was für die Verifizierung während Tests nützlich ist. + +## Häufige Fallstricke beim **Ändern der Barcode-Höhe** + +1. **Zu geringe Höhe** – Einige Scanner benötigen eine Mindestbalkenhöhe (oft 10 mm in physischen Einheiten). Wenn Sie `BarHeight.Pixels` zu niedrig setzen, könnte das erzeugte Bild auf einem echten Scanner nicht lesbar sein. Testen Sie immer mit Ihrer Zielhardware. +2. **Unpassende X‑Dimension und Höhe** – Eine sehr hohe Balkenhöhe kombiniert mit einer winzigen X‑Dimension kann gestreckt wirken und Decodierungsfehler verursachen. Streben Sie ein ausgewogenes Verhältnis an (ungefähr 3:1 bis 5:1), sofern die Spezifikation nichts anderes verlangt. +3. **Vergessen, Parameter zurückzusetzen** – Der Generator behält den Zustand zwischen den Saves. Wenn Sie `BarHeight` für ein Bild ändern und dann dieselbe Instanz für einen anderen Barcode wiederverwenden, bleibt die vorherige Höhe erhalten. Setzen Sie entweder die Eigenschaft zurück oder instanziieren Sie für jeden unterschiedlichen Barcode einen neuen `BarcodeGenerator`. + +## Vollständiges End‑zu‑End‑Beispiel (inklusive NuGet‑Installation) + +Wenn Sie von Grund auf neu beginnen, folgen Sie diesen Schritten, um das Projekt zum Laufen zu bringen: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Ersetzen Sie die automatisch erzeugte `Program.cs` durch den oben gezeigten Codeblock, **denken Sie daran, `YOUR_DIRECTORY`** durch etwas wie `Path.Combine(Environment.CurrentDirectory, "output")` zu ersetzen. Dann: + +```bash +dotnet run +``` + +Sie sollten zwei PNG‑Dateien im Ordner `output` sehen: + +- `DatabarBarHeight30Pixels.png` – ein kompakter 30‑Pixel‑hoher Barcode. +- `DatabarBarHeight60Pixels.png` – eine höhere 60‑Pixel‑Version. + +Beide Bilder sehen ähnlich aus, aber das zweite hat merklich längere Balken, was das Lesen mit niedrigauflösenden Scannern erleichtert. + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator Ausgabe, die verschiedene Balkenhöhen zeigt"} + +## Zusammenfassung & nächste Schritte + +Wir haben behandelt, wie man **Barcode**‑Bilder mit einem **.net barcode generator** erzeugt, die **Barcode-Höhe ändern**‑Eigenschaft fein abgestimmt und die Ergebnisse im PNG‑Format gespeichert. Die wichtigsten Erkenntnisse sind: + +- Instanziieren Sie den Generator mit dem richtigen `EncodeTypes`. +- Steuern Sie die visuelle Größe über `XDimension` und `BarHeight`. +- Rufen Sie `Save` nach jeder Änderung auf, um ein neues Bild zu speichern. +- Passen Sie Auflösung und Format an, + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Wie man Aztec‑Barcode mit benutzerdefiniertem Seitenverhältnis erzeugt mit Aspose.BarCode für .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Wie man Dotcode‑Erweiterungstext erstellt mit Aspose.BarCode für .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Wie man DataMatrix‑Barcodes (ECC 200) erzeugt mit Aspose.BarCode für .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/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/greek/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..061cf1a67 --- /dev/null +++ b/barcode/greek/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-07-18 +description: Παράδειγμα δημιουργίας barcode που δείχνει πώς να ορίσετε διαστάσεις + και να δημιουργήσετε εικόνα barcode DataBar Stacked Omni‑Directional σε C#. Μάθετε + γρήγορα τους τύπους κωδικοποίησης barcode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: el +lastmod: 2026-07-18 +og_description: Το παράδειγμα δημιουργού barcode σας καθοδηγεί στο πώς να ορίσετε + διαστάσεις, να επιλέξετε τύπους κωδικοποίησης barcode και να δημιουργήσετε έργα + C# με εικόνα barcode με ελάχιστο κώδικα. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Παράδειγμα Γεννήτριας Barcode – Γρήγορη Δημιουργία Εικόνας DataBar σε C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Παράδειγμα Γεννήτριας Barcode – Κατασκευή Εικόνας DataBar σε C# +url: /el/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Παράδειγμα Γεννήτριας Barcode – Δημιουργία Εικόνας DataBar σε C# + +Χρειάζεστε ποτέ ένα **παράδειγμα γεννήτριας barcode** που να παράγει πραγματικό barcode χωρίς να σας τρελαίνει; Δεν είστε μόνοι. Οι περισσότεροι προγραμματιστές συναντούν πρόβλημα όταν προσπαθούν να καταλάβουν **πώς να ορίσουν διαστάσεις** για ένα DataBar Stacked Omni‑Directional barcode, ειδικά όταν η τεκμηρίωση είναι κρυμμένη κάτω από στρώματα ορολογίας. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από ένα πλήρες, έτοιμο προς εκτέλεση πρόγραμμα C# που δείχνει **πώς να δημιουργήσετε εικόνες databar**, επιλέγει τους σωστούς **τύπους κωδικοποίησης barcode**, και τελικά **δημιουργεί αρχεία εικόνας barcode c#** που μπορείτε να ενσωματώσετε σε οποιοδήποτε project. Χωρίς περιττά – μόνο ο κώδικας που μπορείτε να αντιγράψετε‑επικολλήσετε, μαζί με τη λογική πίσω από κάθε γραμμή. + +## Τι Θα Χρειαστείτε + +- **.NET 6** (ή οποιαδήποτε πρόσφατη έκδοση .NET) – το API που χρησιμοποιούμε στοχεύει στο .NET Standard, οπότε λειτουργεί και σε .NET Framework. +- **Aspose.BarCode for .NET** – η βιβλιοθήκη που παρέχει το `BarcodeGenerator`. Μπορείτε να την αποκτήσετε από το NuGet με `Install-Package Aspose.BarCode`. +- Ένα **IDE C#** – Visual Studio, Rider ή VS Code αρκούν. +- Ένας φάκελος στον δίσκο όπου θα αποθηκευτούν τα αρχεία PNG (ο κώδικας δημιουργεί τα `DatabarAspectRatio15.png` και `DatabarAspectRatio30.png`). + +Τα έχετε όλα; Τέλεια—ας βουτήξουμε. + +## Παράδειγμα Γεννήτριας Barcode – Αρχικοποίηση της Γεννήτριας + +Πρώτα απ' όλα: χρειαζόμαστε μια παρουσία του `BarcodeGenerator` διαμορφωμένη για τη **συμβολογία DataBar Stacked Omni‑Directional**. Αυτός είναι ο **τύπος κωδικοποίησης barcode** που θα χρησιμοποιήσουμε. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Γιατί είναι σημαντικό:** `EncodeTypes.DatabarStackedOmniDirectional` λέει στο Aspose ακριβώς ποια συμβολογία πρέπει να αποδοθεί. Αν επιλέξετε λάθος τύπο, ο σαρωτής δεν θα αναγνωρίσει το barcode, ό,τι και αν είναι η εικόνα. + +## Πώς να Ορίσετε Διαστάσεις για το Barcode + +Η αναγνωσιμότητα ενός barcode εξαρτάται από τη **διάσταση X** (το πλάτος της πιο στενής γραμμής). Στις περισσότερες περιπτώσεις, μια τιμή 2 pixel λειτουργεί καλά, αλλά μπορείτε να την προσαρμόσετε ανάλογα με τον εκτυπωτή ή την οθόνη σας. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Συμβουλή:** Αν ποτέ αναρωτηθείτε **πώς να ορίσετε διαστάσεις** για μια διαφορετική οικογένεια barcode, η ίδια αλυσίδα ιδιοτήτων (`Parameters.Barcode.XDimension`) ισχύει—απλώς αλλάξτε την τιμή `Pixels`. + +## Πώς να Δημιουργήσετε DataBar Stacked Omni‑Directional Barcode + +Τώρα που η γεννήτρια είναι έτοιμη, θα παίξουμε με την ιδιότητα **aspect ratio**. Αυτό ελέγχει τη σχέση ύψους‑πλάτους του DataBar, επιτρέποντάς σας να δημιουργήσετε ένα σύντομο, τετράγωνο σύμβολο ή ένα ψηλό, στενό. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Τι συμβαίνει;** `AspectRatio = 15` λέει στη μηχανή να κάνει τις γραμμές 15 φορές ψηλότερες από το πλάτος τους. Το παραγόμενο PNG αποθηκεύεται ακριβώς δίπλα στο εκτελέσιμο αρχείο σας. + +## Δημιουργία Εικόνας Barcode C# – Αλλαγή του Aspect Ratio + +Ας αποδείξουμε την ευελιξία αλλάζοντας το ratio σε 30 και αποθηκεύοντας ένα δεύτερο αρχείο. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +Όταν εκτελέσετε το πρόγραμμα, θα έχετε δύο αρχεία PNG: + +| Αρχείο | Aspect Ratio | Προσεγγ. Μέγεθος | +|--------|--------------|-----------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Ανοίξτε τα σε οποιονδήποτε προβολέα εικόνων—θα πρέπει να δείτε καθαρά, σαρωτικά σύμβολα DataBar. + +## Επισκόπηση Τύπων Κωδικοποίησης Barcode (Προαιρετικό αλλά Χρήσιμο) + +Αν σας ενδιαφέρουν άλλοι **τύποι κωδικοποίησης barcode** που υποστηρίζει το Aspose, εδώ είναι ένα γρήγορο cheat‑sheet: + +| EncodeTypes Enum | Περιγραφή | +|------------------|-----------| +| `EncodeTypes.Code128` | Υψηλής πυκνότητας αλφαριθμητικό | +| `EncodeTypes.QR` | Διάστασης 2‑D matrix code | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar για λιανική | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Η εστίασή μας** – συμπαγές, πολυκατευθυντικό | + +Η γνώση του σωστού enum σας σώζει από πολλή δοκιμή‑και‑σφάλμα όταν αλλάζετε projects. + +## Συνηθισμένα Πιθανά Σφάλματα & Πώς να τα Αποφύγετε + +- **Λείπει το πακέτο NuGet** – Ο κώδικας δεν θα μεταγλωττιστεί χωρίς το `Aspose.BarCode`. Εκτελέστε πρώτα `dotnet add package Aspose.BarCode`. +- **Λάθος διαδρομή αρχείου** – Αν χρησιμοποιείτε απόλυτη διαδρομή, ελέγξτε τα backslashes (`\\`) στα Windows. Οι σχετικές διαδρομές (όπως φαίνονται) κρατούν το project φορητό. +- **Πολύ ακραίο aspect ratio** – Τα ratios πάνω από 50 μπορούν να κάνουν το barcode πολύ ψηλό για τυπικούς σαρωτές. Μείνετε στα 15‑30 για τις περισσότερες περιπτώσεις. + +## Πλήρης Πηγαίος Κώδικας (Έτοιμος για Αντιγραφή‑Επικόλληση) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Τρέξτε το πρόγραμμα (`dotnet run` ή πατήστε **F5** στο Visual Studio) και θα δείτε το μήνυμα στην κονσόλα που επιβεβαιώνει ότι τα αρχεία είναι στον δίσκο. + +![Παράδειγμα εξόδου γεννήτριας barcode που εμφανίζει DataBar barcode με aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Παράδειγμα εξόδου γεννήτριας barcode που εμφανίζει DataBar barcode με aspect ratio 15"} + +## Συμπεράσματα + +Μόλις ολοκληρώσαμε ένα **παράδειγμα γεννήτριας barcode** που δείχνει **πώς να ορίσετε διαστάσεις**, επιλέγει τους σωστούς **τύπους κωδικοποίησης barcode**, και τελικά **δημιουργεί αρχεία εικόνας barcode c#** που μπορείτε να ενσωματώσετε οπουδήποτε. Ο κώδικας είναι μικρός, οι έννοιες σαφείς, και τώρα έχετε μια σταθερή βάση για να επεκτείνετε τη λύση—ίσως προσθέτοντας κείμενα, περιστρέφοντας την εικόνα ή αλλάζοντας σε διαφορετική συμβολογία. + +### Τι Ακολουθεί; + +- Πειραματιστείτε με **διαφορετικές διαστάσεις X** για να δείτε πώς αλλάζει η ανοχή του σαρωτή. +- Δοκιμάστε άλλους **EncodeTypes** όπως `Code128` ή `QR` για να εμπλουτίσετε το εργαλείο σας. +- Αυτοματοποιήστε τη δημιουργία σε batch: κάντε βρόχο πάνω από ένα CSV με IDs προϊόντων και δημιουργήστε PNG για καθένα. + +Αν αντιμετωπίσετε πρόβλημα, αφήστε ένα σχόλιο παρακάτω ή ελέγξτε την τεκμηρίωση Aspose.BarCode—είναι γεμάτη παραδείγματα που συμπληρώνουν ό,τι καλύψαμε εδώ. + +Καλή προγραμματιστική, και να σαρώνουν πάντα τα barcodes σας με την πρώτη προσπάθεια! + +## Τι Θα Μάθετε Στη Σειρά Επόμενη; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη, λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να κατακτήσετε επιπλέον δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στα δικά σας projects. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/greek/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..8d15f47f9 --- /dev/null +++ b/barcode/greek/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-07-18 +description: Δημιουργήστε γρήγορα το Planet barcode με C#. Μάθετε πώς να δημιουργείτε + γεμιστές και κενές γραμμές, να ορίζετε τη διάσταση X και να αποθηκεύετε εικόνες + PNG – όλα σε ένα σεμινάριο. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: el +lastmod: 2026-07-18 +og_description: Δημιουργήστε άμεσα το barcode Planet. Αυτός ο οδηγός σας δείχνει πώς + να ορίσετε τη διάσταση X, να εναλλάσσετε μεταξύ γεμάτων και κενών γραμμών και να + εξάγετε αρχεία PNG με το Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Δημιουργία Planet Barcode σε C# – Πλήρης Οδηγός Προγραμματισμού +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Δημιουργία Planet Barcode σε C# – Πλήρης Οδηγός Βήμα‑Βήμα +url: /el/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία Planet Barcode σε C# – Πλήρης Οδηγός Βήμα‑Βήμα + +Έχετε ποτέ χρειαστεί να **δημιουργήσετε εικόνες planet barcode** αλλά δεν ήξερες ποιες ιδιότητες να ρυθμίσεις; Δεν είστε μόνοι. Πολλοί προγραμματιστές συναντούν πρόβλημα όταν οι προεπιλεγμένες γεμιστές γραμμές δεν ανταποκρίνονται στις απαιτήσεις του προτύπου, ή όταν το πλάτος της γραμμής πρέπει να ταιριάζει με το DPI του εκτυπωτή. + +Σε αυτό το tutorial θα μάθετε ακριβώς πώς να **δημιουργήσετε αρχεία planet barcode** χρησιμοποιώντας τη βιβλιοθήκη Aspose.BarCode, πώς να ελέγχετε τα **pixel XDimension**, και πώς να εναλλάσσετε μεταξύ **γεμιστών γραμμών** και **κενών γραμμών** χωρίς να ξαναγράψετε κώδικα. Στο τέλος θα έχετε δύο αρχεία PNG—ένα με συμπαγείς γραμμές και ένα με κενές γραμμές—έτοιμα για οποιοδήποτε ταχυδρομικό σύστημα που απαιτεί τη συμβολική Planet. + +## Προαπαιτούμενα + +- .NET 6.0 ή νεότερο (ο κώδικας λειτουργεί επίσης σε .NET Framework 4.7 +) +- Πακέτο NuGet **Aspose.BarCode for .NET** (`Install-Package Aspose.BarCode`) +- Βασικές γνώσεις C# (θα δείτε γιατί χρησιμοποιούμε δηλώσεις `using` αργότερα) +- Ένας φάκελος με δικαιώματα εγγραφής όπου θα αποθηκευτούν τα PNG + +Αν έχετε όλα αυτά, μπορούμε να προχωρήσουμε κατευθείαν στην υλοποίηση. + +## Βήμα 1 – Ρύθμιση του Project και Προσθήκη της Βιβλιοθήκης + +Πρώτα, δημιουργήστε μια νέα εφαρμογή console (ή οποιοδήποτε project C#) και προσθέστε την βιβλιοθήκη **Planet barcode generator**. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro tip:** Στο Visual Studio, κάντε δεξί‑κλικ στο project → *Manage NuGet Packages* → ψάξτε για **Aspose.BarCode** και κάντε κλικ στο *Install*. Αυτό θα σας δώσει πρόσβαση στο `BarcodeGenerator` και σε όλες τις **παραμέτρους BarcodeGenerator** που θα χρειαστείτε. + +## Βήμα 2 – Αρχικοποίηση του Planet Barcode Generator + +Τώρα δημιουργούμε πραγματικά το παράδειγμα **planet barcode** generator και του δίνουμε τα δεδομένα που θέλουμε να κωδικοποιήσουμε (`"123456"` σε αυτό το παράδειγμα). Το enum `EncodeTypes.Planet` λέει στη βιβλιοθήκη ποια συμβολική να χρησιμοποιήσει. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Why this matters:** Η σημαία `EncodeTypes.Planet` εφαρμόζει αυτόματα το σωστό checksum και τους κανόνες διάταξης για το ταχυδρομικό barcode Planet, ώστε να μην χρειάζεται να τα υπολογίσετε χειροκίνητα. + +## Βήμα 3 – Διαμόρφωση X‑Dimension (Πλάτος Γραμμής) + +Οι περισσότεροι εκτυπωτές απαιτούν κάθε γραμμή να έχει συγκεκριμένο αριθμό pixel. Εδώ ορίζουμε τα **pixel XDimension** σε `4`, μια κοινή τιμή για θερμικούς εκτυπωτές 203 dpi. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Edge case:** Αν στοχεύετε σε εκτυπωτή 300 dpi, ίσως χρειαστείτε `3` ή `5` pixel αντί αυτού. Ρυθμίστε αυτήν την τιμή βάσει της τεκμηρίωσης της συσκευής σας. + +## Βήμα 4 – Αποθήκευση της Έκδοσης με Γεμιστές Γραμμές + +Από προεπιλογή ο generator παράγει **γεμιστές γραμμές** (συμπαγικά μαύρα ορθογώνια). Ας τις γράψουμε στο δίσκο: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Αντικαταστήστε το `YOUR_DIRECTORY` με μια απόλυτη ή σχετική διαδρομή στην οποία η εφαρμογή σας μπορεί να γράψει. Μετά την εκτέλεση αυτής της γραμμής θα βρείτε ένα αρχείο PNG που μοιάζει με κλασικό Planet barcode—ιδανικό για δοκιμή με ταχυδρομικό scanner. + +## Βήμα 5 – Εναλλαγή σε Κενές Γραμμές + +Μερικές φορές οι ταχυδρομικές υπηρεσίες απαιτούν το στυλ “κενές γραμμές”, όπου οι γραμμές χαραγμένες από λευκό φόντο αντί για μαύρο χρώμα. Η βιβλιοθήκη παρέχει έναν απλό διακόπτη: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Ορίζοντας το `FilledBars` σε `false` λέμε στον renderer να αντιστρέψει τη λογική γεμίσματος. Δεν χρειάζεται να δημιουργήσετε νέο αντικείμενο `BarcodeGenerator`; απλώς τροποποιούμε τις υπάρχουσες **παραμέτρους BarcodeGenerator**. + +## Βήμα 6 – Αποθήκευση της Έκδοσης με Κενές Γραμμές + +Τέλος, εξάγουμε τη δεύτερη εικόνα: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Τώρα έχετε δύο διαφορετικά αρχεία PNG, το καθένα συμμορφωμένο με διαφορετική οπτική απαίτηση. + +## Πλήρες Παράδειγμα Εργασίας + +Συνδυάζοντας όλα τα παραπάνω, ορίστε το πλήρες, έτοιμο για αντιγραφή‑και‑επικόλληση πρόγραμμα: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Αναμενόμενη έξοδος** (στο console): + +``` +Both Planet barcode images have been generated successfully. +``` + +Και στο `C:\Barcodes\` θα δείτε: + +- `PostalPlanetFilledBars.png` – συμπαγείς μαύρες γραμμές +- `PostalPlanetEmptyBars.png` – λευκές γραμμές με μαύρα περιγράμματα + +Ανοίξτε τα σε οποιονδήποτε προβολέα εικόνων· και τα δύο θα πρέπει να συμμορφώνονται με την προδιαγραφή Planet. + +## Συχνές Ερωτήσεις & Συμβουλές + +### “Μπορώ να αλλάξω τη μορφή εικόνας;” + +Απολύτως. Η μέθοδος `Save` δέχεται `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, κ.λπ. Απλώς αντικαταστήστε το `BarCodeImageFormat.Png` με τη μορφή που προτιμάτε. + +### “Τι γίνεται αν χρειάζομαι διαφορετικό ύψος barcode;” + +Χρησιμοποιήστε `planetBarcode.Parameters.Barcode.BarHeight` (σε points) για να αυξήσετε ή να μειώσετε το κάθετο μέγεθος. Για παράδειγμα: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “Υπάρχει τρόπος να προσθέσω κείμενο που διαβάζεται από άνθρωπο;” + +Ναι. Ορίστε την ιδιότητα `CodeText` στο `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “Πρέπει να απελευθερώσω τον generator;” + +Το `BarcodeGenerator` υλοποιεί το `IDisposable`. Τυλίξτε το σε μπλοκ `using` αν δημιουργείτε πολλά barcodes σε βρόχο: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “Τι γίνεται με το χειρισμό σφαλμάτων;” + +Τυλίξτε τις κλήσεις `Save` σε μπλοκ `try…catch` για να πιάσετε `IOException` (προβλήματα δίσκου) ή `ArgumentException` (μη έγκυρες παράμετροι). Παράδειγμα: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Ανακεφαλαίωση + +Καλύψαμε όλα όσα χρειάζεστε για να **δημιουργήσετε εικόνες planet barcode** σε C#: + +1. Αρχικοποιήστε τον **Planet barcode generator** με τα δεδομένα σας. +2. Ρυθμίστε τα **pixel XDimension** ώστε να ταιριάζουν με τις προδιαγραφές του εκτυπωτή. +3. Αποθηκεύστε ένα PNG με **γεμιστές γραμμές**. +4. Αλλάξτε το `FilledBars` για να παραγάγετε **κενές γραμμές**. +5. Αποθηκεύστε το δεύτερο PNG. + +Από εδώ μπορείτε να εξερευνήσετε περισσότερες **παραμέτρους BarcodeGenerator**, να πειραματιστείτε με άλλες συμβολικές (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, κ.λπ.), ή να ενσωματώσετε τις εικόνες σε μια ροή αποστολής αλληλογραφίας. + +--- + +**Έτοιμοι για το επόμενο βήμα;** Δοκιμάστε να προσθέσετε έναν QR code στο ίδιο έγγραφο, ή να δημιουργήσετε μια παρτίδα Planet barcodes από λίστα CSV χρησιμοποιώντας βρόχο `foreach`. Το API του Aspose.BarCode είναι αρκετά ευέλικτο για μαζικές λειτουργίες, προσαρμοσμένα χρώματα και ακόμη έξοδο σε διανυσματικό SVG. + +Αν αντιμετωπίσετε δυσκολίες, αφήστε ένα σχόλιο παρακάτω ή ελέγξτε την επίσημη τεκμηρίωση Aspose.BarCode για πιο βαθιές εξηγήσεις. Καλή προγραμματιστική! + +## Τι Πρέπει Να Μάθετε Στη Σύντομη Μελλοντική + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να κατακτήσετε επιπλέον δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στα δικά σας projects. + +- [Create Barcode with Aspose - Set X & Y Dimensions in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/greek/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..4e4ce3bcd --- /dev/null +++ b/barcode/greek/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-07-18 +description: Δημιουργήστε γραμμωτό κώδικα RM4SCC σε C# γρήγορα· μάθετε πώς να ορίσετε + το ύψος του κώδικα και επίσης δημιουργήστε γραμμωτό κώδικα Planet με προσαρμοσμένες + διαστάσεις. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: el +lastmod: 2026-07-18 +og_description: Δημιουργήστε γραμμωτό κώδικα RM4SCC σε C# και ανακαλύψτε πώς να ορίσετε + το ύψος του κώδικα. Δείτε επίσης πώς να δημιουργήσετε γραμμωτό κώδικα Planet με + την ίδια βιβλιοθήκη. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Δημιουργία κωδικού RM4SCC σε C# – Ρύθμιση προσαρμοσμένου ύψους γρήγορα +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Δημιουργία γραμμωτού κώδικα RM4SCC σε C# – Πλήρης οδηγός για τον καθορισμό + του ύψους +url: /el/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία RM4SCC Barcode σε C# – Πλήρης Οδηγός για Ορισμό Ύψους + +Έχετε ποτέ χρειαστεί να **δημιουργήσετε RM4SCC barcode** σε μια εφαρμογή .NET αλλά δεν ήξερες πώς να ελέγξεις το μέγεθός του; Δεν είστε μόνοι. Είτε δημιουργείτε σύστημα αποστολών είτε πίνακα ελέγχου logistics, η σωστή ύψος του barcode μπορεί να είναι η διαφορά μεταξύ μιας λειτουργικής σάρωσης και μιας αποτυχημένης. + +Σε αυτό το tutorial θα περάσουμε από όλη τη διαδικασία: από την εγκατάσταση της βιβλιοθήκης, μέχρι το **generate Planet barcode** ως παράδειγμα δίπλα‑δίπλα, και τελικά το **how to set barcode height** για και τους δύο τύπους barcode. Στο τέλος θα έχετε μια έτοιμη για εκτέλεση console εφαρμογή που παράγει αρχεία PNG με τις ακριβείς διαστάσεις που χρειάζεστε. + +--- + +## Τι Θα Χρειαστείτε + +- **.NET 6 SDK** (ή οποιαδήποτε πρόσφατη έκδοση .NET) – ο κώδικας λειτουργεί επίσης στο .NET Framework, αλλά το .NET 6 είναι η ιδανική επιλογή. +- **Aspose.BarCode for .NET** πακέτο NuGet – αυτή είναι η βιβλιοθήκη που παρέχει την κλάση `BarcodeGenerator`. +- Μία μέτρια γνώση C# – θα κρατήσουμε τη σύνταξη φιλική για αρχάριους. +- Ένα IDE ή κειμενογράφο (Visual Studio, VS Code, Rider—επιλέξτε το αγαπημένο σας). + +> **Pro tip:** Αν βρίσκεστε σε CI/CD pipeline, προσθέστε την αναφορά NuGet στο `.csproj` ώστε η κατασκευή να μην ξεχνάει ποτέ την εξάρτηση. + +--- + +## Βήμα 1: Ρύθμιση του Έργου + +Ανοίξτε ένα τερματικό και δημιουργήστε ένα νέο console project: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +Αυτό είναι όλο – το έργο σας τώρα αναφέρεται στη βιβλιοθήκη που τροφοδοτεί όλα όσα ακολουθούν. + +### Προσθήκη των Using Directives + +Ανοίξτε το `Program.cs` και επικολλήστε τα παρακάτω στην κορυφή: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +Αυτοί οι χώροι ονομάτων μας δίνουν πρόσβαση στο `BarcodeGenerator` και στο enum μορφής εικόνας που θα χρησιμοποιήσουμε αργότερα. + +--- + +## Βήμα 2: Ορισμός Μεθόδου Βοηθού για Αποθήκευση Εικόνων + +Για να αποφύγουμε την επανάληψη της ίδιας λογικής αποθήκευσης, θα την τυλίξουμε σε μια μικρή μέθοδο. Αυτό επίσης δείχνει **how to set barcode height** αργότερα. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Why this matters:** Η κεντρικοποίηση της λογικής αποθήκευσης σημαίνει ότι χρειάζεται να αλλάξετε τη μορφή ή το φάκελο μόνο σε ένα σημείο αν αλλάξουν οι απαιτήσεις. + +--- + +## Βήμα 3: Δημιουργία Planet Barcode (το τμήμα “generate planet barcode”) + +Πριν εμβαθύνουμε στις λεπτομέρειες του RM4SCC, ας δημιουργήσουμε ένα **Planet barcode**. Αυτό σας δίνει έναν γρήγορο οπτικό έλεγχο ότι η βιβλιοθήκη λειτουργεί. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Αναμενόμενο αποτέλεσμα:** Δύο αρχεία PNG εμφανίζονται στο φάκελο `output` — ένα με το αυτόματα υπολογισμένο ύψος από τη βιβλιοθήκη, το άλλο ακριβώς 100 px ύψος. + +--- + +## Βήμα 4: Δημιουργία RM4SCC Barcode – Κύριος Στόχος + +Τώρα για το αστέρι της παράστασης: **create RM4SCC barcode**. Το RM4SCC είναι ο Royal Mail 4‑State Code, ευρέως χρησιμοποιούμενος στο ταχυδρομικό σύστημα του ΗΒ. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**Τι θα δείτε:** +- `RM4SCCDefault.png` – η βιβλιοθήκη αποφασίζει ένα άνετο ύψος βάσει της διάστασης X. +- `RM4SCCHeight100.png` – ένα καθαρό barcode 100 pixel ύψους, έτοιμο για εκτύπωση σε φακέλους. + +> **Why set the height?** Ορισμένοι εκτυπωτές ετικετών απαιτούν ελάχιστο ύψος γραμμής για αξιόπιστη σάρωση. Ορίζοντας το ύψος εξασφαλίζετε συμμόρφωση σε όλες τις συσκευές. + +--- + +## Βήμα 5: Κατανόηση των Ρυθμίσεων Ύψους (Απάντηση στο “how to set barcode height”) + +Και τα δύο παραδείγματα, Planet και RM4SCC, χρησιμοποιούν την ίδια ιδιότητα: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** είναι ένα αντικείμενο `BarHeight` που ομαδοποιεί διάφορες μονάδες μέτρησης (pixels, millimetres, inches). +- **`.Pixels`** είναι η πιο απλή μονάδα για έξοδο προσανατολισμένο στην οθόνη, αλλά μπορείτε επίσης να χρησιμοποιήσετε `.Millimeters` ή `.Inches` αν στοχεύετε σε εκτυπώσεις. + +### Περιπτώσεις Άκρων & Συμβουλές + +| Situation | Recommended Approach | +|-----------|----------------------| +| **Πολύ μικρή διάσταση X (π.χ., 1 px)** | Αυξήστε το `BarHeight` για να διατηρήσετε το barcode αναγνώσιμο. | +| **Εκτύπωση σε εκτυπωτές ετικετών υψηλής ανάλυσης** | Χρησιμοποιήστε `.Millimeters` για μέγεθος ανεξάρτητο από τη συσκευή. | +| **Πολλαπλοί τύποι barcode σε μία εικόνα** | Ορίστε το `BarHeight` *μετά* το `XDimension` για κάθε γεννήτρια ώστε να αποφύγετε τυχαία κληρονομιά. | +| **Δυναμικά δεδομένα (π.χ., κωδικοί που εισάγει ο χρήστης)** | Τυλίξτε τη δημιουργία του γεννήτρια σε μια μέθοδο που δέχεται παραμέτρους `code` και `height`. | + +--- + +## Βήμα 6: Πλήρες Παράδειγμα Λειτουργίας + +Παρακάτω είναι ένα ενιαίο, αυτόνομο πρόγραμμα που μπορείτε να αντιγράψετε‑επικολλήσετε στο `Program.cs`. Περιλαμβάνει όλα, από τη ρύθμιση του έργου μέχρι την αποθήκευση των εικόνων. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Τρέξτε το με: + +```bash +dotnet run +``` + +Θα πρέπει να δείτε την έξοδο της κονσόλας που επιβεβαιώνει την αποθήκευση κάθε αρχείου, και ο φάκελος `output` θα περιέχει τέσσερα PNG που ταιριάζουν με τα ονόματα που εμφανίστηκαν παραπάνω. + +--- + +## Συμπέρασμα + +Τώρα ξέρετε **how to create RM4SCC barcode** σε C# και πώς να ελέγξετε τις διαστάσεις του με μόνο μερικές αναθέσεις ιδιοτήτων. Καλύψαμε επίσης το **generate planet barcode** ως γρήγορο έλεγχο, και εξετάσαμε τις λεπτομέρειες του **how to set barcode height** για διαφορετικά σενάρια εκτύπωσης. + +Τι θα κάνετε μετά; Δοκιμάστε να αντικαταστήσετε το enum `EncodeTypes` με άλλες συμβολές (Code128, QR, DataMatrix) και πειραματιστείτε με το `BarHeight` σε χιλιοστά για εκτυπωτές υψηλής ανάλυσης. Αν χρειάζεται να ενσωματώσετε το barcode σε PDF, συνδυάστε το Aspose.BarCode με το Aspose.PDF — ένα ακόμη ισχυρό ζευγάρι. + +Έχετε ερωτήσεις ή θέλετε να μοιραστείτε τις δικές σας προσαρμογές; Αφήστε ένα σχόλιο παρακάτω, και καλή προγραμματιστική! + +## Τι Θα Πρέπει Να Μάθετε Στη Σύντομη Επόμενη + +Οι παρακάτω οδηγίες καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικά παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να δημιουργήσετε Aztec barcode με προσαρμοσμένη αναλογία διαστάσεων χρησιμοποιώντας Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Πώς να δημιουργήσετε ζώνη ησυχίας barcode για ITF-14 χρησιμοποιώντας Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Πώς να δημιουργήσετε ζώνη ησυχίας barcode για Code 16K χρησιμοποιώντας Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/greek/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..2e40fb9a7 --- /dev/null +++ b/barcode/greek/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-07-18 +description: Μάθετε πώς να δημιουργείτε εικόνες barcode με έναν .net γεννήτρια barcode + και να αλλάζετε εύκολα το ύψος του barcode για σύμβολα GS1‑Databar Omni‑Directional. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: el +lastmod: 2026-07-18 +og_description: Το .net barcode generator σας επιτρέπει να δημιουργείτε γρήγορα εικόνες + barcode. Αυτός ο οδηγός δείχνει πώς να δημιουργήσετε barcode, να ρυθμίσετε το ύψος + των γραμμών και να αποθηκεύσετε αρχεία PNG. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Αλλάξτε το ύψος του barcode με τον .NET δημιουργό barcode +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET δημιουργός barcode – αλλαγή ύψους barcode +url: /el/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – αλλαγή ύψους barcode + +Έχετε αναρωτηθεί ποτέ **πώς να δημιουργήσετε εικόνες barcode** χωρίς να χειρίζεστε μια δεκάδα εξωτερικών εργαλείων; Στον κόσμο του .NET υπάρχει ένας εκπληκτικά απλός τρόπος για να το κάνετε, και το κλειδί είναι το **.net barcode generator**. Με λίγες μόνο γραμμές C# μπορείτε να δημιουργήσετε ένα σύμβολο GS1‑Databar Omni‑Directional, να ρυθμίσετε το ύψος των γραμμών και να αποθηκεύσετε το αποτέλεσμα σε αρχείο PNG. + +Αν δημιουργείτε σύστημα αποθεμάτων, εκτυπωτή ετικετών αποστολής ή οποιαδήποτε εφαρμογή που χρειάζεται έναν κώδικα που μπορεί να σαρωθεί, αυτό το tutorial θα σας μεταφέρει από το μηδέν σε ένα λειτουργικό barcode σε λίγα λεπτά. Θα περάσουμε από τον πλήρη κώδικα, θα εξηγήσουμε γιατί κάθε ρύθμιση είναι σημαντική και θα σας δείξουμε πώς να **αλλάξετε το ύψος του barcode** χωρίς να παραβιάσετε τις προδιαγραφές. + +## Τι θα χρειαστείτε + +- .NET 6.0 ή νεότερο (το API λειτουργεί το ίδιο και σε .NET Framework 4.7+) +- Αναφορά στη βιβλιοθήκη barcode (π.χ., Aspose.BarCode for .NET – οι ίδιες κλάσεις χρησιμοποιούνται από πολλά εμπορικά κιτ) +- Περιβάλλον ανάπτυξης (Visual Studio, Rider ή VS Code με την επέκταση C#) +- Φάκελος όπου έχετε δικαίωμα εγγραφής – το tutorial θα αποθηκεύει αρχεία PNG εκεί + +Αυτό είναι όλο. Δεν χρειάζονται επιπλέον πακέτα NuGet εκτός από τη βιβλιοθήκη barcode. + +## Χρήση του .net barcode generator για αλλαγή ύψους barcode + +Παρακάτω υπάρχει ένα **πλήρες, εκτελέσιμο πρόγραμμα console**. Επικολλήστε το σε ένα νέο έργο C#, προσαρμόστε το φάκελο εξόδου και πατήστε F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Γιατί κάθε γραμμή είναι σημαντική + +| Line | Reason | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Δημιουργεί ένα στιγμιότυπο του **.net barcode generator** με την επιθυμητή συμβολική αναπαράσταση και τα δεδομένα. Η απαρίθμηση `EncodeTypes.DatabarOmniDirectional` ενημερώνει τη βιβλιοθήκη να χρησιμοποιήσει τη μορφή GS1‑Databar Omni‑Directional. | +| `XDimension.Pixels = 2;` | Η X‑διάσταση είναι το πλάτος της πιο λεπτής γραμμής. Ορίζοντάς την σε *2 pixels* παρέχει καθαρή εικόνα στα περισσότερα μοντέρνα οθόνες ενώ διατηρεί το μέγεθος του αρχείου μικρό. | +| `BarHeight.Pixels = 30;` | Αυτό είναι το βήμα **αλλαγής ύψους barcode** που καθορίζει το ύψος κάθε γραμμής. Ύψος 30 pixel είναι μια καλή προεπιλογή για μικρές ετικέτες. | +| `generator.Save(...);` | Αποθηκεύει το barcode σε αρχείο PNG. Το PNG είναι loss‑less, πράγμα που σημαίνει ότι οι σαρωτές βλέπουν το ακριβές μοτίβο που δημιουργήθηκε. | +| `BarHeight.Pixels = 60;` | Εδώ **αλλάζουμε το ύψος του barcode** ξανά—αυτή τη φορά σε 60 pixels. Η βιβλιοθήκη επανασχεδιάζει αυτόματα το σύμβολο με τη νέα διάσταση όταν καλέσετε το `Save` για δεύτερη φορά. | +| `Console.WriteLine(...);` | Σας παρέχει γρήγορη ανατροφοδότηση ότι η διαδικασία ολοκληρώθηκε χωρίς εξαίρεση. | + +> **Συμβουλή επαγγελματία:** Αν χρειάζεστε έξοδο υψηλότερης ανάλυσης για εκτύπωση, αλλάξτε το `BarCodeImageFormat.Png` σε `BarCodeImageFormat.Tiff` και αυξήστε την ιδιότητα `Resolution` (π.χ., `generator.Parameters.ImageResolution = 300;`). Το ύψος των γραμμών θα παραμείνει σεβαστό, απλώς θα αποδοθεί σε πιο λεπτή DPI. + +## Πώς να δημιουργήσετε εικόνες barcode με διαφορετικές ρυθμίσεις + +Το παραπάνω απόσπασμα καλύπτει τα βασικά, αλλά σε πραγματικές περιπτώσεις συχνά απαιτούνται πρόσθετες ρυθμίσεις: + +### Προσαρμογή της X‑διάστασης για μεγαλύτερες εκτυπώσεις +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Η αύξηση της X‑διάστασης κάνει ολόκληρο το barcode μεγαλύτερο χωρίς να αλλάζει τα κωδικοποιημένα δεδομένα. Αυτό είναι χρήσιμο όταν εκτυπώνετε σε μεγάλες ετικέτες. + +### Αλλαγή μορφής εξόδου +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +Το SVG κλιμακώνεται άπειρα, κάτι που είναι τέλειο για σαρωτές στο web που χρειάζονται καθαρά διανυσματικά γραφικά. + +### Προσθήκη κειμένου αναγνώσιμου από άνθρωπο +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Η ενεργοποίηση του `CodeTextVisible` προσθέτει τα ακατέργαστα δεδομένα κάτω από το barcode, χρήσιμο για επαλήθευση κατά τη δοκιμή. + +## Συνηθισμένα λάθη όταν **αλλάζετε το ύψος του barcode** + +1. **Ύψος πολύ μικρό** – Κάποιοι σαρωτές απαιτούν ελάχιστο ύψος γραμμής (συχνά 10 mm σε φυσικές μονάδες). Αν ορίσετε το `BarHeight.Pixels` πολύ χαμηλά, η παραγόμενη εικόνα μπορεί να είναι αδιάβαστη από πραγματικό σαρωτή. Πάντα δοκιμάζετε με το στοχευόμενο υλικό. +2. **Ασυμφωνία X‑διάστασης και ύψους** – Ένα τεράστιο ύψος γραμμής σε συνδυασμό με πολύ μικρή X‑διάσταση μπορεί να φαίνεται τεντωμένο και να προκαλέσει σφάλματα αποκωδικοποίησης. Στοχεύστε σε ισορροπημένη αναλογία (περίπου 3:1 έως 5:1) εκτός αν οι προδιαγραφές ορίζουν διαφορετικά. +3. **Ξεχάνοντας να επαναφέρετε τις παραμέτρους** – Ο generator διατηρεί την κατάσταση μεταξύ των αποθηκεύσεων. Αν αλλάξετε το `BarHeight` για μία εικόνα και στη συνέχεια χρησιμοποιήσετε την ίδια παρουσία για άλλο barcode, το προηγούμενο ύψος θα παραμείνει. Επαναφέρετε την ιδιότητα ή δημιουργήστε νέο `BarcodeGenerator` για κάθε διαφορετικό barcode. + +## Πλήρες παράδειγμα από την αρχή μέχρι το τέλος (συμπεριλαμβανομένης της εγκατάστασης NuGet) + +Αν ξεκινάτε από το μηδέν, ακολουθήστε αυτά τα βήματα για να εκτελέσετε το έργο: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Αντικαταστήστε το αυτόματα δημιουργημένο `Program.cs` με το μπλοκ κώδικα που εμφανίστηκε παραπάνω, **θυμηθείτε να αντικαταστήσετε το `YOUR_DIRECTORY`** με κάτι όπως `Path.Combine(Environment.CurrentDirectory, "output")`. Στη συνέχεια: + +```bash +dotnet run +``` + +Θα πρέπει να δείτε δύο αρχεία PNG στον φάκελο `output`: + +- `DatabarBarHeight30Pixels.png` – ένα συμπαγές barcode ύψους 30 pixel. +- `DatabarBarHeight60Pixels.png` – μια πιο ψηλή έκδοση 60 pixel. + +Και οι δύο εικόνες θα φαίνονται παρόμοιες, αλλά η δεύτερη θα έχει αισθητά μεγαλύτερα bars, κάνοντάς το πιο εύκολο για σαρωτές χαμηλής ανάλυσης να το διαβάσουν. + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator output που δείχνει διαφορετικά ύψη γραμμών"} + +## Σύνοψη & επόμενα βήματα + +Καλύψαμε πώς να **δημιουργήσετε εικόνες barcode** χρησιμοποιώντας ένα **.net barcode generator**, να ρυθμίσουμε τη **αλλαγή ύψους barcode** και να αποθηκεύσουμε τα αποτελέσματα σε μορφή PNG. Τα κύρια σημεία είναι: + +- Δημιουργήστε το στιγμιότυπο του generator με το σωστό `EncodeTypes`. +- Ελέγξτε το οπτικό μέγεθος μέσω `XDimension` και `BarHeight`. +- Καλέστε το `Save` μετά από κάθε αλλαγή για να αποθηκεύσετε μια νέα εικόνα. +- Ρυθμίστε την ανάλυση, τη μορφή, + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να δημιουργήσετε barcode Aztec με προσαρμοσμένη αναλογία διαστάσεων χρησιμοποιώντας Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Πώς να δημιουργήσετε dotcode με εκτεταμένο κείμενο κώδικα χρησιμοποιώντας Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Πώς να δημιουργήσετε DataMatrix Barcodes (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/hindi/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/hindi/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..19ec69dba --- /dev/null +++ b/barcode/hindi/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-07-18 +description: बारकोड जेनरेटर का उदाहरण जो दिखाता है कि कैसे आयाम सेट करें और C# में + DataBar Stacked Omni‑Directional बारकोड छवि उत्पन्न करें। बारकोड एन्कोड प्रकारों + को जल्दी सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: hi +lastmod: 2026-07-18 +og_description: बारकोड जेनरेटर उदाहरण आपको आयाम सेट करने, बारकोड एन्कोड प्रकार चुनने + और न्यूनतम कोड के साथ C# प्रोजेक्ट्स में बारकोड छवि बनाने की प्रक्रिया दिखाता है। +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: बारकोड जेनरेटर उदाहरण – C# में तेज़ DataBar इमेज निर्माण +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: बारकोड जेनरेटर उदाहरण – C# में DataBar इमेज बनाएं +url: /hi/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# बारकोड जेनरेटर उदाहरण – C# में DataBar इमेज बनाना + +क्या आपको कभी **बारकोड जेनरेटर उदाहरण** चाहिए था जो वास्तव में वास्तविक‑दुनिया का बारकोड प्रिंट करे बिना आपके बाल खींचे? आप अकेले नहीं हैं। अधिकांश डेवलपर्स एक बाधा का सामना करते हैं जब वे DataBar Stacked Omni‑Directional बारकोड के **डायमेंशन सेट करने के तरीके** को समझने की कोशिश करते हैं, खासकर जब दस्तावेज़ीकरण शब्दजाल की परतों में छिपा हो। + +इस ट्यूटोरियल में हम एक पूर्ण, तैयार‑चलाने योग्य C# प्रोग्राम के माध्यम से चलेंगे जो दिखाता है **डेटाबार इमेज कैसे जेनरेट करें**, सही **बारकोड एन्कोड टाइप्स** चुनता है, और अंत में **बारकोड इमेज C#** फ़ाइलें बनाता है जिन्हें आप किसी भी प्रोजेक्ट में डाल सकते हैं। कोई फालतू बातें नहीं—सिर्फ वह कोड जिसे आप कॉपी‑पेस्ट कर सकते हैं, साथ ही हर पंक्ति के पीछे की तर्कसंगतता। + +## आपको क्या चाहिए + +- **.NET 6** (या कोई भी नवीनतम .NET संस्करण) – हम जिस API का उपयोग करते हैं वह .NET Standard को लक्षित करता है, इसलिए यह .NET Framework पर भी काम करता है। +- **Aspose.BarCode for .NET** – वह लाइब्रेरी जो `BarcodeGenerator` प्रदान करती है। आप इसे NuGet से `Install-Package Aspose.BarCode` के साथ प्राप्त कर सकते हैं। +- एक **C# IDE** – Visual Studio, Rider, या VS Code काम करेगा। +- डिस्क पर एक फ़ोल्डर जहाँ PNG फ़ाइलें सहेजी जाएँगी (कोड `DatabarAspectRatio15.png` और `DatabarAspectRatio30.png` बनाता है)। + +सब कुछ तैयार है? बढ़िया—चलिए शुरू करते हैं। + +## बारकोड जेनरेटर उदाहरण – जेनरेटर को इनिशियलाइज़ करें + +सबसे पहले: हमें `BarcodeGenerator` का एक इंस्टेंस चाहिए जो **DataBar Stacked Omni‑Directional** सिम्बोलॉजी के लिए कॉन्फ़िगर किया गया हो। यह वह **बारकोड एन्कोड टाइप** है जिसके साथ हम काम करेंगे। + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +**यह क्यों महत्वपूर्ण है:** `EncodeTypes.DatabarStackedOmniDirectional` Aspose को बिल्कुल बताता है कि कौन सी सिम्बोलॉजी रेंडर करनी है। यदि आप गलत प्रकार चुनते हैं, तो स्कैनर बारकोड को पहचान नहीं पाएगा, चाहे इमेज कितनी भी सुंदर क्यों न हो। + +## बारकोड के लिए डायमेंशन कैसे सेट करें + +बारकोड की पढ़ने योग्यता उसके **X‑डायमेंशन** (सबसे पतली बार की चौड़ाई) पर निर्भर करती है। अधिकांश मामलों में 2 पिक्सेल का मान ठीक काम करता है, लेकिन आप इसे अपने प्रिंटर या स्क्रीन के अनुसार समायोजित कर सकते हैं। + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**प्रो टिप:** यदि आप कभी **डायमेंशन सेट करने के तरीके** के बारे में सोचते हैं किसी अलग बारकोड फ़ैमिली के लिए, तो वही प्रॉपर्टी चेन (`Parameters.Barcode.XDimension`) लागू होती है—सिर्फ `Pixels` मान बदलें। + +## DataBar Stacked Omni‑Directional बारकोड कैसे जेनरेट करें + +अब जब जेनरेटर तैयार है, हम **आस्पेक्ट अनुपात** प्रॉपर्टी के साथ खेलेंगे। यह DataBar के ऊँचाई‑से‑चौड़ाई संबंध को नियंत्रित करता है, जिससे आप एक छोटा, वर्गाकार प्रतीक या एक लंबा, पतला प्रतीक बना सकते हैं। + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +**क्या हो रहा है?** `AspectRatio = 15` इंजन को बताता है कि बार को उनकी चौड़ाई से 15 गुना लंबा बनाएं। परिणामी PNG आपके एक्जीक्यूटेबल के बगल में सहेजा जाता है। + +## बारकोड इमेज C# बनाना – आस्पेक्ट अनुपात बदलना + +आइए लचीलापन साबित करें अनुपात को 30 में बदलकर और दूसरी फ़ाइल सहेजकर। + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +जब आप प्रोग्राम चलाएंगे, तो आपके पास दो PNG फ़ाइलें होंगी: + +| फ़ाइल | आस्पेक्ट अनुपात | लगभग आकार | +|------|----------------|------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +उन्हें किसी भी इमेज व्यूअर में खोलें—आपको साफ़, स्कैन करने योग्य DataBar प्रतीक दिखने चाहिए। + +## बारकोड एन्कोड टाइप्स का अवलोकन (वैकल्पिक लेकिन उपयोगी) + +यदि आप Aspose द्वारा समर्थित अन्य **बारकोड एन्कोड टाइप्स** के बारे में जिज्ञासु हैं, तो यहाँ एक त्वरित चीट‑शीट है: + +| EncodeTypes Enum | विवरण | +|------------------|--------| +| `EncodeTypes.Code128` | हाई‑डेंसिटी अल्फ़ान्यूमेरिक | +| `EncodeTypes.QR` | 2‑D मैट्रिक्स कोड | +| `EncodeTypes.DatabarExpanded` | रिटेल के लिए GS1 DataBar | +| `EncodeTypes.DatabarStackedOmniDirectional` | **हमारा फोकस** – कॉम्पैक्ट, ऑम्निडायरेक्शनल | + +सही enum जानने से आप प्रोजेक्ट बदलते समय कई ट्रायल‑एंड‑एरर से बचते हैं। + +## सामान्य गड़बड़ियां और उन्हें कैसे टालें + +- **NuGet पैकेज गायब** – कोड `Aspose.BarCode` के बिना कंपाइल नहीं होगा। पहले `dotnet add package Aspose.BarCode` चलाएँ। +- **गलत फ़ाइल पाथ** – यदि आप एब्सोल्यूट पाथ उपयोग करते हैं, तो Windows पर बैकस्लैश (`\\`) दोबारा जांचें। रिलेटिव पाथ (जैसा दिखाया गया) चीज़ों को पोर्टेबल रखता है। +- **आस्पेक्ट अनुपात बहुत अधिक** – 50 से ऊपर के अनुपात बारकोड को सामान्य स्कैनरों के लिए बहुत लंबा बना सकते हैं। अधिकांश उपयोग मामलों के लिए 15‑30 रखें। + +## पूरा स्रोत कोड (कॉपी‑पेस्ट तैयार) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +प्रोग्राम चलाएँ (`dotnet run` या Visual Studio में **F5** दबाएँ) और आपको कंसोल संदेश दिखाई देगा जो पुष्टि करेगा कि फ़ाइलें डिस्क पर हैं। + +![Barcode generator example output showing DataBar barcode with aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="बारकोड जेनरेटर उदाहरण आउटपुट जिसमें आस्पेक्ट अनुपात 15 के साथ DataBar बारकोड दिखाया गया है"} + +## निष्कर्ष + +हमने अभी एक **बारकोड जेनरेटर उदाहरण** पूरा किया है जो **डायमेंशन सेट करने के तरीके** को दर्शाता है, सही **बारकोड एन्कोड टाइप्स** चुनता है, और अंत में आप कहीं भी एम्बेड कर सकें **बारकोड इमेज C#** फ़ाइलें बनाता है। कोड छोटा है, अवधारणाएँ स्पष्ट हैं, और अब आपके पास समाधान को विस्तारित करने की ठोस नींव है—शायद टेक्स्ट कैप्शन जोड़ना, इमेज को घुमाना, या अलग सिम्बोलॉजी पर स्विच करना। + +### आगे क्या? + +- **विभिन्न X‑डायमेंशन** के साथ प्रयोग करें यह देखने के लिए कि स्कैनर सहनशीलता कैसे बदलती है। +- `Code128` या `QR` जैसे अन्य **EncodeTypes** आज़माएँ ताकि आपका टूलकिट विस्तृत हो। +- बैच जेनरेशन को ऑटोमेट करें: प्रोडक्ट IDs की CSV पर लूप करें और प्रत्येक के लिए PNG आउटपुट करें। + +यदि आपको कोई समस्या आती है, तो नीचे टिप्पणी छोड़ें या Aspose.BarCode दस्तावेज़ देखें—यहाँ कई उदाहरण हैं जो हमने यहाँ कवर किए गए को पूरक करते हैं। + +कोडिंग का आनंद लें, और आपके बारकोड हमेशा पहली कोशिश में स्कैन हों! + +## आपको आगे क्या सीखना चाहिए? + +निम्नलिखित ट्यूटोरियल्स निकट संबंधित विषयों को कवर करते हैं जो इस गाइड में प्रदर्शित तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण-दर-चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ का अन्वेषण करने में मदद करेंगे। + +- [बारकोड जेनरेट करने का तरीका - एक-आयामी बारकोड प्रकार](/barcode/english/net/one-dimensional-barcode-types/) +- [बारकोड इमेज C# बनाना – GS1 DataMatrix उदाहरण](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/hindi/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/hindi/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..ab63aab12 --- /dev/null +++ b/barcode/hindi/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-07-18 +description: C# के साथ Planet बारकोड जल्दी बनाएं। सीखें कैसे भरवां और खाली बार बनाएं, + X‑डायमेंशन सेट करें, और PNG इमेजेस सहेजें – सब कुछ एक ही ट्यूटोरियल में। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: hi +lastmod: 2026-07-18 +og_description: Planet बारकोड तुरंत बनाएं। यह गाइड आपको X‑डायमेंशन सेट करने, भरे और + खाली बार के बीच स्विच करने, और Aspose.BarCode के साथ PNG फ़ाइलें निर्यात करने का + तरीका दिखाता है। +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: C# में प्लैनेट बारकोड बनाएं – पूर्ण प्रोग्रामिंग मार्गदर्शन +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: C# में प्लैनेट बारकोड बनाएं – पूर्ण चरण‑दर‑चरण मार्गदर्शिका +url: /hi/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में Planet बारकोड बनाएं – पूर्ण चरण‑दर‑चरण गाइड + +क्या आपको कभी **create planet barcode** छवियां बनानी पड़ी हैं लेकिन आप नहीं जानते थे कि कौन सी प्रॉपर्टी बदलनी है? आप अकेले नहीं हैं। कई डेवलपर्स को तब समस्या आती है जब डिफ़ॉल्ट भराव वाले बार स्पेसिफिकेशन के अनुसार नहीं होते, या जब बार की चौड़ाई प्रिंटर के DPI से मेल खानी चाहिए। + +इस ट्यूटोरियल में आप सीखेंगे कि Aspose.BarCode लाइब्रेरी का उपयोग करके **create planet barcode** फ़ाइलें कैसे बनाएं, **XDimension pixels** को कैसे नियंत्रित करें, और **filled bars** और **empty bars** के बीच कैसे स्विच करें बिना कोड को फिर से लिखे। अंत तक आपके पास दो PNG फ़ाइलें होंगी—एक ठोस बार वाली और एक खोखली बार वाली—जो किसी भी डाक प्रणाली के लिए तैयार हैं जो Planet सिंबोलॉजी की अपेक्षा करती है। + +## पूर्वापेक्षाएँ + +- .NET 6.0 या बाद का (कोड .NET Framework 4.7 + पर भी काम करता है) +- Aspose.BarCode for .NET NuGet पैकेज (`Install-Package Aspose.BarCode`) +- बेसिक C# ज्ञान (आप बाद में देखेंगे कि हम `using` स्टेटमेंट्स क्यों उपयोग करते हैं) +- डिस्क पर एक लिखने योग्य फ़ोल्डर जहाँ PNG सहेजे जाएंगे + +यदि आपके पास ये हैं, तो हम सीधे कार्यान्वयन में कूद सकते हैं। + +## चरण 1 – प्रोजेक्ट सेट अप करें और लाइब्रेरी जोड़ें + +पहले, एक नया कंसोल ऐप (या कोई भी C# प्रोजेक्ट) बनाएं और **Planet barcode generator** लाइब्रेरी को रेफ़रेंस करें। + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro tip:** Visual Studio में, प्रोजेक्ट पर राइट‑क्लिक करें → *Manage NuGet Packages* → **Aspose.BarCode** खोजें और *Install* पर क्लिक करें। यह आपको `BarcodeGenerator` और सभी **BarcodeGenerator parameters** तक पहुंच देता है जो आपको चाहिए। + +## चरण 2 – Planet Barcode Generator को इनिशियलाइज़ करें + +अब हम वास्तव में **create planet barcode** जेनरेटर इंस्टेंस बनाते हैं और उसे वह डेटा देते हैं जिसे हम एन्कोड करना चाहते हैं (`"123456"` इस उदाहरण में)। `EncodeTypes.Planet` एन्‍यूम लाइब्रेरी को बताता है कि कौन सी सिंबोलॉजी उपयोग करनी है। + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Why this matters:** `EncodeTypes.Planet` फ़्लैग स्वचालित रूप से सही चेकसम और लेआउट नियम लागू करता है Planet पोस्टल बारकोड के लिए, इसलिए आपको उन्हें मैन्युअली गणना करने की ज़रूरत नहीं है। + +## चरण 3 – X‑Dimension (बार की चौड़ाई) कॉन्फ़िगर करें + +अधिकांश प्रिंटर उम्मीद करते हैं कि प्रत्येक बार एक निश्चित संख्या में पिक्सेल हो। यहाँ हम **XDimension pixels** को `4` पर सेट करते हैं, जो 203 dpi थर्मल प्रिंटरों के लिए सामान्य मान है। + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Edge case:** यदि आप 300 dpi प्रिंटर को टार्गेट कर रहे हैं, तो आपको `3` या `5` पिक्सेल की आवश्यकता हो सकती है। इस मान को अपने डिवाइस की डॉक्यूमेंटेशन के आधार पर समायोजित करें। + +## चरण 4 – Filled‑Bar संस्करण सहेजें + +डिफ़ॉल्ट रूप से जेनरेटर **filled bars** (सॉलिड ब्लैक रेक्टैंगल) बनाता है। चलिए इसे डिस्क पर लिखते हैं: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +`YOUR_DIRECTORY` को एक पूर्ण या रिलेटिव पाथ से बदलें जहाँ आपका ऐप लिख सकता है। इस लाइन के चलने के बाद आपको एक PNG फ़ाइल मिलेगी जो क्लासिक Planet बारकोड जैसी दिखेगी—पोस्टल स्कैनर के विरुद्ध टेस्ट करने के लिए परफ़ेक्ट। + +## चरण 5 – Empty Bars पर स्विच करें + +कभी‑कभी डाक सेवाएँ “empty bars” स्टाइल की मांग करती हैं, जहाँ बार सफ़ेद बैकग्राउंड से कटा हुआ होता है न कि काला पेंट किया गया। लाइब्रेरी एक सरल स्विच प्रदान करती है: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +`FilledBars` को `false` सेट करने से रेंडरर बार फ़िल लॉजिक को उलट देता है। नया `BarcodeGenerator` इंस्टेंस बनाने की ज़रूरत नहीं; हम केवल मौजूदा **BarcodeGenerator parameters** को ट्यून करते हैं। + +## चरण 6 – Empty‑Bar संस्करण सहेजें + +अंत में, दूसरी इमेज एक्सपोर्ट करें: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +अब आपके पास दो अलग-अलग PNG फ़ाइलें हैं, प्रत्येक एक अलग विज़ुअल आवश्यकता को पूरा करती हैं। + +## पूर्ण कार्यशील उदाहरण + +सभी हिस्सों को एक साथ जोड़ते हुए, यहाँ पूरा, कॉपी‑एंड‑पेस्ट‑रेडी प्रोग्राम है: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Expected output** (कंसोल पर): + +``` +Both Planet barcode images have been generated successfully. +``` + +और `C:\Barcodes\` में आपको मिलेगा: + +- `PostalPlanetFilledBars.png` – सॉलिड ब्लैक बार +- `PostalPlanetEmptyBars.png` – सफ़ेद बार के साथ ब्लैक आउटलाइन + +उन्हें किसी भी इमेज व्यूअर में खोलें; दोनों को Planet स्पेसिफिकेशन के अनुरूप होना चाहिए। + +## सामान्य प्रश्न और टिप्स + +### “क्या मैं इमेज फ़ॉर्मेट बदल सकता हूँ?” + +बिल्कुल। `Save` मेथड `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, आदि को स्वीकार करता है। बस `BarCodeImageFormat.Png` को अपनी इच्छित फ़ॉर्मेट से बदल दें। + +### “अगर मुझे अलग बारकोड ऊँचाई चाहिए तो?” + +वर्टिकल साइज बढ़ाने या घटाने के लिए `planetBarcode.Parameters.Barcode.BarHeight` (पॉइंट्स में) उपयोग करें। उदाहरण के लिए: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “क्या कोई तरीका है जिससे मानव‑पठनीय कैप्शन जोड़ सकें?” + +हां। `planetBarcode.Parameters.Caption` पर `CodeText` प्रॉपर्टी सेट करें: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “क्या मुझे जेनरेटर को डिस्पोज़ करना चाहिए?” + +`BarcodeGenerator` `IDisposable` को इम्प्लीमेंट करता है। यदि आप लूप में कई बारकोड बना रहे हैं तो इसे `using` ब्लॉक में रैप करें: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “एरर हैंडलिंग के बारे में क्या?” + +`Save` कॉल्स को `try…catch` ब्लॉक में रखें ताकि `IOException` (डिस्क समस्याएँ) या `ArgumentException` (अवैध पैरामीटर) को कैप्चर किया जा सके। उदाहरण: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## सारांश + +हमने C# में **create planet barcode** इमेज बनाने के लिए सभी आवश्यक बातें कवर कर ली हैं: + +1. अपने डेटा के साथ **Planet barcode generator** को इनिशियलाइज़ करें। +2. प्रिंटर स्पेसिफिकेशन से मेल खाने के लिए **XDimension pixels** को एडजस्ट करें। +3. एक **filled bars** PNG सहेजें। +4. `FilledBars` को टॉगल करके **empty bars** बनाएं। +5. दूसरा PNG सहेजें। + +अब आप अधिक **BarcodeGenerator parameters** का अन्वेषण कर सकते हैं, अन्य सिंबोलॉजी (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, आदि) के साथ प्रयोग कर सकते हैं, या इमेज को मेलिंग वर्कफ़्लो में इंटीग्रेट कर सकते हैं। + +--- + +**Ready for the next step?** उसी डॉक्यूमेंट में QR कोड जोड़ने की कोशिश करें, या `foreach` लूप का उपयोग करके CSV सूची से Planet बारकोड का बैच जेनरेट करें। Aspose.BarCode API इतना लचीला है कि वह बल्क ऑपरेशन्स, कस्टम रंग, और यहाँ तक कि वेक्टर‑बेस्ड SVG आउटपुट को भी संभाल सकता है। + +यदि आपको कोई समस्या आती है, तो नीचे कमेंट डालें या आधिकारिक Aspose.BarCode डॉक्यूमेंटेशन में उन्नत फीचर्स के गहरे विवरण देखें। Happy coding! + +## आप को आगे क्या सीखना चाहिए? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोचेज़ को एक्सप्लोर करने में मदद करेंगे। + +- [Aspose के साथ बारकोड बनाएं - जावा में X & Y डाइमेंशन सेट करें](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [जावा में Aspose.BarCode के साथ code128 बारकोड इमेज कैसे बनाएं](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [जावा में code128 बारकोड बनाएं और बार की ऊँचाई सेट करें](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/hindi/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..504a3676b --- /dev/null +++ b/barcode/hindi/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-07-18 +description: C# में तेज़ी से RM4SCC बारकोड बनाएं; बारकोड की ऊँचाई सेट करना सीखें और + कस्टम आयामों के साथ प्लैनेट बारकोड भी जनरेट करें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: hi +lastmod: 2026-07-18 +og_description: C# में RM4SCC बारकोड बनाएं और बारकोड की ऊँचाई सेट करने का तरीका जानें। + साथ ही उसी लाइब्रेरी का उपयोग करके प्लैनेट बारकोड कैसे बनाएं, देखें। +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: C# में RM4SCC बारकोड बनाएं – कस्टम ऊँचाई तेज़ी से सेट करें +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: C# में RM4SCC बारकोड बनाएं – ऊँचाई सेट करने के लिए पूर्ण गाइड +url: /hi/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में RM4SCC बारकोड बनाएं – ऊँचाई सेट करने के लिए पूर्ण गाइड + +क्या आपको कभी .NET ऐप में **create RM4SCC barcode** बनाने की ज़रूरत पड़ी लेकिन आप इसकी साइज को कैसे नियंत्रित करें, यह नहीं पता था? आप अकेले नहीं हैं। चाहे आप एक मेलिंग सिस्टम बना रहे हों या लॉजिस्टिक्स डैशबोर्ड, सही बारकोड ऊँचाई होना यह तय कर सकता है कि स्कैन सफल हो या विफल। + +इस ट्यूटोरियल में हम पूरी प्रक्रिया को समझेंगे: लाइब्रेरी को इंस्टॉल करने से लेकर, **generate Planet barcode** को एक साइड‑बाय‑साइड उदाहरण के रूप में, और अंत में दोनों बारकोड प्रकारों के लिए **how to set barcode height** तक। अंत तक आपके पास एक तैयार‑चलाने‑योग्य कंसोल ऐप होगा जो आवश्यक सटीक आयामों के साथ PNG फ़ाइलें उत्पन्न करेगा। + +--- + +## आप को क्या चाहिए + +- **.NET 6 SDK** (या कोई भी नवीनतम .NET संस्करण) – कोड .NET Framework पर भी काम करता है, लेकिन .NET 6 सबसे उपयुक्त है। +- **Aspose.BarCode for .NET** NuGet पैकेज – यह वह लाइब्रेरी है जो `BarcodeGenerator` क्लास प्रदान करती है। +- C# का बुनियादी ज्ञान – हम सिंटैक्स को शुरुआती‑मित्र बनाकर रखेंगे। +- एक IDE या टेक्स्ट एडिटर (Visual Studio, VS Code, Rider—अपनी पसंद चुनें)। + +> **Pro tip:** यदि आप CI/CD पाइपलाइन पर हैं, तो अपने `.csproj` में NuGet रेफ़रेंस जोड़ें ताकि बिल्ड कभी भी डिपेंडेंसी को न भूलें। + +--- + +## चरण 1: प्रोजेक्ट सेट अप करें + +Open a terminal and create a new console project: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +बस इतना ही—आपका प्रोजेक्ट अब उस लाइब्रेरी को रेफ़रेंस करता है जो आगे की सभी चीज़ों को शक्ति प्रदान करती है। + +### Using डायरेक्टिव्स जोड़ें + +Open `Program.cs` and paste the following at the top: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +ये नेमस्पेस हमें `BarcodeGenerator` और इमेज फ़ॉर्मेट एन्‍युम तक पहुँच देते हैं जिसे हम बाद में उपयोग करेंगे। + +--- + +## चरण 2: इमेज सेव करने के लिए हेल्पर मेथड परिभाषित करें + +एक ही सेव लॉजिक को दोहराने से बचने के लिए, हम इसे एक छोटे मेथड में रैप करेंगे। यह बाद में **how to set barcode height** को भी दर्शाता है। + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Why this matters:** सहेजने के लॉजिक को केंद्रीकृत करने का मतलब है कि यदि आवश्यकताएँ बदलें तो आपको केवल एक जगह फ़ॉर्मेट या फ़ोल्डर बदलना पड़ेगा। + +--- + +## चरण 3: Planet बारकोड जेनरेट करें ("generate planet barcode" भाग) + +RM4SCC विशिष्टताओं में जाने से पहले, चलिए एक **Planet barcode** बनाते हैं। यह आपको लाइब्रेरी के काम करने की त्वरित दृश्य जांच देता है। + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Expected output:** दो PNG फ़ाइलें `output` फ़ोल्डर में दिखाई देंगी—एक लाइब्रेरी की ऑटो‑कैल्कुलेटेड ऊँचाई के साथ, और दूसरी बिल्कुल 100 px ऊँची। + +--- + +## चरण 4: RM4SCC बारकोड बनाएं – मुख्य लक्ष्य + +अब शो का मुख्य सितारा: **create RM4SCC barcode**। RM4SCC रॉयल मेल 4‑स्टेट कोड है, जो यूके के पोस्टल सिस्टम में व्यापक रूप से उपयोग होता है। + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**आपको क्या दिखेगा:** +- `RM4SCCDefault.png` – लाइब्रेरी X‑डायमेंशन के आधार पर एक आरामदायक ऊँचाई तय करती है। +- `RM4SCCHeight100.png` – 100‑पिक्सेल ऊँचा साफ़ बारकोड, लिफ़ाफ़ों पर प्रिंट करने के लिए तैयार। + +> **Why set the height?** कुछ लेबल प्रिंटर विश्वसनीय स्कैनिंग के लिए न्यूनतम बार ऊँचाई की माँग करते हैं। ऊँचाई को फिक्स करके आप सभी डिवाइसों में अनुपालन सुनिश्चित करते हैं। + +--- + +## चरण 5: ऊँचाई सेटिंग्स को समझना ("how to set barcode height" का उत्तर) + +Both the Planet and RM4SCC examples use the same property: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** एक `BarHeight` ऑब्जेक्ट है जो कई माप इकाइयों (पिक्सेल, मिलीमीटर, इंच) को समूहित करता है। +- **`.Pixels`** स्क्रीन‑उन्मुख आउटपुट के लिए सबसे सरल इकाई है, लेकिन यदि आप प्रिंट मीडिया को लक्षित कर रहे हैं तो आप `.Millimeters` या `.Inches` भी उपयोग कर सकते हैं। + +### एज केस और टिप्स + +| स्थिति | सिफारिश किया गया तरीका | +|-----------|----------------------| +| **बहुत छोटा X‑डायमेंशन (जैसे, 1 px)** | `BarHeight` बढ़ाएँ ताकि बारकोड पढ़ने योग्य रहे। | +| **उच्च‑रिज़ॉल्यूशन लेबल प्रिंटर पर प्रिंटिंग** | डिवाइस‑स्वतंत्र साइजिंग के लिए `.Millimeters` उपयोग करें। | +| **एक इमेज में मिश्रित बारकोड प्रकार** | प्रत्येक जेनरेटर के लिए `XDimension` के *बाद* `BarHeight` सेट करें ताकि आकस्मिक इनहेरिटेंस से बचा जा सके। | +| **डायनामिक डेटा (जैसे, उपयोगकर्ता‑द्वारा दर्ज कोड)** | जेनरेटर निर्माण को ऐसे मेथड में रैप करें जो `code` और `height` पैरामीटर स्वीकार करता हो। | + +--- + +## चरण 6: पूर्ण कार्यशील उदाहरण + +नीचे एक एकल, स्व-निहित प्रोग्राम है जिसे आप `Program.cs` में कॉपी‑पेस्ट कर सकते हैं। इसमें प्रोजेक्ट सेटअप से लेकर इमेज सेव करने तक सब कुछ शामिल है। + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Run it with: + +```bash +dotnet run +``` + +आपको कंसोल आउटपुट में प्रत्येक फ़ाइल सहेजी गई की पुष्टि दिखनी चाहिए, और `output` फ़ोल्डर में ऊपर दिखाए गए नामों के चार PNG फ़ाइलें होंगी। + +--- + +## निष्कर्ष + +अब आप C# में **how to create RM4SCC barcode** जानते हैं और कुछ प्रॉपर्टी असाइनमेंट्स से इसकी डाइमेंशन को नियंत्रित कर सकते हैं। हमने **generate planet barcode** को एक त्वरित सत्यापन के रूप में भी कवर किया, और विभिन्न प्रिंटिंग परिदृश्यों के लिए **how to set barcode height** की बारीकियों को समझा। + +अगला कदम? `EncodeTypes` एन्‍युम को अन्य सिम्बोलॉजी (Code128, QR, DataMatrix) के साथ बदलें और हाई‑रिज़ॉल्यूशन प्रिंटरों के लिए `BarHeight` को मिलीमीटर में प्रयोग करें। यदि आपको बारकोड को PDF में एम्बेड करना है, तो Aspose.BarCode को Aspose.PDF के साथ जोड़ें—एक और शक्तिशाली कॉम्बो। + +कोई प्रश्न हैं या अपने खुद के बदलाव साझा करना चाहते हैं? नीचे टिप्पणी छोड़ें, और कोडिंग का आनंद लें! + +## अगले क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स इस गाइड में दिखाए गए तकनीकों पर आधारित निकटतम विषयों को कवर करते हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोच को एक्सप्लोर करने में मदद करेंगे। + +- [Aspose.BarCode for .NET का उपयोग करके कस्टम एस्पेक्ट रेशियो के साथ Aztec बारकोड कैसे जेनरेट करें](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Aspose.BarCode for .NET का उपयोग करके ITF-14 के लिए बारकोड क्वाइट ज़ोन कैसे बनाएं](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Aspose.BarCode for .NET का उपयोग करके Code 16K के लिए बारकोड क्वाइट ज़ोन कैसे बनाएं](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/hindi/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..09b39a9e7 --- /dev/null +++ b/barcode/hindi/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-07-18 +description: सीखें कि .net बारकोड जेनरेटर के साथ बारकोड छवियाँ कैसे बनाएं और GS1‑Databar + Omni‑Directional प्रतीकों के लिए बारकोड की ऊँचाई आसानी से कैसे बदलें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: hi +lastmod: 2026-07-18 +og_description: .net बारकोड जेनरेटर आपको जल्दी से बारकोड इमेज बनाने देता है। यह गाइड + दिखाता है कि बारकोड कैसे जनरेट करें, बार की ऊँचाई कैसे समायोजित करें, और PNG फ़ाइलें + कैसे सहेजें। +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: .NET बारकोड जेनरेटर के साथ बारकोड की ऊँचाई बदलें +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET बारकोड जनरेटर – बारकोड की ऊँचाई बदलें +url: /hi/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – बारकोड की ऊँचाई बदलें + +क्या आप कभी सोचे हैं **बारकोड कैसे जेनरेट करें** छवियों को बिना कई थर्ड‑पार्टी टूल्स के झंझट के? .NET दुनिया में इसे करने का एक आश्चर्यजनक रूप से साफ़ तरीका है, और मुख्य हिस्सा है **.net barcode generator**। केवल कुछ ही C# लाइनों के साथ आप एक GS1‑Databar Omni‑Directional सिम्बल बना सकते हैं, बार की ऊँचाई को समायोजित कर सकते हैं, और परिणाम को PNG फ़ाइल में सहेज सकते हैं। + +यदि आप एक इन्वेंटरी सिस्टम, शिपिंग लेबल प्रिंटर, या कोई भी ऐप बना रहे हैं जिसे स्कैन करने योग्य कोड चाहिए, तो यह ट्यूटोरियल आपको शून्य से कुछ ही मिनटों में काम करने वाला बारकोड देगा। हम पूरे कोड को चरण-दर-चरण देखेंगे, समझाएंगे कि प्रत्येक सेटिंग क्यों महत्वपूर्ण है, और आपको दिखाएंगे कि **बारकोड की ऊँचाई कैसे बदलें** बिना स्पेसिफिकेशन को तोड़े। + +## आपको क्या चाहिए + +- .NET 6.0 या बाद का संस्करण (API .NET Framework 4.7+ पर भी समान रूप से काम करता है) +- बारकोड लाइब्रेरी का रेफ़रेंस (उदाहरण के लिए, Aspose.BarCode for .NET – कई व्यावसायिक किट्स में वही क्लासेज़ उपयोग होते हैं) +- डेवलपमेंट एनवायरनमेंट (Visual Studio, Rider, या VS Code के साथ C# एक्सटेंशन) +- एक फ़ोल्डर जहाँ आपके पास लिखने की अनुमति हो – ट्यूटोरियल PNG फ़ाइलें वहाँ सहेजेगा + +बस इतना ही। बारकोड लाइब्रेरी के अलावा कोई अतिरिक्त NuGet पैकेज नहीं चाहिए। + +## .net barcode generator का उपयोग करके बारकोड की ऊँचाई बदलना + +नीचे एक **पूरा, चलाने योग्य कंसोल प्रोग्राम** दिया गया है। इसे एक नए C# प्रोजेक्ट में पेस्ट करें, आउटपुट फ़ोल्डर को समायोजित करें, और F5 दबाएँ। + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### प्रत्येक पंक्ति क्यों महत्वपूर्ण है + +| पंक्ति | कारण | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | **.net barcode generator** को वांछित सिम्बोलॉजी और डेटा पेलोड के साथ इंस्टैंशिएट करता है। `EncodeTypes.DatabarOmniDirectional` एन्‍युम लाइब्रेरी को बताता है कि वह GS1‑Databar Omni‑Directional फ़ॉर्मेट का उपयोग करे। | +| `XDimension.Pixels = 2;` | X‑डायमेंशन सबसे पतली बार की चौड़ाई है। इसे *2 पिक्सेल* पर सेट करने से अधिकांश मॉनिटर पर स्पष्ट इमेज मिलती है और फ़ाइल आकार छोटा रहता है। | +| `BarHeight.Pixels = 30;` | यह **बारकोड की ऊँचाई बदलें** चरण है जो निर्धारित करता है कि प्रत्येक बार कितनी ऊँची होगी। 30‑पिक्सेल की ऊँचाई छोटे लेबल्स के लिए एक अच्छा डिफ़ॉल्ट है। | +| `generator.Save(...);` | बारकोड को PNG फ़ाइल में सहेजता है। PNG लॉस‑लेस है, जिसका अर्थ है स्कैनर वही सटीक पैटर्न देखेंगे जो आपने जेनरेट किया है। | +| `BarHeight.Pixels = 60;` | यहाँ हम फिर से **बारकोड की ऊँचाई बदलते** हैं—इस बार 60 पिक्सेल। जब आप `Save` को दूसरी बार कॉल करते हैं, लाइब्रेरी स्वचालित रूप से नए डायमेंशन के साथ सिम्बल को पुनः रेंडर करती है। | +| `Console.WriteLine(...);` | आपको त्वरित फीडबैक देता है कि प्रक्रिया बिना किसी एक्सेप्शन के समाप्त हो गई। | + +> **Pro tip:** यदि आपको प्रिंटिंग के लिए उच्च‑रिज़ॉल्यूशन आउटपुट चाहिए, तो `BarCodeImageFormat.Png` को `BarCodeImageFormat.Tiff` में बदलें और `Resolution` प्रॉपर्टी को बढ़ाएँ (उदाहरण के लिए, `generator.Parameters.ImageResolution = 300;`)। बार की ऊँचाई अभी भी सम्मानित रहेगी, बस अधिक फाइन DPI पर रेंडर होगी। + +## विभिन्न सेटिंग्स के साथ बारकोड छवियों को जेनरेट करना + +ऊपर दिया गया स्निपेट बुनियादी बातों को कवर करता है, लेकिन वास्तविक दुनिया के परिदृश्य अक्सर अतिरिक्त समायोजन की मांग करते हैं: + +### बड़े प्रिंट्स के लिए X‑डायमेंशन समायोजित करना +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +X‑डायमेंशन बढ़ाने से संपूर्ण बारकोड बड़ा हो जाता है बिना एन्कोडेड डेटा बदले। यह बड़े लेबल्स पर प्रिंट करने के समय उपयोगी है। + +### आउटपुट फ़ॉर्मेट बदलना +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG अनंत रूप से स्केल करता है, जो वेब‑आधारित स्कैनरों के लिए उपयुक्त है जिन्हें स्पष्ट वेक्टर चाहिए। + +### मानव‑पठनीय टेक्स्ट जोड़ना +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +`CodeTextVisible` को सक्षम करने से बारकोड के नीचे कच्चा डेटा जुड़ जाता है, जो परीक्षण के दौरान सत्यापन के लिए उपयोगी है। + +## जब आप **बारकोड की ऊँचाई बदलते** हैं तो सामान्य गलतियाँ + +1. **ऊँचाई बहुत छोटी** – कुछ स्कैनरों को न्यूनतम बार ऊँचाई चाहिए (अक्सर भौतिक इकाइयों में 10 mm)। यदि आप `BarHeight.Pixels` को बहुत कम सेट करते हैं, तो जेनरेट हुई छवि वास्तविक स्कैनर पर पढ़ने योग्य नहीं हो सकती। हमेशा अपने लक्ष्य हार्डवेयर के साथ परीक्षण करें। +2. **X‑डायमेंशन और ऊँचाई का असंगत मिलान** – बड़ी बार ऊँचाई के साथ बहुत छोटा X‑डायमेंशन खिंचा हुआ दिख सकता है और डिकोडिंग त्रुटियों का कारण बन सकता है। जब तक स्पेसिफिकेशन अन्यथा न कहे, संतुलित अनुपात (लगभग 3:1 से 5:1) का लक्ष्य रखें। +3. **पैरामीटर रीसेट करना भूल जाना** – जेनरेटर सेव्स के बीच स्थिति को रखता है। यदि आप एक छवि के लिए `BarHeight` बदलते हैं और फिर उसी इंस्टेंस को दूसरे बारकोड के लिए पुनः उपयोग करते हैं, तो पिछली ऊँचाई बनी रहेगी। या तो प्रॉपर्टी को रीसेट करें या प्रत्येक अलग बारकोड के लिए नया `BarcodeGenerator` इंस्टैंस बनाएं। + +## पूर्ण एंड‑टू‑एंड उदाहरण (NuGet इंस्टॉल सहित) + +यदि आप शून्य से शुरू कर रहे हैं, तो प्रोजेक्ट चलाने के लिए इन चरणों का पालन करें: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +ऑटो‑जनरेटेड `Program.cs` को पहले दिखाए गए कोड ब्लॉक से बदलें, **`YOUR_DIRECTORY` को कुछ इस तरह बदलना याद रखें** जैसे `Path.Combine(Environment.CurrentDirectory, "output")`। फिर: + +```bash +dotnet run +``` + +आपको `output` फ़ोल्डर में दो PNG फ़ाइलें दिखनी चाहिए: + +- `DatabarBarHeight30Pixels.png` – एक कॉम्पैक्ट 30‑पिक्सेल ऊँचा बारकोड। +- `DatabarBarHeight60Pixels.png` – एक ऊँचा 60‑पिक्सेल संस्करण। + +दोनों छवियाँ समान दिखेंगी, लेकिन दूसरी में स्पष्ट रूप से लंबी बार होंगी, जिससे लो‑रिज़ॉल्यूशन स्कैनरों के लिए पढ़ना आसान होगा। + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator आउटपुट जिसमें विभिन्न बार ऊँचाइयाँ दिखायी गई हैं"} + +## सारांश और अगले कदम + +हमने **बारकोड जेनरेट** करने की विधि को **.net barcode generator** का उपयोग करके कवर किया, **बारकोड की ऊँचाई बदलें** प्रॉपर्टी को फाइन‑ट्यून किया, और परिणाम PNG फ़ॉर्मेट में सहेजे। मुख्य बिंदु हैं: + +- सही `EncodeTypes` के साथ जेनरेटर को इंस्टैंसिएट करें। +- `XDimension` और `BarHeight` के माध्यम से विज़ुअल साइज को नियंत्रित करें। +- प्रत्येक परिवर्तन के बाद `Save` कॉल करें ताकि नई छवि सहेजी जा सके। +- रिज़ॉल्यूशन और फ़ॉर्मेट को समायोजित करें, + +## अब आपको क्या सीखना चाहिए? + +निम्नलिखित ट्यूटोरियल्स उन निकट-संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण-दर-चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर करने में मदद करेंगे। + +- [Aspose.BarCode for .NET का उपयोग करके कस्टम आस्पेक्ट रेशियो के साथ Aztec बारकोड कैसे जेनरेट करें](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Aspose.BarCode for .NET के साथ डॉटकोड विस्तारित कोडटेक्स्ट कैसे बनाएं](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-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/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/hongkong/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..2972a1b77 --- /dev/null +++ b/barcode/hongkong/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-07-18 +description: 條碼產生器範例,示範如何設定尺寸並在 C# 中產生 DataBar Stacked Omni‑Directional 條碼圖像。快速了解條碼編碼類型。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: zh-hant +lastmod: 2026-07-18 +og_description: 條碼產生器範例會一步步指導您如何設定尺寸、選擇條碼編碼類型,並以最少的程式碼建立條碼影像 C# 專案。 +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: 條碼產生器範例 – 快速於 C# 建立 DataBar 圖像 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: 條碼產生器範例 – 使用 C# 建立 DataBar 圖像 +url: /zh-hant/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 條碼產生器範例 – 使用 C# 建立 DataBar 圖像 + +有沒有需要一個 **條碼產生器範例**,能真正產生實際條碼而不讓你抓狂的情況?你並不孤單。大多數開發者在嘗試弄清楚 **如何設定尺寸** 為 DataBar Stacked Omni‑Directional 條碼時會卡住,尤其是文件被大量術語埋沒。 + +在本教學中,我們將逐步說明一個完整、可直接執行的 C# 程式,展示 **how to generate databar** 圖像、挑選正確的 **barcode encode types**,最後 **create barcode image c#** 檔案,讓你可以放入任何專案。沒有多餘的說明——只提供可直接複製貼上的程式碼,並說明每一行的原理。 + +## 您需要的環境 + +- **.NET 6**(或任何較新的 .NET 版本)– 我們使用的 API 目標為 .NET Standard,因此也能在 .NET Framework 上執行。 +- **Aspose.BarCode for .NET** – 提供 `BarcodeGenerator` 的函式庫。你可以透過 NuGet 使用 `Install-Package Aspose.BarCode` 取得。 +- **C# IDE** – Visual Studio、Rider 或 VS Code 都可以。 +- 磁碟上的資料夾,用來儲存 PNG 檔案(程式碼會產生 `DatabarAspectRatio15.png` 與 `DatabarAspectRatio30.png`)。 + +全部準備好了嗎?太好了——讓我們開始吧。 + +## 條碼產生器範例 – 初始化產生器 + +首先,我們需要一個已設定為 **DataBar Stacked Omni‑Directional** 符號的 `BarcodeGenerator` 實例。這就是我們將使用的 **barcode encode type**。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **為什麼這很重要:** `EncodeTypes.DatabarStackedOmniDirectional` 告訴 Aspose 要渲染哪種符號。如果選錯類型,掃描器將無法辨識條碼,無論圖像看起來多好看。 + +## 如何設定條碼的尺寸 + +條碼的可讀性取決於其 **X‑dimension**(最窄條的寬度)。大多數情況下,2 像素的值就足夠,但你可以依據印表機或螢幕進行微調。 + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **小技巧:** 如果你想知道 **how to set dimensions** 為其他條碼系列,只需使用相同的屬性鏈 (`Parameters.Barcode.XDimension`),只要更改 `Pixels` 的值即可。 + +## 如何產生 DataBar Stacked Omni‑Directional 條碼 + +現在產生器已就緒,我們將調整 **aspect ratio** 屬性。此屬性控制 DataBar 的高寬比例,讓你可以產生短而方形的符號或高而窄的符號。 + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **發生了什麼?** `AspectRatio = 15` 告訴引擎條的高度是寬度的 15 倍。產生的 PNG 會儲存在可執行檔旁邊。 + +## 建立條碼圖像 C# – 變更長寬比 + +讓我們透過將比例改為 30 並儲存第二個檔案,來證明其彈性。 + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +執行程式後,你會得到兩個 PNG 檔案: + +| 檔案 | 長寬比 | 大約尺寸 | +|------|--------|----------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +在任何圖像檢視器中開啟它們——你應該會看到乾淨且可掃描的 DataBar 符號。 + +## 條碼編碼類型概覽(可選但實用) + +如果你想了解 Aspose 支援的其他 **barcode encode types**,以下是一張快速備忘表: + +| EncodeTypes 列舉 | 說明 | +|------------------|------| +| `EncodeTypes.Code128` | 高密度字母數字 | +| `EncodeTypes.QR` | 二維矩陣碼 | +| `EncodeTypes.DatabarExpanded` | 零售用 GS1 DataBar | +| `EncodeTypes.DatabarStackedOmniDirectional` | **我們的重點** – 緊湊、全方向 | + +了解正確的列舉可以讓你在切換專案時省去大量的反覆試驗。 + +## 常見陷阱與避免方法 + +- **Missing NuGet package** – 沒有 `Aspose.BarCode` 套件程式碼將無法編譯。請先執行 `dotnet add package Aspose.BarCode`。 +- **Wrong file path** – 若使用絕對路徑,請在 Windows 上再次確認反斜線 (`\\`)。如示範的相對路徑可保持可移植性。 +- **Aspect ratio too extreme** – 超過 50 的長寬比會使條碼對一般掃描器而言過高。大多數情況建議使用 15‑30。 + +## 完整原始碼(可直接複製貼上) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +執行程式(`dotnet run` 或在 Visual Studio 按 **F5**)後,你會在主控台看到確認檔案已寫入磁碟的訊息。 + +![Barcode generator example output showing DataBar barcode with aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="條碼產生器範例輸出,顯示長寬比為 15 的 DataBar 條碼"} + +## 總結 + +我們剛完成一個 **barcode generator example**,示範了 **how to set dimensions**、挑選正確的 **barcode encode types**,最後產生可在任何地方嵌入的 **create barcode image c#** 檔案。程式碼簡潔,概念清晰,現在你已具備堅實的基礎,可延伸此解決方案——例如加入文字說明、旋轉圖像,或切換至其他符號。 + +### 接下來做什麼? + +- 嘗試 **different X‑dimensions** 以觀察掃描容差的變化。 +- 嘗試其他 **EncodeTypes**(如 `Code128` 或 `QR`)以擴充工具箱。 +- 自動化批次產生:遍歷產品 ID 的 CSV,為每筆產生 PNG。 + +如果遇到問題,請在下方留言或查閱 Aspose.BarCode 文件——其中有許多範例可補充本教學的內容。 + +祝開發順利,願你的條碼一次即能成功掃描! + +## 接下來該學什麼? + +以下教學涵蓋與本指南緊密相關的主題,建立在此處示範的技巧之上。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通其他 API 功能,並在自己的專案中探索替代實作方式。 + +- [如何產生條碼 - 一維條碼類型](/barcode/english/net/one-dimensional-barcode-types/) +- [建立條碼圖像 C# – GS1 DataMatrix 範例](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [如何產生 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/hongkong/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/hongkong/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..8df14d819 --- /dev/null +++ b/barcode/hongkong/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-07-18 +description: 使用 C# 快速建立 Planet 條碼。學習如何產生實心與空心條、設定 X 軸尺寸,並儲存 PNG 圖片——一次教學搞掂。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: zh-hant +lastmod: 2026-07-18 +og_description: 即時建立 Planet 條碼。本指南會示範如何設定 X 尺寸、在實心條與空心條之間切換,以及使用 Aspose.BarCode 匯出 + PNG 檔案。 +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: 在 C# 中建立 Planet 條碼 – 完整程式教學 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: 在 C# 中建立 Planet 條碼 – 完整逐步指南 +url: /zh-hant/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中建立 Planet 條碼 – 完整步驟指南 + +是否曾需要 **建立 planet 條碼** 圖片卻不確定要調整哪些屬性?你並不孤單。許多開發者在預設的實心條不符合規範,或是條寬必須符合印表機 DPI 時卡住了。 + +在本教學中,你將學會如何使用 Aspose.BarCode 函式庫 **建立 planet 條碼** 檔案、如何控制 **XDimension 像素**,以及如何在 **實心條** 與 **空心條** 之間切換而不必重新撰寫程式碼。完成後,你會得到兩個 PNG 檔案——一個實心條、一個空心條——可供任何需要 Planet 符號的郵務系統使用。 + +## 前置條件 + +- .NET 6.0 或更新版本(程式碼同樣適用於 .NET Framework 4.7 +) +- Aspose.BarCode for .NET NuGet 套件(`Install-Package Aspose.BarCode`) +- 基本的 C# 知識(稍後會說明為何使用 `using` 陳述式) +- 可寫入的磁碟資料夾,用來儲存 PNG + +只要具備上述條件,即可直接進入實作階段。 + +## 第一步 – 設定專案並加入函式庫 + +首先,建立一個新的 Console 應用程式(或任何 C# 專案),並參考 **Planet 條碼產生器** 函式庫。 + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **小技巧:** 在 Visual Studio 中,右鍵點擊專案 → *Manage NuGet Packages* → 搜尋 **Aspose.BarCode** 並點選 *Install*。這樣即可取得 `BarcodeGenerator` 以及所有需要的 **BarcodeGenerator 參數**。 + +## 第二步 – 初始化 Planet 條碼產生器 + +現在真正 **建立 planet 條碼** 產生器實例,並將要編碼的資料(本例為 `"123456"`)傳入。`EncodeTypes.Planet` 列舉告訴函式庫使用哪種符號。 + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **為何重要:** `EncodeTypes.Planet` 旗標會自動套用正確的檢查碼與版面規則,讓你不必手動計算。 + +## 第三步 – 設定 X‑Dimension(條寬) + +大多數印表機要求每條的寬度為特定像素數。此處將 **XDimension 像素** 設為 `4`,這是 203 dpi 熱感印表機的常見值。 + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **例外情況:** 若目標是 300 dpi 印表機,可能需要 `3` 或 `5` 像素。請依據設備文件調整此數值。 + +## 第四步 – 儲存實心條版本 + +預設情況下產生器會產生 **實心條**(實心黑色矩形)。將其寫入磁碟: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +將 `YOUR_DIRECTORY` 替換為你的程式可寫入的絕對或相對路徑。執行此行後,你會在磁碟上看到一個看起來像傳統 Planet 條碼的 PNG 檔案,適合用來測試郵務掃描器。 + +## 第五步 – 切換為空心條 + +有時郵務服務要求「空心條」樣式,即條紋從白色背景中挖空而非塗黑。函式庫提供簡易開關: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +將 `FilledBars` 設為 `false` 即可讓渲染器反轉條紋填充邏輯。無需重新建立 `BarcodeGenerator` 實例,只要調整現有的 **BarcodeGenerator 參數** 即可。 + +## 第六步 – 儲存空心條版本 + +最後,匯出第二張圖片: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +現在你擁有兩個不同的 PNG 檔案,各自符合不同的視覺需求。 + +## 完整範例程式 + +將所有步驟整合,以下是可直接複製貼上的完整程式: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**預期輸出**(於主控台): + +``` +Both Planet barcode images have been generated successfully. +``` + +在 `C:\Barcodes\` 目錄下,你會看到: + +- `PostalPlanetFilledBars.png` – 實心黑條 +- `PostalPlanetEmptyBars.png` – 白底黑框條 + +使用任何影像檢視器開啟,它們都應符合 Planet 規範。 + +## 常見問題與小技巧 + +### 「可以更換影像格式嗎?」 + +當然可以。`Save` 方法接受 `BarCodeImageFormat.Jpeg`、`Bmp`、`Gif` 等。只要將 `BarCodeImageFormat.Png` 換成你想要的格式即可。 + +### 「如果需要不同的條碼高度呢?」 + +使用 `planetBarcode.Parameters.Barcode.BarHeight`(單位為點)即可調整垂直尺寸。例如: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### 「可以加入可讀的文字說明嗎?」 + +可以。設定 `planetBarcode.Parameters.Caption.CodeText` 屬性: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### 「需要釋放產生器資源嗎?」 + +`BarcodeGenerator` 實作了 `IDisposable`。若在迴圈中大量產生條碼,建議使用 `using` 區塊: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### 「錯誤處理該怎麼做?」 + +將 `Save` 呼叫包在 `try…catch` 區塊,以捕捉 `IOException`(磁碟問題)或 `ArgumentException`(參數無效)等例外。範例: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## 重點回顧 + +我們已說明如何在 C# 中 **建立 planet 條碼** 圖片: + +1. 使用你的資料初始化 **Planet 條碼產生器**。 +2. 調整 **XDimension 像素** 以符合印表機規格。 +3. 儲存 **實心條** PNG。 +4. 將 `FilledBars` 切換為 `false` 產生 **空心條**。 +5. 儲存第二張 PNG。 + +接下來,你可以探索更多 **BarcodeGenerator 參數**、嘗試其他符號(`EncodeTypes.Postnet`、`EncodeTypes.Code128` 等),或將圖像整合至郵寄工作流程中。 + +--- + +**準備好下一步了嗎?** 嘗試在同一文件中加入 QR Code,或使用 `foreach` 迴圈從 CSV 清單批次產生 Planet 條碼。Aspose.BarCode API 足夠彈性,支援大量操作、自訂顏色,甚至向量化的 SVG 輸出。 + +若遇到任何問題,歡迎在下方留言或參考官方 Aspose.BarCode 文件,深入了解進階功能。祝開發順利! + +## 接下來該學什麼? + +以下教學與本指南的技術緊密相關,能幫助你進一步掌握 API 功能,並在專案中探索其他實作方式。 + +- [Create Barcode with Aspose - Set X & Y Dimensions in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/hongkong/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..715cd3d1d --- /dev/null +++ b/barcode/hongkong/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-07-18 +description: 快速在 C# 中建立 RM4SCC 條碼;了解如何設定條碼高度,並可使用自訂尺寸產生 Planet 條碼。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: zh-hant +lastmod: 2026-07-18 +og_description: 在 C# 中建立 RM4SCC 條碼,並了解如何設定條碼高度。亦可參考如何使用相同的函式庫產生 Planet 條碼。 +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: 在 C# 中建立 RM4SCC 條碼 – 快速設定自訂高度 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: 在 C# 中建立 RM4SCC 條碼 – 完整高度設定指南 +url: /zh-hant/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中建立 RM4SCC 條碼 – 完整設定高度指南 + +是否曾經需要在 .NET 應用程式中 **create RM4SCC barcode**,卻不確定如何控制其尺寸?您並不孤單。無論是建置郵件系統或物流儀表板,正確的條碼高度往往是掃描成功與失敗的關鍵。 + +在本教學中,我們將完整說明整個流程:從安裝程式庫、**generate Planet barcode** 作為對照範例,到最終說明 **how to set barcode height** 於兩種條碼。完成後,您將擁有一個可直接執行的 Console 應用程式,產出符合精確尺寸的 PNG 檔案。 + +--- + +## 您需要的環境 + +- **.NET 6 SDK**(或任何近期的 .NET 版本)— 程式碼同樣支援 .NET Framework,但 .NET 6 為最佳選擇。 +- **Aspose.BarCode for .NET** NuGet 套件 — 提供 `BarcodeGenerator` 類別的程式庫。 +- 基本的 C# 知識 — 我們會保持語法對初學者友好。 +- 任一 IDE 或文字編輯器(Visual Studio、VS Code、Rider——自行選擇)。 + +> **專業提示:** 若您在 CI/CD 流程中,請在 `.csproj` 中加入 NuGet 參考,確保建置時不會遺漏相依性。 + +--- + +## 步驟 1:設定專案 + +在終端機中建立新的 Console 專案: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +就這樣——您的專案現在已參考了支援以下所有功能的程式庫。 + +### 加入 Using 指令 + +打開 `Program.cs`,在檔案頂部貼上以下內容: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +這些命名空間讓我們可以使用 `BarcodeGenerator` 以及稍後會用到的影像格式列舉。 + +--- + +## 步驟 2:定義儲存影像的輔助方法 + +為了避免重複相同的儲存邏輯,我們將其包裝成一個小方法。此方法同時示範 **how to set barcode height** 的寫法。 + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **為什麼這很重要:** 集中管理儲存邏輯,若日後需要變更格式或資料夾,只需在一處修改即可。 + +--- + +## 步驟 3:產生 Planet 條碼(「產生 Planet 條碼」部分) + +在深入 RM4SCC 之前,先產生一個 **Planet barcode**,快速檢查程式庫是否正常運作。 + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**預期輸出:** 兩個 PNG 檔案會出現在 `output` 資料夾——一個使用程式庫自動計算的高度,另一個則固定為 100 px 高。 + +--- + +## 步驟 4:建立 RM4SCC 條碼 – 主要目標 + +現在來到本教學的主角:**create RM4SCC barcode**。RM4SCC 為 Royal Mail 4‑State Code,廣泛應用於英國郵政系統。 + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**您將看到:** +- `RM4SCCDefault.png` – 程式庫根據 X‑dimension 自動決定的舒適高度。 +- `RM4SCCHeight100.png` – 高度固定為 100 像素的條碼,適合列印於信封上。 + +> **為什麼要設定高度?** 某些標籤印表機要求最小條碼高度才能可靠掃描。固定高度即可確保在各種設備上皆符合規範。 + +--- + +## 步驟 5:了解高度設定(回應「如何設定條碼高度」) + +Planet 與 RM4SCC 範例皆使用相同的屬性: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** 為 `BarHeight` 物件,內含多種測量單位(像素、毫米、英吋)。 +- **`.Pixels`** 是最直接的螢幕導向單位,若針對列印媒介,也可使用 `.Millimeters` 或 `.Inches`。 + +### 邊緣情況與提示 + +| 情況 | 建議做法 | +|-----------|----------------------| +| **X‑dimension 非常小(例如 1 px)** | 增加 `BarHeight` 以保持條碼可讀性。 | +| **在高解析度標籤印表機上列印** | 使用 `.Millimeters` 取得與裝置無關的尺寸。 | +| **同一圖像內混合多種條碼類型** | 為每個產生器在設定 `XDimension` 後再設定 `BarHeight`,避免意外繼承。 | +| **動態資料(例如使用者輸入的代碼)** | 將產生器建立封裝成接受 `code` 與 `height` 參數的方法。 | + +--- + +## 步驟 6:完整範例 + +以下是一個完整、獨立的程式,您可以直接複製貼上到 `Program.cs`。它涵蓋了從專案設定到儲存影像的全部步驟。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +執行指令: + +```bash +dotnet run +``` + +您應該會在主控台看到每個檔案已儲存的訊息,`output` 資料夾內會出現四個 PNG,名稱如前述說明。 + +--- + +## 結論 + +現在您已掌握 **how to create RM4SCC barcode** 的方法,並能透過簡單的屬性設定控制其尺寸。我們同時示範了 **generate planet barcode** 作為快速驗證,並深入探討 **how to set barcode height** 在不同列印情境下的細節。 + +接下來的建議?嘗試將 `EncodeTypes` 列舉換成其他符號集(Code128、QR、DataMatrix),並在高解析度印表機上以毫米為單位測試 `BarHeight`。若需將條碼嵌入 PDF,可將 Aspose.BarCode 與 Aspose.PDF 結合——同樣是強大的組合。 + +有任何問題或想分享自己的調整嗎?歡迎在下方留言,祝開發順利! + +## 接下來您可以學什麼? + +以下教學與本指南緊密相關,能進一步深化您對 API 功能的掌握,並探索在專案中實作的其他方式。 + +- [如何使用 Aspose.BarCode for .NET 產生自訂長寬比的 Aztec 條碼](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [如何使用 Aspose.BarCode for .NET 為 ITF-14 建立條碼靜區](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [如何使用 Aspose.BarCode for .NET 為 Code 16K 建立條碼靜區](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/hongkong/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..ea6fb3c76 --- /dev/null +++ b/barcode/hongkong/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-07-18 +description: 了解如何使用 .net 條碼產生器產生條碼圖像,並輕鬆調整 GS1‑Databar 全方向符號的條碼高度。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: zh-hant +lastmod: 2026-07-18 +og_description: .NET 條碼產生器讓您快速建立條碼圖像。本指南說明如何產生條碼、調整條碼高度,以及儲存 PNG 檔案。 +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: 使用 .NET 條碼產生器更改條碼高度 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET 條碼產生器 – 更改條碼高度 +url: /zh-hant/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – 更改條碼高度 + +有沒有想過 **如何在不使用一堆第三方工具** 的情況下產生條碼圖像?在 .NET 世界中,有一個相當簡潔的方式,而關鍵就在 **.net barcode generator**。只要幾行 C# 程式碼,就能產生 GS1‑Databar Omni‑Directional 符號、調整條碼高度,並將結果輸出為 PNG 檔案。 + +無論你在開發庫存系統、運單列印機,或任何需要可掃描碼的應用程式,本教學都能在幾分鐘內讓你從零開始得到可用的條碼。我們會逐段說明完整程式碼、解釋每個設定的意義,並示範如何 **更改條碼高度** 而不違背規範。 + +## 你需要的環境 + +- .NET 6.0 或更新版本(在 .NET Framework 4.7+ 上 API 行為相同) +- 條碼函式庫的參考(例如 Aspose.BarCode for .NET —— 多數商業套件皆使用相同類別) +- 開發環境(Visual Studio、Rider,或安裝 C# 擴充功能的 VS Code) +- 具寫入權限的資料夾 —— 教學會把 PNG 檔案儲存於此 + +就這些。除了條碼函式庫本身,無需額外的 NuGet 套件。 + +## 使用 .net barcode generator 更改條碼高度 + +以下是一個 **完整、可執行的 Console 程式**。將它貼到新的 C# 專案中,調整輸出資料夾路徑,然後按 F5 執行。 + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### 為什麼每一行都很重要 + +| 行 | 原因 | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | 使用所需的條碼類型與資料內容實例化 **.net barcode generator**。`EncodeTypes.DatabarOmniDirectional` 列舉告訴函式庫使用 GS1‑Databar Omni‑Directional 格式。 | +| `XDimension.Pixels = 2;` | X‑dimension 為最細條的寬度。設定為 *2 像素* 可在大多數螢幕上產生清晰圖像,同時保持檔案尺寸低。 | +| `BarHeight.Pixels = 30;` | 這就是 **更改條碼高度** 的步驟,決定每根條的高度。30 像素是小標籤的良好預設值。 | +| `generator.Save(...);` | 將條碼寫入 PNG 檔案。PNG 為無損格式,掃描器能看到你產生的精確圖樣。 | +| `BarHeight.Pixels = 60;` | 這裡再次 **更改條碼高度** —— 這次設定為 60 像素。呼叫第二次 `Save` 時,函式庫會自動以新尺寸重新繪製符號。 | +| `Console.WriteLine(...);` | 快速回饋程式已順利完成且未拋出例外。 | + +> **小技巧:** 若需更高解析度的列印輸出,可將 `BarCodeImageFormat.Png` 改為 `BarCodeImageFormat.Tiff`,並提升 `Resolution` 屬性(例如 `generator.Parameters.ImageResolution = 300;`)。條碼高度仍會被遵守,只是以更細的 DPI 呈現。 + +## 如何使用不同設定產生條碼圖像 + +上面的程式碼示範了基礎用法,但實務上常會需要額外調整: + +### 調整 X‑dimension 以適應較大列印 +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +提升 X‑dimension 會讓整個條碼變大,但不會改變編碼資料。這在大型標籤列印時相當方便。 + +### 切換輸出格式 +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG 可無限縮放,非常適合需要向量圖的 Web 掃描器。 + +### 加入可讀文字 +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +啟用 `CodeTextVisible` 後,條碼下方會顯示原始資料,便於測試時驗證。 + +## 常見陷阱:在 **更改條碼高度** 時要注意 + +1. **高度過小** – 某些掃描器要求最小條高(常見為實體 10 mm)。若把 `BarHeight.Pixels` 設得太低,產生的圖像在實機掃描時可能無法辨識。務必以目標硬體測試。 +2. **X‑dimension 與高度不匹配** – 巨大的條高搭配極細的 X‑dimension 會讓條碼看起來被拉長,可能導致解碼錯誤。除非規範另有說明,建議保持大約 3:1 至 5:1 的比例。 +3. **忘記重設參數** – 產生器在多次儲存間會保留狀態。若在產生第一張圖後改變 `BarHeight`,再使用同一個實例產生另一張條碼,先前的高度會被保留下來。請在每次產生不同條碼前重設屬性,或直接重新建立 `BarcodeGenerator` 實例。 + +## 完整端對端範例(含 NuGet 安裝) + +如果從頭開始,請依照以下步驟建立專案: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +將自動產生的 `Program.cs` 替換為前面示範的程式碼,**記得把 `YOUR_DIRECTORY`** 改成類似 `Path.Combine(Environment.CurrentDirectory, "output")` 的路徑。接著: + +```bash +dotnet run +``` + +執行後,你會在 `output` 資料夾看到兩個 PNG 檔案: + +- `DatabarBarHeight30Pixels.png` – 高度為 30 像素的緊湊條碼。 +- `DatabarBarHeight60Pixels.png` – 高度為 60 像素的較高條碼。 + +兩張圖看起來相似,但第二張的條更長,對低解析度掃描器更友好。 + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator output showing different bar heights"} + +## 重點回顧與後續步驟 + +我們說明了如何使用 **.net barcode generator** **產生條碼** 圖像、微調 **更改條碼高度** 的屬性,並以 PNG 格式儲存。關鍵要點如下: + +- 使用正確的 `EncodeTypes` 來實例化產生器。 +- 透過 `XDimension` 與 `BarHeight` 控制視覺尺寸。 +- 每次變更後呼叫 `Save` 產出新圖檔。 +- 需要時調整解析度與格式。 + +## 接下來可以學什麼? + +以下教學與本篇內容緊密相關,能幫助你進一步掌握 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 create dotcode extended codetext with Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-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/hungarian/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/hungarian/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..b9251744f --- /dev/null +++ b/barcode/hungarian/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-07-18 +description: Vonalkód-generátor példa, amely bemutatja, hogyan állíthatók be a méretek, + és hogyan generálható DataBar Stacked Omni‑Directional vonalkód kép C#-ban. Tanulja + meg gyorsan a vonalkód kódolási típusokat. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: hu +lastmod: 2026-07-18 +og_description: A vonalkód-generátor példa végigvezet a méretek beállításán, a vonalkód + kódolási típusok kiválasztásán és a vonalkód kép C# projektek minimális kóddal történő + létrehozásán. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Vonalkód Generátor Példa – Gyors DataBar Kép Létrehozás C#-ban +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Vonalkód-generátor példa – DataBar kép létrehozása C#‑ban +url: /hu/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vonalkód Generátor Példa – DataBar Kép Létrehozása C#-ban + +Valaha is szükséged volt egy **barcode generator example**‑re, ami tényleg egy valós vonalkódot nyomtat ki anélkül, hogy a hajadba nyúltál volna? Nem vagy egyedül. A legtöbb fejlesztő akadályba ütközik, amikor megpróbálja kideríteni, **hogyan állítsuk be a méreteket** egy DataBar Stacked Omni‑Directional vonalkódhoz, különösen, ha a dokumentáció rétegekbe rejtett zsargon alatt van elburkolva. + +Ebben az útmutatóban végigvezetünk egy teljes, azonnal futtatható C# programon, amely megmutatja, **hogyan generáljunk databar** képeket, kiválasztja a megfelelő **barcode encode types**‑t, és végül **create barcode image c#** fájlokat hoz létre, amelyeket bármely projektbe beilleszthetsz. Felesleges szócska nélkül – csak a másolás‑beillesztésre kész kód, plusz a minden sor mögötti magyarázat. + +## Amire Szükséged Lesz + +- **.NET 6** (vagy bármely friss .NET verzió) – az API, amit használunk, .NET Standard‑ra céloz, így .NET Framework‑ön is működik. +- **Aspose.BarCode for .NET** – a könyvtár, amely biztosítja a `BarcodeGenerator`‑t. NuGet‑ről a `Install-Package Aspose.BarCode` paranccsal szerezheted be. +- Egy **C# IDE** – Visual Studio, Rider vagy VS Code megfelel. +- Egy mappa a lemezen, ahová a PNG fájlok mentésre kerülnek (a kód létrehozza a `DatabarAspectRatio15.png` és `DatabarAspectRatio30.png` fájlokat). + +Minden megvan? Remek – vágjunk bele. + +## Barcode Generator Example – A Generátor Inicializálása + +Először is szükségünk van egy `BarcodeGenerator` példányra, amely a **DataBar Stacked Omni‑Directional** szimbólumra van konfigurálva. Ez az a **barcode encode type**, amivel dolgozni fogunk. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Miért fontos:** `EncodeTypes.DatabarStackedOmniDirectional` pontosan megmondja az Aspose‑nak, melyik szimbólumot kell megjeleníteni. Ha rossz típust választasz, a szkenner nem fogja felolvasni a vonalkódot, bármilyen szép is legyen a kép. + +## Hogyan Állítsuk Be a Méreteket a Vonalkódhoz + +Egy vonalkód olvashatósága az **X‑dimension**‑tól (a legkeskenyebb vonal szélessége) függ. A legtöbb esetben a 2 pixel érték megfelelő, de a nyomtató vagy a képernyő igényei szerint módosítható. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Pro tipp:** Ha valaha is azon tűnődsz, **hogyan állítsuk be a méreteket** egy másik vonalkódcsaládnál, ugyanaz a tulajdonságlánc (`Parameters.Barcode.XDimension`) érvényes – csak a `Pixels` értéket változtasd meg. + +## DataBar Stacked Omni‑Directional Vonalkód Generálása + +Most, hogy a generátor készen áll, a **aspect ratio** tulajdonsággal fogunk játszani. Ez szabályozza a DataBar magasság‑szélesség arányát, lehetővé téve egy rövid, szögletes vagy egy magas, keskeny szimbólum létrehozását. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Mi történik?** `AspectRatio = 15` azt mondja a motornak, hogy a vonalak 15‑ször magasabbak legyenek, mint amilyen szélesek. A keletkezett PNG a futtatható állományod mellé kerül mentésre. + +## Create Barcode Image C# – Az Aspect Ratio Módosítása + +Mutassuk be a rugalmasságot az arány 30‑ra cserélésével, és mentsünk egy második fájlt. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +A program futtatásakor két PNG fájl jön létre: + +| Fájl | Aspect Ratio | Kb. Méret | +|------|--------------|-----------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Nyisd meg őket bármely képnézőben – tiszta, beolvasható DataBar szimbólumokat kell látnod. + +## Barcode Encode Types Áttekintés (Opcionális, de Hasznos) + +Ha kíváncsi vagy az Aspose által támogatott egyéb **barcode encode types**‑ra, itt egy gyors cheat‑sheet: + +| EncodeTypes Enum | Leírás | +|------------------|--------| +| `EncodeTypes.Code128` | Magas sűrűségű alfanumerikus | +| `EncodeTypes.QR` | 2‑D mátrixkód | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar kiskereskedelemhez | +| `EncodeTypes.DatabarStackedOmniDirectional` | **A mi fókuszunk** – kompakt, minden irányba olvasható | + +A megfelelő enum ismerete rengeteg próbálgatást takarít meg, amikor projektet váltasz. + +## Gyakori Hibák & Hogyan Kerüld El Őket + +- **Hiányzó NuGet csomag** – A kód nem fordul le `Aspose.BarCode` nélkül. Először futtasd a `dotnet add package Aspose.BarCode` parancsot. +- **Rossz fájlútvonal** – Ha abszolút útvonalat használsz, ellenőrizd a Windows‑os visszaperjeleket (`\\`). A relatív útvonalak (ahogy itt látható) hordozhatóbbek. +- **Túl extrém aspect ratio** – Az 50 fölötti arányok túl magasra nyújthatják a vonalkódot a tipikus szkennerekhez. Maradj a 15‑30 tartományban a legtöbb esetben. + +## Teljes Forráskód (Másolás‑Beillesztés Kész) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Futtasd a programot (`dotnet run` vagy nyomd meg az **F5**‑öt a Visual Studio‑ban), és a konzol üzenet megerősíti, hogy a fájlok a lemezen vannak. + +![Barcode generator example output showing DataBar barcode with aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Vonalkód generátor példa kimenet, DataBar vonalkód 15‑ös aspektus aránnyal"} + +## Összegzés + +Épp most fejeztünk be egy **barcode generator example**‑t, amely bemutatja, **hogyan állítsuk be a méreteket**, kiválasztja a megfelelő **barcode encode types**‑t, és végül **create barcode image c#** fájlokat hoz létre, amelyeket bárhol beágyazhatsz. A kód apró, a koncepciók kristálytisztaak, és most már szilárd alapod van a megoldás továbbfejlesztéséhez – például szöveges feliratok hozzáadásához, a kép forgatásához vagy egy másik szimbólumra való váltáshoz. + +### Mi Következik? + +- Kísérletezz különböző **X‑dimension**‑ökkel, hogy lásd, hogyan változik a szkenner toleranciája. +- Próbálj ki más **EncodeTypes**‑eket, mint a `Code128` vagy a `QR`, hogy bővítsd a szerszámtárad. +- Automatizáld a kötegelt generálást: egy CSV‑ben lévő termék‑azonosítók felett iterálva PNG‑t készíts mindegyikhez. + +Ha elakadsz, hagyj kommentet alább, vagy nézd meg az Aspose.BarCode dokumentációt – rengeteg példát tartalmaz, amelyek kiegészítik ezt az útmutatót. + +Boldog kódolást, és legyenek a vonalkódjaid mindig első próbálkozásra olvashatóak! + +## Mit Tanulj Meg Legközelebb? + +Az alábbi oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás komplett, működő kódpéldákat és lépésről‑lépésre magyarázatokat tartalmaz, hogy mesteri szintre emeld az API funkciókat, és alternatív megvalósítási megközelítéseket fedezz fel saját projektjeidben. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/hungarian/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/hungarian/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..33ea99ec8 --- /dev/null +++ b/barcode/hungarian/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-07-18 +description: Készíts Planet vonalkódot gyorsan C#-ban. Tanuld meg, hogyan generálj + kitöltött és üres sávokat, állítsd be az X‑dimenziót, és ments PNG képeket – mindezt + egyetlen útmutatóban. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: hu +lastmod: 2026-07-18 +og_description: Hozzon létre Planet vonalkódot azonnal. Ez az útmutató megmutatja, + hogyan állíthatja be az X‑dimenziót, válthat a kitöltött és üres sávok között, és + exportálhat PNG fájlokat az Aspose.BarCode segítségével. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Planet vonalkód létrehozása C#-ban – Teljes programozási útmutató +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Planet Barcode létrehozása C#‑ban – Teljes lépésről‑lépésre útmutató +url: /hu/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Planet vonalkód létrehozása C#‑ban – Teljes lépésről‑lépésre útmutató + +Valaha is szükséged volt **planet vonalkód** képek létrehozására, de nem tudtad, mely tulajdonságokat kell módosítani? Nem vagy egyedül. Sok fejlesztő akad el, amikor az alapértelmezett kitöltött vonalak nem felelnek meg a specifikációnak, vagy amikor a vonal szélességét a nyomtató DPI‑jéhez kell igazítani. + +Ebben az útmutatóban pontosan megtanulod, hogyan **hozz létre planet vonalkód** fájlokat az Aspose.BarCode könyvtár segítségével, hogyan szabályozd a **XDimension pixeleket**, és hogyan válts a **kitöltött vonalak** és **üres vonalak** között anélkül, hogy kódot kellene újraírnod. A végére két PNG fájlod lesz – egy szilárd vonalakkal, egy üreges vonalakkal – amely készen áll bármely postai rendszer számára, amely a Planet szimbólumot várja. + +## Előfeltételek + +- .NET 6.0 vagy újabb (a kód a .NET Framework 4.7 + verzión is működik) +- Aspose.BarCode for .NET NuGet csomag (`Install-Package Aspose.BarCode`) +- Alap C# ismeretek (később látni fogod, miért használunk `using` utasításokat) +- Írható mappa a lemezen, ahová a PNG‑eket menteni fogod + +Ha ezek megvannak, akkor egyenesen a megvalósításba ugorhatunk. + +## 1. lépés – A projekt beállítása és a könyvtár hozzáadása + +Először hozz létre egy új konzolos alkalmazást (vagy bármilyen C# projektet), és hivatkozz a **Planet vonalkód generátor** könyvtárra. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro tipp:** A Visual Studio-ban kattints jobb‑gombbal a projektre → *Manage NuGet Packages* → keresd meg a **Aspose.BarCode**‑t, és kattints az *Install* gombra. Ez hozzáférést biztosít a `BarcodeGenerator`‑hez és minden szükséges **BarcodeGenerator paraméterhez**. + +## 2. lépés – A Planet vonalkód generátor inicializálása + +Most ténylegesen **planet vonalkód** generátor példányt hozunk létre, és betápláljuk a kódolni kívánt adatot (`"123456"` ebben a példában). A `EncodeTypes.Planet` enum megmondja a könyvtárnak, melyik szimbólumot használja. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Miért fontos:** A `EncodeTypes.Planet` jelző automatikusan alkalmazza a helyes ellenőrzőösszeget és elrendezési szabályokat a Planet postai vonalkódhoz, így nem kell őket kézzel kiszámolnod. + +## 3. lépés – X‑Dimension beállítása (Vonal szélesség) + +A legtöbb nyomtató azt várja, hogy minden vonal egy meghatározott számú pixel legyen. Itt a **XDimension pixeleket** `4`‑re állítjuk, ami gyakori érték a 203 dpi‑s termikus nyomtatóknál. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Szélsőséges eset:** Ha 300 dpi‑s nyomtatót célozol, lehet, hogy `3` vagy `5` pixelre lesz szükséged. Állítsd ezt az értéket a készülék dokumentációja alapján. + +## 4. lépés – Kitöltött vonal változat mentése + +Alapértelmezés szerint a generátor **kitöltött vonalakat** (szilárd fekete téglalapokat) hoz létre. Írjuk ki ezt a lemezre: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Cseréld le a `YOUR_DIRECTORY`‑t egy abszolút vagy relatív útvonalra, amelyre az alkalmazásod írni tud. A sor futtatása után egy PNG fájlt találsz, amely klasszikus Planet vonalkódnak néz ki – tökéletes a postai szkennerrel való teszteléshez. + +## 5. lépés – Átváltás üres vonalakra + +Néha a postai szolgáltatások a „üres vonalak” stílust igénylik, ahol a vonalak a fehér háttérből vannak kivágva a fekete festés helyett. A könyvtár egy egyszerű kapcsolót biztosít: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +A `FilledBars` `false`‑ra állítása azt mondja a renderelőnek, hogy fordítsa meg a vonal kitöltési logikát. Nem kell új `BarcodeGenerator` példányt létrehozni; csak a meglévő **BarcodeGenerator paramétereket** módosítjuk. + +## 6. lépés – Üres vonal változat mentése + +Végül exportáljuk a második képet: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Most két különálló PNG fájlod van, mindegyik egyedi vizuális követelménynek megfelelően. + +## Teljes működő példa + +Az összes részt összeállítva, itt a teljes, másolás‑beillesztésre készen álló program: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Várt kimenet** (a konzolon): + +``` +Both Planet barcode images have been generated successfully. +``` + +És a `C:\Barcodes\` mappában a következőket fogod látni: + +- `PostalPlanetFilledBars.png` – szilárd fekete vonalak +- `PostalPlanetEmptyBars.png` – fehér vonalak fekete körvonalakkal + +Nyisd meg őket bármely képnézőben; mindkettőnek meg kell felelnie a Planet specifikációnak. + +## Gyakori kérdések és tippek + +### „Módosíthatom a képformátumot?” + +Természetesen. A `Save` metódus elfogadja a `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` stb. formátumokat. Csak cseréld le a `BarCodeImageFormat.Png`‑t a kívánt formátumra. + +### „Mi van, ha más vonalkódmagasságra van szükségem?” + +Használd a `planetBarcode.Parameters.Barcode.BarHeight`‑t (pontban) a függőleges méret növeléséhez vagy csökkentéséhez. Például: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### „Van mód ember által olvasható felirat hozzáadására?” + +Igen. Állítsd be a `CodeText` tulajdonságot a `planetBarcode.Parameters.Caption`‑on: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### „Szükséges-e felszabadítani a generátort?” + +A `BarcodeGenerator` implementálja az `IDisposable` interfészt. Csomagold `using` blokkba, ha egy ciklusban sok vonalkódot hozol létre: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### „Mi a helyzet a hibakezeléssel?” + +Tedd a `Save` hívásokat egy `try…catch` blokkba, hogy elkapd az `IOException`‑t (lemezproblémák) vagy az `ArgumentException`‑t (érvénytelen paraméterek). Példa: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Összefoglalás + +Mindent áttekintettünk, ami a **planet vonalkód** képek C#‑ban történő **létrehozásához** szükséges: + +1. Inicializáld a **Planet vonalkód generátort** a saját adataiddal. +2. Állítsd be a **XDimension pixeleket**, hogy megfeleljenek a nyomtató specifikációinak. +3. Ments egy **kitöltött vonal** PNG‑t. +4. Kapcsold át a `FilledBars`‑t, hogy **üres vonalakat** állíts elő. +5. Mentsd el a második PNG‑t. + +Innen tovább felfedezheted a további **BarcodeGenerator paramétereket**, kísérletezhetsz más szimbólumokkal (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, stb.), vagy beillesztheted a képeket egy postai munkafolyamatba. + +--- + +**Készen állsz a következő lépésre?** Próbálj meg QR kódot hozzáadni ugyanahhoz a dokumentumhoz, vagy generálj egy csomagot Planet vonalkódokból egy CSV lista alapján `foreach` ciklussal. Az Aspose.BarCode API elég rugalmas ahhoz, hogy tömeges műveleteket, egyedi színeket, sőt vektor‑alapú SVG kimenetet is kezeljen. + +Ha bármilyen problémába ütközöl, hagyj megjegyzést alább, vagy nézd meg a hivatalos Aspose.BarCode dokumentációt a haladó funkciók mélyebb megismeréséhez. Boldog kódolást! + +## Mit érdemes legközelebb megtanulni? + +A következő oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás 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. + +- [Készíts vonalkódot Aspose‑val – X és Y dimenziók beállítása Java‑ban](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [Hogyan hozz létre code128 vonalkód képeket Java‑ban az Aspose.BarCode‑dal](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [Hogyan hozz létre code128 vonalkódot Java‑ban és állítsd be a vonalmagasságot](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/hungarian/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..1ae0ab211 --- /dev/null +++ b/barcode/hungarian/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-07-18 +description: Készítsen RM4SCC vonalkódot C#-ban gyorsan; tanulja meg beállítani a + vonalkód magasságát, és generáljon Planet vonalkódot egyedi méretekkel. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: hu +lastmod: 2026-07-18 +og_description: Készíts RM4SCC vonalkódot C#-ban, és fedezd fel, hogyan állítható + be a vonalkód magassága. Emellett nézd meg, hogyan generálhatsz Planet vonalkódot + ugyanazzal a könyvtárral. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: RM4SCC vonalkód létrehozása C#-ban – Egyéni magasság gyors beállítása +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: RM4SCC vonalkód létrehozása C#‑ban – Teljes útmutató a magasság beállításához +url: /hu/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# RM4SCC vonalkód létrehozása C#-ban – Teljes útmutató a magasság beállításához + +Valaha is szükséged volt **RM4SCC vonalkód** létrehozására egy .NET alkalmazásban, de nem tudtad, hogyan szabályozd a méretét? Nem vagy egyedül. Akár egy levelezési rendszert, akár egy logisztikai irányítópultot építesz, a megfelelő vonalkódmagasság lehet a különbség egy működő és egy sikertelen beolvasás között. + +Ebben az útmutatóban végigvezetünk a teljes folyamaton: a könyvtár telepítésétől kezdve a **Planet vonalkód** generálásáig, mint mellékelt példát, és végül a **barcode height beállításáról** mindkét vonalkódtípus esetén. A végére egy azonnal futtatható konzolalkalmazást kapsz, amely a szükséges pontos méretekkel rendelkező PNG fájlokat állít elő. + +--- + +## Amire szükséged lesz + +- **.NET 6 SDK** (vagy bármely friss .NET verzió) – a kód .NET Frameworkön is működik, de a .NET 6 a legideálisabb. +- **Aspose.BarCode for .NET** NuGet csomag – ez a könyvtár biztosítja a `BarcodeGenerator` osztályt. +- Alapvető C# ismeretek – a szintaxis kezdők számára is barátságos lesz. +- IDE vagy szövegszerkesztő (Visual Studio, VS Code, Rider – válaszd a kedved szerint). + +> **Pro tipp:** Ha CI/CD pipeline-t használsz, add hozzá a NuGet hivatkozást a `.csproj` fájlodhoz, hogy a build soha ne felejtse el a függőséget. + +## 1. lépés: A projekt beállítása + +Nyiss egy terminált, és hozz létre egy új konzolprojektet: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +Ennyi—most a projekted hivatkozik arra a könyvtárra, amely mindent meghajt, ami ezután következik. + +### Add the Using Directives + +`Program.cs`-t nyisd meg, és illeszd be a következőt a tetejére: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +## 2. lépés: Segédmetódus definiálása képek mentéséhez + +Az ismétlődő mentési logika elkerülése érdekében egy kis metódusba fogjuk ágyazni. Ez emellett bemutatja, **hogyan állítsuk be a vonalkód magasságát** később. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Miért fontos:** A mentési logika központosítása azt jelenti, hogy ha a követelmények változnak, csak egy helyen kell módosítanod a formátumot vagy a mappát. + +## 3. lépés: Planet vonalkód generálása (a „generate planet barcode” rész) + +Mielőtt az RM4SCC részleteibe merülnénk, hozzunk létre egy **Planet vonalkódot**. Ez egy gyors vizuális ellenőrzést biztosít, hogy a könyvtár működik. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Várt kimenet:** Két PNG fájl jelenik meg az `output` mappában – az egyik a könyvtár által automatikusan kiszámított magassággal, a másik pontosan 100 px magas. + +## 4. lépés: RM4SCC vonalkód létrehozása – Elsődleges cél + +Most jön a főszereplő: **RM4SCC vonalkód létrehozása**. Az RM4SCC a Royal Mail 4‑State Code, amelyet széles körben használnak az Egyesült Királyság postai rendszerében. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**Ami látható lesz:** +- `RM4SCCDefault.png` – a könyvtár a X‑dimenzió alapján kényelmes magasságot választ. +- `RM4SCCHeight100.png` – egy tiszta, 100 pixel magas vonalkód, amely készen áll borítékokra nyomtatásra. + +> **Miért állítsuk be a magasságot?** Egyes címkelőnyomtatók minimális vonalmagasságot igényelnek a megbízható beolvasáshoz. A magasság rögzítésével biztosítod a megfelelőséget minden eszközön. + +## 5. lépés: A magasság beállításainak megértése (válasz a „hogyan állítsuk be a vonalkód magasságát” kérdésre) + +A Planet és az RM4SCC példák is ugyanazt a tulajdonságot használják: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** egy `BarHeight` objektum, amely több mérőegységet (pixel, milliméter, hüvelyk) csoportosít. +- **`.Pixels`** a legegyszerűbb egység a képernyőre irányuló kimenethez, de használhatod a `.Millimeters` vagy `.Inches` értékeket is, ha nyomtatási médiára célozol. + +### Különleges esetek és tippek + +| Situation | Recommended Approach | +|-----------|----------------------| +| **Nagyon kis X‑dimenzió (pl. 1 px)** | `BarHeight` növelése a vonalkód olvashatóságának megőrzéséhez. | +| **Nyomtatás nagy felbontású címkelőnyomtatókon** | Használd a `.Millimeters`-t az eszközfüggetlen méretezéshez. | +| **Keverett vonalkódtípusok egy képen** | `BarHeight` beállítása *az* `XDimension` **után** minden generátor esetén, hogy elkerüld a véletlen öröklődést. | +| **Dinamikus adatok (pl. felhasználó által megadott kódok)** | A generátor létrehozását egy metódusba ágyazni, amely `code` és `height` paramétereket fogad. | + +## 6. lépés: Teljes működő példa + +Az alábbi egy önálló program, amelyet egyszerűen beilleszthetsz a `Program.cs`-be. Tartalmazza a projekt beállításától a képek mentéséig minden lépést. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Futtasd a következővel: + +```bash +dotnet run +``` + +A konzol kimenetben látnod kell, hogy minden fájl mentésre került, és az `output` mappa négy PNG fájlt fog tartalmazni, amelyek a fent bemutatott nevekkel egyeznek. + +## Összegzés + +Most már tudod, **hogyan hozd létre az RM4SCC vonalkódot** C#-ban, és hogyan szabályozd a méreteit néhány tulajdonság beállításával. Emellett bemutattuk a **planet vonalkód generálását** gyors ellenőrzésként, és megvizsgáltuk a **barcode height beállításának** finomságait különböző nyomtatási helyzetekben. + +Következő lépések? Próbáld ki a `EncodeTypes` enum cseréjét más szimbólumokra (Code128, QR, DataMatrix), és kísérletezz a `BarHeight` milliméterben történő beállításával nagy felbontású nyomtatókhoz. Ha a vonalkódot PDF-be szeretnéd beágyazni, kombináld az Aspose.BarCode-ot az Aspose.PDF-el – egy újabb erőteljes párosítást. + +Van kérdésed, vagy szeretnéd megosztani a saját módosításaidat? Írj egy megjegyzést alább, és jó kódolást! + +## Mit érdemes legközelebb 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 teljes működő kódpéldákat és lépésről‑lépésre magyarázatokat tartalmaz, hogy elsajátíthasd a további API funkciókat, és alternatív megvalósítási megközelítéseket fedezhess fel 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 hozzunk létre csendes zónát az ITF-14 vonalkódhoz az Aspose.BarCode for .NET használatával](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Hogyan hozzunk létre csendes zónát a Code 16K vonalkódhoz az Aspose.BarCode for .NET használatával](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/hungarian/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..83dcfabf2 --- /dev/null +++ b/barcode/hungarian/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-07-18 +description: Tanulja meg, hogyan generáljon vonalkódképeket egy .net vonalkódgenerátorral, + és könnyedén változtassa meg a vonalkód magasságát a GS1‑Databar Omni‑Directional + szimbólumokhoz. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: hu +lastmod: 2026-07-18 +og_description: .net vonalkód-generátor lehetővé teszi, hogy gyorsan készítsen vonalkód + képeket. Ez az útmutató bemutatja, hogyan generáljon vonalkódot, állítsa be a vonal + magasságát, és mentse PNG fájlokként. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Módosítsa a vonalkód magasságát a .net vonalkód-generátorral +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET vonalkód generátor – a vonalkód magasságának módosítása +url: /hu/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – vonalkód magasságának módosítása + +Gondolkodtál már azon, **hogyan generálj vonalkód** képeket anélkül, hogy tucatnyi harmadik féltől származó eszközt kellene használni? A .NET világban meglepően egyszerű módja van ennek, és a kulcsfontosságú elem a **.net barcode generator**. Néhány C# sorral előállíthatsz egy GS1‑Databar Omni‑Directional szimbólumot, módosíthatod a vonal magasságát, és elmentheted az eredményt PNG fájlba. + +Ha készletkezelő rendszert, szállítási címke nyomtatót vagy bármilyen alkalmazást építesz, amelynek beolvasható kódra van szüksége, ez a bemutató néhány perc alatt a nulláról egy működő vonalkódot hoz létre. Átnézzük a teljes kódot, elmagyarázzuk, miért fontos minden beállítás, és megmutatjuk, hogyan **változtathatod meg a vonalkód magasságát** anélkül, hogy megsértenéd a specifikációt. + +## Amire szükséged lesz + +- .NET 6.0 vagy újabb (az API ugyanúgy működik a .NET Framework 4.7+ verziókon is) +- A hivatkozás a vonalkód könyvtárra (például Aspose.BarCode for .NET – ugyanazokat az osztályokat sok kereskedelmi csomag használja) +- Fejlesztői környezet (Visual Studio, Rider vagy VS Code a C# kiegészítővel) +- Egy mappa, ahol írási jogosultsággal rendelkezel – a bemutató PNG fájlokat ment ebbe a mappába + +Ennyi. Nincs szükség extra NuGet csomagokra a vonalkód könyvtáron kívül. + +## A .net barcode generator használata a vonalkód magasságának módosításához + +Az alábbi **teljes, futtatható konzolprogram**. Illeszd be egy új C# projektbe, állítsd be a kimeneti mappát, és nyomd meg az F5‑öt. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Miért fontos minden sor + +| Sor | Indok | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Példányosítja a **.net barcode generator**-t a kívánt szimbólummal és adatpayload-del. A `EncodeTypes.DatabarOmniDirectional` enum azt mondja a könyvtárnak, hogy használja a GS1‑Databar Omni‑Directional formátumot. | +| `XDimension.Pixels = 2;` | Az X‑dimenzió a legvékonyabb vonal szélessége. *2 pixel* beállítása éles képet ad a legtöbb monitoron, miközben alacsony fájlméretet tart. | +| `BarHeight.Pixels = 30;` | Ez a **vonalkód magasságának módosítása** lépés, amely meghatározza, milyen magas lesz minden vonal. A 30 pixel magasság jó alapértelmezett kis címkékhez. | +| `generator.Save(...);` | Elmenti a vonalkódot PNG fájlba. A PNG veszteségmentes, ami azt jelenti, hogy a szkennerek a pontosan generált mintát látják. | +| `BarHeight.Pixels = 60;` | Itt ismét **módosítjuk a vonalkód magasságát** – most 60 pixelre. A könyvtár automatikusan újrarajzolja a szimbólumot az új dimenzióval, amikor a `Save`-et másodszor hívod. | +| `Console.WriteLine(...);` | Gyors visszajelzést ad, hogy a folyamat hibamentesen befejeződött. | + +> **Pro tipp:** Ha nyomtatáshoz nagyobb felbontású kimenetre van szükséged, cseréld a `BarCodeImageFormat.Png`-t `BarCodeImageFormat.Tiff`-re, és növeld a `Resolution` tulajdonságot (pl. `generator.Parameters.ImageResolution = 300;`). A vonal magassága továbbra is érvényes marad, csak finomabb DPI‑n lesz renderelve. + +## Hogyan generálj vonalkód képeket különböző beállításokkal + +Az előző kódrészlet az alapokat lefedi, de a valós helyzetek gyakran igényelnek további finomításokat: + +### Az X‑dimenzió beállítása nagyobb nyomatokhoz +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Az X‑dimenzió növelése a teljes vonalkódot nagyobbra méretezi anélkül, hogy megváltoztatná a kódolt adatot. Ez akkor hasznos, ha nagy címkékre nyomsz. + +### Kimeneti formátumok váltása +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +Az SVG végtelenül skálázható, ami tökéletes a web‑alapú szkennerek számára, amelyeknek éles vektorokra van szükségük. + +### Emberi olvasásra alkalmas szöveg hozzáadása +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +`CodeTextVisible` engedélyezése a nyers adatot a vonalkód alá fűzi, ami hasznos a tesztelés során történő ellenőrzéshez. + +## Gyakori hibák, amikor **módosítod a vonalkód magasságát** + +1. **Túl alacsony magasság** – Néhány szkenner minimális vonalmagasságot igényel (gyakran 10 mm fizikai egységben). Ha a `BarHeight.Pixels`-t túl alacsonyra állítod, a generált kép olvashatatlan lehet egy valódi szkenner számára. Mindig teszteld a célhardverrel. +2. **Nem megfelelő X‑dimenzió és magasság** – Egy hatalmas vonalmagasság apró X‑dimenzióval nyúltnak tűnhet, és dekódolási hibákat okozhat. Törekedj kiegyensúlyozott arányra (kb. 3:1‑5:1), hacsak a specifikáció másként nem rendelkezik. +3. **A paraméterek visszaállításának elfelejtése** – A generátor megőrzi az állapotot a mentések között. Ha egy képnél megváltoztatod a `BarHeight`-t, majd ugyanazt a példányt használod egy másik vonalkódhoz, az előző magasság megmarad. Vagy állítsd vissza a tulajdonságot, vagy példányosíts egy új `BarcodeGenerator`-t minden egyes különálló vonalkódhoz. + +## Teljes vég‑től‑végig példa (NuGet telepítéssel együtt) + +Ha a semmiből indulsz, kövesd ezeket a lépéseket a projekt elindításához: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Cseréld le a generált `Program.cs`-t a korábban bemutatott kódrészletre, **ne felejtsd el a `YOUR_DIRECTORY`-t** valami hasonlóra cserélni, például `Path.Combine(Environment.CurrentDirectory, "output")`. Ezután: + +```bash +dotnet run +``` + +A `output` mappában két PNG fájlt kell látnod: + +- `DatabarBarHeight30Pixels.png` – egy kompakt, 30 pixel magas vonalkód. +- `DatabarBarHeight60Pixels.png` – egy magasabb, 60 pixel verzió. + +Mindkét kép hasonló lesz, de a második észrevehetően hosszabb vonalakkal rendelkezik, ami megkönnyíti az alacsony felbontású szkennerek számára a beolvasást. + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator kimenet, amely különböző vonalmagasságokat mutat"} + +## Összefoglalás és következő lépések + +Áttekintettük, hogyan **generálj vonalkód** képeket egy **.net barcode generator** segítségével, finomhangoltuk a **vonalkód magasságának módosítása** tulajdonságot, és PNG formátumban mentettük az eredményeket. A fő tanulságok: + +- Példányosítsd a generátort a megfelelő `EncodeTypes`-szel. +- A vizuális méretet az `XDimension` és `BarHeight` segítségével szabályozd. +- Minden módosítás után hívd meg a `Save`-et, hogy új képet ments. +- Állítsd be a felbontást, formátumot, + +## Mit érdemes még megtanulni? + +A következő bemutató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észletet tartalmaz lépésről‑lépésre magyarázatokkal, hogy elsajátíthasd a további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Hogyan generálj 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 hozz létre dotcode kiterjesztett kódszöveget az Aspose.BarCode for .NET segítségével](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Hogyan generálj DataMatrix vonalkódokat (ECC 200) az Aspose.BarCode for .NET használatával](/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/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/indonesian/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..d5fc9e27a --- /dev/null +++ b/barcode/indonesian/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-07-18 +description: Contoh generator barcode yang menunjukkan cara mengatur dimensi dan menghasilkan + gambar barcode DataBar Stacked Omni‑Directional dalam C#. Pelajari tipe pengkodean + barcode dengan cepat. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: id +lastmod: 2026-07-18 +og_description: Contoh generator barcode memandu Anda cara mengatur dimensi, memilih + jenis enkode barcode, dan membuat proyek gambar barcode C# dengan kode minimal. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Contoh Generator Barcode – Pembuatan Gambar DataBar Cepat dalam C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Contoh Generator Barcode – Membuat Gambar DataBar di C# +url: /id/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Contoh Generator Barcode – Membuat Gambar DataBar di C# + +Pernah butuh **contoh generator barcode** yang benar‑benar mencetak barcode dunia nyata tanpa membuat Anda frustasi? Anda tidak sendirian. Kebanyakan pengembang menemui kebuntuan ketika mencoba mencari tahu **cara mengatur dimensi** untuk barcode DataBar Stacked Omni‑Directional, terutama ketika dokumentasinya tersembunyi di bawah lapisan jargon. + +Dalam tutorial ini kami akan membahas program C# lengkap yang siap dijalankan yang menunjukkan **cara menghasilkan gambar databar**, memilih **tipe enkode barcode** yang tepat, dan akhirnya **membuat file gambar barcode c#** yang dapat Anda masukkan ke proyek mana pun. Tanpa basa‑basi—hanya kode yang dapat Anda salin‑tempel, plus penjelasan di balik setiap baris. + +## Apa yang Anda Butuhkan + +- **.NET 6** (atau versi .NET terbaru) – API yang kami gunakan menargetkan .NET Standard, sehingga juga berfungsi di .NET Framework. +- **Aspose.BarCode for .NET** – pustaka yang menyediakan `BarcodeGenerator`. Anda dapat mengunduhnya dari NuGet dengan `Install-Package Aspose.BarCode`. +- **IDE C#** – Visual Studio, Rider, atau VS Code sudah cukup. +- Sebuah folder di disk tempat file PNG akan disimpan (kode membuat `DatabarAspectRatio15.png` dan `DatabarAspectRatio30.png`). + +Sudah semua? Bagus—mari kita mulai. + +## Contoh Generator Barcode – Menginisialisasi Generator + +Hal pertama yang harus dilakukan: kita memerlukan sebuah instance `BarcodeGenerator` yang dikonfigurasi untuk simbol **DataBar Stacked Omni‑Directional**. Ini adalah **tipe enkode barcode** yang akan kita gunakan. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Mengapa ini penting:** `EncodeTypes.DatabarStackedOmniDirectional` memberi tahu Aspose secara tepat simbol mana yang harus dirender. Jika Anda memilih tipe yang salah, pemindai tidak akan mengenali barcode, tidak peduli seindah apa gambar tersebut. + +## Cara Mengatur Dimensi untuk Barcode + +Keterbacaan barcode bergantung pada **X‑dimension**‑nya (lebar bar paling tipis). Dalam kebanyakan kasus nilai 2 pixel sudah cukup, tetapi Anda dapat menyesuaikannya untuk printer atau layar Anda. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Tips pro:** Jika Anda pernah bertanya‑tanya **cara mengatur dimensi** untuk keluarga barcode lain, rantai properti yang sama (`Parameters.Barcode.XDimension`) berlaku—cukup ubah nilai `Pixels`. + +## Cara Menghasilkan Barcode DataBar Stacked Omni‑Directional + +Setelah generator siap, kita akan bermain dengan properti **aspect ratio**. Ini mengontrol hubungan tinggi‑lebar DataBar, memungkinkan Anda menghasilkan simbol pendek dan kotak atau yang tinggi dan sempit. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Apa yang terjadi?** `AspectRatio = 15` memberi tahu mesin untuk membuat bar 15 kali lebih tinggi daripada lebarnya. PNG yang dihasilkan disimpan tepat di sebelah executable Anda. + +## Membuat Gambar Barcode C# – Mengubah Aspect Ratio + +Mari buktikan fleksibilitas dengan mengubah rasio menjadi 30 dan menyimpan file kedua. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +Saat Anda menjalankan program, Anda akan mendapatkan dua file PNG: + +| File | Rasio Aspek | Ukuran Perkiraan | +|------|--------------|-------------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Buka mereka di penampil gambar apa pun—Anda akan melihat simbol DataBar yang bersih dan dapat dipindai. + +## Ikhtisar Tipe Enkode Barcode (Opsional tapi Berguna) + +Jika Anda penasaran tentang **tipe enkode barcode** lain yang didukung Aspose, berikut lembar cheat cepat: + +| EncodeTypes Enum | Deskripsi | +|------------------|-----------| +| `EncodeTypes.Code128` | Alfanumerik ber‑densitas tinggi | +| `EncodeTypes.QR` | Kode matriks 2‑D | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar untuk ritel | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Fokus kami** – kompak, omnidirectional | + +## Kesalahan Umum & Cara Menghindarinya + +- **Paket NuGet hilang** – Kode tidak akan terkompilasi tanpa `Aspose.BarCode`. Jalankan `dotnet add package Aspose.BarCode` terlebih dahulu. +- **Path file salah** – Jika Anda menggunakan path absolut, periksa kembali backslash (`\\`) pada Windows. Path relatif (seperti yang ditunjukkan) menjaga portabilitas. +- **Aspect ratio terlalu ekstrem** – Rasio di atas 50 dapat membuat barcode terlalu tinggi untuk pemindai umum. Tetap gunakan 15‑30 untuk kebanyakan kasus. + +## Kode Sumber Lengkap (Siap Salin‑Tempel) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Jalankan program (`dotnet run` atau tekan **F5** di Visual Studio) dan Anda akan melihat pesan konsol yang mengonfirmasi file berada di disk. + +![Barcode generator example output showing DataBar barcode with aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Contoh output generator barcode yang menampilkan barcode DataBar dengan aspect ratio 15"} + +## Kesimpulan + +Kami baru saja menyelesaikan **contoh generator barcode** yang menunjukkan **cara mengatur dimensi**, memilih **tipe enkode barcode** yang tepat, dan akhirnya **membuat file gambar barcode c#** yang dapat Anda sematkan di mana saja. Kodenya sangat kecil, konsepnya sangat jelas, dan kini Anda memiliki dasar yang kuat untuk memperluas solusi—mungkin menambahkan caption teks, memutar gambar, atau beralih ke simbol lain. + +### Apa Selanjutnya? + +- Bereksperimen dengan **X‑dimension berbeda** untuk melihat bagaimana toleransi pemindai berubah. +- Coba **EncodeTypes** lain seperti `Code128` atau `QR` untuk memperluas toolkit Anda. +- Otomatiskan pembuatan batch: loop melalui CSV ID produk dan hasilkan PNG untuk masing‑masing. + +Jika Anda mengalami kendala, tinggalkan komentar di bawah atau periksa dokumentasi Aspose.BarCode—dokumentasinya penuh dengan contoh yang melengkapi apa yang kami bahas di sini. + +Selamat coding, semoga barcode Anda selalu dapat dipindai pada percobaan pertama! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Cara Menghasilkan Barcode - Tipe Barcode Satu Dimensi](/barcode/english/net/one-dimensional-barcode-types/) +- [Membuat gambar barcode C# – Contoh GS1 DataMatrix](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [Cara Menghasilkan Barcode DataMatrix (ECC 200) dengan Aspose.BarCode untuk .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/indonesian/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/indonesian/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..ab8502e58 --- /dev/null +++ b/barcode/indonesian/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-07-18 +description: Buat barcode Planet dengan cepat menggunakan C#. Pelajari cara menghasilkan + bar terisi dan kosong, mengatur dimensi X, serta menyimpan gambar PNG – semua dalam + satu tutorial. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: id +lastmod: 2026-07-18 +og_description: Buat kode batang Planet secara instan. Panduan ini menunjukkan cara + mengatur dimensi X, beralih antara batang terisi dan kosong, serta mengekspor file + PNG dengan Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Buat Planet Barcode di C# – Panduan Pemrograman Lengkap +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Buat Planet Barcode di C# – Panduan Langkah-demi-Langkah Lengkap +url: /id/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buat Planet Barcode di C# – Panduan Langkah‑per‑Langkah Lengkap + +Pernah membutuhkan untuk **create planet barcode** gambar tetapi tidak yakin properti mana yang harus diubah? Anda tidak sendirian. Banyak pengembang mengalami kebuntuan ketika bar terisi default tidak sesuai dengan spesifikasi, atau ketika lebar bar harus cocok dengan DPI printer. + +Dalam tutorial ini Anda akan belajar secara tepat cara **create planet barcode** file menggunakan perpustakaan Aspose.BarCode, cara mengontrol **XDimension pixels**, dan cara beralih antara **filled bars** dan **empty bars** tanpa menulis ulang kode apa pun. Pada akhir tutorial Anda akan memiliki dua file PNG—satu dengan bar solid dan satu dengan bar berongga—siap untuk sistem pos mana pun yang mengharapkan simbol Planet. + +## Prasyarat + +- .NET 6.0 atau lebih baru (kode ini juga berfungsi pada .NET Framework 4.7 +) +- Paket NuGet Aspose.BarCode untuk .NET (`Install-Package Aspose.BarCode`) +- Pengetahuan dasar C# (Anda akan melihat mengapa kami menggunakan pernyataan `using` nanti) +- Folder yang dapat ditulisi di disk tempat PNG akan disimpan + +Jika Anda sudah memiliki semua ini, kita dapat langsung melompat ke implementasinya. + +## Langkah 1 – Siapkan Proyek dan Tambahkan Perpustakaan + +Pertama, buat aplikasi console baru (atau proyek C# apa pun) dan referensikan perpustakaan **Planet barcode generator**. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro tip:** Di Visual Studio, klik kanan proyek → *Manage NuGet Packages* → cari **Aspose.BarCode** dan klik *Install*. Ini memberi Anda akses ke `BarcodeGenerator` dan semua **BarcodeGenerator parameters** yang Anda perlukan. + +## Langkah 2 – Inisialisasi Planet Barcode Generator + +Sekarang kita benar‑benar **create planet barcode** instance generator dan memberi data yang ingin kita enkode (`"123456"` dalam contoh ini). Enum `EncodeTypes.Planet` memberi tahu perpustakaan simbol mana yang akan digunakan. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Why this matters:** Flag `EncodeTypes.Planet` secara otomatis menerapkan checksum dan aturan tata letak yang benar untuk barcode pos Planet, sehingga Anda tidak perlu menghitungnya secara manual. + +## Langkah 3 – Konfigurasi X‑Dimension (Lebar Bar) + +Sebagian besar printer mengharapkan setiap bar memiliki jumlah piksel tertentu. Di sini kami mengatur **XDimension pixels** ke `4`, nilai yang umum untuk printer termal 203 dpi. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Edge case:** Jika Anda menargetkan printer 300 dpi, Anda mungkin memerlukan `3` atau `5` piksel sebagai gantinya. Sesuaikan nilai ini berdasarkan dokumentasi perangkat Anda. + +## Langkah 4 – Simpan Versi Filled‑Bar + +Secara default generator menghasilkan **filled bars** (persegi panjang hitam solid). Mari kita tulis ke disk: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Ganti `YOUR_DIRECTORY` dengan jalur absolut atau relatif yang dapat ditulisi oleh aplikasi Anda. Setelah baris ini dijalankan Anda akan menemukan file PNG yang tampak seperti barcode Planet klasik—sempurna untuk pengujian dengan pemindai pos. + +## Langkah 5 – Beralih ke Empty Bars + +Terkadang layanan pos memerlukan gaya “empty bars”, di mana bar dipotong dari latar belakang putih alih‑alih dicat hitam. Perpustakaan menyediakan saklar sederhana: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Menetapkan `FilledBars` ke `false` memberi tahu renderer untuk membalik logika pengisian bar. Tidak perlu membuat instance `BarcodeGenerator` baru; kami cukup menyesuaikan **BarcodeGenerator parameters** yang sudah ada. + +## Langkah 6 – Simpan Versi Empty‑Bar + +Akhirnya, ekspor gambar kedua: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Sekarang Anda memiliki dua file PNG yang berbeda, masing‑masing memenuhi persyaratan visual yang berbeda. + +## Contoh Kerja Penuh + +Menggabungkan semua bagian, berikut program lengkap yang siap disalin‑tempel: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Expected output** (di konsol): + +``` +Both Planet barcode images have been generated successfully. +``` + +Dan di `C:\Barcodes\` Anda akan melihat: + +- `PostalPlanetFilledBars.png` – bar hitam solid +- `PostalPlanetEmptyBars.png` – bar putih dengan outline hitam + +Buka keduanya dengan penampil gambar apa pun; keduanya harus mematuhi spesifikasi Planet. + +## Pertanyaan Umum & Tips + +### “Can I change the image format?” + +Tentu saja. Metode `Save` menerima `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, dll. Cukup ganti `BarCodeImageFormat.Png` dengan format yang Anda inginkan. + +### “What if I need a different barcode height?” + +Gunakan `planetBarcode.Parameters.Barcode.BarHeight` (dalam poin) untuk meningkatkan atau menurunkan ukuran vertikal. Contohnya: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “Is there a way to add a human‑readable caption?” + +Ya. Atur properti `CodeText` pada `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “Do I need to dispose the generator?” + +`BarcodeGenerator` mengimplementasikan `IDisposable`. Bungkus dalam blok `using` jika Anda membuat banyak barcode dalam loop: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “What about error handling?” + +Bungkus pemanggilan `Save` dalam blok `try…catch` untuk menangkap `IOException` (masalah disk) atau `ArgumentException` (parameter tidak valid). Contoh: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Ringkasan + +Kami telah membahas semua yang Anda perlukan untuk **create planet barcode** gambar di C#: + +1. Inisialisasi **Planet barcode generator** dengan data Anda. +2. Sesuaikan **XDimension pixels** agar cocok dengan spesifikasi printer. +3. Simpan PNG **filled bars**. +4. Alihkan `FilledBars` untuk menghasilkan **empty bars**. +5. Simpan PNG kedua. + +Dari sini Anda dapat menjelajahi lebih banyak **BarcodeGenerator parameters**, bereksperimen dengan simbol lain (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, dll.), atau mengintegrasikan gambar ke dalam alur kerja pengiriman surat. + +--- + +**Siap untuk langkah berikutnya?** Cobalah menambahkan QR code ke dokumen yang sama, atau menghasilkan batch barcode Planet dari daftar CSV menggunakan loop `foreach`. API Aspose.BarCode cukup fleksibel untuk menangani operasi massal, warna kustom, bahkan output SVG berbasis vektor. + +Jika Anda mengalami kendala, tinggalkan komentar di bawah atau periksa dokumentasi resmi Aspose.BarCode untuk penjelasan lebih mendalam tentang fitur lanjutan. 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 dengan penjelasan langkah‑per‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Create Barcode with Aspose - Set X & Y Dimensions in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/indonesian/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..e57610186 --- /dev/null +++ b/barcode/indonesian/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-07-18 +description: Buat kode batang RM4SCC dalam C# dengan cepat; pelajari cara mengatur + tinggi kode batang dan juga menghasilkan kode batang Planet dengan dimensi khusus. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: id +lastmod: 2026-07-18 +og_description: Buat kode batang RM4SCC di C# dan temukan cara mengatur tinggi kode + batang. Juga lihat cara menghasilkan kode batang Planet dengan pustaka yang sama. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Buat Kode Bar RM4SCC di C# – Atur Tinggi Kustom dengan Cepat +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Buat Kode Bar RM4SCC di C# – Panduan Lengkap Mengatur Tinggi +url: /id/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buat Barcode RM4SCC di C# – Panduan Lengkap untuk Mengatur Tinggi + +Pernah perlu **create RM4SCC barcode** dalam aplikasi .NET tetapi tidak yakin cara mengontrol ukurannya? Anda tidak sendirian. Baik Anda membangun sistem pengiriman surat atau dasbor logistik, mendapatkan tinggi barcode yang tepat dapat menjadi perbedaan antara pemindaian yang berhasil dan yang gagal. + +Dalam tutorial ini kami akan membahas seluruh proses: mulai dari menginstal pustaka, hingga **generate Planet barcode** sebagai contoh berdampingan, dan akhirnya **how to set barcode height** untuk kedua jenis barcode. Pada akhir tutorial Anda akan memiliki aplikasi konsol siap‑jalankan yang menghasilkan file PNG dengan dimensi tepat yang Anda butuhkan. + +--- + +## Apa yang Anda Butuhkan + +- **.NET 6 SDK** (atau versi .NET terbaru) – kode ini juga berfungsi di .NET Framework, tetapi .NET 6 adalah pilihan yang tepat. +- **Aspose.BarCode for .NET** paket NuGet – ini adalah pustaka yang menyediakan kelas `BarcodeGenerator`. +- Pengetahuan dasar tentang C# – kami akan menjaga sintaks tetap ramah pemula. +- Sebuah IDE atau editor teks (Visual Studio, VS Code, Rider—pilih yang Anda suka). + +> **Pro tip:** Jika Anda menggunakan pipeline CI/CD, tambahkan referensi NuGet di file `.csproj` Anda sehingga proses build tidak pernah melupakan dependensi. + +## Langkah 1: Siapkan Proyek + +Buka terminal dan buat proyek konsol baru: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +Itu saja—proyek Anda kini merujuk ke pustaka yang mendukung semua yang akan datang. + +### Tambahkan Direktif Using + +Buka `Program.cs` dan tempelkan berikut ini di bagian atas: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +Namespace ini memberi kita akses ke `BarcodeGenerator` dan enum format gambar yang akan kita gunakan nanti. + +## Langkah 2: Definisikan Metode Pembantu untuk Menyimpan Gambar + +Untuk menghindari pengulangan logika penyimpanan yang sama, kami akan membungkusnya dalam metode kecil. Ini juga menunjukkan **how to set barcode height** nanti. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Mengapa ini penting:** Memusatkan logika penyimpanan berarti Anda hanya perlu mengubah format atau folder di satu tempat jika persyaratan berubah. + +## Langkah 3: Hasilkan Planet Barcode (bagian “generate planet barcode”) + +Sebelum kita menyelami detail RM4SCC, mari buat **Planet barcode**. Ini memberi Anda pemeriksaan visual cepat bahwa pustaka berfungsi. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Output yang diharapkan:** Dua file PNG muncul di folder `output`—satu dengan tinggi yang dihitung otomatis oleh pustaka, yang lainnya tepat setinggi 100 px. + +## Langkah 4: Buat RM4SCC Barcode – Tujuan Utama + +Sekarang untuk bintang utama: **create RM4SCC barcode**. RM4SCC adalah Royal Mail 4‑State Code, yang banyak digunakan dalam sistem pos di Inggris. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**Apa yang akan Anda lihat:** +- `RM4SCCDefault.png` – pustaka menentukan tinggi yang nyaman berdasarkan X‑dimension. +- `RM4SCCHeight100.png` – barcode setinggi 100 pixel yang tajam siap dicetak pada amplop. + +> **Mengapa mengatur tinggi?** Beberapa printer label membutuhkan tinggi bar minimum untuk pemindaian yang dapat diandalkan. Dengan menetapkan tinggi, Anda menjamin kepatuhan di semua perangkat. + +## Langkah 5: Memahami Pengaturan Tinggi (Menjawab “how to set barcode height”) + +Baik contoh Planet maupun RM4SCC menggunakan properti yang sama: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** adalah objek `BarHeight` yang mengelompokkan beberapa satuan ukuran (pixel, milimeter, inci). +- **`.Pixels`** adalah satuan paling sederhana untuk output yang berorientasi layar, tetapi Anda juga dapat menggunakan `.Millimeters` atau `.Inches` jika Anda menargetkan media cetak. + +### Kasus Pojok & Tips + +| Situasi | Pendekatan yang Disarankan | +|-----------|----------------------| +| **Dimensi X sangat kecil (mis., 1 px)** | Tingkatkan `BarHeight` untuk menjaga barcode tetap terbaca. | +| **Mencetak pada printer label resolusi tinggi** | Gunakan `.Millimeters` untuk ukuran yang tidak tergantung perangkat. | +| **Berbagai jenis barcode dalam satu gambar** | Setel `BarHeight` *setelah* `XDimension` untuk setiap generator agar tidak terjadi pewarisan tidak sengaja. | +| **Data dinamis (mis., kode yang dimasukkan pengguna)** | Bungkus pembuatan generator dalam metode yang menerima parameter `code` dan `height`. | + +## Langkah 6: Contoh Kerja Lengkap + +Berikut adalah program tunggal yang berdiri sendiri yang dapat Anda salin‑tempel ke `Program.cs`. Program ini mencakup semua hal mulai dari penyiapan proyek hingga penyimpanan gambar. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Jalankan dengan: + +```bash +dotnet run +``` + +Anda akan melihat output konsol yang mengonfirmasi setiap file disimpan, dan folder `output` akan berisi empat PNG yang sesuai dengan nama yang ditampilkan di atas. + +## Kesimpulan + +Anda kini tahu **how to create RM4SCC barcode** di C# dan mengontrol dimensinya hanya dengan beberapa penetapan properti. Kami juga membahas **generate planet barcode** sebagai pemeriksaan cepat, dan mengeksplorasi nuansa **how to set barcode height** untuk berbagai skenario pencetakan. + +Langkah selanjutnya? Coba ganti enum `EncodeTypes` dengan simbolologi lain (Code128, QR, DataMatrix) dan bereksperimen dengan `BarHeight` dalam milimeter untuk printer resolusi tinggi. Jika Anda perlu menyematkan barcode ke dalam PDF, gabungkan Aspose.BarCode dengan Aspose.PDF—kombinasi kuat lainnya. + +Ada pertanyaan atau ingin berbagi modifikasi Anda? Tinggalkan komentar di bawah, dan selamat coding! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait erat 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 mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Cara menghasilkan Aztec barcode dengan rasio aspek khusus menggunakan Aspose.BarCode untuk .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Cara Membuat Zona Tenang Barcode untuk ITF-14 Menggunakan Aspose.BarCode untuk .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Cara membuat zona tenang barcode untuk Code 16K menggunakan Aspose.BarCode untuk .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/indonesian/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..5d4f195ea --- /dev/null +++ b/barcode/indonesian/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-07-18 +description: Pelajari cara menghasilkan gambar barcode dengan generator barcode .net + dan dengan mudah mengubah tinggi barcode untuk simbol GS1‑Databar Omni‑Directional. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: id +lastmod: 2026-07-18 +og_description: .net barcode generator memungkinkan Anda dengan cepat membuat gambar + barcode. Panduan ini menunjukkan cara menghasilkan barcode, menyesuaikan tinggi + bar, dan menyimpan file PNG. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Ubah tinggi barcode dengan generator barcode .net +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: Generator barcode .net – ubah tinggi barcode +url: /id/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – mengubah tinggi barcode + +Pernah bertanya-tanya **bagaimana cara menghasilkan barcode** gambar tanpa harus mengelola banyak alat pihak ketiga? Di dunia .NET ada cara yang cukup bersih untuk melakukannya, dan komponen kuncinya adalah **.net barcode generator**. Dengan hanya beberapa baris C# Anda dapat membuat simbol GS1‑Databar Omni‑Directional, menyesuaikan tinggi bar, dan menyimpan hasilnya ke file PNG. + +Jika Anda sedang membangun sistem inventaris, printer label pengiriman, atau aplikasi apa pun yang membutuhkan kode yang dapat dipindai, tutorial ini akan membawa Anda dari nol hingga barcode yang berfungsi dalam hitungan menit. Kami akan menelusuri kode lengkap, menjelaskan mengapa setiap pengaturan penting, dan menunjukkan cara **mengubah tinggi barcode** tanpa melanggar spesifikasi. + +## Apa yang Anda butuhkan + +- .NET 6.0 atau lebih baru (API berfungsi sama pada .NET Framework 4.7+) +- Referensi ke perpustakaan barcode (misalnya, Aspose.BarCode for .NET – kelas yang sama digunakan oleh banyak paket komersial) +- Lingkungan pengembangan (Visual Studio, Rider, atau VS Code dengan ekstensi C#) +- Folder di mana Anda memiliki izin menulis – tutorial akan menyimpan file PNG di sana + +Itu saja. Tidak ada paket NuGet tambahan selain perpustakaan barcode itu sendiri. + +## Menggunakan .net barcode generator untuk mengubah tinggi barcode + +Berikut ini adalah **program konsol lengkap yang dapat dijalankan**. Tempelkan ke dalam proyek C# baru, sesuaikan folder output, dan tekan F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Mengapa setiap baris penting + +| Baris | Alasan | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Membuat instance **.net barcode generator** dengan simbol dan data payload yang diinginkan. Enum `EncodeTypes.DatabarOmniDirectional` memberi tahu perpustakaan untuk menggunakan format GS1‑Databar Omni‑Directional. | +| `XDimension.Pixels = 2;` | X‑dimension adalah lebar bar paling tipis. Menetapkannya ke *2 pixel* menghasilkan gambar tajam pada kebanyakan monitor sambil menjaga ukuran file tetap kecil. | +| `BarHeight.Pixels = 30;` | Ini adalah langkah **mengubah tinggi barcode** yang menentukan seberapa tinggi setiap bar. Tinggi 30 pixel adalah nilai default yang baik untuk label kecil. | +| `generator.Save(...);` | Menyimpan barcode ke file PNG. PNG bersifat loss‑less, yang berarti pemindai melihat pola persis yang Anda hasilkan. | +| `BarHeight.Pixels = 60;` | Di sini kami **mengubah tinggi barcode** lagi—kali ini menjadi 60 pixel. Perpustakaan secara otomatis merender ulang simbol dengan dimensi baru ketika Anda memanggil `Save` untuk kedua kalinya. | +| `Console.WriteLine(...);` | Memberikan umpan balik cepat bahwa proses selesai tanpa melempar pengecualian. | + +> **Tips pro:** Jika Anda membutuhkan output resolusi lebih tinggi untuk pencetakan, ubah `BarCodeImageFormat.Png` menjadi `BarCodeImageFormat.Tiff` dan tingkatkan properti `Resolution` (mis., `generator.Parameters.ImageResolution = 300;`). Tinggi bar tetap dipertahankan, hanya dirender pada DPI yang lebih halus. + +## Cara menghasilkan gambar barcode dengan pengaturan berbeda + +Potongan kode di atas mencakup dasar-dasarnya, tetapi skenario dunia nyata sering memerlukan penyesuaian tambahan: + +### Menyesuaikan X‑dimension untuk cetakan lebih besar +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Meningkatkan X‑dimension membuat seluruh barcode menjadi lebih besar tanpa mengubah data yang dikodekan. Ini berguna saat Anda mencetak pada label besar. + +### Mengganti format output +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG dapat diskalakan tak terbatas, yang sempurna untuk pemindai berbasis web yang membutuhkan vektor tajam. + +### Menambahkan teks yang dapat dibaca manusia +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Mengaktifkan `CodeTextVisible` menambahkan data mentah di bawah barcode, berguna untuk verifikasi selama pengujian. + +## Kesalahan umum saat Anda **mengubah tinggi barcode** + +1. **Tinggi terlalu kecil** – Beberapa pemindai memerlukan tinggi bar minimum (seringkali 10 mm dalam satuan fisik). Jika Anda menetapkan `BarHeight.Pixels` terlalu rendah, gambar yang dihasilkan mungkin tidak dapat dibaca pada pemindai sebenarnya. Selalu uji dengan perangkat keras target Anda. +2. **X‑dimension dan tinggi tidak cocok** – Tinggi bar yang sangat besar dipasangkan dengan X‑dimension yang kecil dapat terlihat terdistorsi dan dapat menyebabkan kesalahan decoding. Usahakan rasio seimbang (sekitar 3:1 hingga 5:1) kecuali spesifikasi menyatakan lain. +3. **Lupa mereset parameter** – Generator menyimpan keadaan antar penyimpanan. Jika Anda mengubah `BarHeight` untuk satu gambar dan kemudian menggunakan kembali instance yang sama untuk barcode lain, tinggi sebelumnya akan tetap ada. Reset properti tersebut atau buat instance baru `BarcodeGenerator` untuk setiap barcode yang berbeda. + +## Contoh lengkap end‑to‑end (termasuk instalasi NuGet) + +Jika Anda memulai dari awal, ikuti langkah-langkah berikut untuk menjalankan proyek: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Ganti `Program.cs` yang dihasilkan otomatis dengan blok kode yang ditampilkan sebelumnya, **ingat untuk mengganti `YOUR_DIRECTORY`** dengan sesuatu seperti `Path.Combine(Environment.CurrentDirectory, "output")`. Kemudian: + +```bash +dotnet run +``` + +Anda seharusnya melihat dua file PNG di folder `output`: + +- `DatabarBarHeight30Pixels.png` – barcode tinggi 30 pixel yang kompak. +- `DatabarBarHeight60Pixels.png` – versi tinggi 60 pixel yang lebih tinggi. + +Kedua gambar akan terlihat serupa, tetapi yang kedua akan memiliki bar yang secara jelas lebih panjang, memudahkan pemindai beresolusi rendah untuk membaca. + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator output menunjukkan tinggi bar yang berbeda"} + +## Ringkasan & langkah selanjutnya + +Kami telah membahas cara **menghasilkan barcode** gambar menggunakan **.net barcode generator**, menyesuaikan properti **mengubah tinggi barcode**, dan menyimpan hasilnya dalam format PNG. Poin pentingnya adalah: + +- Membuat instance generator dengan `EncodeTypes` yang tepat. +- Mengontrol ukuran visual melalui `XDimension` dan `BarHeight`. +- Memanggil `Save` setelah setiap perubahan untuk menyimpan gambar baru. +- Menyesuaikan resolusi, format, + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang terkait erat yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber daya menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [Cara menghasilkan barcode Aztec dengan rasio aspek khusus menggunakan Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Cara membuat dotcode dengan teks kode ekstended menggunakan Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Cara Menghasilkan Barcode DataMatrix (ECC 200) dengan 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/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/italian/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..e0953c240 --- /dev/null +++ b/barcode/italian/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-07-18 +description: Esempio di generatore di codici a barre che mostra come impostare le + dimensioni e generare un'immagine di codice a barre DataBar Stacked Omni‑Directional + in C#. Impara rapidamente i tipi di codifica dei codici a barre. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: it +lastmod: 2026-07-18 +og_description: L'esempio di generatore di codici a barre ti guida nella definizione + delle dimensioni, nella scelta dei tipi di codifica e nella creazione di progetti + C# per immagini di codici a barre con un codice minimo. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Esempio di Generatore di Codici a Barre – Creazione Rapida di Immagini DataBar + in C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Esempio di generatore di codici a barre – Crea immagine DataBar in C# +url: /it/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Esempio di Generatore di Codici a Barre – Creare Immagine DataBar in C# + +Hai mai avuto bisogno di un **esempio di generatore di codici a barre** che stampi davvero un codice a barre reale senza impazzire? Non sei solo. La maggior parte degli sviluppatori si blocca quando cerca di capire **come impostare le dimensioni** per un codice DataBar Stacked Omni‑Directional, soprattutto quando la documentazione è sepolta sotto strati di gergo tecnico. + +In questo tutorial percorreremo un programma C# completo, pronto all'uso, che mostra **come generare immagini databar**, sceglie i giusti **barcode encode types**, e infine **create barcode image c#** file che puoi inserire in qualsiasi progetto. Niente fronzoli—solo il codice da copiare‑incollare, più la spiegazione dietro ogni riga. + +## Cosa Ti Serve + +- **.NET 6** (o qualsiasi versione recente di .NET) – l'API che usiamo punta a .NET Standard, quindi funziona anche su .NET Framework. +- **Aspose.BarCode for .NET** – la libreria che fornisce `BarcodeGenerator`. Puoi ottenerla da NuGet con `Install-Package Aspose.BarCode`. +- Un **IDE C#** – Visual Studio, Rider o VS Code vanno bene. +- Una cartella su disco dove salvare i file PNG (il codice crea `DatabarAspectRatio15.png` e `DatabarAspectRatio30.png`). + +Hai tutto? Ottimo—tuffiamoci. + +## Esempio di Generatore di Codici a Barre – Inizializzare il Generatore + +Prima di tutto: ci serve un'istanza di `BarcodeGenerator` configurata per la simbologia **DataBar Stacked Omni‑Directional**. Questo è il **barcode encode type** con cui lavoreremo. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Perché è importante:** `EncodeTypes.DatabarStackedOmniDirectional` indica ad Aspose esattamente quale simbologia renderizzare. Se scegli il tipo sbagliato, lo scanner non riconoscerà il codice a barre, per quanto bella sia l'immagine. + +## Come Impostare le Dimensioni per il Codice a Barre + +La leggibilità di un codice a barre dipende dalla sua **X‑dimension** (la larghezza della barra più stretta). Nella maggior parte dei casi un valore di 2 pixel è sufficiente, ma puoi modificarlo per adattarlo alla tua stampante o schermo. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Consiglio pro:** Se ti chiedi **come impostare le dimensioni** per un'altra famiglia di codici a barre, la stessa catena di proprietà (`Parameters.Barcode.XDimension`) vale—basta cambiare il valore di `Pixels`. + +## Come Generare un Codice DataBar Stacked Omni‑Directional + +Ora che il generatore è pronto, giocheremo con la proprietà **aspect ratio**. Questa controlla il rapporto altezza‑larghezza del DataBar, permettendoti di produrre un simbolo corto e quadrato o uno alto e stretto. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Cosa succede?** `AspectRatio = 15` dice al motore di rendere le barre 15 volte più alte della loro larghezza. Il PNG risultante viene salvato accanto all'eseguibile. + +## Creare Immagine di Codice a Barre C# – Cambiare l'Aspect Ratio + +Dimostriamo la flessibilità cambiando il rapporto a 30 e salvando un secondo file. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +Quando esegui il programma, otterrai due file PNG: + +| File | Aspect Ratio | Dimensione Approx. | +|------|--------------|--------------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Aprili con qualsiasi visualizzatore di immagini—dovresti vedere simboli DataBar puliti e leggibili. + +## Panoramica dei Barcode Encode Types (Opzionale ma Utile) + +Se sei curioso di conoscere gli altri **barcode encode types** supportati da Aspose, ecco una rapida cheat‑sheet: + +| EncodeTypes Enum | Descrizione | +|------------------|-------------| +| `EncodeTypes.Code128` | Alfanumerico ad alta densità | +| `EncodeTypes.QR` | Codice matrice 2‑D | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar per il retail | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Il nostro focus** – compatto, omnidirezionale | + +Conoscere l'enum giusto ti salva da molti tentativi ed errori quando cambi progetto. + +## Problemi Comuni & Come Evitarli + +- **Pacchetto NuGet mancante** – Il codice non compila senza `Aspose.BarCode`. Esegui prima `dotnet add package Aspose.BarCode`. +- **Percorso file errato** – Se usi un percorso assoluto, controlla le doppie barre rovesciate (`\\`) su Windows. I percorsi relativi (come mostrato) mantengono la portabilità. +- **Aspect ratio troppo estremo** – Rapporti superiori a 50 possono rendere il codice a barre troppo alto per gli scanner tipici. Attieniti a 15‑30 per la maggior parte dei casi d'uso. + +## Codice Sorgente Completo (Pronto per Copia‑Incolla) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Esegui il programma (`dotnet run` o premi **F5** in Visual Studio) e vedrai il messaggio nella console che conferma che i file sono stati salvati su disco. + +![Esempio di output del generatore di codici a barre che mostra il DataBar con aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Esempio di output del generatore di codici a barre che mostra il DataBar con aspect ratio 15"} + +## Conclusioni + +Abbiamo appena completato un **esempio di generatore di codici a barre** che dimostra **come impostare le dimensioni**, sceglie i corretti **barcode encode types**, e infine **create barcode image c#** file che puoi incorporare ovunque. Il codice è piccolo, i concetti sono cristallini, e ora hai una solida base per estendere la soluzione—magari aggiungendo didascalie di testo, ruotando l'immagine o passando a un'altra simbologia. + +### Qual è il Prossimo Passo? + +- Sperimenta con **diverse X‑dimension** per vedere come varia la tolleranza dello scanner. +- Prova altri **EncodeTypes** come `Code128` o `QR` per ampliare il tuo toolkit. +- Automatizza la generazione in batch: cicla su un CSV di ID prodotto e genera un PNG per ciascuno. + +Se incontri difficoltà, lascia un commento qui sotto o consulta la documentazione di Aspose.BarCode—è ricca di esempi che completano quanto trattato qui. + +Buon coding, e che i tuoi codici a barre scansionino 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 ulteriori funzionalità dell'API e a esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/italian/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..32bb98682 --- /dev/null +++ b/barcode/italian/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-07-18 +description: Crea rapidamente il codice a barre Planet con C#. Scopri come generare + barre piene e vuote, impostare la dimensione X e salvare immagini PNG – tutto in + un unico tutorial. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: it +lastmod: 2026-07-18 +og_description: Crea il codice a barre Planet istantaneamente. Questa guida ti mostra + come impostare la dimensione X, passare da barre piene a vuote e esportare file + PNG con Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Crea Planet Barcode in C# – Guida completa alla programmazione +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Crea il codice a barre Planet in C# – Guida completa passo passo +url: /it/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea il codice a barre Planet in C# – Guida completa passo‑passo + +Hai mai dovuto **creare immagini di codice a barre planet** ma non sapevi quali proprietà modificare? Non sei solo. Molti sviluppatori si trovano in difficoltà quando le barre riempite di default non soddisfano le specifiche, o quando la larghezza della barra deve corrispondere alla DPI della stampante. + +In questo tutorial imparerai esattamente come **creare file di codice a barre planet** usando la libreria Aspose.BarCode, come controllare i **pixel XDimension**, e come passare da **barre riempite** a **barre vuote** senza riscrivere alcun codice. Alla fine avrai due file PNG—uno con barre solide e uno con barre cave—pronti per qualsiasi sistema postale che richieda la simbologia Planet. + +## Prerequisiti + +- .NET 6.0 o successivo (il codice funziona anche su .NET Framework 4.7 +) +- Pacchetto NuGet Aspose.BarCode for .NET (`Install-Package Aspose.BarCode`) +- Conoscenze di base di C# (vedrai più avanti perché usiamo le istruzioni `using`) +- Una cartella scrivibile su disco dove salvare i PNG + +Se hai tutto questo, possiamo passare subito all'implementazione. + +## Passo 1 – Configura il progetto e aggiungi la libreria + +Per prima cosa, crea una nuova console app (o qualsiasi progetto C#) e aggiungi il riferimento alla **libreria generatore di codice a barre Planet**. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Suggerimento:** In Visual Studio, fai clic destro sul progetto → *Manage NuGet Packages* → cerca **Aspose.BarCode** e premi *Install*. Questo ti dà accesso a `BarcodeGenerator` e a tutti i **parametri di BarcodeGenerator** di cui avrai bisogno. + +## Passo 2 – Inizializza il generatore di codice a barre Planet + +Ora creiamo effettivamente l'istanza del generatore **planet barcode** e gli forniamo i dati da codificare (`"123456"` in questo esempio). L'enumerazione `EncodeTypes.Planet` indica alla libreria quale simbologia utilizzare. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Perché è importante:** Il flag `EncodeTypes.Planet` applica automaticamente il checksum corretto e le regole di layout per il codice a barre postale Planet, così non devi calcolarli manualmente. + +## Passo 3 – Configura X‑Dimension (larghezza barra) + +La maggior parte delle stampanti si aspetta che ogni barra abbia un numero specifico di pixel. Qui impostiamo i **pixel XDimension** a `4`, valore comune per stampanti termiche a 203 dpi. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Caso limite:** Se la tua stampante è a 300 dpi, potresti aver bisogno di `3` o `5` pixel. Regola questo valore in base alla documentazione del tuo dispositivo. + +## Passo 4 – Salva la versione a barre riempite + +Per impostazione predefinita il generatore produce **barre riempite** (rettangoli neri solidi). Scriviamola su disco: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Sostituisci `YOUR_DIRECTORY` con un percorso assoluto o relativo a cui la tua app può scrivere. Dopo l'esecuzione di questa riga troverai un file PNG che assomiglia a un classico codice a barre Planet—perfetto per testarlo con uno scanner postale. + +## Passo 5 – Passa a barre vuote + +A volte i servizi postali richiedono lo stile “barre vuote”, dove le barre sono intagliate su uno sfondo bianco invece di essere dipinte di nero. La libreria espone un semplice interruttore: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Impostare `FilledBars` a `false` dice al renderer di invertire la logica di riempimento delle barre. Non è necessario creare una nuova istanza di `BarcodeGenerator`; basta modificare i **parametri di BarcodeGenerator** esistenti. + +## Passo 6 – Salva la versione a barre vuote + +Infine, esporta la seconda immagine: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Ora disponi di due file PNG distinti, ciascuno conforme a un requisito visivo diverso. + +## Esempio completo funzionante + +Mettendo insieme tutti i pezzi, ecco il programma completo, pronto per il copia‑incolla: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Output previsto** (sulla console): + +``` +Both Planet barcode images have been generated successfully. +``` + +E in `C:\Barcodes\` vedrai: + +- `PostalPlanetFilledBars.png` – barre nere solide +- `PostalPlanetEmptyBars.png` – barre bianche con contorni neri + +Aprili con qualsiasi visualizzatore di immagini; dovrebbero entrambi rispettare la specifica Planet. + +## Domande comuni e consigli + +### “Posso cambiare il formato dell’immagine?” + +Assolutamente. Il metodo `Save` accetta `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, ecc. Basta sostituire `BarCodeImageFormat.Png` con il formato desiderato. + +### “E se ho bisogno di un’altezza diversa per il codice a barre?” + +Usa `planetBarcode.Parameters.Barcode.BarHeight` (in punti) per aumentare o diminuire la dimensione verticale. Per esempio: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “C’è un modo per aggiungere una didascalia leggibile dall’uomo?” + +Sì. Imposta la proprietà `CodeText` su `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “Devo rilasciare il generatore?” + +Il `BarcodeGenerator` implementa `IDisposable`. Avvolgilo in un blocco `using` se crei molti codici a barre in un ciclo: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “E per la gestione degli errori?” + +Racchiudi le chiamate a `Save` in un blocco `try…catch` per catturare `IOException` (problemi di disco) o `ArgumentException` (parametri non validi). Esempio: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Riepilogo + +Abbiamo coperto tutto ciò che serve per **creare immagini di codice a barre planet** in C#: + +1. Inizializza il **generatore di codice a barre Planet** con i tuoi dati. +2. Regola i **pixel XDimension** per corrispondere alle specifiche della stampante. +3. Salva un PNG con **barre riempite**. +4. Attiva `FilledBars` per produrre **barre vuote**. +5. Salva il secondo PNG. + +Da qui puoi esplorare altri **parametri di BarcodeGenerator**, sperimentare con altre simbologie (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, ecc.), o integrare le immagini in un flusso di lavoro di spedizione. + +--- + +**Pronto per il passo successivo?** Prova ad aggiungere un QR code allo stesso documento, o genera un batch di codici a barre Planet da un elenco CSV usando un ciclo `foreach`. L’API Aspose.BarCode è sufficientemente flessibile da gestire operazioni in blocco, colori personalizzati e persino output vettoriale SVG. + +Se incontri difficoltà, lascia un commento qui sotto o consulta la documentazione ufficiale di Aspose.BarCode per approfondimenti sulle funzionalità avanzate. Buona programmazione! + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare ulteriori funzionalità dell’API e a esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Crea codice a barre con Aspose - Imposta le dimensioni X & Y in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [Come creare immagini di codice a barre code128 in Java con Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [Come creare codice a barre code128 in Java e impostare l’altezza della barra](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/italian/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..2e2711948 --- /dev/null +++ b/barcode/italian/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,274 @@ +--- +category: general +date: 2026-07-18 +description: Crea rapidamente un codice a barre RM4SCC in C#; scopri come impostare + l'altezza del codice a barre e genera anche un codice a barre Planet con dimensioni + personalizzate. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: it +lastmod: 2026-07-18 +og_description: Crea un codice a barre RM4SCC in C# e scopri come impostare l’altezza + del codice a barre. Vedi anche come generare il codice a barre Planet con la stessa + libreria. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Crea codice a barre RM4SCC in C# – Imposta rapidamente un'altezza personalizzata +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Crea codice a barre RM4SCC in C# – Guida completa per impostare l'altezza +url: /it/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea codice a barre RM4SCC in C# – Guida completa per impostare l’altezza + +Hai mai dovuto **creare un codice a barre RM4SCC** in un’app .NET ma non sapevi come controllarne le dimensioni? Non sei solo. Che tu stia costruendo un sistema di mailing o un cruscotto logistico, ottenere l’altezza corretta del codice a barre può fare la differenza tra una scansione riuscita e una fallita. + +In questo tutorial percorreremo l’intero processo: dall’installazione della libreria, alla **generazione di un codice a barre Planet** come esempio affiancato, e infine a **come impostare l’altezza del codice a barre** per entrambi i tipi. Alla fine avrai un’app console pronta all’uso che genera file PNG con le dimensioni esatte di cui hai bisogno. + +--- + +## Cosa ti serve + +- **.NET 6 SDK** (o qualsiasi versione recente di .NET) – il codice funziona anche su .NET Framework, ma .NET 6 è il punto ideale. +- **Aspose.BarCode for .NET** pacchetto NuGet – è la libreria che fornisce la classe `BarcodeGenerator`. +- Una modesta conoscenza di C# – manterremo la sintassi adatta ai principianti. +- Un IDE o editor di testo (Visual Studio, VS Code, Rider—scegli il tuo preferito). + +> **Suggerimento:** Se lavori su una pipeline CI/CD, aggiungi il riferimento NuGet nel tuo file `.csproj` così la build non dimentica mai la dipendenza. + +--- + +## Passo 1: Configura il progetto + +Apri un terminale e crea un nuovo progetto console: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +Fatto—il tuo progetto ora fa riferimento alla libreria che alimenta tutto ciò che segue. + +### Aggiungi le direttive `using` + +Apri `Program.cs` e incolla quanto segue in cima: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +Questi namespace ci danno accesso a `BarcodeGenerator` e all’enum del formato immagine che utilizzeremo più avanti. + +--- + +## Passo 2: Definisci un metodo di supporto per salvare le immagini + +Per evitare di ripetere la stessa logica di salvataggio, la racchiudiamo in un piccolo metodo. Questo dimostra anche **come impostare l’altezza del codice a barre** più avanti. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Perché è importante:** Centralizzare la logica di salvataggio significa dover modificare il formato o la cartella in un solo punto se i requisiti cambiano. + +--- + +## Passo 3: Genera un codice a barre Planet (la parte “generate planet barcode”) + +Prima di addentrarci nei dettagli di RM4SCC, creiamo un **codice a barre Planet**. Questo ti fornisce un rapido controllo visivo che la libreria funzioni correttamente. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Output previsto:** Due file PNG appaiono nella cartella `output`—uno con l’altezza calcolata automaticamente dalla libreria, l’altro esattamente alto 100 px. + +--- + +## Passo 4: Crea codice a barre RM4SCC – Obiettivo principale + +Ora la star dello spettacolo: **crea codice a barre RM4SCC**. RM4SCC è il Royal Mail 4‑State Code, ampiamente usato nel sistema postale del Regno Unito. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**Ciò che vedrai:** +- `RM4SCCDefault.png` – la libreria decide un’altezza comoda in base alla X‑dimension. +- `RM4SCCHeight100.png` – un codice a barre nitido alto 100 pixel, pronto per la stampa su buste. + +> **Perché impostare l’altezza?** Alcune stampanti di etichette richiedono un’altezza minima delle barre per una scansione affidabile. Fissando l’altezza garantisci la conformità su tutti i dispositivi. + +--- + +## Passo 5: Comprendere le impostazioni di altezza (Rispondendo a “how to set barcode height”) + +Sia l’esempio Planet che quello RM4SCC usano la stessa proprietà: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** è un oggetto `BarHeight` che raggruppa diverse unità di misura (pixel, millimetri, pollici). +- **`.Pixels`** è l’unità più semplice per output orientato allo schermo, ma puoi anche usare `.Millimeters` o `.Inches` se il target è la stampa. + +### Casi particolari e consigli + +| Situazione | Approccio consigliato | +|------------|-----------------------| +| **X‑dimension molto piccola (es. 1 px)** | Aumenta `BarHeight` per mantenere il codice leggibile. | +| **Stampa su stampanti di etichette ad alta risoluzione** | Usa `.Millimeters` per una dimensione indipendente dal dispositivo. | +| **Tipi di codice a barre misti in una stessa immagine** | Imposta `BarHeight` *dopo* `XDimension` per ogni generatore, così eviti eredità accidentali. | +| **Dati dinamici (es. codici inseriti dall’utente)** | Avvolgi la creazione del generatore in un metodo che accetti parametri `code` e `height`. | + +--- + +## Passo 6: Esempio completo funzionante + +Di seguito trovi un programma unico, autonomo, che puoi copiare‑incollare in `Program.cs`. Include tutto, dall’impostazione del progetto al salvataggio delle immagini. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Eseguilo con: + +```bash +dotnet run +``` + +Dovresti vedere l’output della console che conferma il salvataggio di ciascun file, e la cartella `output` conterrà quattro PNG con i nomi mostrati sopra. + +--- + +## Conclusione + +Ora sai **come creare un codice a barre RM4SCC** in C# e controllarne le dimensioni con un paio di assegnazioni di proprietà. Abbiamo anche coperto **generate planet barcode** come rapido controllo di sanità, e approfondito le sfumature di **how to set barcode height** per diversi scenari di stampa. + +Passi successivi? Prova a sostituire l’enum `EncodeTypes` con altre simbologie (Code128, QR, DataMatrix) e sperimenta `BarHeight` in millimetri per stampanti ad alta risoluzione. Se devi incorporare il codice a barre in un PDF, abbina Aspose.BarCode a Aspose.PDF—un’altra combinazione potente. + +Hai domande o vuoi condividere le tue modifiche? Lascia un commento qui sotto, e buona programmazione! + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare ulteriori funzionalità dell’API e a esplorare approcci alternativi nei tuoi progetti. + +- [Come generare un 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 creare una zona silenziosa per il codice a barre ITF-14 usando Aspose.BarCode per .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Come creare una zona silenziosa per il codice a barre Code 16K usando Aspose.BarCode per .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/italian/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..537ef5d20 --- /dev/null +++ b/barcode/italian/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-07-18 +description: Scopri come generare immagini di codici a barre con un generatore di + codici a barre .net e modifica facilmente l'altezza del codice a barre per i simboli + GS1‑Databar Omni‑Directional. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: it +lastmod: 2026-07-18 +og_description: Il generatore di codici a barre .net ti consente di creare rapidamente + immagini di codici a barre. Questa guida mostra come generare codici a barre, regolare + l'altezza delle barre e salvare file PNG. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Modifica l'altezza del codice a barre con il generatore di codici a barre + .NET +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET generatore di codici a barre – cambia l’altezza del codice a barre +url: /it/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generatore di codici a barre .net – modifica altezza del codice a barre + +Ti sei mai chiesto **come generare immagini di codici a barre** senza dover gestire una dozzina di strumenti di terze parti? Nel mondo .NET esiste un modo sorprendentemente semplice per farlo, e l'elemento chiave è il **.net barcode generator**. Con poche righe di C# puoi creare un simbolo GS1‑Databar Omni‑Directional, regolare l'altezza delle barre e salvare il risultato in un file PNG. + +Se stai costruendo un sistema di inventario, una stampante di etichette di spedizione o qualsiasi app che richieda un codice leggibile, questo tutorial ti porterà da zero a un codice a barre funzionante in pochi minuti. Esamineremo il codice completo, spiegheremo perché ogni impostazione è importante e ti mostreremo come **modificare l'altezza del codice a barre** senza violare le specifiche. + +## Cosa ti serve + +- .NET 6.0 o versioni successive (l'API funziona allo stesso modo su .NET Framework 4.7+) +- Un riferimento alla libreria di codici a barre (ad esempio, Aspose.BarCode for .NET – le stesse classi sono utilizzate da molti kit commerciali) +- Un ambiente di sviluppo (Visual Studio, Rider o VS Code con l'estensione C#) +- Una cartella in cui hai permessi di scrittura – il tutorial salverà i file PNG lì + +Tutto qui. Nessun pacchetto NuGet aggiuntivo oltre alla libreria di codici a barre stessa. + +## Utilizzare il generatore di codici a barre .net per modificare l'altezza del codice a barre + +Di seguito trovi un **programma console completo e eseguibile**. Incollalo in un nuovo progetto C#, regola la cartella di output e premi F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Perché ogni riga è importante + +| Riga | Motivo | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Istanzia il **.net barcode generator** con la simbologia e i dati desiderati. L'enumerazione `EncodeTypes.DatabarOmniDirectional` indica alla libreria di utilizzare il formato GS1‑Databar Omni‑Directional. | +| `XDimension.Pixels = 2;` | La X‑dimension è la larghezza della barra più sottile. Impostandola a *2 pixel* si ottiene un'immagine nitida sulla maggior parte dei monitor mantenendo ridotto il peso del file. | +| `BarHeight.Pixels = 30;` | Questo è il passaggio di **modifica dell'altezza del codice a barre** che determina l'altezza di ciascuna barra. Un'altezza di 30 pixel è un buon valore predefinito per etichette piccole. | +| `generator.Save(...);` | Salva il codice a barre in un file PNG. PNG è senza perdita, il che significa che gli scanner vedono esattamente il pattern generato. | +| `BarHeight.Pixels = 60;` | Qui **modifichiamo nuovamente l'altezza del codice a barre**, questa volta a 60 pixel. La libreria rigenera automaticamente il simbolo con la nuova dimensione quando chiami `Save` una seconda volta. | +| `Console.WriteLine(...);` | Ti fornisce un rapido feedback che il processo è terminato senza sollevare eccezioni. | + +> **Consiglio professionale:** Se hai bisogno di output ad alta risoluzione per la stampa, passa da `BarCodeImageFormat.Png` a `BarCodeImageFormat.Tiff` e aumenta la proprietà `Resolution` (ad esempio, `generator.Parameters.ImageResolution = 300;`). L'altezza delle barre verrà comunque rispettata, ma renderizzata a un DPI più fine. + +## Come generare immagini di codici a barre con impostazioni diverse + +Il frammento sopra copre le basi, ma scenari reali spesso richiedono ulteriori regolazioni: + +### Regolare la X‑dimension per stampe più grandi +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Aumentare la X‑dimension rende l'intero codice a barre più grande senza modificare i dati codificati. È utile quando si stampa su etichette di grandi dimensioni. + +### Cambiare i formati di output +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG si scala all'infinito, il che è perfetto per scanner basati sul web che necessitano di vettori nitidi. + +### Aggiungere testo leggibile dall'uomo +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Abilitare `CodeTextVisible` aggiunge i dati grezzi sotto il codice a barre, utile per la verifica durante i test. + +## Errori comuni quando **modifichi l'altezza del codice a barre** + +1. **Altezza troppo piccola** – Alcuni scanner richiedono un'altezza minima della barra (spesso 10 mm in unità fisiche). Se imposti `BarHeight.Pixels` troppo basso, l'immagine generata potrebbe risultare illeggibile su uno scanner reale. Testa sempre con l'hardware di destinazione. +2. **X‑dimension e altezza non corrispondenti** – Un'altezza della barra molto grande associata a una X‑dimension piccola può apparire allungata e causare errori di decodifica. Mira a un rapporto equilibrato (circa 3:1 a 5:1) a meno che le specifiche non indichino diversamente. +3. **Dimenticare di reimpostare i parametri** – Il generatore mantiene lo stato tra i salvataggi. Se cambi `BarHeight` per un'immagine e poi riutilizzi la stessa istanza per un altro codice a barre, l'altezza precedente rimarrà. Reimposta la proprietà o istanzia un nuovo `BarcodeGenerator` per ogni codice a barre distinto. + +## Esempio completo end‑to‑end (inclusa l'installazione di NuGet) + +Se parti da zero, segui questi passaggi per avviare il progetto: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Sostituisci il `Program.cs` generato automaticamente con il blocco di codice mostrato in precedenza, **ricordati di sostituire `YOUR_DIRECTORY`** con qualcosa come `Path.Combine(Environment.CurrentDirectory, "output")`. Poi: + +```bash +dotnet run +``` + +Dovresti vedere due file PNG nella cartella `output`: + +- `DatabarBarHeight30Pixels.png` – un codice a barre compatto alto 30 pixel. +- `DatabarBarHeight60Pixels.png` – una versione più alta di 60 pixel. + +Entrambe le immagini avranno un aspetto simile, ma la seconda presenterà barre visibilmente più lunghe, facilitando la lettura da parte di scanner a bassa risoluzione. + +![Barcode height example](/images/barcode-height.png){alt="output del generatore di codici a barre .net che mostra diverse altezze delle barre"} + +## Riepilogo e prossimi passi + +Abbiamo coperto come **generare immagini di codici a barre** usando un **.net barcode generator**, affinato la proprietà **change barcode height**, e salvato i risultati in formato PNG. I punti chiave sono: + +- Istanziare il generatore con il corretto `EncodeTypes`. +- Controllare le dimensioni visive tramite `XDimension` e `BarHeight`. +- Chiamare `Save` dopo ogni modifica per salvare una nuova immagine. +- Regolare risoluzione, formato, + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo passo per aiutarti a padroneggiare funzionalità aggiuntive dell'API ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Come generare un 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 creare un dotcode con testo esteso usando Aspose.BarCode per .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Come generare codici a barre 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/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/japanese/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..d3c95ab36 --- /dev/null +++ b/barcode/japanese/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-07-18 +description: C#でサイズを設定し、DataBar Stacked Omni‑Directional バーコード画像を生成するバーコードジェネレータの例です。バーコードのエンコードタイプをすぐに学べます。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: ja +lastmod: 2026-07-18 +og_description: バーコードジェネレータの例では、寸法の設定方法、バーコードエンコードタイプの選択方法、そして最小限のコードでバーコード画像を作成するC#プロジェクトの作成方法を案内します。 +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: バーコードジェネレータ例 – C#での高速DataBar画像作成 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: バーコードジェネレーター例 – C#でDataBar画像を作成 +url: /ja/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode Generator Example – Build DataBar Image in C# + +実際に使える **barcode generator example** が欲しくて、髪の毛を抜きそうになったことはありませんか? あなたは一人ではありません。多くの開発者が、DataBar Stacked Omni‑Directional バーコードの **how to set dimensions** を把握しようとしたときに、ドキュメントが専門用語の山に埋もれて壁にぶつかります。 + +このチュートリアルでは、**databar** 画像を生成し、適切な **barcode encode types** を選択し、最終的に **create barcode image c#** ファイルを作成できる、完全に実行可能な C# プログラムを順を追って解説します。余計な説明は省き、コピー&ペーストできるコードと各行の理由を示します。 + +## What You’ll Need + +- **.NET 6**(または最近の .NET バージョン) – 使用する API は .NET Standard を対象としているため、.NET Framework でも動作します。 +- **Aspose.BarCode for .NET** – `BarcodeGenerator` を提供するライブラリです。`Install-Package Aspose.BarCode` で NuGet から取得できます。 +- **C# IDE** – Visual Studio、Rider、または VS Code があれば OK。 +- PNG ファイルを保存するフォルダー(コードは `DatabarAspectRatio15.png` と `DatabarAspectRatio30.png` を作成します)。 + +すべて揃いましたか? では、始めましょう。 + +## Barcode Generator Example – Initialize the Generator + +まず最初に、**DataBar Stacked Omni‑Directional** シンボロジー用に設定された `BarcodeGenerator` のインスタンスが必要です。これが今回扱う **barcode encode type** です。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Why this matters:** `EncodeTypes.DatabarStackedOmniDirectional` は、Aspose に対してどのシンボロジーを描画すべきか正確に指示します。間違ったタイプを選んでも、画像が綺麗でもスキャナはバーコードを認識できません。 + +## How to Set Dimensions for the Barcode + +バーコードの読み取りやすさは **X‑dimension**(最細バーの幅)に依存します。多くの場合、2 ピクセルが適切ですが、プリンタや画面に合わせて調整可能です。 + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Pro tip:** 別のバーコードファミリーで **how to set dimensions** を調べたいときは、同じプロパティチェーン(`Parameters.Barcode.XDimension`)を使い、`Pixels` の値だけ変更すれば OK です。 + +## How to Generate DataBar Stacked Omni‑Directional Barcode + +ジェネレータの準備ができたら、**aspect ratio** プロパティを操作します。これにより DataBar の高さと幅の比率を調整でき、短くて四角いシンボルや、細長いシンボルを作成できます。 + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **What’s happening?** `AspectRatio = 15` は、バーの高さを幅の 15 倍にすることをエンジンに指示します。生成された PNG は実行ファイルと同じディレクトリに保存されます。 + +## Create Barcode Image C# – Changing the Aspect Ratio + +比率を 30 に変えて、2 番目のファイルを保存し、柔軟性を実証しましょう。 + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +プログラムを実行すると、次の 2 つの PNG ファイルが生成されます。 + +| ファイル | アスペクト比 | おおよそのサイズ | +|------|--------------|--------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +任意の画像ビューアで開くと、クリーンでスキャン可能な DataBar シンボルが確認できるはずです。 + +## Barcode Encode Types Overview (Optional but Handy) + +Aspose がサポートする他の **barcode encode types** に興味がある場合、以下の簡易表をご参照ください。 + +| EncodeTypes Enum | 説明 | +|------------------|------| +| `EncodeTypes.Code128` | 高密度の英数字 | +| `EncodeTypes.QR` | 2‑D マトリックスコード | +| `EncodeTypes.DatabarExpanded` | 小売向け GS1 DataBar | +| `EncodeTypes.DatabarStackedOmniDirectional` | **本チュートリアルの対象** – コンパクトで全方向対応 | + +正しい enum を選ぶことで、プロジェクト間の切り替え時に多くの試行錯誤を防げます。 + +## Common Pitfalls & How to Avoid Them + +- **Missing NuGet package** – `Aspose.BarCode` が無いとコードはコンパイルできません。まず `dotnet add package Aspose.BarCode` を実行してください。 +- **Wrong file path** – 絶対パスを使用する場合は、Windows のバックスラッシュ(`\\`)を忘れずに。相対パス(例示通り)を使うと移植性が向上します。 +- **Aspect ratio too extreme** – 50 以上の比率は、一般的なスキャナでは高さが大きすぎて認識できなくなることがあります。ほとんどのユースケースでは 15‑30 が推奨です。 + +## Full Source Code (Copy‑Paste Ready) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +プログラムを実行(`dotnet run` または Visual Studio で **F5**)すると、コンソールにファイルがディスクに保存された旨のメッセージが表示されます。 + +![Barcode generator example output showing DataBar barcode with aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Barcode generator example output showing DataBar barcode with aspect ratio 15"} + +## Wrapping Up + +これで **barcode generator example** が完成し、**how to set dimensions** の方法、適切な **barcode encode types** の選択、そして **create barcode image c#** ファイルの作成手順を実演しました。コードはシンプルで概念は明快です。これを土台に、テキストキャプションの追加、画像の回転、別シンボロジーへの切り替えなど、機能拡張に挑戦してみてください。 + +### What’s Next? + +- **異なる X‑dimension** を試して、スキャナの許容範囲がどう変わるか確認する。 +- `Code128` や `QR` など他の **EncodeTypes** を試し、ツールキットを拡充する。 +- バッチ生成を自動化:CSV の商品 ID をループで処理し、各 ID に対して PNG を出力する。 + +問題が発生したらコメントを残すか、Aspose.BarCode の公式ドキュメントを参照してください。豊富なサンプルが本チュートリアルを補完しています。 + +Happy coding, and may your barcodes always scan on the first try! + +## What Should You Learn Next? + +以下のチュートリアルは、本ガイドで示した手法に基づき、関連トピックを深掘りするためのものです。各リソースには、完全に動作するコード例とステップバイステップの解説が含まれており、API の追加機能を習得したり、別の実装アプローチを自分のプロジェクトで試したりするのに役立ちます。 + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/japanese/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/japanese/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..450459b73 --- /dev/null +++ b/barcode/japanese/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-07-18 +description: C#でPlanetバーコードを素早く作成。塗りつぶしバーと空白バーの生成方法、Xディメンションの設定、PNG画像の保存方法をすべて1つのチュートリアルで学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: ja +lastmod: 2026-07-18 +og_description: Planetバーコードをすぐに作成できます。このガイドでは、Xディメンションの設定、塗りつぶしバーと空白バーの切り替え、そして Aspose.BarCode + を使用した PNG ファイルのエクスポート方法を紹介します。 +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: C#でプラネットバーコードを作成 – 完全プログラミングチュートリアル +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: C#でPlanet Barcodeを作成する – 完全ステップバイステップガイド +url: /ja/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#でPlanetバーコードを作成 – 完全ステップバイステップガイド + +**create planet barcode** 画像を作成したいと思ったことはありますか、しかしどのプロパティを調整すればよいか分からなかったことはありませんか? あなたは一人ではありません。デフォルトの塗りつぶしバーが仕様と合わなかったり、バー幅をプリンターの DPI に合わせなければならない場合、多くの開発者が壁にぶつかります。 + +このチュートリアルでは、Aspose.BarCode ライブラリを使用して **create planet barcode** ファイルを作成する方法、**XDimension ピクセル** の制御方法、そして **filled bars** と **empty bars** をコードを書き換えることなく切り替える方法を正確に学びます。最後には、実線バーの PNG と空洞バーの PNG の 2 つのファイルが作成され、Planet シンボルを期待するあらゆる郵便システムで使用できるようになります。 + +## 前提条件 + +- .NET 6.0 以降 (コードは .NET Framework 4.7 + でも動作します) +- Aspose.BarCode for .NET NuGet パッケージ (`Install-Package Aspose.BarCode`) +- 基本的な C# の知識 (`using` ステートメントを後で使用する理由が分かります) +- PNG を保存するための書き込み可能なフォルダー + +これらが揃っていれば、すぐに実装に進むことができます。 + +## Step 1 – プロジェクトのセットアップとライブラリの追加 + +まず、新しいコンソール アプリ(または任意の C# プロジェクト)を作成し、**Planet barcode generator** ライブラリを参照します。 + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro tip:** Visual Studio でプロジェクトを右クリック → *Manage NuGet Packages* → **Aspose.BarCode** を検索し、*Install* をクリックします。これにより `BarcodeGenerator` と必要なすべての **BarcodeGenerator parameters** にアクセスできるようになります。 + +## Step 2 – Planet Barcode Generator の初期化 + +ここで実際に **create planet barcode** ジェネレーターのインスタンスを作成し、エンコードしたいデータ(この例では `"123456"`)を渡します。`EncodeTypes.Planet` 列挙体は、使用するシンボルをライブラリに指示します。 + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Why this matters:** `EncodeTypes.Planet` フラグは、Planet 郵便バーコードに必要な正しいチェックサムとレイアウト規則を自動的に適用するため、手動で計算する必要がありません。 + +## Step 3 – X‑Dimension(バー幅)の設定 + +多くのプリンターは各バーが特定のピクセル数であることを期待します。ここでは **XDimension ピクセル** を `4` に設定します。これは 203 dpi のサーマルプリンターで一般的な値です。 + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Edge case:** 300 dpi のプリンターを対象とする場合、代わりに `3` または `5` ピクセルが必要になることがあります。デバイスのドキュメントに基づいてこの値を調整してください。 + +## Step 4 – 塗りつぶしバー バージョンの保存 + +デフォルトではジェネレーターは **filled bars**(黒の実矩形)を生成します。これをディスクに書き込みましょう: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +`YOUR_DIRECTORY` を、アプリが書き込み可能な絶対パスまたは相対パスに置き換えてください。この行が実行されると、クラシックな Planet バーコードのような PNG ファイルが作成され、郵便スキャナーでのテストに最適です。 + +## Step 5 – 空バーへの切り替え + +時々、郵便サービスは「empty bars」スタイルを要求します。これはバーが黒く塗られる代わりに白い背景からくり抜かれる形式です。ライブラリはシンプルなスイッチを提供しています: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +`FilledBars` を `false` に設定すると、レンダラーはバーの塗りつぶしロジックを反転させます。新しい `BarcodeGenerator` インスタンスを作成する必要はなく、既存の **BarcodeGenerator parameters** を調整するだけです。 + +## Step 6 – 空バー バージョンの保存 + +最後に、2 番目の画像をエクスポートします: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +これで、異なる視覚要件に合わせた 2 つの PNG ファイルが作成されました。 + +## 完全な動作例 + +すべての要素を組み合わせた、コピー&ペーストで使用できる完全なプログラムは以下の通りです: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**期待される出力**(コンソール上): + +``` +Both Planet barcode images have been generated successfully. +``` + +`C:\Barcodes\` フォルダーには次のように表示されます: + +- `PostalPlanetFilledBars.png` – 黒の実線バー +- `PostalPlanetEmptyBars.png` – 黒い輪郭の白いバー + +任意の画像ビューアで開いてください。どちらも Planet 仕様に準拠しているはずです。 + +## よくある質問とヒント + +### 「画像形式を変更できますか?」 + +もちろんです。`Save` メソッドは `BarCodeImageFormat.Jpeg`、`Bmp`、`Gif` などを受け付けます。`BarCodeImageFormat.Png` を希望の形式に置き換えるだけです。 + +### 「バーコードの高さを変更したい場合は?」 + +垂直サイズを増減するには、`planetBarcode.Parameters.Barcode.BarHeight`(ポイント単位)を使用します。例: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### 「人が読めるキャプションを追加できますか?」 + +はい。`planetBarcode.Parameters.Caption` の `CodeText` プロパティを設定します: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### 「ジェネレーターを破棄する必要がありますか?」 + +`BarcodeGenerator` は `IDisposable` を実装しています。ループで多数のバーコードを作成する場合は、`using` ブロックでラップしてください: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### 「エラーハンドリングはどうすれば?」 + +`Save` 呼び出しを `try…catch` ブロックで囲み、`IOException`(ディスクの問題)や `ArgumentException`(無効なパラメータ)を捕捉します。例: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## まとめ + +C#で **create planet barcode** 画像を作成するために必要なすべてをカバーしました: + +1. データで **Planet barcode generator** を初期化します。 +2. プリンター仕様に合わせて **XDimension ピクセル** を調整します。 +3. **filled bars** の PNG を保存します。 +4. `FilledBars` を切り替えて **empty bars** を生成します。 +5. 2 番目の PNG を保存します。 + +ここからは、さらに多くの **BarcodeGenerator parameters** を調査したり、他のシンボル(`EncodeTypes.Postnet`、`EncodeTypes.Code128` など)を試したり、画像を郵送ワークフローに統合したりできます。 + +--- + +**次のステップに進む準備はできましたか?** 同じドキュメントに QR コードを追加したり、`foreach` ループを使って CSV リストから Planet バーコードのバッチを生成したりしてみてください。Aspose.BarCode API は大量処理、カスタムカラー、さらにはベクターベースの SVG 出力にも対応できる柔軟性があります。 + +問題が発生した場合は、下にコメントを残すか、公式の Aspose.BarCode ドキュメントで高度な機能の詳細を確認してください。コーディングを楽しんで! + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした、密接に関連するトピックをカバーしています。各リソースには、ステップバイステップの解説と完全な動作コード例が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを探求するのに役立ちます。 + +- [Aspose を使用したバーコード作成 - Java で X & Y 次元を設定](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [Aspose.BarCode を使用した Java で code128 バーコード画像を作成する方法](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [Java で code128 バーコードを作成し、バー高さを設定する方法](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/japanese/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..c104c1787 --- /dev/null +++ b/barcode/japanese/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-07-18 +description: C#でRM4SCCバーコードを素早く作成し、バーコードの高さの設定方法を学び、カスタム寸法でPlanetバーコードも生成します。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: ja +lastmod: 2026-07-18 +og_description: C#でRM4SCCバーコードを作成し、バーコードの高さの設定方法を確認してください。同じライブラリでPlanetバーコードを生成する方法もご覧ください。 +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: C#でRM4SCCバーコードを作成 – カスタム高さを高速に設定 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: C#でRM4SCCバーコードを作成 – 高さ設定の完全ガイド +url: /ja/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#でRM4SCCバーコードを作成 – 高さ設定の完全ガイド + +.NETアプリで **RM4SCCバーコードを作成** したいが、サイズの制御方法が分からないことはありませんか? あなたは一人ではありません。メールシステムや物流ダッシュボードを構築している場合でも、適切なバーコードの高さは、スキャンが成功するか失敗するかの違いを生む重要な要素です。 + +このチュートリアルでは、ライブラリのインストールから、**Planetバーコードを生成**するサイドバイサイドの例、そして両方のバーコードタイプに対する **バーコードの高さの設定方法** まで、全工程を順に解説します。最後まで実行すれば、必要な正確な寸法のPNGファイルを出力するコンソールアプリが完成します。 + +--- + +## 必要なもの + +- **.NET 6 SDK**(または最近の.NETバージョン) – コードは.NET Frameworkでも動作しますが、.NET 6が最適です。 +- **Aspose.BarCode for .NET** NuGetパッケージ – `BarcodeGenerator` クラスを提供するライブラリです。 +- C#の基礎知識 – 文法は初心者にも分かりやすくしています。 +- IDEまたはテキストエディタ(Visual Studio、VS Code、Riderなど、お好きなもの) + +> **Pro tip:** CI/CDパイプラインを使用している場合は、`.csproj` にNuGet参照を追加しておくと、ビルド時に依存関係が忘れられることはありません。 + +## Step 1: プロジェクトのセットアップ + +ターミナルを開き、次のコマンドで新しいコンソールプロジェクトを作成します: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +これで完了です—プロジェクトは、以降のすべての処理を支えるライブラリを参照するようになりました。 + +### Usingディレクティブの追加 + +`Program.cs` を開き、冒頭に以下を貼り付けます: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +これらの名前空間により、後で使用する `BarcodeGenerator` と画像フォーマット列挙型にアクセスできるようになります。 + +## Step 2: 画像保存用ヘルパーメソッドの定義 + +同じ保存ロジックを繰り返さないように、tinyメソッドでラップします。これにより、後で **バーコードの高さの設定方法** を示す例にもなります。 + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Why this matters:** 保存ロジックを一元化すると、要件が変わった際にフォーマットやフォルダーを一箇所だけ変更すれば済むようになります。 + +## Step 3: Planetバーコードの生成(“generate planet barcode”部分) + +RM4SCCの詳細に入る前に、**Planetバーコード** を作成してみましょう。これにより、ライブラリが正しく動作しているかをすぐに視覚的に確認できます。 + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Expected output:** `output` フォルダーに2つのPNGファイルが生成されます—1つはライブラリが自動計算した高さ、もう1つは正確に100 pxの高さです。 + +## Step 4: RM4SCCバーコードの作成 – 主目的 + +いよいよ本題の **RM4SCCバーコードの作成** です。RM4SCCはRoyal Mail 4‑State Codeの略で、英国の郵便システムで広く使用されています。 + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**What you’ll see:** +- `RM4SCCDefault.png` – ライブラリがX‑dimensionに基づいて快適な高さを自動決定します。 +- `RM4SCCHeight100.png` – 高さ100ピクセルの鮮明なバーコードで、封筒印刷に最適です。 + +> **Why set the height?** 一部のラベルプリンターは、確実なスキャンのために最小バー高さを要求します。高さを固定することで、デバイス間のコンプライアンスが保証されます。 + +## Step 5: 高さ設定の理解(“how to set barcode height”への回答) + +Planet と RM4SCC の例はどちらも同じプロパティを使用しています: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** は `BarHeight` オブジェクトで、ピクセル、ミリメートル、インチなど複数の測定単位をまとめます。 +- **`.Pixels`** は画面向け出力で最もシンプルな単位ですが、印刷媒体を対象とする場合は `.Millimeters` や `.Inches` も使用できます。 + +### エッジケースとヒント + +| Situation | Recommended Approach | +|-----------|----------------------| +| **非常に小さいX‑dimension(例:1 px)** | `BarHeight` を増やしてバーコードの可読性を保ちます。 | +| **高解像度ラベルプリンターで印刷** | デバイスに依存しないサイズ指定のために `.Millimeters` を使用します。 | +| **1つの画像に混在するバーコードタイプ** | 各ジェネレータで `XDimension` の後に `BarHeight` を設定し、意図しない継承を防ぎます。 | +| **動的データ(例:ユーザー入力コード)** | `code` と `height` パラメータを受け取るメソッドでジェネレータ作成をラップします。 | + +## Step 6: 完全動作サンプル + +以下は `Program.cs` にコピー&ペーストできる、単一の自己完結型プログラムです。プロジェクトのセットアップから画像保存まで、すべてが含まれています。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +次のコマンドで実行します: + +```bash +dotnet run +``` + +コンソールに各ファイルが保存されたことが確認でき、`output` フォルダーには上記で示した名前の4つのPNGが格納されます。 + +## Conclusion + +これで **C#でRM4SCCバーコードを作成** し、数行のプロパティ設定だけでサイズを制御できるようになりました。**Planetバーコードの生成** も簡単なサニティチェックとしてカバーし、**バーコードの高さの設定方法** をさまざまな印刷シナリオで検討しました。 + +次のステップは? `EncodeTypes` 列挙体を他のシンボロジー(Code128、QR、DataMatrix)に置き換えてみたり、印刷品質の高いプリンター向けに `BarHeight` をミリメートルで試したりしてください。PDFにバーコードを埋め込む必要がある場合は、Aspose.BarCode と Aspose.PDF を組み合わせると強力です。 + +質問がある、あるいは独自の調整を共有したい方は、下のコメント欄にどうぞ。Happy coding! + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを基にした、密接に関連するトピックを扱っています。各リソースには、完全な動作コード例とステップバイステップの解説が含まれており、追加のAPI機能を習得したり、プロジェクトで代替実装アプローチを探求したりするのに役立ちます。 + +- [Aspose.BarCode for .NET を使用したカスタムアスペクト比の Aztec バーコード生成](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Aspose.BarCode for .NET を使用した ITF-14 のバーコードクワイエットゾーン作成](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Aspose.BarCode for .NET を使用した Code 16K のバーコードクワイエットゾーン作成](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/japanese/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..300a13ee1 --- /dev/null +++ b/barcode/japanese/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-07-18 +description: .NETのバーコードジェネレータでバーコード画像を生成する方法と、GS1‑Databar Omni‑Directionalシンボルのバーコード高さを簡単に変更する方法を学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: ja +lastmod: 2026-07-18 +og_description: .NET バーコードジェネレーターは、バーコード画像を迅速に作成できます。このガイドでは、バーコードの生成方法、バーの高さの調整、PNG + ファイルの保存方法を示します。 +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: .NET バーコードジェネレータでバーコードの高さを変更する +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET バーコードジェネレーター – バーコードの高さを変更 +url: /ja/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net バーコードジェネレーター – バーコードの高さを変更する + +サードパーティ製ツールを何十個も使い分けることなく、**バーコードを生成する方法**を知りたくありませんか? .NET の世界では、驚くほどシンプルな方法があり、その鍵となるのが **.net barcode generator** です。数行の C# だけで GS1‑Databar Omni‑Directional シンボルを作成し、バーの高さを調整し、結果を PNG ファイルとして出力できます。 + +在庫管理システムや出荷ラベルプリンター、あるいはスキャン可能なコードが必要なアプリを作成しているなら、このチュートリアルで数分で動作するバーコードを作成できます。完全なコードを順に解説し、各設定がなぜ重要かを説明し、**バーコードの高さを変更**する方法を仕様を壊さずに示します。 + +## 必要なもの + +- .NET 6.0 以降(API は .NET Framework 4.7+ でも同様に動作します) +- バーコードライブラリへの参照(例: Aspose.BarCode for .NET – 多くの商用キットで同じクラスが使用されています) +- 開発環境(Visual Studio、Rider、または C# 拡張機能付き VS Code) +- 書き込み権限のあるフォルダー – チュートリアルは PNG ファイルをそこに保存します + +以上です。バーコードライブラリ以外に追加の NuGet パッケージは必要ありません。 + +## .net barcode generator を使用してバーコードの高さを変更する + +以下は **完全な実行可能コンソールプログラム** です。新しい C# プロジェクトに貼り付け、出力フォルダーを調整し、F5 キーで実行してください。 + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### 各行が重要な理由 + +| 行 | 理由 | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | 目的のシンボルとデータペイロードで **.net barcode generator** のインスタンスを作成します。`EncodeTypes.DatabarOmniDirectional` 列挙体は、ライブラリに GS1‑Databar Omni‑Directional 形式を使用するよう指示します。 | +| `XDimension.Pixels = 2;` | X‑dimension は最も細いバーの幅を表します。*2 ピクセル* に設定すると、ほとんどのモニターで鮮明な画像が得られ、ファイルサイズも小さく抑えられます。 | +| `BarHeight.Pixels = 30;` | これは **バーコードの高さを変更** するステップで、各バーの高さを決定します。30 ピクセルの高さは小さなラベルに適したデフォルトです。 | +| `generator.Save(...);` | バーコードを PNG ファイルとして保存します。PNG はロスレス形式なので、スキャナーは生成した正確なパターンを読み取れます。 | +| `BarHeight.Pixels = 60;` | ここで再び **バーコードの高さを変更** します—今回は 60 ピクセルです。`Save` を2回目に呼び出すと、ライブラリは新しい寸法でシンボルを自動的に再描画します。 | +| `Console.WriteLine(...);` | 例外が発生せずに処理が完了したことをすぐにフィードバックします。 | + +> **プロのコツ:** 印刷用に高解像度の出力が必要な場合は、`BarCodeImageFormat.Png` を `BarCodeImageFormat.Tiff` に切り替え、`Resolution` プロパティを上げてください(例: `generator.Parameters.ImageResolution = 300;`)。バーの高さは引き続き尊重され、より細かい DPI で描画されます。 + +## 異なる設定でバーコード画像を生成する方法 + +上記のスニペットは基本をカバーしていますが、実際のシナリオでは追加の調整が必要になることが多いです: + +### 大きな印刷向けに X‑dimension を調整する +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +X‑dimension を増やすと、エンコードされたデータは変わらずにバーコード全体が大きくなります。大きなラベルに印刷する際に便利です。 + +### 出力フォーマットの切り替え +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG は無限にスケールできるため、鮮明なベクタが必要なウェブベースのスキャナーに最適です。 + +### 人が読めるテキストの追加 +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +`CodeTextVisible` を有効にすると、バーコードの下に生データが付加され、テスト時の検証に役立ちます。 + +## **バーコードの高さを変更**する際の一般的な落とし穴 + +1. **高さが小さすぎる** – 一部のスキャナーは最小バー高さ(物理単位でしばしば 10 mm)を要求します。`BarHeight.Pixels` を低すぎる値に設定すると、実際のスキャナーで画像が読めなくなる可能性があります。必ず対象ハードウェアでテストしてください。 +2. **X‑dimension と高さの不一致** – 非常に大きなバー高さに対し X‑dimension が極小だと、バーが伸びすぎて見た目が不自然になり、デコードエラーを引き起こすことがあります。仕様で別途指示がない限り、概ね 3:1〜5:1 のバランスを目指してください。 +3. **パラメータのリセット忘れ** – ジェネレーターは保存間で状態を保持します。ある画像で `BarHeight` を変更した後、同じインスタンスを別のバーコードに再利用すると、前の高さが残ります。プロパティをリセットするか、バーコードごとに新しい `BarcodeGenerator` をインスタンス化してください。 + +## NuGet インストールを含むフルエンドツーエンド例 + +ゼロから始める場合は、以下の手順でプロジェクトを実行できるようにしてください: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +自動生成された `Program.cs` を先ほどのコードブロックに置き換え、**`YOUR_DIRECTORY` を `Path.Combine(Environment.CurrentDirectory, "output")` のように置き換えることを忘れずに**。その後: + +```bash +dotnet run +``` + +`output` フォルダーに 2 つの PNG ファイルが作成されているはずです: + +- `DatabarBarHeight30Pixels.png` – コンパクトな 30 ピクセルのバーコード。 +- `DatabarBarHeight60Pixels.png` – より高い 60 ピクセルのバーコード。 + +両画像は見た目は似ていますが、2 番目はバーが目立って長くなるため、低解像度スキャナーでも読み取りやすくなります。 + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator の出力(異なるバー高さを表示)"} + +## まとめと次のステップ + +**.net barcode generator** を使用して **バーコードを生成** する方法、**バーコードの高さを変更** プロパティの微調整、そして PNG 形式で結果を保存する方法をカバーしました。主なポイントは次のとおりです: + +- 正しい `EncodeTypes` でジェネレーターをインスタンス化する。 +- `XDimension` と `BarHeight` で視覚的サイズを制御する。 +- 各変更後に `Save` を呼び出して新しい画像を保存する。 +- 解像度やフォーマットを調整する、 + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックを扱っています。各リソースには、ステップバイステップの解説と完全な動作コード例が含まれており、追加の 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 create dotcode extended codetext with Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-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/korean/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/korean/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..af80ebffd --- /dev/null +++ b/barcode/korean/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-07-18 +description: C#에서 차원을 설정하고 DataBar Stacked Omni‑Directional 바코드 이미지를 생성하는 방법을 보여주는 + 바코드 생성기 예제입니다. 바코드 인코딩 유형을 빠르게 배우세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: ko +lastmod: 2026-07-18 +og_description: 바코드 생성기 예제는 차원 설정, 바코드 인코드 유형 선택 및 최소한의 코드로 바코드 이미지 C# 프로젝트를 만드는 방법을 + 단계별로 안내합니다. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: 바코드 생성기 예제 – C#에서 빠른 DataBar 이미지 생성 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: 바코드 생성기 예제 – C#에서 DataBar 이미지 만들기 +url: /ko/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 바코드 생성기 예제 – C#에서 DataBar 이미지 만들기 + +실제 바코드를 출력하는 **barcode generator example**가 필요했던 적 있나요? 머리카락이 빠질 정도로 고민한 적이 있다면 혼자가 아닙니다. 대부분의 개발자는 특히 문서가 전문 용어로 가득 차 있을 때 DataBar Stacked Omni‑Directional 바코드의 **how to set dimensions**를 파악하는 데 벽에 부딪칩니다. + +이 튜토리얼에서는 완전하고 바로 실행 가능한 C# 프로그램을 단계별로 살펴보며 **how to generate databar** 이미지 생성, 올바른 **barcode encode types** 선택, 그리고 최종적으로 **create barcode image c#** 파일을 만들어 어떤 프로젝트에도 삽입할 수 있게 합니다. 불필요한 내용은 없습니다—복사‑붙여넣기 할 수 있는 코드와 각 라인 뒤에 있는 이유만 제공합니다. + +## 필요 사항 + +- **.NET 6** (또는 최신 .NET 버전) – 우리가 사용하는 API는 .NET Standard를 목표로 하므로 .NET Framework에서도 동작합니다. +- **Aspose.BarCode for .NET** – `BarcodeGenerator`를 제공하는 라이브러리입니다. NuGet에서 `Install-Package Aspose.BarCode` 명령으로 설치할 수 있습니다. +- **C# IDE** – Visual Studio, Rider, 또는 VS Code 중 하나면 충분합니다. +- PNG 파일이 저장될 디스크상의 폴더(코드가 `DatabarAspectRatio15.png`와 `DatabarAspectRatio30.png`를 생성합니다). + +다 준비되셨나요? 좋습니다—시작해봅시다. + +## 바코드 생성기 예제 – 생성기 초기화 + +우선, **DataBar Stacked Omni‑Directional** 심볼로지를 사용하도록 설정된 `BarcodeGenerator` 인스턴스가 필요합니다. 이것이 우리가 작업할 **barcode encode type**입니다. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **왜 중요한가:** `EncodeTypes.DatabarStackedOmniDirectional`는 Aspose에 정확히 어떤 심볼로지를 렌더링할지 알려줍니다. 잘못된 타입을 선택하면 이미지가 아무리 예뻐도 스캐너가 바코드를 인식하지 못합니다. + +## 바코드 차원 설정 방법 + +바코드 가독성은 **X‑dimension**(가장 얇은 바의 너비)에 달려 있습니다. 대부분의 경우 2 픽셀 값이면 충분하지만 프린터나 화면에 맞게 조정할 수 있습니다. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **팁:** 다른 바코드 패밀리의 **how to set dimensions**가 궁금하다면 동일한 속성 체인(`Parameters.Barcode.XDimension`)을 사용하면 됩니다—`Pixels` 값을 바꾸기만 하면 됩니다. + +## DataBar Stacked Omni‑Directional 바코드 생성 방법 + +이제 생성기가 준비되었으니 **aspect ratio** 속성을 조정해 보겠습니다. 이 속성은 DataBar의 높이‑대‑너비 비율을 제어하여 짧고 정사각형에 가까운 심볼이나 높고 좁은 심볼을 만들 수 있게 합니다. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **무슨 일인가요?** `AspectRatio = 15`는 엔진에게 바의 높이를 너비보다 15배 크게 만들도록 지시합니다. 결과 PNG는 실행 파일 바로 옆에 저장됩니다. + +## Create Barcode Image C# – Aspect Ratio 변경하기 + +비율을 30으로 바꾸고 두 번째 파일을 저장하여 유연성을 확인해 봅시다. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +프로그램을 실행하면 두 개의 PNG 파일이 생성됩니다: + +| 파일 | 비율 | 대략적인 크기 | +|------|------|--------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +이미지 뷰어에서 열어보세요—깨끗하고 스캔 가능한 DataBar 심볼이 보일 것입니다. + +## Barcode Encode Types 개요 (선택 사항이지만 유용함) + +Aspose가 지원하는 다른 **barcode encode types**에 궁금하다면, 간단한 요약표를 확인하세요: + +| EncodeTypes 열거형 | 설명 | +|------------------|-------------| +| `EncodeTypes.Code128` | 고밀도 영숫자 | +| `EncodeTypes.QR` | 2‑D 매트릭스 코드 | +| `EncodeTypes.DatabarExpanded` | 소매용 GS1 DataBar | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Our focus** – 컴팩트하고 전방향 | + +## 흔히 발생하는 실수와 회피 방법 + +- **Missing NuGet package** – `Aspose.BarCode`가 없으면 코드를 컴파일할 수 없습니다. 먼저 `dotnet add package Aspose.BarCode`를 실행하세요. +- **Wrong file path** – 절대 경로를 사용할 경우 Windows에서 백슬래시(`\\`)를 다시 확인하세요. (예시와 같이) 상대 경로를 사용하면 이식성이 유지됩니다. +- **Aspect ratio too extreme** – 비율이 50을 초과하면 일반 스캐너에 너무 높아질 수 있습니다. 대부분의 경우 15‑30 사이를 유지하세요. + +## 전체 소스 코드 (복사‑붙여넣기 준비됨) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +프로그램을 실행하세요(`dotnet run` 또는 Visual Studio에서 **F5** 키). 그러면 파일이 디스크에 저장되었음을 확인하는 콘솔 메시지가 표시됩니다. + +![바코드 생성기 예제 출력 (측면 비율 15인 DataBar 바코드 표시)](placeholder/path/to/image.png){: .align-center alt="바코드 생성기 예제 출력 (측면 비율 15인 DataBar 바코드 표시)"} + +## 마무리 + +우리는 **barcode generator example**를 완성했으며, **how to set dimensions**를 보여주고 올바른 **barcode encode types**를 선택한 뒤, 어디에든 삽입할 수 있는 **create barcode image c#** 파일을 생성했습니다. 코드는 작고 개념은 명확하며, 이제 텍스트 캡션 추가, 이미지 회전, 혹은 다른 심볼로지로 전환하는 등 솔루션을 확장할 탄탄한 기반을 갖추었습니다. + +### 다음 단계 + +- 스캐너 허용 오차가 어떻게 변하는지 확인하기 위해 **different X‑dimensions**를 실험해 보세요. +- `Code128`이나 `QR`과 같은 다른 **EncodeTypes**를 시도해 도구 모음을 확장하세요. +- 배치 생성 자동화: 제품 ID가 들어 있는 CSV를 순회하면서 각각에 대해 PNG를 생성합니다. + +문제가 발생하면 아래에 댓글을 남기거나 Aspose.BarCode 문서를 확인하세요—여기서 다룬 내용과 보완되는 예제가 많이 있습니다. + +코딩 즐겁게 하시고, 바코드가 언제나 첫 번째 시도에서 스캔되길 바랍니다! + +## 다음에 배울 내용은? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 주제를 다룹니다. 각 자료는 완전한 작동 코드 예제와 단계별 설명을 포함하여 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색하도록 돕습니다. + +- [바코드 생성 방법 - 1차원 바코드 유형](/barcode/english/net/one-dimensional-barcode-types/) +- [바코드 이미지 C# 생성 – GS1 DataMatrix 예제](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/korean/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/korean/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..708cda65c --- /dev/null +++ b/barcode/korean/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-07-18 +description: C#로 Planet 바코드를 빠르게 만들기. 채워진 바와 빈 바를 생성하고, X‑디멘션을 설정하며, PNG 이미지를 저장하는 + 방법을 한 번에 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: ko +lastmod: 2026-07-18 +og_description: Planet 바코드를 즉시 생성하세요. 이 가이드는 X‑디멘션을 설정하고, 채워진 바와 비어있는 바를 전환하며, Aspose.BarCode로 + PNG 파일을 내보내는 방법을 보여줍니다. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: C#로 행성 바코드 만들기 – 완전한 프로그래밍 워크스루 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: C#로 플래닛 바코드 만들기 – 전체 단계별 가이드 +url: /ko/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 Planet 바코드 만들기 – 전체 단계별 가이드 + +Planet 바코드 이미지를 **생성**해야 하는데 어떤 속성을 조정해야 할지 몰라 고민한 적 있나요? 혼자가 아닙니다. 기본 채워진 막대가 사양에 맞지 않거나, 막대 너비가 프린터 DPI와 일치해야 할 때 많은 개발자가 막히곤 합니다. + +이 튜토리얼에서는 Aspose.BarCode 라이브러리를 사용해 **Planet 바코드** 파일을 정확히 만드는 방법, **XDimension 픽셀**을 제어하는 방법, 그리고 코드를 다시 작성하지 않고 **채워진 막대**와 **비어있는 막대** 사이를 전환하는 방법을 배웁니다. 마지막에는 두 개의 PNG 파일(하나는 실선 막대, 하나는 빈 막대)이 생성되어 Planet 심볼을 요구하는 모든 우편 시스템에 바로 사용할 수 있습니다. + +## Prerequisites + +- .NET 6.0 이상 (코드는 .NET Framework 4.7 +에서도 작동합니다) +- Aspose.BarCode for .NET NuGet 패키지 (`Install-Package Aspose.BarCode`) +- 기본 C# 지식 (`using` 문이 왜 필요한지 나중에 확인해 보세요) +- PNG를 저장할 수 있는 쓰기 가능한 폴더 + +위 항목을 모두 갖추었다면 바로 구현 단계로 넘어갈 수 있습니다. + +## Step 1 – Set Up the Project and Add the Library + +먼저 새 콘솔 앱(또는 任意 C# 프로젝트)을 만들고 **Planet 바코드 생성기** 라이브러리를 참조합니다. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro tip:** Visual Studio에서 프로젝트를 우클릭 → *Manage NuGet Packages* → **Aspose.BarCode**를 검색하고 *Install*를 클릭합니다. 이렇게 하면 `BarcodeGenerator`와 필요한 **BarcodeGenerator parameters**를 사용할 수 있게 됩니다. + +## Step 2 – Initialise the Planet Barcode Generator + +이제 실제로 **Planet 바코드** 생성기 인스턴스를 만들고 인코딩할 데이터(`"123456"` 예시)를 전달합니다. `EncodeTypes.Planet` 열거형은 라이브러리에 사용할 심볼을 알려줍니다. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Why this matters:** `EncodeTypes.Planet` 플래그는 Planet 우편 바코드에 맞는 체크섬과 레이아웃 규칙을 자동으로 적용하므로 직접 계산할 필요가 없습니다. + +## Step 3 – Configure X‑Dimension (Bar Width) + +대부분의 프린터는 각 막대가 특정 픽셀 수를 갖길 기대합니다. 여기서는 **XDimension 픽셀**을 `4`로 설정합니다. 이는 203 dpi 열전사 프린터에서 흔히 사용되는 값입니다. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Edge case:** 300 dpi 프린터를 목표로 한다면 `3` 또는 `5` 픽셀로 조정해야 할 수도 있습니다. 장치 문서를 참고해 값을 맞추세요. + +## Step 4 – Save the Filled‑Bar Version + +기본적으로 생성기는 **채워진 막대**(실선 검은 사각형)를 출력합니다. 이를 디스크에 저장해 보겠습니다. + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +`YOUR_DIRECTORY`를 앱이 쓸 수 있는 절대 경로나 상대 경로로 바꾸세요. 이 라인이 실행된 후에는 클래식한 Planet 바코드와 같은 PNG 파일이 생성되어 우편 스캐너 테스트에 바로 사용할 수 있습니다. + +## Step 5 – Switch to Empty Bars + +일부 우편 서비스는 흰 배경에 검은 윤곽선만 남기는 “빈 막대” 스타일을 요구합니다. 라이브러리는 간단한 스위치를 제공합니다: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +`FilledBars`를 `false`로 설정하면 렌더러가 막대 채우기 로직을 반전시킵니다. 새 `BarcodeGenerator` 인스턴스를 만들 필요 없이 기존 **BarcodeGenerator parameters**만 수정하면 됩니다. + +## Step 6 – Save the Empty‑Bar Version + +마지막으로 두 번째 이미지를 내보냅니다: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +이제 서로 다른 시각적 요구사항을 만족하는 두 개의 PNG 파일이 준비되었습니다. + +## Full Working Example + +모든 코드를 한데 모아 복사‑붙여넣기만 하면 동작하는 전체 프로그램은 다음과 같습니다: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Expected output** (on the console): + +``` +Both Planet barcode images have been generated successfully. +``` + +그리고 `C:\Barcodes\` 폴더에는 다음 파일이 생성됩니다: + +- `PostalPlanetFilledBars.png` – 실선 검은 막대 +- `PostalPlanetEmptyBars.png` – 흰 배경에 검은 윤곽선 + +이미지 뷰어로 열어보면 두 파일 모두 Planet 사양을 충족합니다. + +## Common Questions & Tips + +### “이미지 형식을 바꿀 수 있나요?” + +물론 가능합니다. `Save` 메서드는 `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` 등 다양한 형식을 지원합니다. `BarCodeImageFormat.Png`를 원하는 형식으로 교체하면 됩니다. + +### “바코드 높이를 다르게 지정하려면?” + +`planetBarcode.Parameters.Barcode.BarHeight`(포인트 단위)를 사용해 수직 크기를 늘리거나 줄일 수 있습니다. 예시: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “사람이 읽을 수 있는 캡션을 추가할 수 있나요?” + +네. `planetBarcode.Parameters.Caption`의 `CodeText` 속성을 설정하면 됩니다: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “Generator를 반드시 Dispose 해야 하나요?” + +`BarcodeGenerator`는 `IDisposable`을 구현합니다. 루프 안에서 여러 바코드를 생성한다면 `using` 블록으로 감싸는 것이 좋습니다: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “오류 처리는 어떻게 하나요?” + +`Save` 호출을 `try…catch` 블록으로 감싸 `IOException`(디스크 문제)이나 `ArgumentException`(잘못된 매개변수) 등을 잡아낼 수 있습니다. 예시: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Recap + +C#에서 **Planet 바코드** 이미지를 만들기 위해 알아야 할 모든 내용을 정리하면 다음과 같습니다: + +1. 데이터를 사용해 **Planet 바코드 생성기**를 초기화합니다. +2. 프린터 사양에 맞게 **XDimension 픽셀**을 조정합니다. +3. **채워진 막대** PNG를 저장합니다. +4. `FilledBars`를 토글해 **빈 막대**를 생성합니다. +5. 두 번째 PNG를 저장합니다. + +이제 더 많은 **BarcodeGenerator parameters**를 탐색하고, 다른 심볼(`EncodeTypes.Postnet`, `EncodeTypes.Code128` 등)을 실험하거나, 메일링 워크플로에 이미지를 통합해 보세요. + +--- + +**다음 단계가 준비되셨나요?** 동일 문서에 QR 코드를 추가하거나 CSV 목록을 `foreach` 루프로 읽어 다수의 Planet 바코드를 생성해 보세요. Aspose.BarCode API는 대량 작업, 사용자 정의 색상, 벡터 기반 SVG 출력까지 유연하게 지원합니다. + +문제가 발생하면 아래 댓글을 남기거나 공식 Aspose.BarCode 문서를 참고해 고급 기능을 깊이 파고들어 보세요. 즐거운 코딩 되세요! + + +## What Should You Learn Next? + +다음 튜토리얼들은 이 가이드에서 다룬 기술을 기반으로 하여 관련 주제를 자세히 설명합니다. 각 리소스는 완전한 코드 예제와 단계별 설명을 제공하므로 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용하는 데 도움이 됩니다. + +- [Create Barcode with Aspose - Set X & Y Dimensions in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/korean/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..64a00d972 --- /dev/null +++ b/barcode/korean/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-07-18 +description: C#에서 RM4SCC 바코드를 빠르게 생성하고, 바코드 높이 설정 방법을 배우며, 맞춤형 크기로 Planet 바코드도 생성합니다. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: ko +lastmod: 2026-07-18 +og_description: C#에서 RM4SCC 바코드를 생성하고 바코드 높이를 설정하는 방법을 알아보세요. 또한 같은 라이브러리를 사용하여 Planet + 바코드를 생성하는 방법도 확인하세요. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: C#에서 RM4SCC 바코드 만들기 – 맞춤 높이 빠르게 설정 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: C#에서 RM4SCC 바코드 만들기 – 높이 설정 전체 가이드 +url: /ko/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 RM4SCC 바코드 생성 – 높이 설정 전체 가이드 + +.NET 앱에서 **RM4SCC 바코드**를 생성해야 했지만 크기를 제어하는 방법을 몰랐던 적이 있나요? 당신만 그런 것이 아닙니다. 메일링 시스템이나 물류 대시보드를 구축하든, 올바른 바코드 높이는 스캔이 성공하는지 실패하는지를 가르는 차이가 될 수 있습니다. + +이 튜토리얼에서는 라이브러리 설치부터 **Planet 바코드 생성**을 나란히 예시로 보여주고, 마지막으로 두 바코드 유형 모두에 대해 **바코드 높이 설정 방법**을 다룰 것입니다. 끝까지 따라오시면 정확한 치수의 PNG 파일을 출력하는 실행 가능한 콘솔 앱을 손에 넣게 됩니다. + +--- + +## 준비물 + +- **.NET 6 SDK** (또는 최신 .NET 버전) – 코드는 .NET Framework에서도 동작하지만 .NET 6이 가장 적합합니다. +- **Aspose.BarCode for .NET** NuGet 패키지 – `BarcodeGenerator` 클래스를 제공하는 라이브러리입니다. +- 약간의 C# 지식 – 문법은 초보자도 이해하기 쉽게 구성했습니다. +- IDE 또는 텍스트 편집기 (Visual Studio, VS Code, Rider 등 원하는 도구) + +> **프로 팁:** CI/CD 파이프라인을 사용한다면 `.csproj` 파일에 NuGet 참조를 추가해 두면 빌드 시마다 의존성을 잊어버리지 않습니다. + +--- + +## Step 1: 프로젝트 설정 + +터미널을 열고 새 콘솔 프로젝트를 생성합니다: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +이제 프로젝트가 모든 후속 작업에 필요한 라이브러리를 참조하게 됩니다. + +### Using 지시문 추가 + +`Program.cs` 파일을 열고 상단에 다음 코드를 붙여넣으세요: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +이 네임스페이스들을 통해 `BarcodeGenerator`와 이미지 포맷 열거형에 접근할 수 있습니다. + +--- + +## Step 2: 이미지 저장을 위한 헬퍼 메서드 정의 + +동일한 저장 로직을 반복하지 않기 위해 작은 메서드로 감싸겠습니다. 이 메서드는 **바코드 높이 설정 방법**을 나중에 보여줄 때도 활용됩니다. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **왜 중요한가:** 저장 로직을 중앙화하면 포맷이나 폴더 경로가 바뀔 때 한 곳만 수정하면 되므로 유지보수가 쉬워집니다. + +--- + +## Step 3: Planet 바코드 생성 ( “generate planet barcode” 부분) + +RM4SCC에 들어가기 전에 **Planet 바코드**를 한 번 만들어 보겠습니다. 라이브러리가 정상 작동하는지 빠르게 확인할 수 있는 시각적 검증 단계입니다. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**예상 출력:** `output` 폴더에 두 개의 PNG 파일이 생성됩니다 – 하나는 라이브러리가 자동 계산한 높이, 다른 하나는 정확히 100 px 높이입니다. + +--- + +## Step 4: RM4SCC 바코드 생성 – 주요 목표 + +이제 본격적으로 **RM4SCC 바코드**를 만들어 보겠습니다. RM4SCC는 영국 우편 시스템에서 널리 사용되는 Royal Mail 4‑State Code입니다. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**출력 결과:** +- `RM4SCCDefault.png` – 라이브러리가 X‑dimension을 기준으로 적절한 높이를 자동 결정합니다. +- `RM4SCCHeight100.png` – 정확히 100픽셀 높이의 바코드로, 봉투 인쇄에 바로 사용할 수 있습니다. + +> **왜 높이를 지정해야 할까?** 일부 라벨 프린터는 안정적인 스캔을 위해 최소 바 높이를 요구합니다. 높이를 고정하면 모든 장치에서 규격을 만족하게 됩니다. + +--- + +## Step 5: 높이 설정 이해하기 ( “how to set barcode height” 답변) + +Planet과 RM4SCC 예제 모두 동일한 속성을 사용합니다: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`**는 픽셀, 밀리미터, 인치 등 여러 측정 단위를 묶은 `BarHeight` 객체입니다. +- **`.Pixels`**는 화면‑중심 출력에 가장 직관적인 단위이며, 필요에 따라 `.Millimeters` 또는 `.Inches`를 사용해 인쇄 매체에 맞출 수 있습니다. + +### 엣지 케이스 및 팁 + +| 상황 | 권장 접근법 | +|-----------|----------------------| +| **X‑dimension이 매우 작을 때 (예: 1 px)** | 바코드 가독성을 유지하려면 `BarHeight`를 늘리세요. | +| **고해상도 라벨 프린터에 인쇄할 경우** | 장치 독립적인 크기 지정이 가능한 `.Millimeters`를 사용하세요. | +| **하나의 이미지에 여러 바코드 유형을 섞을 경우** | 각 `BarcodeGenerator`에 대해 `XDimension` 설정 후 `BarHeight`를 지정해 상속을 방지하세요. | +| **동적 데이터 (예: 사용자 입력 코드)** | `code`와 `height` 매개변수를 받는 메서드로 생성 로직을 감싸세요. | + +--- + +## Step 6: 전체 작업 예제 + +아래 코드는 `Program.cs`에 그대로 복사‑붙여넣기 할 수 있는 단일 프로그램입니다. 프로젝트 설정부터 이미지 저장까지 모든 과정을 포함하고 있습니다. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +다음 명령으로 실행합니다: + +```bash +dotnet run +``` + +콘솔에 각 파일 저장이 확인되는 메시지가 출력되고, `output` 폴더에 위에서 언급한 네 개의 PNG 파일이 생성됩니다. + +--- + +## 결론 + +이제 C#에서 **RM4SCC 바코드 생성**과 몇 줄의 속성 할당만으로 높이를 제어하는 방법을 알게 되었습니다. 또한 **Planet 바코드 생성**을 통해 빠른 검증을 수행했으며, 다양한 인쇄 시나리오에 맞는 **바코드 높이 설정**의 미묘한 차이도 이해했습니다. + +다음 단계는? `EncodeTypes` 열거형을 다른 심볼(예: Code128, QR, DataMatrix)으로 교체하고, 고해상도 프린터를 위해 `BarHeight`를 밀리미터 단위로 실험해 보세요. 바코드를 PDF에 삽입해야 한다면 Aspose.BarCode와 Aspose.PDF를 조합하면 강력한 솔루션이 됩니다. + +질문이 있거나 직접 만든 팁을 공유하고 싶다면 아래 댓글에 남겨 주세요. 즐거운 코딩 되세요! + +## What Should You Learn Next? + +다음 튜토리얼들은 이 가이드에서 다룬 기술을 기반으로 하며, 추가 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 Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [How to create barcode quiet zone for Code 16K using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/korean/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..e9151f8a2 --- /dev/null +++ b/barcode/korean/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-07-18 +description: .net 바코드 생성기를 사용하여 바코드 이미지를 생성하는 방법을 배우고, GS1‑Databar Omni‑Directional + 기호의 바코드 높이를 쉽게 변경하세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: ko +lastmod: 2026-07-18 +og_description: .NET 바코드 생성기는 바코드 이미지를 빠르게 만들 수 있게 해줍니다. 이 가이드는 바코드 생성 방법, 바 높이 조정 + 및 PNG 파일 저장 방법을 보여줍니다. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: .NET 바코드 생성기로 바코드 높이 변경 +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET 바코드 생성기 – 바코드 높이 변경 +url: /ko/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – 바코드 높이 변경 + +수많은 서드파티 도구를 사용하지 않고도 **바코드 생성 방법**을 궁금해 본 적 있나요? .NET 세계에서는 놀라울 정도로 간단하게 할 수 있는 방법이 있으며, 핵심은 **.net barcode generator**입니다. 몇 줄의 C# 코드만으로 GS1‑Databar Omni‑Directional 심볼을 만들고, 바 높이를 조정한 뒤 PNG 파일로 저장할 수 있습니다. + +재고 관리 시스템, 배송 라벨 프린터, 혹은 스캔 가능한 코드를 필요로 하는 앱을 개발하고 있다면, 이 튜토리얼을 통해 몇 분 만에 작동하는 바코드를 만들 수 있습니다. 전체 코드를 단계별로 살펴보고, 각 설정이 왜 중요한지 설명하며, **바코드 높이 변경**을 사양을 어기지 않고 수행하는 방법을 보여드립니다. + +## 필요 사항 + +- .NET 6.0 이상 (API는 .NET Framework 4.7+에서도 동일하게 작동합니다) +- 바코드 라이브러리에 대한 참조 (예: Aspose.BarCode for .NET – 많은 상용 키트에서 동일한 클래스를 사용합니다) +- 개발 환경 (Visual Studio, Rider, 또는 C# 확장 기능이 포함된 VS Code) +- 쓰기 권한이 있는 폴더 – 튜토리얼은 PNG 파일을 해당 폴더에 저장합니다 + +이것만 있으면 됩니다. 바코드 라이브러리 외에 추가 NuGet 패키지는 필요하지 않습니다. + +## .net barcode generator를 사용하여 바코드 높이 변경하기 + +아래는 **완전하고 실행 가능한 콘솔 프로그램**입니다. 새 C# 프로젝트에 붙여넣고, 출력 폴더를 조정한 뒤 F5 키를 눌러 실행하세요. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### 각 라인이 중요한 이유 + +| 라인 | 이유 | +|------|------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | 원하는 심볼과 데이터 페이로드를 사용하여 **.net barcode generator**를 인스턴스화합니다. `EncodeTypes.DatabarOmniDirectional` 열거형은 라이브러리에게 GS1‑Databar Omni‑Directional 형식을 사용하도록 지정합니다. | +| `XDimension.Pixels = 2;` | X‑dimension은 가장 얇은 바의 너비를 의미합니다. *2 픽셀*로 설정하면 대부분의 모니터에서 선명한 이미지를 제공하면서 파일 크기를 작게 유지합니다. | +| `BarHeight.Pixels = 30;` | 이것이 **바코드 높이 변경** 단계이며, 각 바의 높이를 결정합니다. 30 픽셀 높이는 작은 라벨에 적합한 기본값입니다. | +| `generator.Save(...);` | 바코드를 PNG 파일로 저장합니다. PNG는 무손실 포맷이므로 스캐너가 생성된 정확한 패턴을 읽을 수 있습니다. | +| `BarHeight.Pixels = 60;` | 여기서 **바코드 높이 변경**을 다시 수행합니다—이번에는 60 픽셀로 설정합니다. 두 번째로 `Save`를 호출하면 라이브러리가 새로운 차원으로 심볼을 자동으로 다시 렌더링합니다. | +| `Console.WriteLine(...);` | 예외가 발생하지 않고 프로세스가 완료되었음을 빠르게 알려줍니다. | + +> **팁:** 인쇄용으로 고해상도 출력이 필요하면 `BarCodeImageFormat.Png`를 `BarCodeImageFormat.Tiff`로 변경하고 `Resolution` 속성을 높이세요(예: `generator.Parameters.ImageResolution = 300;`). 바 높이는 그대로 유지되며, 더 높은 DPI로 렌더링됩니다. + +## 다양한 설정으로 바코드 이미지 생성하기 + +위 코드 조각은 기본을 다루지만, 실제 상황에서는 추가 조정이 필요할 때가 많습니다: + +### 큰 출력물을 위한 X‑dimension 조정 +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +X‑dimension을 늘리면 인코딩된 데이터는 그대로 두고 바코드 전체가 커집니다. 큰 라벨에 인쇄할 때 유용합니다. + +### 출력 포맷 전환 +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG는 무한히 확대가 가능해, 선명한 벡터가 필요한 웹 기반 스캐너에 최적입니다. + +### 인간이 읽을 수 있는 텍스트 추가 +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +`CodeTextVisible`을 활성화하면 바코드 아래에 원시 데이터가 추가되어 테스트 중 검증에 유용합니다. + +## **바코드 높이 변경** 시 흔히 발생하는 실수 + +1. **높이가 너무 작음** – 일부 스캐너는 최소 바 높이를 요구합니다(보통 물리 단위로 10 mm). `BarHeight.Pixels`를 너무 낮게 설정하면 실제 스캐너에서 이미지가 읽히지 않을 수 있습니다. 항상 목표 하드웨어에서 테스트하세요. +2. **X‑dimension과 높이 불일치** – 매우 큰 바 높이에 작은 X‑dimension을 사용하면 바가 늘어나 보이고 디코딩 오류가 발생할 수 있습니다. 사양에 별도 언급이 없으면 대략 3:1~5:1 비율을 목표로 하세요. +3. **파라미터 초기화 누락** – 생성기는 저장 사이에 상태를 유지합니다. 하나의 이미지에서 `BarHeight`를 변경한 뒤 같은 인스턴스를 다른 바코드에 재사용하면 이전 높이가 그대로 남습니다. 속성을 재설정하거나 각 바코드마다 새로운 `BarcodeGenerator` 인스턴스를 생성하세요. + +## 전체 엔드‑투‑엔드 예제 (NuGet 설치 포함) + +처음부터 시작한다면, 다음 단계에 따라 프로젝트를 실행하세요: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +자동 생성된 `Program.cs`를 앞서 보여준 코드 블록으로 교체하고, **`YOUR_DIRECTORY`를 `Path.Combine(Environment.CurrentDirectory, "output")`와 같은 경로로 바꾸는 것을 잊지 마세요**. 그런 다음: + +```bash +dotnet run +``` + +`output` 폴더에 두 개의 PNG 파일이 생성됩니다: + +- `DatabarBarHeight30Pixels.png` – 30 픽셀 높이의 컴팩트한 바코드. +- `DatabarBarHeight60Pixels.png` – 60 픽셀 높이의 더 긴 버전. + +두 이미지 모두 비슷해 보이지만, 두 번째는 바가 눈에 띄게 길어 저해상도 스캐너가 읽기 쉬워집니다. + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator 출력 (다양한 바 높이 표시)"} + +## 요약 및 다음 단계 + +**.net barcode generator**를 사용해 **바코드** 이미지를 생성하고, **바코드 높이 변경** 속성을 미세 조정한 뒤 PNG 형식으로 저장하는 방법을 다루었습니다. 주요 포인트는 다음과 같습니다: + +- 올바른 `EncodeTypes`로 생성기를 인스턴스화합니다. +- `XDimension`과 `BarHeight`를 통해 시각적 크기를 제어합니다. +- 각 변경 후 `Save`를 호출해 새로운 이미지를 저장합니다. +- 해상도와 포맷을 조정합니다, + +## 다음에 배워야 할 내용은? + +다음 튜토리얼들은 이 가이드에서 보여준 기술을 기반으로 하는 밀접한 주제를 다룹니다. 각 자료에는 완전한 코드 예제와 단계별 설명이 포함되어 있어 추가 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 create dotcode extended codetext with Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-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/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/polish/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..1e989a697 --- /dev/null +++ b/barcode/polish/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-07-18 +description: Przykład generatora kodów kreskowych pokazujący, jak ustawić wymiary + i wygenerować obraz kodu DataBar Stacked Omni‑Directional w C#. Szybko poznaj typy + kodowania kodów kreskowych. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: pl +lastmod: 2026-07-18 +og_description: Przykład generatora kodów kreskowych prowadzi Cię krok po kroku, jak + ustawić wymiary, wybrać typy kodowania i tworzyć obrazy kodów kreskowych w projektach + C# przy minimalnym kodzie. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Przykład generatora kodów kreskowych – szybkie tworzenie obrazu DataBar + w C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Przykład generatora kodów kreskowych – Tworzenie obrazu DataBar w C# +url: /pl/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Przykład generatora kodów kreskowych – Tworzenie obrazu DataBar w C# + +Czy kiedykolwiek potrzebowałeś **przykładu generatora kodów kreskowych**, który naprawdę generuje rzeczywisty kod kreskowy, nie wyrywając sobie włosów? Nie jesteś sam. Większość programistów napotyka problem, gdy próbuje ustalić **jak ustawić wymiary** dla kodu DataBar Stacked Omni‑Directional, zwłaszcza gdy dokumentacja jest ukryta pod warstwą żargonu. + +W tym samouczku przejdziemy krok po kroku przez kompletny, gotowy do uruchomienia program w C#, który pokazuje **jak generować obrazy databar**, wybiera odpowiednie **barcode encode types**, i w końcu **create barcode image c#** pliki, które możesz wkleić do dowolnego projektu. Bez zbędnego balastu — tylko kod, który możesz skopiować‑wkleić, oraz uzasadnienie każdej linii. + +## Czego będziesz potrzebować + +- **.NET 6** (lub dowolna nowsza wersja .NET) – API, którego używamy, celuje w .NET Standard, więc działa także na .NET Framework. +- **Aspose.BarCode for .NET** – biblioteka udostępniająca `BarcodeGenerator`. Możesz ją pobrać z NuGet za pomocą `Install-Package Aspose.BarCode`. +- **IDE C#** – Visual Studio, Rider lub VS Code będą odpowiednie. +- Folder na dysku, w którym zostaną zapisane pliki PNG (kod tworzy `DatabarAspectRatio15.png` i `DatabarAspectRatio30.png`). + +Masz wszystko? Świetnie—zanurzmy się. + +## Przykład generatora kodów kreskowych – Inicjalizacja generatora + +Najpierw potrzebujemy instancji `BarcodeGenerator` skonfigurowanej dla symbologii **DataBar Stacked Omni‑Directional**. To jest **barcode encode type**, z którym będziemy pracować. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Dlaczego to ma znaczenie:** `EncodeTypes.DatabarStackedOmniDirectional` mówi Aspose dokładnie, którą symbologię ma renderować. Jeśli wybierzesz niewłaściwy typ, skaner nie rozpozna kodu kreskowego, bez względu na to, jak ładny będzie obraz. + +## Jak ustawić wymiary dla kodu kreskowego + +Czytelność kodu kreskowego zależy od jego **X‑dimension** (szerokość najcieńszego paska). W większości przypadków wartość 2 piksele działa dobrze, ale możesz ją dostosować do swojego drukarki lub ekranu. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Wskazówka:** Jeśli kiedykolwiek zastanawiasz się **jak ustawić wymiary** dla innej rodziny kodów, ta sama łańcuchowa właściwość (`Parameters.Barcode.XDimension`) ma zastosowanie — po prostu zmień wartość `Pixels`. + +## Jak wygenerować DataBar Stacked Omni‑Directional + +Teraz, gdy generator jest gotowy, pobawimy się właściwością **aspect ratio**. Kontroluje ona stosunek wysokości do szerokości DataBar, pozwalając uzyskać krótki, kwadratowy symbol lub wysoki, wąski. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Co się dzieje?** `AspectRatio = 15` mówi silnikowi, aby słupki były 15‑krotnie wyższe niż szerokie. Powstały plik PNG zostaje zapisany tuż obok twojego pliku wykonywalnego. + +## Create Barcode Image C# – Zmiana współczynnika proporcji + +Pokażmy elastyczność, zmieniając współczynnik na 30 i zapisując drugi plik. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +Po uruchomieniu programu otrzymasz dwa pliki PNG: + +| Plik | Współczynnik proporcji | Przybliżony rozmiar | +|------|------------------------|---------------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Otwórz je w dowolnym przeglądarce obrazów — powinieneś zobaczyć czyste, skanowalne symbole DataBar. + +## Przegląd typów kodów kreskowych (Opcjonalnie, ale przydatny) + +Jeśli jesteś ciekawy innych **barcode encode types** obsługiwanych przez Aspose, oto szybka ściągawka: + +| Enum EncodeTypes | Opis | +|------------------|------| +| `EncodeTypes.Code128` | Wysokiej gęstości alfanumeryczny | +| `EncodeTypes.QR` | Kod macierzowy 2‑D | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar dla handlu detalicznego | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Nasze skupienie** – kompaktowy, omnidirectional | + +Znajomość właściwego enumu oszczędza wiele prób i błędów przy przełączaniu projektów. + +## Częste pułapki i jak ich unikać + +- **Brak pakietu NuGet** – Kod nie skompiluje się bez `Aspose.BarCode`. Najpierw uruchom `dotnet add package Aspose.BarCode`. +- **Nieprawidłowa ścieżka pliku** – Jeśli używasz ścieżki bezwzględnej, sprawdź podwójne ukośniki (`\\`) w Windows. Ścieżki względne (tak jak pokazano) są bardziej przenośne. +- **Zbyt ekstremalny współczynnik proporcji** – Współczynniki powyżej 50 mogą sprawić, że kod będzie za wysoki dla typowych skanerów. Trzymaj się zakresu 15‑30 dla większości zastosowań. + +## Pełny kod źródłowy (Gotowy do kopiowania) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Uruchom program (`dotnet run` lub naciśnij **F5** w Visual Studio) i zobacz komunikat w konsoli potwierdzający, że pliki znajdują się na dysku. + +![Przykładowy wynik generatora kodów kreskowych pokazujący kod DataBar z współczynnikiem proporcji 15](placeholder/path/to/image.png){: .align-center alt="Przykładowy wynik generatora kodów kreskowych pokazujący kod DataBar z współczynnikiem proporcji 15"} + +## Podsumowanie + +Właśnie ukończyliśmy **przykład generatora kodów kreskowych**, który demonstruje **jak ustawić wymiary**, wybiera właściwe **barcode encode types**, i w końcu **create barcode image c#** pliki, które możesz osadzić gdziekolwiek. Kod jest niewielki, koncepcje przejrzyste, a Ty masz solidną bazę do rozbudowy rozwiązania — np. dodania podpisów tekstowych, obrotu obrazu lub przejścia na inną symbologię. + +### Co dalej? + +- Eksperymentuj z **różnymi X‑dimension** aby zobaczyć, jak zmienia się tolerancja skanera. +- Wypróbuj inne **EncodeTypes**, takie jak `Code128` czy `QR`, aby poszerzyć swój zestaw narzędzi. +- Zautomatyzuj generowanie wsadowe: iteruj po pliku CSV z identyfikatorami produktów i generuj PNG dla każdego. + +Jeśli napotkasz problem, zostaw komentarz poniżej lub sprawdź dokumentację Aspose.BarCode — jest pełna przykładów uzupełniających to, co tutaj omówiliśmy. + +Miłego kodowania i niech twoje kody kreskowe zawsze skanują się za pierwszym razem! + +## 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, 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 w własnych projektach. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/polish/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..87b1cd300 --- /dev/null +++ b/barcode/polish/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-07-18 +description: Szybko twórz kod kreskowy Planet w C#. Dowiedz się, jak generować wypełnione + i puste paski, ustawiać wymiar X oraz zapisywać obrazy PNG – wszystko w jednym samouczku. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: pl +lastmod: 2026-07-18 +og_description: Twórz kod kreskowy Planet natychmiast. Ten przewodnik pokazuje, jak + ustawić wymiar X, przełączać się między wypełnionymi a pustymi paskami oraz eksportować + pliki PNG za pomocą Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Stwórz kod kreskowy planety w C# – Kompletny przewodnik programistyczny +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Utwórz Planet Barcode w C# – Pełny przewodnik krok po kroku +url: /pl/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utwórz kod kreskowy Planet w C# – Pełny przewodnik krok po kroku + +Czy kiedykolwiek potrzebowałeś **utworzyć kod kreskowy planet** obrazy, ale nie byłeś pewien, które właściwości dostosować? Nie jesteś sam. Wielu programistów napotyka problem, gdy domyślne wypełnione paski nie spełniają wymagań specyfikacji lub gdy szerokość paska musi odpowiadać DPI drukarki. + +W tym samouczku dowiesz się dokładnie, jak **utworzyć kod kreskowy planet** pliki przy użyciu biblioteki Aspose.BarCode, jak kontrolować **piksele XDimension**, oraz jak przełączać się między **wypełnionymi paskami** a **pustymi paskami** bez przepisywania kodu. Na końcu będziesz mieć dwa pliki PNG — jeden z pełnymi paskami, a drugi z pustymi paskami — gotowe dla każdego systemu pocztowego oczekującego symbologii Planet. + +## Wymagania wstępne + +- .NET 6.0 lub nowszy (kod działa także na .NET Framework 4.7 +) +- Pakiet NuGet Aspose.BarCode for .NET (`Install-Package Aspose.BarCode`) +- Podstawowa znajomość C# (zobaczysz później, dlaczego używamy instrukcji `using`) +- Zapisywalny folder na dysku, w którym zostaną zapisane pliki PNG + +Jeśli masz to wszystko, możemy od razu przejść do implementacji. + +## Krok 1 – Skonfiguruj projekt i dodaj bibliotekę + +Najpierw utwórz nową aplikację konsolową (lub dowolny projekt C#) i odwołaj się do biblioteki **Planet barcode generator**. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro tip:** W Visual Studio kliknij prawym przyciskiem myszy projekt → *Manage NuGet Packages* → wyszukaj **Aspose.BarCode** i kliknij *Install*. Dzięki temu uzyskasz dostęp do `BarcodeGenerator` oraz wszystkich **parametrów BarcodeGenerator**, których będziesz potrzebował. + +## Krok 2 – Zainicjuj generator kodu kreskowego Planet + +Teraz faktycznie **tworzymy generator kodu kreskowego planet** i podajemy mu dane, które chcemy zakodować (`"123456"` w tym przykładzie). Enum `EncodeTypes.Planet` informuje bibliotekę, której symbologii użyć. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Dlaczego to ważne:** Flaga `EncodeTypes.Planet` automatycznie stosuje prawidłową sumę kontrolną i zasady układu dla pocztowego kodu kreskowego Planet, więc nie musisz ich obliczać ręcznie. + +## Krok 3 – Skonfiguruj X‑Dimension (szerokość paska) + +Większość drukarek oczekuje, że każdy pasek będzie miał określoną liczbę pikseli. Tutaj ustawiamy **piksele XDimension** na `4`, co jest typową wartością dla termicznych drukarek 203 dpi. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Edge case:** Jeśli celujesz w drukarkę 300 dpi, możesz potrzebować `3` lub `5` pikseli. Dostosuj tę wartość zgodnie z dokumentacją swojego urządzenia. + +## Krok 4 – Zapisz wersję z wypełnionymi paskami + +Domyślnie generator tworzy **wypełnione paski** (solidne czarne prostokąty). Zapiszmy je na dysku: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Zastąp `YOUR_DIRECTORY` ścieżką absolutną lub względną, do której aplikacja ma prawo zapisu. Po wykonaniu tej linii znajdziesz plik PNG wyglądający jak klasyczny kod kreskowy Planet — idealny do testów z czytnikiem pocztowym. + +## Krok 5 – Przełącz na puste paski + +Czasami usługi pocztowe wymagają stylu „pustych pasków”, gdzie paski są wycięte z białego tła zamiast pomalowane na czarno. Biblioteka udostępnia prosty przełącznik: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Ustawienie `FilledBars` na `false` mówi rendererowi, aby odwrócił logikę wypełniania pasków. Nie ma potrzeby tworzenia nowej instancji `BarcodeGenerator`; wystarczy zmodyfikować istniejące **parametry BarcodeGenerator**. + +## Krok 6 – Zapisz wersję z pustymi paskami + +Na koniec wyeksportuj drugi obraz: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Teraz masz dwa odrębne pliki PNG, każdy spełniający inny wymóg wizualny. + +## Pełny działający przykład + +Składając wszystkie elementy razem, oto kompletny, gotowy do skopiowania program: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Oczekiwany wynik** (w konsoli): + +``` +Both Planet barcode images have been generated successfully. +``` + +A w `C:\Barcodes\` zobaczysz: + +- `PostalPlanetFilledBars.png` – solidne czarne paski +- `PostalPlanetEmptyBars.png` – białe paski z czarnymi konturami + +Otwórz je w dowolnym przeglądarce obrazów; oba powinny spełniać specyfikację Planet. + +## Często zadawane pytania i wskazówki + +### „Czy mogę zmienić format obrazu?” + +Oczywiście. Metoda `Save` akceptuje `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` itd. Wystarczy zamienić `BarCodeImageFormat.Png` na żądany format. + +### „Co zrobić, jeśli potrzebuję innej wysokości kodu kreskowego?” + +Użyj `planetBarcode.Parameters.Barcode.BarHeight` (w punktach), aby zwiększyć lub zmniejszyć rozmiar pionowy. Na przykład: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### „Czy da się dodać czytelny dla człowieka podpis?” + +Tak. Ustaw właściwość `CodeText` w `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### „Czy muszę zwolnić generator?” + +`BarcodeGenerator` implementuje `IDisposable`. Owiń go w blok `using`, jeśli tworzysz wiele kodów kreskowych w pętli: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### „A co z obsługą błędów?” + +Umieść wywołania `Save` w bloku `try…catch`, aby przechwycić `IOException` (problemy z dyskiem) lub `ArgumentException` (nieprawidłowe parametry). Przykład: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Podsumowanie + +Omówiliśmy wszystko, co potrzebne, aby **utworzyć kod kreskowy planet** obrazy w C#: + +1. Zainicjuj **generator kodu kreskowego Planet** z własnymi danymi. +2. Dostosuj **piksele XDimension**, aby pasowały do specyfikacji drukarki. +3. Zapisz PNG z **wypełnionymi paskami**. +4. Przełącz `FilledBars`, aby uzyskać **puste paski**. +5. Zapisz drugi PNG. + +Od tego momentu możesz eksplorować więcej **parametrów BarcodeGenerator**, eksperymentować z innymi symbologiami (`EncodeTypes.Postnet`, `EncodeTypes.Code128` itp.) lub integrować obrazy w przepływie pracy pocztowej. + +--- + +**Gotowy na kolejny krok?** Spróbuj dodać kod QR do tego samego dokumentu lub wygenerować batch kodów Planet z listy CSV przy użyciu pętli `foreach`. API Aspose.BarCode jest na tyle elastyczne, że obsłuży operacje masowe, niestandardowe kolory, a nawet wektorowy format SVG. + +Jeśli napotkasz problemy, zostaw komentarz poniżej lub sprawdź oficjalną dokumentację Aspose.BarCode, aby zgłębić zaawansowane funkcje. Szczęśliwego kodowania! + +## 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 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 w własnych projektach. + +- [Create Barcode with Aspose - Set X & Y Dimensions in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/polish/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..4ceb1536a --- /dev/null +++ b/barcode/polish/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-07-18 +description: Szybko utwórz kod kreskowy RM4SCC w C#; dowiedz się, jak ustawić wysokość + kodu kreskowego i także wygenerować kod Planet z niestandardowymi wymiarami. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: pl +lastmod: 2026-07-18 +og_description: Utwórz kod kreskowy RM4SCC w C# i dowiedz się, jak ustawić wysokość + kodu kreskowego. Zobacz także, jak wygenerować kod kreskowy Planet przy użyciu tej + samej biblioteki. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Utwórz kod kreskowy RM4SCC w C# – szybkie ustawienie własnej wysokości +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Utwórz kod kreskowy RM4SCC w C# – Pełny przewodnik ustawiania wysokości +url: /pl/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utwórz kod kreskowy RM4SCC w C# – Pełny przewodnik ustawiania wysokości + +Czy kiedykolwiek potrzebowałeś **utworzyć kod kreskowy RM4SCC** w aplikacji .NET, ale nie byłeś pewien, jak kontrolować jego rozmiar? Nie jesteś sam. Niezależnie od tego, czy tworzysz system pocztowy, czy pulpit logistyczny, uzyskanie właściwej wysokości kodu kreskowego może być różnicą między udanym skanowaniem a niepowodzeniem. + +W tym samouczku przeprowadzimy Cię przez cały proces: od instalacji biblioteki, przez **generowanie kodu kreskowego Planet** jako przykład obok, aż po **sposób ustawiania wysokości kodu kreskowego** dla obu typów kodów. Na końcu będziesz mieć gotową do uruchomienia aplikację konsolową, która generuje pliki PNG o dokładnych wymiarach, których potrzebujesz. + +--- + +## Czego będziesz potrzebować + +- **.NET 6 SDK** (lub dowolna nowsza wersja .NET) – kod działa również na .NET Framework, ale .NET 6 jest optymalnym wyborem. +- **Aspose.BarCode for .NET** pakiet NuGet – to biblioteka, która dostarcza klasę `BarcodeGenerator`. +- Umiarkowana znajomość C# – zachowamy składnię przyjazną dla początkujących. +- IDE lub edytor tekstu (Visual Studio, VS Code, Rider — wybierz, co wolisz). + +> **Wskazówka:** Jeśli korzystasz z potoku CI/CD, dodaj odwołanie NuGet w pliku `.csproj`, aby kompilacja nigdy nie zapomniała o zależności. + +## Krok 1: Konfiguracja projektu + +Otwórz terminal i utwórz nowy projekt konsolowy: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +Gotowe — Twój projekt teraz odwołuje się do biblioteki, która napędza wszystko, co następuje. + +### Dodaj dyrektywy using + +Otwórz `Program.cs` i wklej poniższy kod na początku: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +Te przestrzenie nazw dają dostęp do `BarcodeGenerator` oraz wyliczenia formatu obrazu, którego użyjemy później. + +## Krok 2: Zdefiniuj metodę pomocniczą do zapisywania obrazów + +Aby uniknąć powtarzania tego samego kodu zapisu, opakujemy go w małą metodę. To także pokazuje **jak ustawić wysokość kodu kreskowego** później. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Dlaczego to ważne:** Centralizacja logiki zapisu oznacza, że w razie zmiany wymagań musisz zmienić format lub folder tylko w jednym miejscu. + +## Krok 3: Generowanie kodu kreskowego Planet (część „generowanie kodu kreskowego planet”) + +Zanim przejdziemy do szczegółów RM4SCC, uruchommy **kod kreskowy Planet**. Daje to szybkie wizualne sprawdzenie, że biblioteka działa. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Oczekiwany wynik:** Dwa pliki PNG pojawiają się w folderze `output` — jeden z wysokością automatycznie obliczoną przez bibliotekę, drugi dokładnie 100 px wysokości. + +## Krok 4: Utworzenie kodu kreskowego RM4SCC – Główny cel + +Teraz gwiazda programu: **utworzyć kod kreskowy RM4SCC**. RM4SCC to Royal Mail 4‑State Code, szeroko stosowany w brytyjskim systemie pocztowym. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**Co zobaczysz:** +- `RM4SCCDefault.png` – biblioteka wybiera wygodną wysokość na podstawie wymiaru X. +- `RM4SCCHeight100.png` – wyraźny kod kreskowy o wysokości 100 pikseli, gotowy do drukowania na kopertach. + +> **Dlaczego ustawiać wysokość?** Niektóre drukarki etykiet wymagają minimalnej wysokości kreski dla niezawodnego skanowania. Ustalając wysokość, zapewniasz zgodność na różnych urządzeniach. + +## Krok 5: Zrozumienie ustawień wysokości (odpowiedź na pytanie „jak ustawić wysokość kodu kreskowego”) + +Zarówno przykłady Planet, jak i RM4SCC używają tej samej właściwości: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** jest obiektem `BarHeight`, który grupuje kilka jednostek miary (piksele, milimetry, cale). +- **`.Pixels`** jest najprostszą jednostką dla wyjścia skierowanego na ekran, ale możesz także użyć `.Millimeters` lub `.Inches`, jeśli celujesz w media drukowane. + +### Przypadki brzegowe i wskazówki + +| Situation | Recommended Approach | +|-----------|----------------------| +| **Bardzo mały wymiar X (np. 1 px)** | Zwiększ `BarHeight`, aby kod kreskowy był czytelny. | +| **Drukowanie na drukarkach etykiet o wysokiej rozdzielczości** | Użyj `.Millimeters` dla rozmiaru niezależnego od urządzenia. | +| **Mieszane typy kodów kreskowych w jednym obrazie** | Ustaw `BarHeight` *po* `XDimension` dla każdego generatora, aby uniknąć przypadkowego dziedziczenia. | +| **Dynamiczne dane (np. kody wprowadzane przez użytkownika)** | Opakuj tworzenie generatora w metodę przyjmującą parametry `code` i `height`. | + +## Krok 6: Pełny działający przykład + +Poniżej znajduje się pojedynczy, samodzielny program, który możesz skopiować i wkleić do `Program.cs`. Zawiera wszystko od konfiguracji projektu po zapisywanie obrazów. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Uruchom go za pomocą: + +```bash +dotnet run +``` + +## Zakończenie + +Teraz wiesz **jak utworzyć kod kreskowy RM4SCC** w C# i kontrolować jego wymiary przy użyciu kilku przypisań właściwości. Omówiliśmy także **generowanie kodu kreskowego Planet** jako szybkie sprawdzenie, oraz zgłębiliśmy niuanse **ustawiania wysokości kodu kreskowego** w różnych scenariuszach drukowania. + +Kolejne kroki? Spróbuj zamienić wyliczenie `EncodeTypes` na inne symbologie (Code128, QR, DataMatrix) i eksperymentuj z `BarHeight` w milimetrach dla drukarek wysokiej rozdzielczości. Jeśli potrzebujesz osadzić kod kreskowy w PDF, połącz Aspose.BarCode z Aspose.PDF — kolejna potężna kombinacja. + +Masz pytania lub chcesz podzielić się własnymi modyfikacjami? zostaw komentarz poniżej i powodzenia w kodowaniu! + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne, działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Jak wygenerować kod kreskowy Aztec z niestandardowym współczynnikiem proporcji przy użyciu Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Jak utworzyć strefę ciszy (quiet zone) kodu kreskowego dla ITF-14 przy użyciu Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Jak utworzyć strefę ciszy kodu kreskowego dla Code 16K przy użyciu Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/polish/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..dd91fcc65 --- /dev/null +++ b/barcode/polish/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-07-18 +description: Dowiedz się, jak generować obrazy kodów kreskowych za pomocą generatora + kodów kreskowych .NET i łatwo zmieniać wysokość kodu kreskowego dla symboli GS1‑Databar + Omni‑Directional. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: pl +lastmod: 2026-07-18 +og_description: Generator kodów kreskowych .net pozwala szybko tworzyć obrazy kodów + kreskowych. Ten przewodnik pokazuje, jak generować kody kreskowe, dostosować wysokość + pasków i zapisywać pliki PNG. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Zmień wysokość kodu kreskowego przy użyciu generatora kodów kreskowych .NET +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET generator kodów kreskowych – zmień wysokość kodu kreskowego +url: /pl/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – zmiana wysokości kodu kreskowego + +Zastanawiałeś się kiedyś **jak generować obrazy kodów kreskowych** bez używania dziesiątek narzędzi firm trzecich? W świecie .NET istnieje zaskakująco prosty sposób, a kluczowym elementem jest **.net barcode generator**. Dzięki kilku liniom C# możesz stworzyć symbol GS1‑Databar Omni‑Directional, dostosować wysokość pasków i zapisać wynik jako plik PNG. + +Jeśli tworzysz system inwentaryzacji, drukarkę etykiet wysyłkowych lub dowolną aplikację potrzebującą kodu do zeskanowania, ten samouczek przeprowadzi Cię od zera do działającego kodu kreskowego w kilka minut. Przejdziemy przez kompletny kod, wyjaśnimy, dlaczego każde ustawienie ma znaczenie, i pokażemy, jak **zmienić wysokość kodu kreskowego** nie łamiąc specyfikacji. + +## Czego będziesz potrzebować + +- .NET 6.0 lub nowszy (API działa tak samo na .NET Framework 4.7+) +- Odwołanie do biblioteki kodów kreskowych (np. Aspose.BarCode for .NET – te same klasy są używane w wielu komercyjnych zestawach) +- Środowisko programistyczne (Visual Studio, Rider lub VS Code z rozszerzeniem C#) +- Folder, w którym masz uprawnienia do zapisu – samouczek zapisze tam pliki PNG + +To wszystko. Nie potrzebujesz dodatkowych pakietów NuGet poza samą biblioteką kodów kreskowych. + +## Używanie .net barcode generator do zmiany wysokości kodu kreskowego + +Poniżej znajduje się **kompletny, działający program konsolowy**. Wklej go do nowego projektu C#, dostosuj folder wyjściowy i naciśnij F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Dlaczego każda linia ma znaczenie + +| Linia | Powód | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Tworzy **.net barcode generator** z wybraną symbologią i danymi. Enum `EncodeTypes.DatabarOmniDirectional` informuje bibliotekę, aby użyła formatu GS1‑Databar Omni‑Directional. | +| `XDimension.Pixels = 2;` | X‑dimension określa szerokość najcieńszego paska. Ustawienie na *2 piksele* zapewnia wyraźny obraz na większości monitorów przy jednoczesnym utrzymaniu małego rozmiaru pliku. | +| `BarHeight.Pixels = 30;` | To krok **zmiany wysokości kodu kreskowego**, który określa, jak wysokie będą poszczególne paski. Wysokość 30 pikseli to dobre domyślne ustawienie dla małych etykiet. | +| `generator.Save(...);` | Zapisuje kod kreskowy do pliku PNG. PNG jest bezstratny, co oznacza, że skanery widzą dokładny wygenerowany wzór. | +| `BarHeight.Pixels = 60;` | Tutaj ponownie **zmieniamy wysokość kodu kreskowego** – tym razem na 60 pikseli. Biblioteka automatycznie renderuje symbol z nowym wymiarem przy drugim wywołaniu `Save`. | +| `Console.WriteLine(...);` | Daje szybki komunikat zwrotny, że proces zakończył się bez wyjątków. | + +> **Porada:** Jeśli potrzebujesz wyjścia o wyższej rozdzielczości do druku, zamień `BarCodeImageFormat.Png` na `BarCodeImageFormat.Tiff` i zwiększ właściwość `Resolution` (np. `generator.Parameters.ImageResolution = 300;`). Wysokość pasków nadal będzie zachowana, tylko zostanie wyrenderowana przy wyższej DPI. + +## Jak generować obrazy kodów kreskowych z różnymi ustawieniami + +Powyższy fragment obejmuje podstawy, ale w rzeczywistych scenariuszach często potrzebne są dodatkowe modyfikacje: + +### Dostosowanie X‑dimension dla większych wydruków +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Zwiększenie X‑dimension powoduje, że cały kod kreskowy staje się większy, nie zmieniając zakodowanych danych. Jest to przydatne przy drukowaniu na dużych etykietach. + +### Zmiana formatu wyjściowego +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG skaluje się nieskończenie, co jest idealne dla skanerów internetowych, które potrzebują wyraźnych wektorów. + +### Dodawanie tekstu czytelnego dla człowieka +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Włączenie `CodeTextVisible` dodaje surowe dane pod kodem kreskowym, co jest przydatne do weryfikacji podczas testów. + +## Typowe pułapki przy **zmianie wysokości kodu kreskowego** + +1. **Zbyt mała wysokość** – Niektóre skanery wymagają minimalnej wysokości paska (często 10 mm w jednostkach fizycznych). Jeśli ustawisz `BarHeight.Pixels` zbyt nisko, wygenerowany obraz może być nieczytelny dla rzeczywistego skanera. Zawsze testuj na docelowym sprzęcie. +2. **Niezgodność X‑dimension i wysokości** – Duża wysokość paska połączona z małą X‑dimension może wyglądać na rozciągniętą i powodować błędy dekodowania. Dąż do zrównoważonego stosunku (około 3:1 do 5:1), chyba że specyfikacja wymaga inaczej. +3. **Zapomnienie o zresetowaniu parametrów** – Generator zachowuje stan między zapisami. Jeśli zmienisz `BarHeight` dla jednego obrazu i ponownie użyjesz tej samej instancji dla innego kodu kreskowego, poprzednia wysokość pozostanie. Zresetuj właściwość lub utwórz nowy `BarcodeGenerator` dla każdego odrębnego kodu. + +## Pełny przykład od początku do końca (włącznie z instalacją NuGet) + +Jeśli zaczynasz od zera, wykonaj następujące kroki, aby uruchomić projekt: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Zastąp automatycznie wygenerowany `Program.cs` kodem z poprzedniego bloku, **pamiętaj, aby zamienić `YOUR_DIRECTORY`** na coś w rodzaju `Path.Combine(Environment.CurrentDirectory, "output")`. Następnie: + +```bash +dotnet run +``` + +Powinieneś zobaczyć dwa pliki PNG w folderze `output`: + +- `DatabarBarHeight30Pixels.png` – kompaktowy kod kreskowy o wysokości 30 pikseli. +- `DatabarBarHeight60Pixels.png` – wyższa wersja o wysokości 60 pikseli. + +Oba obrazy będą wyglądały podobnie, ale drugi będzie miał wyraźnie dłuższe paski, co ułatwi odczyt skanerom o niskiej rozdzielczości. + +![Barcode height example](/images/barcode-height.png){alt="Wynik .net barcode generator pokazujący różne wysokości pasków"} + +## Podsumowanie i kolejne kroki + +Omówiliśmy, jak **generować obrazy kodów kreskowych** przy użyciu **.net barcode generator**, precyzyjnie dostosowaliśmy właściwość **change barcode height** i zapisaliśmy wyniki w formacie PNG. Najważniejsze wnioski to: + +- Utwórz generator z odpowiednim `EncodeTypes`. +- Kontroluj rozmiar wizualny za pomocą `XDimension` i `BarHeight`. +- Wywołuj `Save` po każdej zmianie, aby zapisać nowy obraz. +- Dostosuj rozdzielczość, format, + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne, działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Jak generować kod Aztec z niestandardowym współczynnikiem proporcji przy użyciu Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Jak utworzyć rozszerzony kod tekstowy dotcode przy użyciu Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Jak generować kody DataMatrix (ECC 200) przy użyciu 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/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/portuguese/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..a4aca40fe --- /dev/null +++ b/barcode/portuguese/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-07-18 +description: Exemplo de gerador de código de barras mostrando como definir dimensões + e gerar uma imagem de código de barras DataBar Stacked Omni‑Directional em C#. Aprenda + rapidamente os tipos de codificação de código de barras. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: pt +lastmod: 2026-07-18 +og_description: O exemplo de gerador de código de barras orienta você sobre como definir + dimensões, escolher tipos de codificação de código de barras e criar projetos de + imagem de código de barras em C# com o mínimo de código. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Exemplo de Gerador de Código de Barras – Criação Rápida de Imagem DataBar + em C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Exemplo de Gerador de Código de Barras – Criar Imagem DataBar em C# +url: /pt/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Exemplo de Gerador de Código de Barras – Criar Imagem DataBar em C# + +Já precisou de um **exemplo de gerador de código de barras** que realmente imprima um código de barras do mundo real sem fazer você perder a cabeça? Você não está sozinho. A maioria dos desenvolvedores bate em um muro quando tenta descobrir **como definir dimensões** para um código de barras DataBar Stacked Omni‑Directional, especialmente quando a documentação está enterrada sob camadas de jargão. + +Neste tutorial vamos percorrer um programa C# completo, pronto‑para‑executar, que mostra **como gerar imagens databar**, escolhe os **tipos de codificação de código de barras** corretos e, finalmente, **cria arquivos de imagem de código de barras c#** que você pode inserir em qualquer projeto. Sem enrolação — apenas o código que você pode copiar‑colar, mais o raciocínio por trás de cada linha. + +## O que Você Precisa + +- **.NET 6** (ou qualquer versão recente do .NET) – a API que usamos tem alvo .NET Standard, então funciona também no .NET Framework. +- **Aspose.BarCode for .NET** – a biblioteca que fornece `BarcodeGenerator`. Você pode obtê‑la no NuGet com `Install-Package Aspose.BarCode`. +- Um **IDE C#** – Visual Studio, Rider ou VS Code servem. +- Uma pasta no disco onde os arquivos PNG serão salvos (o código cria `DatabarAspectRatio15.png` e `DatabarAspectRatio30.png`). + +Tudo pronto? Ótimo — vamos começar. + +## Exemplo de Gerador de Código de Barras – Inicializar o Gerador + +Primeiro passo: precisamos de uma instância de `BarcodeGenerator` configurada para a simbologia **DataBar Stacked Omni‑Directional**. Este é o **tipo de codificação de código de barras** com o qual vamos trabalhar. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Por que isso importa:** `EncodeTypes.DatabarStackedOmniDirectional` indica ao Aspose exatamente qual simbologia renderizar. Se você escolher o tipo errado, o scanner não reconhecerá o código de barras, não importa o quão bonito a imagem esteja. + +## Como Definir Dimensões para o Código de Barras + +A legibilidade de um código de barras depende da sua **X‑dimension** (a largura da barra mais estreita). Na maioria dos casos, um valor de 2 pixels funciona bem, mas você pode ajustá‑lo conforme sua impressora ou tela. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Dica de especialista:** Se algum dia você se perguntar **como definir dimensões** para outra família de códigos de barras, a mesma cadeia de propriedades (`Parameters.Barcode.XDimension`) se aplica — basta mudar o valor de `Pixels`. + +## Como Gerar Código de Barras DataBar Stacked Omni‑Directional + +Agora que o gerador está pronto, vamos brincar com a propriedade **aspect ratio**. Ela controla a relação altura‑largura do DataBar, permitindo que você produza um símbolo curto e quadrado ou um alto e estreito. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **O que está acontecendo?** `AspectRatio = 15` indica ao motor que as barras devem ser 15 vezes mais altas que largas. O PNG resultante é salvo ao lado do seu executável. + +## Criar Imagem de Código de Barras C# – Alterando a Proporção + +Vamos provar a flexibilidade trocando a proporção para 30 e salvando um segundo arquivo. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +Ao executar o programa, você terá dois arquivos PNG: + +| Arquivo | Proporção | Tamanho Aproximado | +|---------|-----------|--------------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Abra-os em qualquer visualizador de imagens — você deverá ver símbolos DataBar limpos e legíveis. + +## Visão Geral dos Tipos de Codificação de Código de Barras (Opcional, mas Útil) + +Se você tem curiosidade sobre outros **tipos de codificação de código de barras** suportados pelo Aspose, aqui está um cheat‑sheet rápido: + +| Enum EncodeTypes | Descrição | +|------------------|-----------| +| `EncodeTypes.Code128` | Alfanumérico de alta densidade | +| `EncodeTypes.QR` | Código matricial 2‑D | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar para varejo | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Nosso foco** – compacto, omnidirecional | + +Conhecer o enum correto economiza muito tempo de tentativa‑e‑erro quando você troca de projeto. + +## Armadilhas Comuns & Como Evitá‑las + +- **Pacote NuGet ausente** – O código não compila sem `Aspose.BarCode`. Execute `dotnet add package Aspose.BarCode` primeiro. +- **Caminho de arquivo errado** – Se usar um caminho absoluto, verifique as barras invertidas (`\\`) no Windows. Caminhos relativos (como mostrado) mantêm a portabilidade. +- **Proporção extrema** – Proporções acima de 50 podem deixar o código de barras alto demais para scanners típicos. Mantenha entre 15‑30 para a maioria dos casos de uso. + +## Código Fonte Completo (Pronto para Copiar e Colar) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Execute o programa (`dotnet run` ou pressione **F5** no Visual Studio) e você verá a mensagem no console confirmando que os arquivos foram gravados no disco. + +![Barcode generator example output showing DataBar barcode with aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Exemplo de saída do gerador de código de barras mostrando DataBar com proporção 15"} + +## Conclusão + +Acabamos de concluir um **exemplo de gerador de código de barras** que demonstra **como definir dimensões**, escolhe os **tipos de codificação de código de barras** corretos e, finalmente, **cria arquivos de imagem de código de barras c#** que você pode incorporar em qualquer lugar. O código é pequeno, os conceitos são claros como cristal, e agora você tem uma base sólida para expandir a solução — talvez adicionando legendas de texto, girando a imagem ou mudando para outra simbologia. + +### Próximos Passos? + +- Experimente **diferentes X‑dimensions** para ver como a tolerância do scanner muda. +- Teste outros **EncodeTypes** como `Code128` ou `QR` para ampliar seu conjunto de ferramentas. +- Automatize a geração em lote: faça um loop sobre um CSV de IDs de produto e gere um PNG para cada um. + +Se encontrar algum problema, deixe um comentário abaixo ou consulte a documentação do Aspose.BarCode — ela está repleta de exemplos que complementam o que abordamos aqui. + +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 cobrem tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas de implementação em seus próprios projetos. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/portuguese/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..fff2d8ed6 --- /dev/null +++ b/barcode/portuguese/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-07-18 +description: Crie códigos de barras Planet rapidamente com C#. Aprenda a gerar barras + preenchidas e vazias, definir a dimensão X e salvar imagens PNG – tudo em um único + tutorial. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: pt +lastmod: 2026-07-18 +og_description: Crie o código de barras Planet instantaneamente. Este guia mostra + como definir a dimensão X, alternar entre barras preenchidas e vazias e exportar + arquivos PNG com o Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Criar Planet Barcode em C# – Guia Completo de Programação +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Criar Código de Barras Planet em C# – Guia Completo Passo a Passo +url: /pt/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar Código de Barras Planet em C# – Guia Completo Passo a Passo + +Já precisou **criar código de barras planet** imagens mas não tinha certeza de quais propriedades ajustar? Você não está sozinho. Muitos desenvolvedores se deparam com um obstáculo quando as barras preenchidas padrão não atendem ao que a especificação exige, ou quando a largura da barra deve corresponder ao DPI da impressora. + +Neste tutorial você aprenderá exatamente como **criar código de barras planet** arquivos usando a biblioteca Aspose.BarCode, como controlar os **pixels XDimension**, e como alternar entre **barras preenchidas** e **barras vazias** sem reescrever nenhum código. Ao final você terá dois arquivos PNG—um com barras sólidas e outro com barras ocas—prontos para qualquer sistema postal que espere a simbologia Planet. + +## Pré-requisitos + +- .NET 6.0 ou posterior (o código também funciona em .NET Framework 4.7 +) +- Pacote NuGet Aspose.BarCode para .NET (`Install-Package Aspose.BarCode`) +- Conhecimento básico de C# (você verá por que usamos declarações `using` mais adiante) +- Uma pasta gravável no disco onde os PNGs serão salvos + +Se você tem isso, podemos pular direto para a implementação. + +## Etapa 1 – Configurar o Projeto e Adicionar a Biblioteca + +Primeiro, crie um novo aplicativo console (ou qualquer projeto C#) e faça referência à biblioteca **Planet barcode generator**. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Dica profissional:** No Visual Studio, clique com o botão direito no projeto → *Gerenciar Pacotes NuGet* → procure por **Aspose.BarCode** e clique em *Instalar*. Isso lhe dá acesso ao `BarcodeGenerator` e a todos os **parâmetros do BarcodeGenerator** que você precisará. + +## Etapa 2 – Inicializar o Gerador de Código de Barras Planet + +Agora realmente **criar planet barcode** instância do gerador e alimentá‑la com os dados que queremos codificar (`"123456"` neste exemplo). O enum `EncodeTypes.Planet` indica à biblioteca qual simbologia usar. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Por que isso importa:** A flag `EncodeTypes.Planet` aplica automaticamente o checksum correto e as regras de layout para o código de barras postal Planet, então você não precisa calculá‑los manualmente. + +## Etapa 3 – Configurar X‑Dimension (Largura da Barra) + +A maioria das impressoras espera que cada barra tenha um número específico de pixels. Aqui definimos os **pixels XDimension** para `4`, que é um valor comum para impressoras térmicas de 203 dpi. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Caso extremo:** Se você estiver mirando uma impressora de 300 dpi, talvez precise de `3` ou `5` pixels em vez disso. Ajuste esse valor com base na documentação do seu dispositivo. + +## Etapa 4 – Salvar a Versão com Barras Preenchidas + +Por padrão o gerador produz **barras preenchidas** (retângulos pretos sólidos). Vamos gravar isso no disco: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Substitua `YOUR_DIRECTORY` por um caminho absoluto ou relativo que seu aplicativo possa gravar. Depois que esta linha for executada, você encontrará um arquivo PNG que se parece com um clássico código de barras Planet—perfeito para testes contra um scanner postal. + +## Etapa 5 – Alternar para Barras Vazias + +Às vezes os serviços postais exigem o estilo “barras vazias”, onde as barras são recortadas de um fundo branco em vez de pintadas de preto. A biblioteca expõe uma troca simples: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Definir `FilledBars` como `false` indica ao renderizador que inverta a lógica de preenchimento das barras. Não é necessário criar uma nova instância de `BarcodeGenerator`; basta ajustar os **parâmetros do BarcodeGenerator** existentes. + +## Etapa 6 – Salvar a Versão com Barras Vazias + +Finalmente, exporte a segunda imagem: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Agora você tem dois arquivos PNG distintos, cada um atendendo a um requisito visual diferente. + +## Exemplo Completo Funcional + +Juntando todas as peças, aqui está o programa completo, pronto para copiar e colar: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Saída esperada** (no console): + +``` +Both Planet barcode images have been generated successfully. +``` + +E em `C:\Barcodes\` você verá: + +- `PostalPlanetFilledBars.png` – barras pretas sólidas +- `PostalPlanetEmptyBars.png` – barras brancas com contornos pretos + +Abra‑as em qualquer visualizador de imagens; ambos devem estar em conformidade com a especificação Planet. + +## Perguntas Frequentes & Dicas + +### “Posso mudar o formato da imagem?” + +Absolutamente. O método `Save` aceita `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, etc. Basta substituir `BarCodeImageFormat.Png` pelo formato desejado. + +### “E se eu precisar de uma altura de código de barras diferente?” + +Use `planetBarcode.Parameters.Barcode.BarHeight` (em pontos) para aumentar ou diminuir o tamanho vertical. Por exemplo: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “Existe uma maneira de adicionar uma legenda legível por humanos?” + +Sim. Defina a propriedade `CodeText` em `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “Preciso descartar o gerador?” + +O `BarcodeGenerator` implementa `IDisposable`. Envolva‑o em um bloco `using` se você estiver criando muitos códigos de barras em um loop: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “E quanto ao tratamento de erros?” + +Envolva as chamadas `Save` em um bloco `try…catch` para capturar `IOException` (problemas de disco) ou `ArgumentException` (parâmetros inválidos). Exemplo: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Recapitulação + +Cobremos tudo que você precisa para **criar código de barras planet** imagens em C#: + +1. Inicializar o **gerador de código de barras Planet** com seus dados. +2. Ajustar os **pixels XDimension** para corresponder às especificações da impressora. +3. Salvar um PNG com **barras preenchidas**. +4. Alternar `FilledBars` para produzir **barras vazias**. +5. Salvar o segundo PNG. + +A partir daqui você pode explorar mais **parâmetros do BarcodeGenerator**, experimentar outras simbologias (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, etc.), ou integrar as imagens em um fluxo de trabalho de mailing. + +--- + +**Pronto para o próximo passo?** Tente adicionar um QR code ao mesmo documento, ou gerar um lote de códigos de barras Planet a partir de uma lista CSV usando um loop `foreach`. A API Aspose.BarCode é flexível o suficiente para lidar com operações em massa, cores personalizadas e até saída vetorial SVG. + +Se encontrar algum obstáculo, deixe um comentário abaixo ou consulte a documentação oficial do Aspose.BarCode para mergulhos mais profundos em recursos avançados. Feliz codificaçã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. + +- [Criar Código de Barras com Aspose - Definir Dimensões X & Y em Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [Como criar imagens de código de barras code128 em Java com Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [Como criar código de barras code128 em Java e definir altura da barra](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/portuguese/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..6dee864bb --- /dev/null +++ b/barcode/portuguese/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,274 @@ +--- +category: general +date: 2026-07-18 +description: Crie código de barras RM4SCC em C# rapidamente; aprenda como definir + a altura do código de barras e também gerar código de barras Planet com dimensões + personalizadas. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: pt +lastmod: 2026-07-18 +og_description: Crie código de barras RM4SCC em C# e descubra como definir a altura + do código de barras. Veja também como gerar o código de barras Planet com a mesma + biblioteca. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Criar código de barras RM4SCC em C# – Defina a altura personalizada rapidamente +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Criar código de barras RM4SCC em C# – Guia completo para definir a altura +url: /pt/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar Código de Barras RM4SCC em C# – Guia Completo para Definir a Altura + +Já precisou **criar código de barras RM4SCC** em um aplicativo .NET, mas não sabia como controlar seu tamanho? Você não está sozinho. Seja construindo um sistema de correspondência ou um painel de logística, obter a altura correta do código de barras pode ser a diferença entre uma leitura bem‑sucedida e uma falha. + +Neste tutorial vamos percorrer todo o processo: desde a instalação da biblioteca, até **gerar código de barras Planet** como exemplo lado a lado, e finalmente **como definir a altura do código de barras** para ambos os tipos. Ao final, você terá um aplicativo console pronto‑para‑executar que gera arquivos PNG com as dimensões exatas que você precisa. + +--- + +## O Que Você Precisa + +- **.NET 6 SDK** (ou qualquer versão recente do .NET) – o código também funciona no .NET Framework, mas o .NET 6 é o ponto ideal. +- **Aspose.BarCode for .NET** pacote NuGet – esta é a biblioteca que fornece a classe `BarcodeGenerator`. +- Um conhecimento básico de C# – manteremos a sintaxe amigável para iniciantes. +- Uma IDE ou editor de texto (Visual Studio, VS Code, Rider—escolha o que preferir). + +> **Dica profissional:** Se você estiver em um pipeline CI/CD, adicione a referência NuGet no seu `.csproj` para que a compilação nunca esqueça a dependência. + +--- + +## Etapa 1: Configurar o Projeto + +Abra um terminal e crie um novo projeto console: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +É isso – seu projeto agora referencia a biblioteca que alimenta tudo que vem a seguir. + +### Adicionar as Diretivas Using + +Abra `Program.cs` e cole o seguinte no topo: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +Esses namespaces nos dão acesso ao `BarcodeGenerator` e ao enum de formato de imagem que usaremos mais adiante. + +--- + +## Etapa 2: Definir um Método Auxiliar para Salvar Imagens + +Para evitar repetir a mesma lógica de salvamento, vamos encapsulá‑la em um pequeno método. Isso também demonstra **como definir a altura do código de barras** mais adiante. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Por que isso importa:** Centralizar a lógica de salvamento significa que você só precisa mudar o formato ou a pasta em um único lugar caso os requisitos mudem. + +--- + +## Etapa 3: Gerar um Código de Barras Planet (a parte “gerar código de barras planet”) + +Antes de mergulharmos nos detalhes do RM4SCC, vamos criar um **código de barras Planet**. Isso fornece uma verificação visual rápida de que a biblioteca está funcionando. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Saída esperada:** Dois arquivos PNG aparecem na pasta `output` — um com a altura calculada automaticamente pela biblioteca, o outro exatamente 100 px de altura. + +--- + +## Etapa 4: Criar Código de Barras RM4SCC – Objetivo Principal + +Agora, a estrela do show: **criar código de barras RM4SCC**. RM4SCC é o Royal Mail 4‑State Code, amplamente usado no sistema postal do Reino Unido. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**O que você verá:** +- `RM4SCCDefault.png` – a biblioteca decide uma altura confortável com base na dimensão X. +- `RM4SCCHeight100.png` – um código de barras nítido de 100 pixels de altura pronto para impressão em envelopes. + +> **Por que definir a altura?** Algumas impressoras de etiquetas exigem uma altura mínima de barra para leitura confiável. Ao fixar a altura, você garante conformidade em diferentes dispositivos. + +--- + +## Etapa 5: Entendendo as Configurações de Altura (Respondendo “como definir a altura do código de barras”) + +Tanto os exemplos Planet quanto RM4SCC usam a mesma propriedade: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** é um objeto `BarHeight` que agrupa várias unidades de medida (pixels, milímetros, polegadas). +- **`.Pixels`** é a unidade mais direta para saída orientada a tela, mas você também pode usar `.Millimeters` ou `.Inches` se estiver direcionando mídia impressa. + +### Casos de Borda & Dicas + +| Situação | Abordagem Recomendada | +|-----------|----------------------| +| **Dimensão X muito pequena (ex.: 1 px)** | Aumente `BarHeight` para manter o código de barras legível. | +| **Impressão em impressoras de etiquetas de alta resolução** | Use `.Millimeters` para dimensionamento independente de dispositivo. | +| **Tipos de código de barras misturados em uma única imagem** | Defina `BarHeight` *depois* de `XDimension` para cada gerador, evitando herança acidental. | +| **Dados dinâmicos (ex.: códigos inseridos pelo usuário)** | Envolva a criação do gerador em um método que aceita parâmetros `code` e `height`. | + +--- + +## Etapa 6: Exemplo Completo Funcional + +Abaixo está um programa único e autocontido que você pode copiar‑colar em `Program.cs`. Ele inclui tudo, desde a configuração do projeto até a gravação das imagens. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Execute com: + +```bash +dotnet run +``` + +Você deverá ver a saída no console confirmando cada arquivo salvo, e a pasta `output` conterá quatro PNGs correspondentes aos nomes mostrados acima. + +--- + +## Conclusão + +Agora você sabe **como criar código de barras RM4SCC** em C# e controlar suas dimensões com apenas algumas atribuições de propriedade. Também cobrimos **gerar código de barras Planet** como verificação rápida, e exploramos as nuances de **como definir a altura do código de barras** para diferentes cenários de impressão. + +Próximos passos? Experimente trocar o enum `EncodeTypes` por outras simbologias (Code128, QR, DataMatrix) e experimente `BarHeight` em milímetros para impressoras de alta resolução. Se precisar incorporar o código de barras em um PDF, combine Aspose.BarCode com Aspose.PDF — outra combinação poderosa. + +Tem perguntas ou quer compartilhar suas próprias adaptações? Deixe um comentário abaixo e feliz codificação! + +## O Que Você Deve Aprender a Seguir? + +Os tutoriais a seguir abordam tópicos estreitamente 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 de implementação em seus próprios projetos. + +- [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 Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [How to create barcode quiet zone for Code 16K using Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/portuguese/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..e302bd76a --- /dev/null +++ b/barcode/portuguese/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-07-18 +description: Aprenda a gerar imagens de código de barras com um gerador de códigos + de barras .net e altere facilmente a altura do código de barras para símbolos GS1‑Databar + Omni‑Directional. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: pt +lastmod: 2026-07-18 +og_description: O gerador de códigos de barras .net permite criar imagens de códigos + de barras rapidamente. Este guia mostra como gerar códigos de barras, ajustar a + altura das barras e salvar arquivos PNG. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Alterar a altura do código de barras com o gerador de código de barras .NET +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: Gerador de código de barras .NET – alterar altura do código de barras +url: /pt/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – alterar altura do código de barras + +Já se perguntou **como gerar código de barras** sem lidar com dezenas de ferramentas de terceiros? No mundo .NET há uma maneira surpreendentemente simples de fazer isso, e a peça chave é o **.net barcode generator**. Com apenas algumas linhas de C# você pode criar um símbolo GS1‑Databar Omni‑Directional, ajustar a altura das barras e salvar o resultado em um arquivo PNG. + +Se você está construindo um sistema de inventário, uma impressora de etiquetas de envio ou qualquer aplicativo que precise de um código escaneável, este tutorial levará você do zero a um código de barras funcional em minutos. Vamos percorrer o código completo, explicar por que cada configuração importa e mostrar como **alterar a altura do código de barras** sem violar a especificação. + +## O que você precisará + +- .NET 6.0 ou superior (a API funciona da mesma forma no .NET Framework 4.7+) +- Uma referência à biblioteca de códigos de barras (por exemplo, Aspose.BarCode for .NET – as mesmas classes são usadas por muitos kits comerciais) +- Um ambiente de desenvolvimento (Visual Studio, Rider ou VS Code com a extensão C#) +- Uma pasta onde você tem permissão de escrita – o tutorial salvará arquivos PNG lá + +É isso. Nenhum pacote NuGet extra além da própria biblioteca de códigos de barras. + +## Usando o .net barcode generator para alterar a altura do código de barras + +Abaixo está um **programa de console completo e executável**. Cole-o em um novo projeto C#, ajuste a pasta de saída e pressione F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Por que cada linha importa + +| Line | Reason | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Instancia o **.net barcode generator** com a simbologia desejada e o payload de dados. O enum `EncodeTypes.DatabarOmniDirectional` indica à biblioteca para usar o formato GS1‑Databar Omni‑Directional. | +| `XDimension.Pixels = 2;` | A X‑dimension é a largura da barra mais fina. Definir para *2 pixels* fornece uma imagem nítida na maioria dos monitores, mantendo o tamanho do arquivo baixo. | +| `BarHeight.Pixels = 30;` | Esta é a etapa de **alterar a altura do código de barras** que determina quão alta cada barra será. Uma altura de 30 pixels é um bom padrão para etiquetas pequenas. | +| `generator.Save(...);` | Persiste o código de barras em um arquivo PNG. PNG é sem perdas, o que significa que os scanners veem o padrão exato que você gerou. | +| `BarHeight.Pixels = 60;` | Aqui **alteramos a altura do código de barras** novamente—desta vez para 60 pixels. A biblioteca re‑renderiza automaticamente o símbolo com a nova dimensão quando você chama `Save` pela segunda vez. | +| `Console.WriteLine(...);` | Fornece um feedback rápido de que o processo terminou sem lançar exceção. | + +> **Dica profissional:** Se você precisar de saída de alta resolução para impressão, troque `BarCodeImageFormat.Png` por `BarCodeImageFormat.Tiff` e aumente a propriedade `Resolution` (por exemplo, `generator.Parameters.ImageResolution = 300;`). A altura das barras ainda será respeitada, apenas renderizada em DPI mais fino. + +## Como gerar imagens de código de barras com diferentes configurações + +O trecho acima cobre o básico, mas cenários do mundo real frequentemente exigem ajustes adicionais: + +### Ajustando a X‑dimension para impressões maiores +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Aumentar a X‑dimension torna todo o código de barras maior sem alterar os dados codificados. Isso é útil quando você imprime em etiquetas grandes. + +### Alterando formatos de saída +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG escala infinitamente, o que é perfeito para scanners baseados na web que precisam de vetores nítidos. + +### Adicionando texto legível por humanos +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Habilitar `CodeTextVisible` adiciona os dados brutos sob o código de barras, útil para verificação durante testes. + +## Armadilhas comuns ao **alterar a altura do código de barras** + +1. **Altura muito pequena** – Alguns scanners exigem uma altura mínima de barra (geralmente 10 mm em unidades físicas). Se você definir `BarHeight.Pixels` muito baixo, a imagem gerada pode ser ilegível em um scanner real. Sempre teste com o hardware alvo. +2. **X‑dimension e altura incompatíveis** – Uma altura de barra enorme combinada com uma X‑dimension diminuta pode parecer esticada e causar erros de decodificação. Procure uma proporção equilibrada (aproximadamente 3:1 a 5:1) a menos que a especificação indique o contrário. +3. **Esquecer de redefinir parâmetros** – O gerador mantém o estado entre salvamentos. Se você alterar `BarHeight` para uma imagem e depois reutilizar a mesma instância para outro código de barras, a altura anterior permanecerá. Redefina a propriedade ou instancie um novo `BarcodeGenerator` para cada código de barras distinto. + +## Exemplo completo de ponta a ponta (incluindo instalação via NuGet) + +Se você está começando do zero, siga estas etapas para colocar o projeto em funcionamento: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Substitua o `Program.cs` gerado automaticamente pelo bloco de código mostrado anteriormente, **lembre-se de substituir `YOUR_DIRECTORY`** por algo como `Path.Combine(Environment.CurrentDirectory, "output")`. Em seguida: + +```bash +dotnet run +``` + +Você deverá ver dois arquivos PNG na pasta `output`: + +- `DatabarBarHeight30Pixels.png` – um código de barras compacto com 30 pixels de altura. +- `DatabarBarHeight60Pixels.png` – uma versão mais alta com 60 pixels. + +Ambas as imagens terão aparência similar, mas a segunda terá barras visivelmente mais longas, facilitando a leitura por scanners de baixa resolução. + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator output mostrando diferentes alturas de barra"} + +## Recapitulação & próximos passos + +Abordamos como **gerar códigos de barras** usando um **.net barcode generator**, ajustamos a propriedade **alterar a altura do código de barras** e salvamos os resultados em formato PNG. Os principais pontos são: + +- Instanciar o gerador com o `EncodeTypes` correto. +- Controlar o tamanho visual via `XDimension` e `BarHeight`. +- Chamar `Save` após cada alteração para persistir uma nova imagem. +- Ajustar resolução, formato, + +## 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 for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Como criar texto de código estendido para dotcode com Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Como gerar códigos de barras DataMatrix (ECC 200) com 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/russian/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/russian/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..4d10520c4 --- /dev/null +++ b/barcode/russian/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-07-18 +description: Пример генератора штрихкодов, показывающий, как задать размеры и создать + изображение штрихкода DataBar Stacked Omni‑Directional на C#. Быстро изучайте типы + кодирования штрихкодов. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: ru +lastmod: 2026-07-18 +og_description: Пример генератора штрихкодов пошагово покажет, как задать размеры, + выбрать типы кодирования и создать проект C# для изображения штрихкода с минимальным + количеством кода. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Пример генератора штрихкодов — Быстрое создание изображений DataBar на C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Пример генератора штрихкодов – создание изображения DataBar в C# +url: /ru/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Пример генератора штрихкодов – создание изображения DataBar на C# + +Нужен **пример генератора штрихкодов**, который действительно выводит реальный штрихкод, не сводя вас к отчаянию? Вы не одиноки. Большинство разработчиков сталкиваются с проблемой, когда пытаются понять **как задать размеры** для штрихкода DataBar Stacked Omni‑Directional, особенно когда документация завалена жаргоном. + +В этом руководстве мы пройдем полностью готовую к запуску программу на C#, которая показывает **как генерировать изображения databar**, выбирает правильные **barcode encode types** и, наконец, **create barcode image c#** файлы, которые можно добавить в любой проект. Без лишних слов — только код, который можно скопировать‑вставить, плюс объяснение каждой строки. + +## Что понадобится + +- **.NET 6** (или любая современная версия .NET) — API, которое мы используем, ориентировано на .NET Standard, поэтому работает и в .NET Framework. +- **Aspose.BarCode for .NET** — библиотека, предоставляющая `BarcodeGenerator`. Можно установить её через NuGet командой `Install-Package Aspose.BarCode`. +- **IDE для C#** — Visual Studio, Rider или VS Code подойдут. +- Папка на диске, куда будут сохраняться PNG‑файлы (код создаёт `DatabarAspectRatio15.png` и `DatabarAspectRatio30.png`). + +Все готово? Отлично — приступим. + +## Пример генератора штрихкодов – инициализация генератора + +Первым делом нам нужен экземпляр `BarcodeGenerator`, настроенный для символьной системы **DataBar Stacked Omni‑Directional**. Это **barcode encode type**, с которым мы будем работать. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Почему это важно:** `EncodeTypes.DatabarStackedOmniDirectional` сообщает Aspose, какой именно символьный набор отрисовать. Если выбрать неправильный тип, сканер не распознает штрихкод, независимо от того, как красиво выглядит изображение. + +## Как задать размеры штрихкода + +Читаемость штрихкода зависит от его **X‑dimension** (ширина самой узкой полоски). В большинстве случаев значение 2 пикселя работает отлично, но вы можете изменить его под ваш принтер или экран. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Совет:** Если когда‑нибудь понадобится **как задать размеры** для другой семейства штрихкодов, используйте ту же цепочку свойств (`Parameters.Barcode.XDimension`) — просто измените значение `Pixels`. + +## Как сгенерировать DataBar Stacked Omni‑Directional штрихкод + +Теперь, когда генератор готов, поиграем со свойством **aspect ratio**. Оно управляет отношением высоты к ширине DataBar, позволяя получить короткий, квадратный символ или высокий, узкий. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Что происходит?** `AspectRatio = 15` заставляет движок делать полосы в 15 раз выше, чем они шире. Полученный PNG сохраняется рядом с исполняемым файлом. + +## Create Barcode Image C# – изменение соотношения сторон + +Продемонстрируем гибкость, изменив коэффициент на 30 и сохранив второй файл. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +При запуске программы вы получите два PNG‑файла: + +| Файл | Соотношение сторон | Приблизительный размер | +|------|--------------------|------------------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Откройте их в любом просмотрщике изображений — вы увидите чистые, сканируемые символы DataBar. + +## Обзор Barcode Encode Types (Опционально, но полезно) + +Если вам интересны другие **barcode encode types**, поддерживаемые Aspose, вот быстрый шпаргалка: + +| Enum EncodeTypes | Описание | +|------------------|----------| +| `EncodeTypes.Code128` | Высокоплотный буквенно‑цифровой код | +| `EncodeTypes.QR` | 2‑D матричный код | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar для розничной торговли | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Наш фокус** — компактный, всенаправленный | + +Знание правильного enum избавит вас от множества попыток и ошибок при переключении проектов. + +## Распространённые подводные камни и как их избежать + +- **Отсутствует пакет NuGet** — код не скомпилируется без `Aspose.BarCode`. Сначала выполните `dotnet add package Aspose.BarCode`. +- **Неправильный путь к файлу** — если используете абсолютный путь, проверьте обратные слеши (`\\`) в Windows. Относительные пути (как в примере) делают проект переносимым. +- **Слишком экстремальное соотношение** — коэффициенты выше 50 могут сделать штрихкод слишком высоким для типичных сканеров. Оставайтесь в диапазоне 15‑30 для большинства сценариев. + +## Полный исходный код (готов к копированию) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Запустите программу (`dotnet run` или нажмите **F5** в Visual Studio) — в консоли появится сообщение, подтверждающее, что файлы созданы на диске. + +![Пример вывода генератора штрихкода, показывающий DataBar штрихкод с соотношением сторон 15](placeholder/path/to/image.png){: .align-center alt="Пример вывода генератора штрихкода, показывающий DataBar штрихкод с соотношением сторон 15"} + +## Итоги + +Мы только что завершили **пример генератора штрихкодов**, который демонстрирует **как задать размеры**, выбирает правильные **barcode encode types** и, наконец, **create barcode image c#** файлы, которые можно внедрить куда угодно. Код небольшой, концепции предельно ясны, и теперь у вас есть прочная база для расширения решения — возможно, добавления подписи, вращения изображения или перехода к другой символьной системе. + +### Что дальше? + +- Поэкспериментируйте с **разными X‑dimension** и посмотрите, как меняется допуск сканера. +- Попробуйте другие **EncodeTypes**, такие как `Code128` или `QR`, чтобы расширить набор инструментов. +- Автоматизируйте пакетную генерацию: пройдитесь по CSV с идентификаторами товаров и создайте PNG для каждого. + +Если возникнут проблемы, оставьте комментарий ниже или обратитесь к документации Aspose.BarCode — там полно примеров, дополняющих то, что мы рассмотрели здесь. + +Счастливого кодинга, и пусть ваши штрихкоды всегда сканируются с первой попытки! + +## Что стоит изучить дальше? + +Следующие руководства охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом пособии. Каждый ресурс включает полностью рабочие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/russian/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/russian/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..f21f3d508 --- /dev/null +++ b/barcode/russian/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-07-18 +description: Создайте штрих‑код Planet быстро с помощью C#. Узнайте, как генерировать + заполненные и пустые полосы, задавать X‑размер и сохранять PNG‑изображения — всё + в одном руководстве. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: ru +lastmod: 2026-07-18 +og_description: Создайте штрих‑код Planet мгновенно. Это руководство показывает, как + установить X‑размер, переключаться между заполненными и пустыми полосами и экспортировать + PNG‑файлы с помощью Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Создание Planet Barcode на C# – Полный пошаговый обзор программирования +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Создание Planet Barcode на C# – Полное пошаговое руководство +url: /ru/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание штрих‑кода Planet в C# – Полное пошаговое руководство + +Когда‑то вам нужно было **создать штрих‑код planet**, но вы не знали, какие свойства менять? Вы не одиноки. Многие разработчики сталкиваются с тем, что заполненные полосы по умолчанию не соответствуют спецификации, либо ширина полосы должна соответствовать DPI принтера. + +В этом руководстве вы узнаете, как **создавать файлы штрих‑кода planet** с помощью библиотеки Aspose.BarCode, как управлять **пикселями XDimension**, и как переключаться между **заполненными полосами** и **пустыми полосами**, не переписывая код. В конце у вас будет два PNG‑файла — один с сплошными полосами, другой с пустыми — готовые для любой почтовой системы, использующей симбологию Planet. + +## Требования + +- .NET 6.0 или новее (код также работает на .NET Framework 4.7 +) +- NuGet‑пакет Aspose.BarCode for .NET (`Install-Package Aspose.BarCode`) +- Базовые знания C# (позже вы увидите, зачем нужны `using`‑операторы) +- Папка, в которую приложение может записывать PNG‑файлы + +Если всё это у вас есть, можно сразу переходить к реализации. + +## Шаг 1 – Создание проекта и подключение библиотеки + +Сначала создайте новое консольное приложение (или любой проект C#) и добавьте ссылку на библиотеку **генератора штрих‑кода Planet**. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Совет:** В Visual Studio щёлкните правой кнопкой мыши по проекту → *Manage NuGet Packages* → найдите **Aspose.BarCode** и нажмите *Install*. Это даст вам доступ к `BarcodeGenerator` и всем необходимым **параметрам BarcodeGenerator**. + +## Шаг 2 – Инициализация генератора штрих‑кода Planet + +Теперь действительно **создаём экземпляр генератора штрих‑кода planet** и передаём ему данные, которые нужно закодировать (`"123456"` в этом примере). Перечисление `EncodeTypes.Planet` сообщает библиотеке, какую симбологию использовать. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Почему это важно:** Флаг `EncodeTypes.Planet` автоматически применяет правильные контрольные суммы и правила раскладки для почтового штрих‑кода Planet, так что вам не придётся рассчитывать их вручную. + +## Шаг 3 – Настройка X‑Dimension (ширина полосы) + +Большинство принтеров ожидают, что каждая полоса будет иметь определённое количество пикселей. Здесь мы задаём **пиксели XDimension** равными `4`, что является распространённым значением для термопринтеров с разрешением 203 dpi. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Особый случай:** Если вы нацелены на принтер с 300 dpi, вам может потребоваться `3` или `5` пикселей. Подберите значение, исходя из документации вашего устройства. + +## Шаг 4 – Сохранение версии с заполненными полосами + +По умолчанию генератор создаёт **заполненные полосы** (сплошные чёрные прямоугольники). Запишем их на диск: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Замените `YOUR_DIRECTORY` на абсолютный или относительный путь, в который приложение имеет право записывать. После выполнения этой строки вы найдёте PNG‑файл, выглядящий как классический штрих‑код Planet — идеальный для тестирования с почтовым сканером. + +## Шаг 5 – Переключение на пустые полосы + +Иногда почтовые службы требуют стиль «пустые полосы», когда полосы вырезаются из белого фона вместо того, чтобы быть закрашенными чёрным. Библиотека предоставляет простой переключатель: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Установка `FilledBars` в `false` заставляет рендерер инвертировать логику заполнения полос. Не нужно создавать новый экземпляр `BarcodeGenerator`; достаточно изменить существующие **параметры BarcodeGenerator**. + +## Шаг 6 – Сохранение версии с пустыми полосами + +Наконец, экспортируем второе изображение: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Теперь у вас есть два разных PNG‑файла, каждый соответствует своему визуальному требованию. + +## Полный рабочий пример + +Объединив все части, получаем готовую к копированию и вставке программу: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Ожидаемый вывод** (в консоль): + +``` +Both Planet barcode images have been generated successfully. +``` + +А в `C:\Barcodes\` вы увидите: + +- `PostalPlanetFilledBars.png` — сплошные чёрные полосы +- `PostalPlanetEmptyBars.png` — белые полосы с чёрными контурами + +Откройте их в любом просмотрщике изображений; оба файла должны соответствовать спецификации Planet. + +## Часто задаваемые вопросы и советы + +### «Можно ли изменить формат изображения?» + +Конечно. Метод `Save` принимает `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` и т.д. Просто замените `BarCodeImageFormat.Png` на нужный вам формат. + +### «А если нужна другая высота штрих‑кода?» + +Используйте `planetBarcode.Parameters.Barcode.BarHeight` (в пунктах), чтобы увеличить или уменьшить вертикальный размер. Например: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### «Можно ли добавить читаемый человеком подпись?» + +Да. Установите свойство `CodeText` у `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### «Нужно ли освобождать генератор?» + +`BarcodeGenerator` реализует `IDisposable`. Оберните его в блок `using`, если создаёте много штрих‑кодов в цикле: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### «Как обрабатывать ошибки?» + +Оберните вызовы `Save` в блок `try…catch`, чтобы отлавливать `IOException` (проблемы с диском) или `ArgumentException` (некорректные параметры). Пример: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Итоги + +Мы рассмотрели всё, что нужно для **создания штрих‑кода planet** в C#: + +1. Инициализировать **генератор штрих‑кода Planet** с вашими данными. +2. Настроить **пиксели XDimension** в соответствии со спецификациями принтера. +3. Сохранить PNG с **заполненными полосами**. +4. Переключить `FilledBars` для получения **пустых полос**. +5. Сохранить второй PNG. + +Дальше вы можете изучать дополнительные **параметры BarcodeGenerator**, экспериментировать с другими симболологиями (`EncodeTypes.Postnet`, `EncodeTypes.Code128` и т.д.) или интегрировать изображения в почтовый рабочий процесс. + +--- + +**Готовы к следующему шагу?** Попробуйте добавить QR‑код в тот же документ или сгенерировать пакет штрих‑кодов Planet из CSV‑списка с помощью цикла `foreach`. API Aspose.BarCode достаточно гибок для пакетных операций, пользовательских цветов и даже векторного вывода SVG. + +Если возникнут проблемы, оставьте комментарий ниже или обратитесь к официальной документации Aspose.BarCode для более глубокого изучения продвинутых возможностей. Приятного кодинга! + +## Что изучать дальше? + +Следующие руководства охватывают смежные темы, построенные на техниках, продемонстрированных в этом пособии. Каждый ресурс содержит полностью работающие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [Create Barcode with Aspose - Set X & Y Dimensions in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/russian/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..1d2be2e22 --- /dev/null +++ b/barcode/russian/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-07-18 +description: Создайте штрих‑код RM4SCC на C# быстро; узнайте, как задать высоту штрих‑кода + и сгенерировать штрих‑код Planet с пользовательскими размерами. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: ru +lastmod: 2026-07-18 +og_description: Создайте штрих‑код RM4SCC на C# и узнайте, как задать высоту штрих‑кода. + Также посмотрите, как сгенерировать штрих‑код Planet с помощью той же библиотеки. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Создание штрих‑кода RM4SCC на C# – Быстрая установка пользовательской высоты +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Создание штрих‑кода RM4SCC в C# – Полное руководство по установке высоты +url: /ru/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание штрих‑кода RM4SCC в C# – Полное руководство по установке высоты + +Когда‑нибудь вам нужно было **создать штрих‑код RM4SCC** в приложении .NET, но вы не знали, как управлять его размером? Вы не одиноки. Независимо от того, создаёте ли вы систему рассылки или панель логистики, правильная высота штрих‑кода может стать разницей между успешным сканированием и неудачей. + +В этом руководстве мы пройдём весь процесс: от установки библиотеки до **генерации штрих‑кода Planet** в качестве примера рядом, и, наконец, до **того, как установить высоту штрих‑кода** для обоих типов штрих‑кодов. К концу вы получите готовое к запуску консольное приложение, которое выводит PNG‑файлы с точными нужными вам размерами. + +--- + +## Что понадобится + +- **.NET 6 SDK** (или любая современная версия .NET) – код работает и на .NET Framework, но .NET 6 — оптимальный вариант. +- **Aspose.BarCode for .NET** пакет NuGet – это библиотека, предоставляющая класс `BarcodeGenerator`. +- Небольшие знания C# – мы постараемся сделать синтаксис дружелюбным для начинающих. +- IDE или текстовый редактор (Visual Studio, VS Code, Rider — выбирайте, что вам нравится). + +> **Совет:** Если вы используете CI/CD конвейер, добавьте ссылку на NuGet в ваш `.csproj`, чтобы сборка никогда не забывала о зависимости. + +--- + +## Шаг 1: Настройка проекта + +Откройте терминал и создайте новый консольный проект: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +Вот и всё — ваш проект теперь ссылается на библиотеку, которая обеспечивает всё, что будет дальше. + +### Добавьте директивы using + +Откройте `Program.cs` и вставьте следующее в начало: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +Эти пространства имён дают нам доступ к `BarcodeGenerator` и перечислению форматов изображений, которое мы будем использовать позже. + +--- + +## Шаг 2: Определите вспомогательный метод для сохранения изображений + +Чтобы избежать повторения одинаковой логики сохранения, мы обернём её в небольшой метод. Это также демонстрирует **как установить высоту штрих‑кода** позже. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Почему это важно:** Централизация логики сохранения означает, что вам нужно будет менять формат или папку только в одном месте, если требования изменятся. + +--- + +## Шаг 3: Генерация штрих‑кода Planet (часть «генерация штрих‑кода planet») + +Прежде чем перейти к деталям RM4SCC, давайте создадим **штрих‑код Planet**. Это даст вам быструю визуальную проверку того, что библиотека работает. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Ожидаемый результат:** В папке `output` появятся два PNG‑файла — один с автоматически рассчитанной высотой библиотекой, другой ровно 100 px в высоту. + +--- + +## Шаг 4: Создание штрих‑кода RM4SCC — основная цель + +А теперь звезда шоу: **создать штрих‑код RM4SCC**. RM4SCC — это Royal Mail 4‑State Code, широко используемый в почтовой системе Великобритании. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**Что вы увидите:** +- `RM4SCCDefault.png` — библиотека выбирает удобную высоту на основе X‑dimension. +- `RM4SCCHeight100.png` — чёткий штрих‑код высотой 100 пикселей, готовый к печати на конвертах. + +> **Зачем устанавливать высоту?** Некоторые принтеры этикеток требуют минимальную высоту полосы для надёжного сканирования. Фиксируя высоту, вы гарантируете соответствие требованиям на разных устройствах. + +--- + +## Шаг 5: Понимание настроек высоты (Ответ на вопрос «как установить высоту штрих‑кода») + +И примеры Planet, и RM4SCC используют одно и то же свойство: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** — это объект `BarHeight`, который объединяет несколько единиц измерения (пиксели, миллиметры, дюймы). +- **`.Pixels`** — самая простая единица для вывода на экран, но вы также можете использовать `.Millimeters` или `.Inches`, если ориентируетесь на печатные носители. + +### Пограничные случаи и советы + +| Ситуация | Рекомендуемый подход | +|-----------|----------------------| +| **Очень маленькое X‑dimension (например, 1 px)** | Увеличьте `BarHeight`, чтобы штрих‑код оставался читаемым. | +| **Печать на высоко‑разрешающих принтерах этикеток** | Используйте `.Millimeters` для независимого от устройства размера. | +| **Смешанные типы штрих‑кодов в одном изображении** | Устанавливайте `BarHeight` *после* `XDimension` для каждого генератора, чтобы избежать случайного наследования. | +| **Динамические данные (например, коды, вводимые пользователем)** | Оборачивайте создание генератора в метод, принимающий параметры `code` и `height`. | + +--- + +## Шаг 6: Полный рабочий пример + +Ниже представлен единый, автономный пример программы, который вы можете скопировать и вставить в `Program.cs`. Он включает всё — от настройки проекта до сохранения изображений. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Запустите его с помощью: + +```bash +dotnet run +``` + +Вы должны увидеть вывод в консоли, подтверждающий сохранение каждого файла, а папка `output` будет содержать четыре PNG‑файла с именами, указанными выше. + +--- + +## Заключение + +Теперь вы знаете **как создать штрих‑код RM4SCC** в C# и управлять его размерами с помощью всего лишь нескольких назначений свойств. Мы также рассмотрели **генерацию штрих‑кода planet** как быструю проверку, и изучили нюансы **установки высоты штрих‑кода** для различных сценариев печати. + +Следующие шаги? Попробуйте заменить перечисление `EncodeTypes` на другие символьные наборы (Code128, QR, DataMatrix) и поэкспериментировать с `BarHeight` в миллиметрах для высоко‑разрешающих принтеров. Если нужно встроить штрих‑код в PDF, комбинируйте Aspose.BarCode с Aspose.PDF — ещё один мощный набор. + +Есть вопросы или хотите поделиться своими настройками? Оставьте комментарий ниже, и счастливого кодинга! + +## Что вам стоит изучить дальше? + +Следующие руководства охватывают тесно связанные темы, которые опираются на техники, продемонстрированные в этом руководстве. Каждый ресурс включает полные рабочие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [Как сгенерировать Aztec штрих‑код с пользовательским соотношением сторон, используя Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Как создать тихую зону штрих‑кода для ITF-14 с помощью Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Как создать тихую зону штрих‑кода для Code 16K с использованием Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/russian/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..5cdc43dbb --- /dev/null +++ b/barcode/russian/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-07-18 +description: Узнайте, как генерировать изображения штрих‑кодов с помощью .NET‑генератора + штрих‑кодов и легко менять высоту штрих‑кода для символов GS1‑Databar Omni‑Directional. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: ru +lastmod: 2026-07-18 +og_description: .NET‑генератор штрихкодов позволяет быстро создавать изображения штрихкодов. + Это руководство показывает, как генерировать штрихкоды, регулировать высоту полос + и сохранять файлы PNG. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Измените высоту штрихкода с помощью .NET‑генератора штрихкодов +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET‑генератор штрихкодов – изменить высоту штрихкода +url: /ru/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – изменение высоты штрих‑кода + +Когда‑нибудь задумывались **как генерировать штрих‑коды** без необходимости использовать десятки сторонних инструментов? В мире .NET существует удивительно простой способ сделать это, и ключевым элементом является **.net barcode generator**. Всего несколькими строками C# вы можете создать символ GS1‑Databar Omni‑Directional, отрегулировать высоту полос и сохранить результат в файл PNG. + +Если вы разрабатываете систему учёта, принтер этикеток для доставки или любое приложение, которому нужен сканируемый код, этот учебник поможет перейти от нуля к работающему штрих‑коду за несколько минут. Мы пройдёмся по полному коду, объясним, почему каждая настройка важна, и покажем, как **изменить высоту штрих‑кода** без нарушения спецификации. + +## Что вам понадобится + +- .NET 6.0 или новее (API работает одинаково на .NET Framework 4.7+) +- Ссылка на библиотеку штрих‑кодов (например, Aspose.BarCode for .NET – те же классы используются во многих коммерческих наборах) +- Среда разработки (Visual Studio, Rider или VS Code с расширением C#) +- Папка, в которой у вас есть права на запись — в ней учебник сохранит файлы PNG + +Вот и всё. Нет дополнительных пакетов NuGet, кроме самой библиотеки штрих‑кодов. + +## Использование .net barcode generator для изменения высоты штрих‑кода + +Ниже представлен **полный, исполняемый консольный пример**. Вставьте его в новый C#‑проект, укажите папку вывода и нажмите F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Почему каждая строка важна + +| Строка | Причина | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Создаёт экземпляр **.net barcode generator** с нужной символикой и данными. Перечисление `EncodeTypes.DatabarOmniDirectional` указывает библиотеке использовать формат GS1‑Databar Omni‑Directional. | +| `XDimension.Pixels = 2;` | X‑dimension — это ширина самой тонкой полосы. Установка значения *2 пикселя* даёт чёткое изображение на большинстве мониторов при небольшом размере файла. | +| `BarHeight.Pixels = 30;` | Это шаг **изменения высоты штрих‑кода**, определяющий высоту каждой полосы. Высота 30 пикселей — хороший вариант по умолчанию для небольших этикеток. | +| `generator.Save(...);` | Сохраняет штрих‑код в файл PNG. PNG — без потерь, что означает, что сканеры видят точно сгенерированный шаблон. | +| `BarHeight.Pixels = 60;` | Здесь мы **изменяем высоту штрих‑кода** ещё раз — на этот раз до 60 пикселей. Библиотека автоматически перерисовывает символ с новой размерностью при повторном вызове `Save`. | +| `Console.WriteLine(...);` | Выводит быстрый отзыв о том, что процесс завершён без исключений. | + +> **Pro tip:** Если вам нужен вывод более высокого разрешения для печати, замените `BarCodeImageFormat.Png` на `BarCodeImageFormat.Tiff` и увеличьте свойство `Resolution` (например, `generator.Parameters.ImageResolution = 300;`). Высота полос останется учтённой, только будет отрисована с более тонким DPI. + +## Как генерировать изображения штрих‑кодов с различными настройками + +Приведённый выше фрагмент покрывает основы, но в реальных сценариях часто требуются дополнительные настройки: + +### Регулировка X‑dimension для больших печатей +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Увеличение X‑dimension делает весь штрих‑код больше, не меняя закодированных данных. Это удобно, когда печатаете на больших этикетках. + +### Переключение форматов вывода +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG масштабируется бесконечно, что идеально подходит для веб‑сканеров, которым нужны чёткие векторные изображения. + +### Добавление читаемого человеком текста +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Включение `CodeTextVisible` добавляет исходные данные под штрих‑кодом, что полезно для проверки во время тестирования. + +## Распространённые подводные камни при **изменении высоты штрих‑кода** + +1. **Слишком маленькая высота** – Некоторые сканеры требуют минимальную высоту полос (часто 10 мм в физических единицах). Если задать `BarHeight.Pixels` слишком низко, полученное изображение может быть нечитаемым реальным сканером. Всегда тестируйте с целевым оборудованием. +2. **Несоответствие X‑dimension и высоты** – Огромная высота полос при крошечной X‑dimension выглядит растянутой и может вызвать ошибки декодирования. Стремитесь к сбалансированному соотношению (примерно 3:1‑5:1), если только спецификация не предписывает иначе. +3. **Забыли сбросить параметры** – Генератор сохраняет состояние между сохранениями. Если изменить `BarHeight` для одного изображения и затем использовать тот же экземпляр для другого штрих‑кода, прежняя высота останется. Сбросьте свойство или создайте новый `BarcodeGenerator` для каждого отдельного штрих‑кода. + +## Полный пример от начала до конца (включая установку NuGet) + +Если вы начинаете с нуля, выполните следующие шаги, чтобы запустить проект: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Замените автоматически сгенерированный `Program.cs` кодом из блока выше, **не забудьте заменить `YOUR_DIRECTORY`** на что‑то вроде `Path.Combine(Environment.CurrentDirectory, "output")`. Затем: + +```bash +dotnet run +``` + +Вы должны увидеть два PNG‑файла в папке `output`: + +- `DatabarBarHeight30Pixels.png` – компактный штрих‑код высотой 30 пикселей. +- `DatabarBarHeight60Pixels.png` – более высокий вариант высотой 60 пикселей. + +Оба изображения выглядят схоже, но второе имеет заметно более длинные полосы, что облегчает чтение сканерами низкого разрешения. + +![Barcode height example](/images/barcode-height.png){alt="Вывод .net barcode generator, показывающий разные высоты полос"} + +## Итоги и дальнейшие шаги + +Мы рассмотрели, как **генерировать штрих‑коды** с помощью **.net barcode generator**, точно настроили свойство **изменения высоты штрих‑кода** и сохранили результаты в формате PNG. Ключевые выводы: + +- Создайте генератор с правильным `EncodeTypes`. +- Управляйте визуальными размерами через `XDimension` и `BarHeight`. +- Вызывайте `Save` после каждого изменения, чтобы сохранить новое изображение. +- Настройте разрешение, формат, + +## Что стоит изучить дальше? + +Следующие учебники охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс содержит полностью работающие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [Как сгенерировать Aztec‑barcode с пользовательским соотношением сторон, используя Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Как создать расширенный код текста dotcode с помощью Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-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/spanish/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/spanish/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..bda21f91b --- /dev/null +++ b/barcode/spanish/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-07-18 +description: Ejemplo de generador de códigos de barras que muestra cómo establecer + dimensiones y generar una imagen de código de barras DataBar Stacked Omni‑Directional + en C#. Aprende rápidamente los tipos de codificación de códigos de barras. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: es +lastmod: 2026-07-18 +og_description: El ejemplo de generador de códigos de barras te guía para establecer + dimensiones, elegir tipos de codificación y crear proyectos de imágenes de códigos + de barras en C# con el mínimo código. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Ejemplo de Generador de Código de Barras – Creación Rápida de Imagen DataBar + en C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Ejemplo de Generador de Código de Barras – Crear Imagen DataBar en C# +url: /es/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ejemplo de Generador de Códigos de Barras – Crear Imagen DataBar en C# + +¿Alguna vez necesitaste un **barcode generator example** que realmente genere un código de barras del mundo real sin volverte loco? No estás solo. La mayoría de los desarrolladores se topan con un muro cuando intentan averiguar **how to set dimensions** para un código de barras DataBar Stacked Omni‑Directional, especialmente cuando la documentación está enterrada bajo capas de jerga. + +En este tutorial recorreremos un programa C# completo y listo para ejecutar que muestra **how to generate databar** imágenes, elige los **barcode encode types** correctos y, finalmente, **create barcode image c#** archivos que puedes insertar en cualquier proyecto. Sin rodeos, solo el código que puedes copiar‑pegar, más la lógica detrás de cada línea. + +## Lo que Necesitarás + +- **.NET 6** (o cualquier versión reciente de .NET) – la API que usamos apunta a .NET Standard, por lo que también funciona en .NET Framework. +- **Aspose.BarCode for .NET** – la biblioteca que proporciona `BarcodeGenerator`. Puedes obtenerla de NuGet con `Install-Package Aspose.BarCode`. +- Un **C# IDE** – Visual Studio, Rider o VS Code sirven. +- Una carpeta en disco donde se guardarán los archivos PNG (el código crea `DatabarAspectRatio15.png` y `DatabarAspectRatio30.png`). + +¿Tienes todo eso? Genial, vamos a sumergirnos. + +## Ejemplo de Generador de Códigos de Barras – Inicializar el Generador + +Primero lo primero: necesitamos una instancia de `BarcodeGenerator` configurada para la simbología **DataBar Stacked Omni‑Directional**. Este es el **barcode encode type** con el que trabajaremos. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Por qué es importante:** `EncodeTypes.DatabarStackedOmniDirectional` le indica a Aspose exactamente qué simbología renderizar. Si eliges el tipo incorrecto, el escáner no reconocerá el código de barras, sin importar lo bonita que se vea la imagen. + +## Cómo Establecer Dimensiones para el Código de Barras + +La legibilidad de un código de barras depende de su **X‑dimension** (el ancho de la barra más estrecha). En la mayoría de los casos, un valor de 2 píxeles funciona bien, pero puedes ajustarlo según tu impresora o pantalla. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Consejo profesional:** Si alguna vez te preguntas **how to set dimensions** para una familia de códigos de barras diferente, la misma cadena de propiedades (`Parameters.Barcode.XDimension`) se aplica; solo cambia el valor de `Pixels`. + +## Cómo Generar el Código de Barras DataBar Stacked Omni‑Directional + +Ahora que el generador está listo, jugaremos con la propiedad **aspect ratio**. Esto controla la relación altura‑ancho del DataBar, permitiéndote producir un símbolo corto y cuadrado o uno alto y estrecho. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **¿Qué está pasando?** `AspectRatio = 15` indica al motor que haga las barras 15 veces más altas que anchas. El PNG resultante se guarda justo al lado de tu ejecutable. + +## Crear Imagen de Código de Barras C# – Cambiando la Relación de Aspecto + +Demostremos la flexibilidad cambiando la relación a 30 y guardando un segundo archivo. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +Al ejecutar el programa, tendrás dos archivos PNG: + +| Archivo | Relación de aspecto | Tamaño aprox. | +|------|--------------|--------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Ábrelos en cualquier visor de imágenes; deberías ver símbolos DataBar limpios y escaneables. + +## Visión General de los Tipos de Codificación de Código de Barras (Opcional pero Útil) + +Si tienes curiosidad sobre otros **barcode encode types** compatibles con Aspose, aquí tienes una hoja de referencia rápida: + +| EncodeTypes Enum | Descripción | +|------------------|-------------| +| `EncodeTypes.Code128` | Alfanumérico de alta densidad | +| `EncodeTypes.QR` | Código matricial 2‑D | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar para retail | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Nuestro enfoque** – compacto, omnidireccional | + +## Errores Comunes y Cómo Evitarlos + +- **Missing NuGet package** – El código no compilará sin `Aspose.BarCode`. Ejecuta `dotnet add package Aspose.BarCode` primero. +- **Wrong file path** – Si utilizas una ruta absoluta, verifica las barras invertidas (`\\`) en Windows. Las rutas relativas (como se muestra) mantienen la portabilidad. +- **Aspect ratio too extreme** – Relaciones superiores a 50 pueden hacer que el código de barras sea demasiado alto para los escáneres típicos. Mantén entre 15‑30 para la mayoría de los casos. + +## Código Fuente Completo (Listo para Copiar‑Pegar) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Ejecuta el programa (`dotnet run` o presiona **F5** en Visual Studio) y verás el mensaje en la consola confirmando que los archivos están en disco. + +![Ejemplo de salida del generador de códigos de barras mostrando código DataBar con relación de aspecto 15](placeholder/path/to/image.png){: .align-center alt="Ejemplo de salida del generador de códigos de barras mostrando código DataBar con relación de aspecto 15"} + +## Conclusión + +Acabamos de completar un **barcode generator example** que demuestra **how to set dimensions**, elige los **barcode encode types** correctos y, finalmente, **create barcode image c#** archivos que puedes incrustar en cualquier lugar. El código es pequeño, los conceptos son muy claros, y ahora tienes una base sólida para ampliar la solución—quizás añadiendo subtítulos de texto, rotando la imagen o cambiando a una simbología diferente. + +### ¿Qué Sigue? + +- Experimenta con **different X‑dimensions** para ver cómo cambia la tolerancia del escáner. +- Prueba otros **EncodeTypes** como `Code128` o `QR` para ampliar tu conjunto de herramientas. +- Automatiza la generación por lotes: recorre un CSV de IDs de productos y genera un PNG para cada uno. + +Si encuentras algún problema, deja un comentario abajo o revisa la documentación de Aspose.BarCode; está llena de ejemplos que complementan lo que cubrimos aquí. + +¡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 amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Cómo Generar Código de Barras - Tipos de Códigos de Barras Unidimensionales](/barcode/english/net/one-dimensional-barcode-types/) +- [Crear imagen de código de barras C# – Ejemplo GS1 DataMatrix](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [Cómo Generar Códigos 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/spanish/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/spanish/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..82223bb34 --- /dev/null +++ b/barcode/spanish/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-07-18 +description: Crea códigos de barras Planet rápidamente con C#. Aprende a generar barras + llenas y vacías, establecer la dimensión X y guardar imágenes PNG, todo en un solo + tutorial. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: es +lastmod: 2026-07-18 +og_description: Crea códigos de barras Planet al instante. Esta guía te muestra cómo + establecer la dimensión X, alternar entre barras rellenas y vacías, y exportar archivos + PNG con Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Crear código de barras planetario en C# – Guía completa de programación +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Crear código de barras Planet en C# – Guía completa paso a paso +url: /es/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear Planet Barcode en C# – Guía completa paso a paso + +¿Alguna vez necesitaste **create planet barcode** imágenes pero no estabas seguro de qué propiedades ajustar? No estás solo. Muchos desarrolladores se topan con un obstáculo cuando las barras rellenas por defecto no son lo que la especificación exige, o cuando el ancho de la barra debe coincidir con el DPI de una impresora. + +En este tutorial aprenderás exactamente cómo **create planet barcode** archivos usando la biblioteca Aspose.BarCode, cómo controlar los **XDimension pixels**, y cómo alternar entre **filled bars** y **empty bars** sin volver a escribir código. Al final tendrás dos archivos PNG—uno con barras sólidas y otro con barras huecas—listos para cualquier sistema postal que espere la simbología Planet. + +## Requisitos + +- .NET 6.0 o posterior (el código también funciona en .NET Framework 4.7 + ) +- Paquete NuGet Aspose.BarCode for .NET (`Install-Package Aspose.BarCode`) +- Conocimientos básicos de C# (verás por qué usamos sentencias `using` más adelante) +- Una carpeta con permisos de escritura donde se guardarán los PNG + +Si ya cuentas con esto, podemos pasar directamente a la implementación. + +## Paso 1 – Configurar el proyecto y agregar la biblioteca + +Primero, crea una nueva aplicación de consola (o cualquier proyecto C#) y referencia la **Planet barcode generator** library. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Consejo profesional:** En Visual Studio, haz clic derecho en el proyecto → *Manage NuGet Packages* → busca **Aspose.BarCode** y haz clic en *Install*. Esto te dará acceso a `BarcodeGenerator` y a todos los **BarcodeGenerator parameters** que necesitarás. + +## Paso 2 – Inicializar el generador de Planet Barcode + +Ahora creamos realmente la instancia del generador **planet barcode** y le pasamos los datos que queremos codificar (`"123456"` en este ejemplo). El enum `EncodeTypes.Planet` indica a la biblioteca qué simbología usar. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Por qué es importante:** La bandera `EncodeTypes.Planet` aplica automáticamente el checksum correcto y las reglas de diseño para el código postal Planet, por lo que no tienes que calcularlas manualmente. + +## Paso 3 – Configurar X‑Dimension (Ancho de barra) + +La mayoría de las impresoras esperan que cada barra tenga un número específico de píxeles. Aquí establecemos los **XDimension pixels** a `4`, que es un valor común para impresoras térmicas de 203 dpi. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Caso límite:** Si apuntas a una impresora de 300 dpi, podrías necesitar `3` o `5` píxeles en su lugar. Ajusta este valor según la documentación de tu dispositivo. + +## Paso 4 – Guardar la versión de barras rellenas + +Por defecto el generador produce **filled bars** (rectángulos negros sólidos). Guardémoslo en disco: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Reemplaza `YOUR_DIRECTORY` con una ruta absoluta o relativa a la que tu aplicación pueda escribir. Después de ejecutar esta línea encontrarás un archivo PNG que se ve como un clásico Planet barcode—perfecto para probar contra un escáner postal. + +## Paso 5 – Cambiar a barras vacías + +A veces los servicios postales requieren el estilo de “empty bars”, donde las barras se recortan de un fondo blanco en lugar de pintarse negras. La biblioteca expone un interruptor sencillo: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Establecer `FilledBars` a `false` indica al renderizador que invierta la lógica de relleno de barras. No es necesario crear una nueva instancia de `BarcodeGenerator`; simplemente ajustamos los **BarcodeGenerator parameters** existentes. + +## Paso 6 – Guardar la versión de barras vacías + +Finalmente, exporta la segunda imagen: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Ahora tienes dos archivos PNG distintos, cada uno cumpliendo con un requisito visual diferente. + +## Ejemplo completo funcionando + +Juntando todas las piezas, aquí tienes el programa completo listo para copiar y pegar: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Salida esperada** (en la consola): + +``` +Both Planet barcode images have been generated successfully. +``` + +Y en `C:\Barcodes\` verás: + +- `PostalPlanetFilledBars.png` – barras negras sólidas +- `PostalPlanetEmptyBars.png` – barras blancas con contornos negros + +Ábrelas con cualquier visor de imágenes; ambas deberían cumplir con la especificación Planet. + +## Preguntas frecuentes y consejos + +### “¿Puedo cambiar el formato de imagen?” + +Claro. El método `Save` acepta `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, etc. Simplemente reemplaza `BarCodeImageFormat.Png` por el formato que desees. + +### “¿Qué pasa si necesito una altura de código de barras diferente?” + +Usa `planetBarcode.Parameters.Barcode.BarHeight` (en puntos) para aumentar o disminuir el tamaño vertical. Por ejemplo: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “¿Hay forma de añadir una leyenda legible por humanos?” + +Sí. Asigna la propiedad `CodeText` en `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “¿Necesito disponer del generador?” + +`BarcodeGenerator` implementa `IDisposable`. Envuélvelo en un bloque `using` si vas a crear muchos códigos de barras dentro de un bucle: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “¿Qué hay del manejo de errores?” + +Envuelve las llamadas a `Save` en un bloque `try…catch` para capturar `IOException` (problemas de disco) o `ArgumentException` (parámetros inválidos). Ejemplo: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Resumen + +Hemos cubierto todo lo que necesitas para **create planet barcode** imágenes en C#: + +1. Inicializar el **Planet barcode generator** con tus datos. +2. Ajustar los **XDimension pixels** para que coincidan con las especificaciones de la impresora. +3. Guardar un PNG con **filled bars**. +4. Cambiar `FilledBars` para producir **empty bars**. +5. Guardar el segundo PNG. + +Desde aquí puedes explorar más **BarcodeGenerator parameters**, experimentar con otras simbologías (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, etc.), o integrar las imágenes en un flujo de trabajo de envío postal. + +--- + +**¿Listo para el siguiente paso?** Prueba a añadir un código QR al mismo documento, o genera un lote de Planet barcodes a partir de una lista CSV usando un bucle `foreach`. La API de Aspose.BarCode es lo suficientemente flexible como para manejar operaciones masivas, colores personalizados e incluso salida vectorial SVG. + +Si encuentras algún obstáculo, deja un comentario abajo o consulta la documentación oficial de Aspose.BarCode para profundizar en funciones avanzadas. ¡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 características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Crear código de barras con Aspose - Establecer dimensiones X & Y en Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [Cómo crear imágenes de código de barras code128 en Java con Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [Cómo crear código de barras code128 en Java y establecer la altura de barra](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/spanish/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..0a59de74a --- /dev/null +++ b/barcode/spanish/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-07-18 +description: Crea un código de barras RM4SCC en C# rápidamente; aprende cómo establecer + la altura del código de barras y también generar un código de barras Planet con + dimensiones personalizadas. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: es +lastmod: 2026-07-18 +og_description: Crea un código de barras RM4SCC en C# y descubre cómo establecer la + altura del código de barras. También ve cómo generar un código de barras Planet + con la misma biblioteca. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Crear código de barras RM4SCC en C# – Establecer altura personalizada rápidamente +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Crear código de barras RM4SCC en C# – Guía completa para establecer la altura +url: /es/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear código de barras RM4SCC en C# – Guía completa para establecer la altura + +¿Alguna vez necesitaste **crear código de barras RM4SCC** en una aplicación .NET pero no estabas seguro de cómo controlar su tamaño? No estás solo. Ya sea que estés construyendo un sistema de correo o un panel de logística, obtener la altura correcta del código de barras puede ser la diferencia entre una lectura que funciona y una que falla. + +En este tutorial recorreremos todo el proceso: desde la instalación de la biblioteca, hasta **generar código de barras Planet** como ejemplo paralelo, y finalmente **cómo establecer la altura del código de barras** para ambos tipos de códigos. Al final tendrás una aplicación de consola lista para ejecutar que genera archivos PNG con las dimensiones exactas que necesitas. + +--- + +## Lo que necesitarás + +- **.NET 6 SDK** (o cualquier versión reciente de .NET) – el código funciona también en .NET Framework, pero .NET 6 es el punto óptimo. +- **Aspose.BarCode for .NET** paquete NuGet – esta es la biblioteca que proporciona la clase `BarcodeGenerator`. +- Un conocimiento básico de C# – mantendremos la sintaxis amigable para principiantes. +- Un IDE o editor de texto (Visual Studio, VS Code, Rider—elige el que prefieras). + +> **Consejo profesional:** Si estás en una canalización CI/CD, agrega la referencia NuGet en tu `.csproj` para que la compilación nunca olvide la dependencia. + +## Paso 1: Configurar el proyecto + +Abre una terminal y crea un nuevo proyecto de consola: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +Eso es todo—tu proyecto ahora referencia la biblioteca que impulsa todo lo que sigue. + +### Agregar las directivas using + +Abre `Program.cs` y pega lo siguiente en la parte superior: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +## Paso 2: Definir un método auxiliar para guardar imágenes + +Para evitar repetir la misma lógica de guardado, la envolveremos en un pequeño método. Esto también demuestra **cómo establecer la altura del código de barras** más adelante. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Por qué es importante:** Centralizar la lógica de guardado significa que solo tendrás que cambiar el formato o la carpeta en un solo lugar si los requisitos cambian. + +## Paso 3: Generar un código de barras Planet (la parte “generar código de barras planet”) + +Antes de sumergirnos en los detalles de RM4SCC, generemos un **código de barras Planet**. Esto te brinda una rápida comprobación visual de que la biblioteca funciona. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Salida esperada:** Aparecen dos archivos PNG en la carpeta `output`—uno con la altura auto‑calculada por la biblioteca, el otro exactamente de 100 px de alto. + +## Paso 4: Crear código de barras RM4SCC – Objetivo principal + +Ahora, la estrella del espectáculo: **crear código de barras RM4SCC**. RM4SCC es el Royal Mail 4‑State Code, ampliamente usado en el sistema postal del Reino Unido. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**Lo que verás:** +- `RM4SCCDefault.png` – la biblioteca decide una altura cómoda basada en la X‑dimension. +- `RM4SCCHeight100.png` – un código de barras nítido de 100 píxeles de alto listo para imprimir en sobres. + +> **¿Por qué establecer la altura?** Algunas impresoras de etiquetas exigen una altura mínima de barra para un escaneo fiable. Al fijar la altura garantizas el cumplimiento en todos los dispositivos. + +## Paso 5: Entendiendo la configuración de altura (respondiendo a “cómo establecer la altura del código de barras”) + +Tanto los ejemplos Planet como RM4SCC usan la misma propiedad: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** es un objeto `BarHeight` que agrupa varias unidades de medida (píxeles, milímetros, pulgadas). +- **`.Pixels`** es la unidad más directa para salida orientada a pantalla, pero también puedes usar `.Millimeters` o `.Inches` si apuntas a medios impresos. + +### Casos límite y consejos + +| Situación | Enfoque recomendado | +|-----------|----------------------| +| **Dimensión X muy pequeña (p. ej., 1 px)** | Incrementa `BarHeight` para mantener el código de barras legible. | +| **Impresión en impresoras de etiquetas de alta resolución** | Usa `.Millimeters` para un dimensionado independiente del dispositivo. | +| **Tipos de código de barras mixtos en una sola imagen** | Establece `BarHeight` *después* de `XDimension` para cada generador para evitar herencia accidental. | +| **Datos dinámicos (p. ej., códigos ingresados por el usuario)** | Envuelve la creación del generador en un método que acepte parámetros `code` y `height`. | + +## Paso 6: Ejemplo completo funcional + +A continuación tienes un programa único y autocontenido que puedes copiar y pegar en `Program.cs`. Incluye todo, desde la configuración del proyecto hasta el guardado de imágenes. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Ejecuta con: + +```bash +dotnet run +``` + +Deberías ver la salida de consola confirmando cada archivo guardado, y la carpeta `output` contendrá cuatro PNG que coinciden con los nombres mostrados arriba. + +## Conclusión + +Ahora sabes **cómo crear código de barras RM4SCC** en C# y controlar sus dimensiones con solo un par de asignaciones de propiedades. También cubrimos **generar código de barras planet** como una rápida comprobación, y exploramos los matices de **cómo establecer la altura del código de barras** para diferentes escenarios de impresión. + +¿Próximos pasos? Prueba cambiar el enum `EncodeTypes` por otras simbologías (Code128, QR, DataMatrix) y experimenta con `BarHeight` en milímetros para impresoras de alta resolución. Si necesitas incrustar el código de barras en un PDF, combina Aspose.BarCode con Aspose.PDF—otra combinación poderosa. + +¿Tienes preguntas o quieres compartir tus propios ajustes? Deja un comentario abajo, ¡y 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 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 generar código de barras Aztec con relación de aspecto personalizada usando Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Cómo crear zona silenciosa de código de barras para ITF-14 usando Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Cómo crear zona silenciosa de código de barras para Code 16K usando Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/spanish/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..9e70077e2 --- /dev/null +++ b/barcode/spanish/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-07-18 +description: Aprende cómo generar imágenes de códigos de barras con un generador de + códigos de barras .NET y cambia fácilmente la altura del código de barras para los + símbolos GS1‑Databar Omni‑Directional. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: es +lastmod: 2026-07-18 +og_description: El generador de códigos de barras .net le permite crear rápidamente + imágenes de códigos de barras. Esta guía muestra cómo generar códigos de barras, + ajustar la altura de las barras y guardar archivos PNG. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Cambiar la altura del código de barras con el generador de códigos de barras + .net +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET generador de códigos de barras – cambiar la altura del código de barras +url: /es/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – cambiar la altura del código de barras + +¿Alguna vez te has preguntado **cómo generar códigos de barras** sin tener que manejar una docena de herramientas de terceros? En el mundo .NET hay una forma sorprendentemente sencilla de hacerlo, y la pieza clave es el **.net barcode generator**. Con solo unas pocas líneas de C# puedes crear un símbolo GS1‑Databar Omni‑Directional, ajustar la altura de la barra y guardar el resultado en un archivo PNG. + +Si estás construyendo un sistema de inventario, una impresora de etiquetas de envío, o cualquier aplicación que necesite un código escaneable, este tutorial te llevará de cero a un código de barras funcional en minutos. Revisaremos el código completo, explicaremos por qué cada configuración es importante y te mostraremos cómo **cambiar la altura del código de barras** sin romper la especificación. + +## Lo que necesitarás + +- .NET 6.0 o posterior (la API funciona igual en .NET Framework 4.7+) +- Una referencia a la biblioteca de códigos de barras (por ejemplo, Aspose.BarCode for .NET – las mismas clases son usadas por muchos kits comerciales) +- Un entorno de desarrollo (Visual Studio, Rider o VS Code con la extensión C#) +- Una carpeta donde tengas permiso de escritura – el tutorial guardará archivos PNG allí + +Eso es todo. No se requieren paquetes NuGet adicionales más allá de la propia biblioteca de códigos de barras. + +## Usando el .net barcode generator para cambiar la altura del código de barras + +A continuación tienes un **programa de consola completo y ejecutable**. Pégalo en un nuevo proyecto C#, ajusta la carpeta de salida y pulsa F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Por qué cada línea es importante + +| Línea | Razón | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Instancia el **.net barcode generator** con la simbología y los datos deseados. El enumerado `EncodeTypes.DatabarOmniDirectional` indica a la biblioteca que use el formato GS1‑Databar Omni‑Directional. | +| `XDimension.Pixels = 2;` | La X‑dimension es el ancho de la barra más delgada. Configurarla a *2 píxeles* produce una imagen nítida en la mayoría de monitores mientras mantiene bajo el tamaño del archivo. | +| `BarHeight.Pixels = 30;` | Este es el paso de **cambiar la altura del código de barras** que determina cuán alta será cada barra. Una altura de 30 píxeles es un buen valor predeterminado para etiquetas pequeñas. | +| `generator.Save(...);` | Guarda el código de barras en un archivo PNG. PNG es sin pérdida, lo que significa que los escáneres ven el patrón exacto que generaste. | +| `BarHeight.Pixels = 60;` | Aquí **cambiamos la altura del código de barras** nuevamente—esta vez a 60 píxeles. La biblioteca vuelve a renderizar automáticamente el símbolo con la nueva dimensión cuando llamas a `Save` por segunda vez. | +| `Console.WriteLine(...);` | Te brinda una respuesta rápida de que el proceso terminó sin lanzar una excepción. | + +> **Consejo profesional:** Si necesitas una salida de mayor resolución para impresión, cambia `BarCodeImageFormat.Png` a `BarCodeImageFormat.Tiff` y aumenta la propiedad `Resolution` (p. ej., `generator.Parameters.ImageResolution = 300;`). La altura de la barra seguirá respetándose, solo se renderizará a un DPI más fino. + +## Cómo generar imágenes de códigos de barras con diferentes configuraciones + +El fragmento anterior cubre lo básico, pero los escenarios del mundo real a menudo requieren ajustes adicionales: + +### Ajustando la X‑dimension para impresiones más grandes +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Aumentar la X‑dimension hace que todo el código de barras sea más grande sin alterar los datos codificados. Es útil cuando imprimes en etiquetas grandes. + +### Cambiando formatos de salida +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG escala infinitamente, lo que es perfecto para escáneres basados en web que necesitan vectores nítidos. + +### Añadiendo texto legible por humanos +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Activar `CodeTextVisible` agrega los datos sin procesar bajo el código de barras, útil para verificación durante pruebas. + +## Errores comunes al **cambiar la altura del código de barras** + +1. **Altura demasiado pequeña** – Algunos escáneres requieren una altura mínima de barra (a menudo 10 mm en unidades físicas). Si estableces `BarHeight.Pixels` demasiado bajo, la imagen generada podría ser ilegible en un escáner real. Siempre prueba con tu hardware objetivo. +2. **Dimensión X y altura desajustadas** – Una altura de barra enorme combinada con una X‑dimension diminuta puede verse estirada y causar errores de decodificación. Busca una proporción equilibrada (aproximadamente 3:1 a 5:1) a menos que la especificación indique lo contrario. +3. **Olvidar restablecer los parámetros** – El generador mantiene el estado entre guardados. Si cambias `BarHeight` para una imagen y luego reutilizas la misma instancia para otro código de barras, la altura anterior permanecerá. Restablece la propiedad o instancia un nuevo `BarcodeGenerator` para cada código de barras distinto. + +## Ejemplo completo de extremo a extremo (incluyendo instalación de NuGet) + +Si estás comenzando desde cero, sigue estos pasos para poner en marcha el proyecto: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Reemplaza el `Program.cs` autogenerado con el bloque de código mostrado anteriormente, **recuerda reemplazar `YOUR_DIRECTORY`** con algo como `Path.Combine(Environment.CurrentDirectory, "output")`. Luego: + +```bash +dotnet run +``` + +Deberías ver dos archivos PNG en la carpeta `output`: + +- `DatabarBarHeight30Pixels.png` – un código de barras compacto de 30 píxeles de altura. +- `DatabarBarHeight60Pixels.png` – una versión más alta de 60 píxeles. + +Ambas imágenes se verán similares, pero la segunda tendrá barras notablemente más largas, facilitando la lectura para escáneres de baja resolución. + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator output mostrando diferentes alturas de barra"} + +## Recapitulación y próximos pasos + +Hemos cubierto cómo **generar códigos de barras** usando un **.net barcode generator**, afinado la propiedad **cambiar la altura del código de barras**, y guardado los resultados en formato PNG. Los puntos clave son: + +- Instanciar el generador con el `EncodeTypes` correcto. +- Controlar el tamaño visual mediante `XDimension` y `BarHeight`. +- Llamar a `Save` después de cada cambio para persistir una nueva imagen. +- Ajustar la resolución, el formato, + +## ¿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 generar códigos de barras Aztec con relación de aspecto personalizada usando Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Cómo crear texto de código extendido dotcode con Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Cómo generar códigos de barras DataMatrix (ECC 200) con 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/swedish/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/swedish/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..cdee07d77 --- /dev/null +++ b/barcode/swedish/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-07-18 +description: Exempel på streckkodsgenerator som visar hur man ställer in dimensioner + och genererar en DataBar Stacked Omni‑Directional‑streckkodsbild i C#. Lär dig snabbt + streckkodskodningstyper. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: sv +lastmod: 2026-07-18 +og_description: Barcode‑generatorexemplet guidar dig genom hur du ställer in dimensioner, + väljer kodningstyper för streckkoder och skapar streckkodsbilder i C#‑projekt med + minimal kod. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Exempel på streckkodsgenerator – Snabb skapande av DataBar-bild i C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Exempel på streckkodsgenerator – Skapa DataBar-bild i C# +url: /sv/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode Generator‑exempel – Skapa DataBar‑bild i C# + +Har du någonsin behövt ett **barcode generator example** som faktiskt skriver ut en riktig streckkod utan att dra i håret? Du är inte ensam. De flesta utvecklare stöter på problem när de försöker lista ut **hur man ställer in dimensioner** för en DataBar Stacked Omni‑Directional streckkod, särskilt när dokumentationen är begravd under lager av jargong. + +I den här handledningen går vi igenom ett komplett, färdigt‑att‑köra C#‑program som visar **how to generate databar** bilder, väljer rätt **barcode encode types**, och slutligen **create barcode image c#** filer som du kan släppa in i vilket projekt som helst. Inga onödigheter—bara koden du kan kopiera‑klistra, plus resonemanget bakom varje rad. + +## Vad du behöver + +- **.NET 6** (eller någon nyare .NET‑version) – API‑et vi använder riktar sig mot .NET Standard, så det fungerar även på .NET Framework. +- **Aspose.BarCode for .NET** – biblioteket som tillhandahåller `BarcodeGenerator`. Du kan hämta det från NuGet med `Install-Package Aspose.BarCode`. +- En **C# IDE** – Visual Studio, Rider eller VS Code räcker. +- En mapp på disken där PNG‑filerna sparas (koden skapar `DatabarAspectRatio15.png` och `DatabarAspectRatio30.png`). + +Har du allt? Bra—låt oss dyka ner. + +## Barcode Generator‑exempel – Initiera generatorn + +Först och främst: vi behöver en instans av `BarcodeGenerator` konfigurerad för **DataBar Stacked Omni‑Directional**‑symbologi. Detta är den **barcode encode type** vi kommer att arbeta med. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Varför detta är viktigt:** `EncodeTypes.DatabarStackedOmniDirectional` talar om för Aspose exakt vilken symbologi som ska renderas. Om du väljer fel typ kommer skannern inte att känna igen streckkoden, oavsett hur snygg bilden ser ut. + +## Hur man ställer in dimensioner för streckkoden + +En streckkods läsbarhet beror på dess **X‑dimension** (bredden på den smalaste stapeln). I de flesta fall fungerar ett värde på 2 pixlar bra, men du kan justera det för att passa din skrivare eller skärm. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Proffstips:** Om du någonsin undrar **hur man ställer in dimensioner** för en annan streckkodsfamilj, gäller samma egenskapskedja (`Parameters.Barcode.XDimension`)—byt bara `Pixels`‑värdet. + +## Hur man genererar DataBar Stacked Omni‑Directional streckkod + +Nu när generatorn är klar kommer vi att leka med egenskapen **aspect ratio**. Den styr förhållandet mellan höjd och bredd för DataBar, så att du kan skapa en kort, kvadratisk symbol eller en hög, smal. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Vad händer?** `AspectRatio = 15` instruerar motorn att göra staplarna 15  gånger högre än de är breda. Den resulterande PNG‑filen sparas precis bredvid ditt körbara program. + +## Skapa streckkodsbilder i C# – Ändra aspect ratio + +Låt oss bevisa flexibiliteten genom att byta ratio till 30 och spara en andra fil. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +När du kör programmet får du två PNG‑filer: + +| Fil | Aspect Ratio | Ungef. storlek | +|------|--------------|----------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Öppna dem i någon bildvisare—du bör se rena, skannbara DataBar‑symboler. + +## Översikt över barcode encode types (Valfritt men praktiskt) + +Om du är nyfiken på andra **barcode encode types** som stöds av Aspose, här är ett snabbt fusklapp: + +| EncodeTypes Enum | Beskrivning | +|------------------|-------------| +| `EncodeTypes.Code128` | High‑density alphanumeric | +| `EncodeTypes.QR` | 2‑D matrix code | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar for retail | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Our focus** – compact, omnidirectional | + +Att känna till rätt enum sparar dig från mycket trial‑and‑error när du byter projekt. + +## Vanliga fallgropar & hur man undviker dem + +- **Missing NuGet package** – Koden kommer inte att kompilera utan `Aspose.BarCode`. Kör `dotnet add package Aspose.BarCode` först. +- **Wrong file path** – Om du använder en absolut sökväg, dubbelkolla bakstrecken (`\\`) på Windows. Relativa sökvägar (som visas) håller det portabelt. +- **Aspect ratio too extreme** – Ratio över 50 kan göra streckkoden för hög för vanliga skannrar. Håll dig till 15‑30 för de flesta användningsfall. + +## Fullständig källkod (Klar att kopiera‑klistra) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Kör programmet (`dotnet run` eller tryck **F5** i Visual Studio) så ser du konsolmeddelandet som bekräftar att filerna finns på disken. + +![Barcode generator example output showing DataBar barcode with aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Barcode generator‑exempelutdata som visar DataBar‑streckkod med aspect ratio 15"} + +## Sammanfattning + +Vi har just avslutat ett **barcode generator example** som demonstrerar **how to set dimensions**, väljer rätt **barcode encode types**, och slutligen **create barcode image c#** filer som du kan bädda in var som helst. Koden är liten, koncepten är kristallklara, och du har nu en solid grund för att utöka lösningen—kanske lägga till textbeskrivningar, rotera bilden, eller byta till en annan symbologi. + +### Vad blir nästa? + +- Experimentera med **different X‑dimensions** för att se hur skannertolerans förändras. +- Prova andra **EncodeTypes** som `Code128` eller `QR` för att bredda ditt verktygssats. +- Automatisera batch‑generering: loopa över en CSV med produkt‑ID:n och skapa en PNG för varje. + +Om du stöter på problem, lämna en kommentar nedan eller kolla Aspose.BarCode‑dokumentationen—den är full av exempel som kompletterar det vi gick igenom här. + +Lycka till med kodningen, 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 genererar streckkod – En-dimensionella streckkodstyper](/barcode/english/net/one-dimensional-barcode-types/) +- [Skapa streckkodsbilder i C# – GS1 DataMatrix‑exempel](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [Hur man genererar DataMatrix‑streckkoder (ECC 200) med Aspose.BarCode för .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/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/swedish/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..e5c7c6e31 --- /dev/null +++ b/barcode/swedish/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-07-18 +description: Skapa Planet‑streckkod snabbt med C#. Lär dig hur du genererar fyllda + och tomma staplar, ställer in X‑dimensionen och sparar PNG‑bilder – allt i en handledning. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: sv +lastmod: 2026-07-18 +og_description: Skapa Planet‑streckkod omedelbart. Den här guiden visar hur du ställer + in X‑dimension, växlar mellan fyllda och tomma staplar och exporterar PNG‑filer + med Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Skapa Planet Barcode i C# – Fullständig programmeringsgenomgång +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Skapa Planet Barcode i C# – Fullständig steg‑för‑steg‑guide +url: /sv/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa Planet-streckkod i C# – Fullständig steg‑för‑steg‑guide + +Har du någonsin behövt **create planet barcode** bilder men var osäker på vilka egenskaper som ska justeras? Du är inte ensam. Många utvecklare stöter på problem när de förifyllda staplarna inte är vad specifikationen kräver, eller när stapelbredden måste matcha en skrivarens DPI. + +I den här handledningen kommer du att lära dig exakt hur du **create planet barcode** filer med Aspose.BarCode-biblioteket, hur du styr **XDimension pixels**, och hur du växlar mellan **filled bars** och **empty bars** utan att skriva om någon kod. I slutet har du två PNG-filer – en med solida staplar och en med ihåliga staplar – redo för vilket postsystem som helst som förväntar sig Planet‑symbologi. + +## Förutsättningar + +- .NET 6.0 eller senare (koden fungerar även på .NET Framework 4.7 +) +- Aspose.BarCode för .NET NuGet‑paket (`Install-Package Aspose.BarCode`) +- Grundläggande C#‑kunskaper (du kommer att se varför vi använder `using`‑satser senare) +- En skrivbar mapp på disken där PNG‑filerna ska sparas + +Om du har dessa kan vi hoppa rakt in i implementeringen. + +## Steg 1 – Ställ in projektet och lägg till biblioteket + +Först, skapa en ny konsolapp (eller något C#‑projekt) och referera till **Planet barcode generator**‑biblioteket. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Proffstips:** I Visual Studio, högerklicka på projektet → *Manage NuGet Packages* → sök efter **Aspose.BarCode** och klicka på *Install*. Detta ger dig åtkomst till `BarcodeGenerator` och alla **BarcodeGenerator parameters** du kommer att behöva. + +## Steg 2 – Initiera Planet Barcode Generator + +Nu skapar vi faktiskt en **create planet barcode**‑generatorinstans och matar den med de data vi vill koda (`"123456"` i detta exempel). Enum‑värdet `EncodeTypes.Planet` talar om för biblioteket vilken symbologi som ska användas. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Varför detta är viktigt:** Flaggan `EncodeTypes.Planet` tillämpar automatiskt korrekt kontrollsumma och layoutregler för Planet‑poststapelkod, så du behöver inte beräkna dem manuellt. + +## Steg 3 – Konfigurera X‑Dimension (stapelförhållande) + +De flesta skrivare förväntar sig att varje stapel har ett specifikt antal pixlar. Här sätter vi **XDimension pixels** till `4`, vilket är ett vanligt värde för 203 dpi termiska skrivare. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Edge case:** Om du riktar dig mot en 300 dpi‑skrivare kan du behöva `3` eller `5` pixlar istället. Justera detta värde baserat på din enhets dokumentation. + +## Steg 4 – Spara versionen med fyllda staplar + +Som standard genererar generatorn **filled bars** (solida svarta rektanglar). Låt oss skriva detta till disk: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Ersätt `YOUR_DIRECTORY` med en absolut eller relativ sökväg som din app kan skriva till. Efter att den här raden har körts hittar du en PNG‑fil som ser ut som en klassisk Planet‑stapelkod – perfekt för testning mot en postskanner. + +## Steg 5 – Växla till tomma staplar + +Ibland kräver posttjänster stilen “empty bars”, där staplarna är urholkade i en vit bakgrund istället för målade svarta. Biblioteket erbjuder en enkel växel: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Att sätta `FilledBars` till `false` instruerar renderaren att invertera stapelfyllningslogiken. Ingen anledning att skapa en ny `BarcodeGenerator`‑instans; vi justerar bara de befintliga **BarcodeGenerator parameters**. + +## Steg 6 – Spara versionen med tomma staplar + +Slutligen, exportera den andra bilden: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Nu har du två separata PNG‑filer, var och en som uppfyller ett annat visuellt krav. + +## Fullt fungerande exempel + +När vi sätter ihop alla bitarna, här är det kompletta, kopiera‑och‑klistra‑klara programmet: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Förväntad output** (i konsolen): + +``` +Both Planet barcode images have been generated successfully. +``` + +Och i `C:\Barcodes\` kommer du att se: + +- `PostalPlanetFilledBars.png` – solida svarta staplar +- `PostalPlanetEmptyBars.png` – vita staplar med svarta konturer + +Öppna dem i någon bildvisare; de bör båda följa Planet‑specifikationen. + +## Vanliga frågor & tips + +### “Kan jag ändra bildformatet?” + +Absolut. Metoden `Save` accepterar `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` osv. Byt bara ut `BarCodeImageFormat.Png` mot det format du önskar. + +### “Vad händer om jag behöver en annan stapelhöjd?” + +Använd `planetBarcode.Parameters.Barcode.BarHeight` (i punkter) för att öka eller minska den vertikala storleken. Till exempel: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “Finns det ett sätt att lägga till en mänskligt läsbar bildtext?” + +Ja. Sätt egenskapen `CodeText` på `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “Behöver jag avyttra generatorn?” + +`BarcodeGenerator` implementerar `IDisposable`. Omge den med ett `using`‑block om du skapar många stapelkoder i en loop: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “Hur hanterar man fel?” + +Omge `Save`‑anropen med ett `try…catch`‑block för att fånga `IOException` (diskproblem) eller `ArgumentException` (ogiltiga parametrar). Exempel: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Sammanfattning + +Vi har gått igenom allt du behöver för att **create planet barcode** bilder i C#: + +1. Initiera **Planet barcode generator** med dina data. +2. Justera **XDimension pixels** för att matcha skrivarens specifikationer. +3. Spara en **filled bars** PNG. +4. Växla `FilledBars` för att producera **empty bars**. +5. Spara den andra PNG‑filen. + +Härifrån kan du utforska fler **BarcodeGenerator parameters**, experimentera med andra symbologier (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, osv.), eller integrera bilderna i ett posthanteringsflöde. + +--- + +**Redo för nästa steg?** Försök lägga till en QR‑kod i samma dokument, eller generera en batch av Planet‑stapelkoder från en CSV‑lista med en `foreach`‑loop. Aspose.BarCode‑API:n är tillräckligt flexibel för att hantera massoperationer, anpassade färger och till och med vektorbaserad SVG‑output. + +Om du stöter på problem, lämna en kommentar nedan eller kolla den officiella Aspose.BarCode‑dokumentationen för djupare insikter i avancerade funktioner. Lycka till med kodningen! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närliggande ämnen som bygger på teknikerna som demonstreras i denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Skapa streckkod med Aspose – Ställ in X‑ och Y‑dimensioner i Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [Hur man skapar code128‑streckkods bilder i Java med Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [Hur man skapar code128‑streckkod i Java och ställer in stapelhöjd](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/swedish/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..9ff42becf --- /dev/null +++ b/barcode/swedish/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-07-18 +description: Skapa RM4SCC‑streckkod i C# snabbt; lär dig hur du ställer in streckkodens + höjd och även genererar Planet‑streckkod med anpassade dimensioner. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: sv +lastmod: 2026-07-18 +og_description: Skapa RM4SCC-streckkod i C# och upptäck hur du ställer in streckkodens + höjd. Se också hur du genererar Planet-streckkod med samma bibliotek. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Skapa RM4SCC-streckkod i C# – Ställ in anpassad höjd snabbt +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Skapa RM4SCC-streckkod i C# – Fullständig guide för att ange höjden +url: /sv/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa RM4SCC-streckkod i C# – Fullständig guide för att ställa in höjd + +Har du någonsin behövt **skapa RM4SCC barcode** i en .NET-app men varit osäker på hur du styr dess storlek? Du är inte ensam. Oavsett om du bygger ett postningssystem eller en logistikdashboard, kan rätt streckkodshöjd vara skillnaden mellan en lyckad skanning och en som misslyckas. + +I den här handledningen går vi igenom hela processen: från att installera biblioteket, till **generate Planet barcode** som ett sid‑vid‑sidexempel, och slutligen till **how to set barcode height** för båda streckkodstyperna. I slutet har du en färdigkörbar konsolapp som genererar PNG‑filer med exakt de dimensioner du behöver. + +--- + +## Vad du behöver + +- **.NET 6 SDK** (eller någon nyare .NET‑version) – koden fungerar även på .NET Framework, men .NET 6 är den optimala versionen. +- **Aspose.BarCode for .NET** NuGet‑paket – detta är biblioteket som tillhandahåller `BarcodeGenerator`‑klassen. +- En måttlig kunskap i C# – vi håller syntaxen nybörjarvänlig. +- En IDE eller textredigerare (Visual Studio, VS Code, Rider—välj själv). + +> **Pro tip:** Om du kör i en CI/CD‑pipeline, lägg till NuGet‑referensen i din `.csproj` så att bygget aldrig glömmer beroendet. + +--- + +## Steg 1: Ställ in projektet + +Open a terminal and create a new console project: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +Det är allt—ditt projekt refererar nu till biblioteket som driver allt som följer. + +### Lägg till using‑direktiven + +Open `Program.cs` and paste the following at the top: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +Dessa namnrymder ger oss åtkomst till `BarcodeGenerator` och bildformat‑enum som vi kommer att använda senare. + +--- + +## Steg 2: Definiera en hjälpfunktion för att spara bilder + +För att undvika att upprepa samma sparlogik, kapslar vi in den i en liten metod. Detta visar också **how to set barcode height** senare. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Why this matters:** Att centralisera sparlogiken betyder att du bara behöver ändra formatet eller mappen på ett ställe om kraven förändras. + +--- + +## Steg 3: Generera en Planet‑streckkod (delen “generate planet barcode”) + +Innan vi dyker in i RM4SCC‑detaljerna, låt oss skapa en **Planet barcode**. Detta ger dig en snabb visuell kontroll att biblioteket fungerar. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Expected output:** Två PNG‑filer visas i `output`‑mappen—en med bibliotekets automatiskt beräknade höjd, den andra exakt 100 px hög. + +--- + +## Steg 4: Skapa RM4SCC‑streckkod – Huvudmålet + +Nu till stjärnan i showen: **create RM4SCC barcode**. RM4SCC är Royal Mail 4‑State Code, som är allmänt använd i det brittiska postsystemet. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**What you’ll see:** +- `RM4SCCDefault.png` – biblioteket bestämmer en bekväm höjd baserat på X‑dimensionen. +- `RM4SCCHeight100.png` – en skarp 100‑pixel hög streckkod redo för utskrift på kuvert. + +> **Why set the height?** Vissa etikett‑skrivare kräver en minimal stapelhöjd för pålitlig skanning. Genom att fixera höjden garanterar du efterlevnad över enheter. + +--- + +## Steg 5: Förstå höjdinställningarna (Svar på “how to set barcode height”) + +Both the Planet and RM4SCC examples use the same property: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** är ett `BarHeight`‑objekt som grupperar flera måttenheter (pixels, millimetres, inches). +- **`.Pixels`** är den mest enkla enheten för skärm‑orienterad output, men du kan också använda `.Millimeters` eller `.Inches` om du riktar dig mot utskriftsmedia. + +### Kantfall & Tips + +| Situation | Recommended Approach | +|-----------|----------------------| +| **Mycket liten X‑dimension (t.ex. 1 px)** | Öka `BarHeight` för att hålla streckkoden läsbar. | +| **Utskrift på högupplösta etikett‑skrivare** | Använd `.Millimeters` för enhetsoberoende storlek. | +| **Blandade streckkodstyper i en bild** | Ställ in `BarHeight` *efter* `XDimension` för varje generator för att undvika oavsiktlig ärvning. | +| **Dynamisk data (t.ex. användar‑inmatade koder)** | Kapsla generatorns skapande i en metod som accepterar `code` och `height`‑parametrar. | + +--- + +## Steg 6: Fullt fungerande exempel + +Nedan är ett enda, självständigt program som du kan kopiera‑klistra in i `Program.cs`. Det innehåller allt från projektinställning till sparande av bilder. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Run it with: + +```bash +dotnet run +``` + +Du bör se konsolutdata som bekräftar varje sparad fil, och `output`‑mappen kommer att innehålla fyra PNG‑filer som matchar namnen ovan. + +--- + +## Slutsats + +Du vet nu **how to create RM4SCC barcode** i C# och hur du styr dess dimensioner med bara ett par egenskaps‑tilldelningar. Vi gick också igenom **generate planet barcode** som en snabb kontroll, och utforskade nyanserna i **how to set barcode height** för olika utskrifts‑scenarier. + +Nästa steg? Prova att byta ut `EncodeTypes`‑enum för andra symboler (Code128, QR, DataMatrix) och experimentera med `BarHeight` i millimetres för högupplösta skrivare. Om du behöver bädda in streckkoden i en PDF, kombinera Aspose.BarCode med Aspose.PDF—en annan kraftfull kombination. + +Har du frågor eller vill dela dina egna justeringar? lämna en kommentar nedan, och 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 denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Hur man 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 skapar tyst zon för streckkod för ITF-14 med Aspose.BarCode för .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Hur man skapar tyst zon för streckkod för Code 16K med Aspose.BarCode för .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/swedish/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..109288e62 --- /dev/null +++ b/barcode/swedish/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-07-18 +description: Lär dig hur du genererar streckkodsbilder med en .net‑streckkodsgenerator + och enkelt ändrar streckkodshöjden för GS1‑Databar Omni‑Directional‑symboler. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: sv +lastmod: 2026-07-18 +og_description: .net streckkodsgenerator låter dig snabbt skapa streckkodsbilder. + Den här guiden visar hur du genererar streckkoder, justerar stapelhöjden och sparar + PNG‑filer. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Ändra streckkodshöjd med .net streckkodsgenerator +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .net streckkodsgenerator – ändra streckkodshöjd +url: /sv/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net streckkodsgenerator – ändra streckkodshöjd + +Har du någonsin undrat **hur man genererar streckkod**‑bilder utan att jonglera med dussintals tredjepartsverktyg? I .NET‑världen finns ett förvånansvärt enkelt sätt att göra det, och nyckelkomponenten är **.net barcode generator**. Med bara några rader C# kan du skapa en GS1‑Databar Omni‑Directional‑symbol, justera stapelhöjden och spara resultatet som en PNG‑fil. + +Om du bygger ett lagersystem, en fraktetikett‑skrivare eller någon app som behöver en läsbar kod, så tar den här handledningen dig från noll till en fungerande streckkod på några minuter. Vi går igenom hela koden, förklarar varför varje inställning är viktig och visar hur du **ändrar streckkodshöjden** utan att bryta specifikationen. + +## Vad du behöver + +- .NET 6.0 eller senare (API:et fungerar likadant på .NET Framework 4.7+) +- En referens till streckkodsbiblioteket (t.ex. Aspose.BarCode for .NET – samma klasser används av många kommersiella paket) +- En utvecklingsmiljö (Visual Studio, Rider eller VS Code med C#‑tillägget) +- En mapp där du har skrivrättigheter – handledningen sparar PNG‑filer där + +Det är allt. Inga extra NuGet‑paket utöver själva streckkodsbiblioteket. + +## Använda .net barcode generator för att ändra streckkodshöjd + +Nedan är ett **komplett, körbart konsolprogram**. Klistra in det i ett nytt C#‑projekt, justera utdatamappen och tryck F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Varför varje rad är viktig + +| Rad | Orsak | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Skapar en **.net barcode generator** med önskad symboltyp och datapayload. Enum‑värdet `EncodeTypes.DatabarOmniDirectional` talar om för biblioteket att använda GS1‑Databar Omni‑Directional‑formatet. | +| `XDimension.Pixels = 2;` | X‑dimensionen är bredden på den tunnaste stapeln. Att sätta den till *2 pixlar* ger en skarp bild på de flesta skärmar samtidigt som filstorleken hålls låg. | +| `BarHeight.Pixels = 30;` | Detta är steget för **ändra streckkodshöjd** som bestämmer hur höga varje stapel blir. En höjd på 30 pixlar är ett bra standardvärde för små etiketter. | +| `generator.Save(...);` | Sparar streckkoden till en PNG‑fil. PNG är förlustfri, vilket betyder att skannrarna ser exakt det mönster du genererat. | +| `BarHeight.Pixels = 60;` | Här **ändrar vi streckkodshöjden** igen—denna gång till 60 pixlar. Biblioteket renderar automatiskt om symbolen med den nya dimensionen när du anropar `Save` en andra gång. | +| `Console.WriteLine(...);` | Ger dig snabb återkoppling att processen avslutades utan att kasta ett undantag. | + +> **Proffstips:** Om du behöver högre upplösning för utskrift, byt `BarCodeImageFormat.Png` till `BarCodeImageFormat.Tiff` och öka `Resolution`‑egenskapen (t.ex. `generator.Parameters.ImageResolution = 300;`). Stapelhöjden respekteras fortfarande, den renderas bara med en finare DPI. + +## Hur man genererar streckkodsbilder med olika inställningar + +Kodsnutten ovan täcker grunderna, men verkliga scenarier kräver ofta extra justeringar: + +### Justera X‑dimensionen för större utskrifter +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Att öka X‑dimensionen gör hela streckkoden större utan att ändra den kodade datan. Detta är praktiskt när du skriver ut på stora etiketter. + +### Byta utdataformat +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG skalas oändligt, vilket är perfekt för webbaserade skannrar som behöver skarpa vektorer. + +### Lägga till mänskligt läsbar text +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Att aktivera `CodeTextVisible` lägger till den råa datan under streckkoden, användbart för verifiering under testning. + +## Vanliga fallgropar när du **ändrar streckkodshöjd** + +1. **För låg höjd** – Vissa skannrar kräver en minsta stapelhöjd (ofta 10 mm i fysiska enheter). Om du sätter `BarHeight.Pixels` för lågt kan den genererade bilden bli oläslig på en riktig skanner. Testa alltid med din mål‑hardware. +2. **Ej matchande X‑dimension och höjd** – En enorm stapelhöjd ihop med en liten X‑dimension kan se utdragen ut och kan orsaka avkodningsfel. Sikta på ett balanserat förhållande (ungefär 3:1 till 5:1) om inte specifikationen säger annat. +3. **Glömmer att återställa parametrar** – Generatorn behåller tillstånd mellan sparningar. Om du ändrar `BarHeight` för en bild och sedan återanvänder samma instans för en annan streckkod, så kvarstår den tidigare höjden. Återställ antingen egenskapen eller skapa en ny `BarcodeGenerator` för varje unik streckkod. + +## Fullt end‑to‑end‑exempel (inklusive NuGet‑installation) + +Om du börjar från början, följ dessa steg för att få projektet att köras: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Ersätt den automatiskt genererade `Program.cs` med kodblocket som visades tidigare, **kom ihåg att ersätta `YOUR_DIRECTORY`** med något i stil med `Path.Combine(Environment.CurrentDirectory, "output")`. Sedan: + +```bash +dotnet run +``` + +Du bör se två PNG‑filer i mappen `output`: + +- `DatabarBarHeight30Pixels.png` – en kompakt streckkod på 30 pixlar i höjd. +- `DatabarBarHeight60Pixels.png` – en högre version på 60 pixlar. + +Båda bilderna ser liknande ut, men den andra har märkbart längre staplar, vilket gör den lättare för lågupplösta skannrar att läsa. + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator output som visar olika stapelhöjder"} + +## Sammanfattning & nästa steg + +Vi har gått igenom hur man **genererar streckkod**‑bilder med en **.net barcode generator**, finjusterat egenskapen **ändra streckkodshöjd**, och sparat resultaten i PNG‑format. De viktigaste slutsatserna är: + +- Instansiera generatorn med rätt `EncodeTypes`. +- Styr den visuella storleken via `XDimension` och `BarHeight`. +- Anropa `Save` efter varje ändring för att spara en ny bild. +- Justera upplösning, format, + +## 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 denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Hur man 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 skapar dotcode med utökad kodtext med Aspose.BarCode för .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Hur man genererar DataMatrix‑streckkoder (ECC 200) med Aspose.BarCode för .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/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/thai/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..f9bdc2a81 --- /dev/null +++ b/barcode/thai/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-07-18 +description: ตัวอย่างเครื่องสร้างบาร์โค้ดที่แสดงวิธีตั้งค่าขนาดและสร้างภาพบาร์โค้ด + DataBar Stacked Omni‑Directional ด้วย C# เรียนรู้ประเภทการเข้ารหัสบาร์โค้ดอย่างรวดเร็ว. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: th +lastmod: 2026-07-18 +og_description: ตัวอย่างเครื่องสร้างบาร์โค้ดจะอธิบายขั้นตอนการตั้งค่าขนาด, เลือกประเภทการเข้ารหัสบาร์โค้ด, + และสร้างโครงการภาพบาร์โค้ดด้วย C# ด้วยโค้ดที่น้อยที่สุด +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: ตัวอย่างเครื่องสร้างบาร์โค้ด – การสร้างภาพ DataBar อย่างรวดเร็วใน C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: ตัวอย่างการสร้างบาร์โค้ด – สร้างภาพ DataBar ด้วย C# +url: /th/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ตัวอย่างตัวสร้างบาร์โค้ด – สร้างภาพ DataBar ด้วย C# + +เคยต้องการ **ตัวอย่างตัวสร้างบาร์โค้ด** ที่จริงจังและสร้างบาร์โค้ดจริงได้โดยไม่ต้องบิดหัวไหม? คุณไม่ได้อยู่คนเดียว นักพัฒนาส่วนใหญ่มักเจออุปสรรคเมื่อต้องกำหนด **วิธีตั้งค่าขนาด** สำหรับบาร์โค้ด DataBar Stacked Omni‑Directional โดยเฉพาะเมื่อเอกสารอธิบายซับซ้อนเกินไป + +ในบทเรียนนี้เราจะเดินผ่านโปรแกรม C# ที่พร้อมรันเต็มรูปแบบ ซึ่งจะแสดง **วิธีสร้างภาพ databar** เลือก **barcode encode types** ที่ถูกต้อง และสุดท้าย **สร้างไฟล์ barcode image c#** ที่คุณสามารถนำไปใช้ในโปรเจกต์ใดก็ได้ ไม่มีส่วนเกิน—แค่โค้ดที่คัดลอก‑วางได้ พร้อมเหตุผลของแต่ละบรรทัด + +## สิ่งที่คุณต้องเตรียม + +- **.NET 6** (หรือเวอร์ชัน .NET ล่าสุด) – API ที่เราใช้รองรับ .NET Standard จึงทำงานได้บน .NET Framework ด้วย +- **Aspose.BarCode for .NET** – ไลบรารีที่ให้ `BarcodeGenerator` คุณสามารถติดตั้งจาก NuGet ด้วย `Install-Package Aspose.BarCode` +- **IDE สำหรับ C#** – Visual Studio, Rider หรือ VS Code ก็ได้ +- โฟลเดอร์บนดิสก์ที่ไฟล์ PNG จะถูกบันทึก (โค้ดจะสร้าง `DatabarAspectRatio15.png` และ `DatabarAspectRatio30.png`) + +เตรียมครบหรือยัง? ดีแล้ว—มาเริ่มกันเลย + +## ตัวอย่างตัวสร้างบาร์โค้ด – เริ่มต้นตัวสร้าง + +ก่อนอื่นเราต้องมีอินสแตนซ์ของ `BarcodeGenerator` ที่ตั้งค่าสำหรับสัญลักษณ์ **DataBar Stacked Omni‑Directional** นี่คือ **barcode encode type** ที่เราจะทำงานด้วย + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **ทำไมเรื่องนี้สำคัญ:** `EncodeTypes.DatabarStackedOmniDirectional` บอกให้ Aspose รู้ว่าจะเรนเดอร์สัญลักษณ์ใด หากเลือกประเภทผิด ตัวสแกนเนอร์จะไม่อ่านบาร์โค้ดได้ แม้ภาพจะสวยแค่ไหนก็ตาม + +## วิธีตั้งค่าขนาดสำหรับบาร์โค้ด + +ความอ่านง่ายของบาร์โค้ดขึ้นกับ **X‑dimension** (ความกว้างของบาร์ที่แคบที่สุด) ส่วนใหญ่ค่า 2 พิกเซลทำงานได้ดี แต่คุณสามารถปรับให้เหมาะกับเครื่องพิมพ์หรือหน้าจอของคุณได้ + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **เคล็ดลับ:** หากคุณต้องการ **วิธีตั้งค่าขนาด** สำหรับบาร์โค้ดตระกูลอื่น ๆ ให้ใช้โซ่คุณสมบัติเช่นเดียวกัน (`Parameters.Barcode.XDimension`) เพียงเปลี่ยนค่า `Pixels` เท่านั้น + +## วิธีสร้าง DataBar Stacked Omni‑Directional Barcode + +เมื่อเครื่องสร้างพร้อมแล้ว เราจะเล่นกับคุณสมบัติ **aspect ratio** ซึ่งควบคุมความสัมพันธ์ความสูงต่อความกว้างของ DataBar ทำให้คุณสร้างสัญลักษณ์ที่สั้นและเป็นสี่เหลี่ยมจัตุรัส หรือสูงและแคบได้ตามต้องการ + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **กำลังเกิดอะไรขึ้น?** `AspectRatio = 15` บอกให้เอนจินทำบาร์ให้สูงกว่าความกว้าง 15 เท่า PNG ที่ได้จะถูกบันทึกไว้ข้างไฟล์ executable ของคุณ + +## สร้าง Barcode Image C# – เปลี่ยน Aspect Ratio + +มาทดสอบความยืดหยุ่นโดยสลับอัตราส่วนเป็น 30 แล้วบันทึกไฟล์ที่สอง + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +เมื่อรันโปรแกรม คุณจะได้ไฟล์ PNG สองไฟล์: + +| ไฟล์ | อัตราส่วน | ขนาดโดยประมาณ | +|------|------------|----------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +เปิดไฟล์ด้วยโปรแกรมดูภาพใดก็ได้—you should see clean, scannable DataBar symbols. + +## ภาพรวมของ Barcode Encode Types (ตัวเลือกแต่เป็นประโยชน์) + +หากคุณสนใจ **barcode encode types** อื่น ๆ ที่ Aspose รองรับ นี่คือชีตสรุปสั้น ๆ: + +| EncodeTypes Enum | คำอธิบาย | +|------------------|-----------| +| `EncodeTypes.Code128` | ตัวอักษรและตัวเลขความหนาแน่นสูง | +| `EncodeTypes.QR` | รหัสเมทริกซ์ 2‑D | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar สำหรับการค้าปลีก | +| `EncodeTypes.DatabarStackedOmniDirectional` | **โฟกัสของเรา** – กะทัดรัด, omnidirectional | + +การรู้ enum ที่ถูกต้องจะช่วยลดการลองผิดลองถูกเมื่อต้องสลับโปรเจกต์ + +## ข้อผิดพลาดทั่วไปและวิธีหลีกเลี่ยง + +- **ขาดแพ็กเกจ NuGet** – โค้ดจะไม่คอมไพล์หากไม่มี `Aspose.BarCode` รัน `dotnet add package Aspose.BarCode` ก่อน +- **เส้นทางไฟล์ผิด** – หากใช้เส้นทางแบบ absolute ตรวจสอบเครื่องหมาย backslash (`\\`) บน Windows เส้นทางแบบ relative (ตามตัวอย่าง) จะทำให้พกพาง่ายกว่า +- **อัตราส่วนสูงเกินไป** – อัตราส่วนเหนือ 50 ทำให้บาร์โค้ดสูงเกินกว่าสแกนเนอร์ทั่วไป ควรอยู่ในช่วง 15‑30 สำหรับการใช้งานส่วนใหญ่ + +## โค้ดเต็ม (พร้อมคัดลอก‑วาง) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +รันโปรแกรม (`dotnet run` หรือกด **F5** ใน Visual Studio) แล้วคุณจะเห็นข้อความในคอนโซลยืนยันว่าไฟล์ถูกสร้างบนดิสก์แล้ว + +![ตัวอย่างผลลัพธ์ของตัวสร้างบาร์โค้ด แสดง DataBar barcode ด้วยอัตราส่วน 15](placeholder/path/to/image.png){: .align-center alt="ตัวอย่างผลลัพธ์ของตัวสร้างบาร์โค้ด แสดง DataBar barcode ด้วยอัตราส่วน 15"} + +## สรุป + +เราได้สร้าง **ตัวอย่างตัวสร้างบาร์โค้ด** ที่สาธิต **วิธีตั้งค่าขนาด**, เลือก **barcode encode types** ที่ถูกต้อง, และสุดท้าย **สร้างไฟล์ barcode image c#** ที่คุณสามารถฝังลงในโปรเจกต์ใดก็ได้ โค้ดสั้น กระชับ แนวคิดชัดเจน และคุณมีพื้นฐานที่มั่นคงสำหรับต่อยอด—เช่น เพิ่มคำบรรยาย, หมุนภาพ, หรือเปลี่ยนสัญลักษณ์เป็นแบบอื่น + +### ขั้นตอนต่อไปคืออะไร? + +- ทดลองกับ **X‑dimension** ต่าง ๆ เพื่อดูว่าความทนทานของสแกนเนอร์เปลี่ยนแปลงอย่างไร +- ลอง **EncodeTypes** อื่น ๆ เช่น `Code128` หรือ `QR` เพื่อขยายเครื่องมือของคุณ +- ทำการสร้างแบบแบตช์อัตโนมัติ: วนลูปไฟล์ CSV ของรหัสสินค้าและสร้าง PNG สำหรับแต่ละรายการ + +หากเจอปัญหาใด ๆ คอมเมนต์ด้านล่างหรือดูเอกสาร Aspose.BarCode – มีตัวอย่างเพิ่มเติมที่สอดคล้องกับสิ่งที่เราอธิบายไว้ที่นี่ + +ขอให้เขียนโค้ดสนุกและบาร์โค้ดของคุณสแกนได้สำเร็จตั้งแต่ครั้งแรก! + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่อธิบายในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอน‑ขั้นตอน เพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโปรเจกต์ของคุณ + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/thai/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..dc5165db4 --- /dev/null +++ b/barcode/thai/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,278 @@ +--- +category: general +date: 2026-07-18 +description: สร้างบาร์โค้ด Planet อย่างรวดเร็วด้วย C# เรียนรู้วิธีสร้างบาร์ที่เต็มและว่าง + ตั้งค่า X‑dimension และบันทึกภาพ PNG – ทั้งหมดในบทเรียนเดียว +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: th +lastmod: 2026-07-18 +og_description: สร้างบาร์โค้ด Planet ได้ทันที คู่มือนี้จะแสดงวิธีตั้งค่า X‑dimension, + สลับระหว่างบาร์ที่เต็มและบาร์ที่ว่าง, และส่งออกไฟล์ PNG ด้วย Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: สร้าง Planet Barcode ด้วย C# – คู่มือการเขียนโปรแกรมเต็มรูปแบบ +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: สร้าง Planet Barcode ด้วย C# – คู่มือเต็มขั้นตอนแบบทีละขั้นตอน +url: /th/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้าง Planet Barcode ด้วย C# – คู่มือเต็มขั้นตอน + +เคยต้องการ **สร้าง planet barcode** รูปภาพแต่ไม่แน่ใจว่าจะปรับคุณสมบัติใด? คุณไม่ได้เป็นคนเดียว นักพัฒนาหลายคนเจออุปสรรคเมื่อบาร์ที่เติมเต็มตามค่าเริ่มต้นไม่ตรงตามสเปค หรือเมื่อความกว้างของบาร์ต้องตรงกับ DPI ของเครื่องพิมพ์ + +ในบทเรียนนี้คุณจะได้เรียนรู้อย่างละเอียดว่าอย่างไรที่จะ **สร้าง planet barcode** ไฟล์โดยใช้ไลบรารี Aspose.BarCode, วิธีควบคุม **XDimension pixels**, และวิธีสลับระหว่าง **filled bars** กับ **empty bars** โดยไม่ต้องเขียนโค้ดใหม่. เมื่อจบคุณจะมีไฟล์ PNG สองไฟล์—หนึ่งที่มีบาร์ทึบและอีกหนึ่งที่มีบาร์เป็นรู—พร้อมใช้งานกับระบบไปรษณีย์ใด ๆ ที่ต้องการสัญลักษณ์ Planet + +## ข้อกำหนดเบื้องต้น + +- .NET 6.0 หรือรุ่นต่อไป (โค้ดทำงานได้บน .NET Framework 4.7 + ด้วยเช่นกัน) +- แพคเกจ NuGet Aspose.BarCode สำหรับ .NET (`Install-Package Aspose.BarCode`) +- ความรู้พื้นฐาน C# (คุณจะเห็นว่าทำไมเราถึงใช้คำสั่ง `using` ในภายหลัง) +- โฟลเดอร์ที่สามารถเขียนได้บนดิสก์ที่ PNG จะถูกบันทึก + +หากคุณมีทั้งหมดนี้ เราสามารถกระโดดเข้าสู่การทำงานได้เลย + +## ขั้นตอนที่ 1 – ตั้งค่าโปรเจกต์และเพิ่มไลบรารี + +ขั้นแรก สร้างแอปคอนโซลใหม่ (หรือโปรเจกต์ C# ใด ๆ) แล้วอ้างอิงไลบรารี **Planet barcode generator** + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro tip:** ใน Visual Studio, คลิกขวาที่โปรเจกต์ → *Manage NuGet Packages* → ค้นหา **Aspose.BarCode** แล้วคลิก *Install*. สิ่งนี้จะทำให้คุณเข้าถึง `BarcodeGenerator` และ **BarcodeGenerator parameters** ทั้งหมดที่คุณต้องการ. + +## ขั้นตอนที่ 2 – เริ่มต้น Planet Barcode Generator + +ตอนนี้เราจะ **สร้าง planet barcode** อินสแตนซ์ของ generator และใส่ข้อมูลที่ต้องการเข้ารหัส (`"123456"` ในตัวอย่างนี้). enum `EncodeTypes.Planet` บอกไลบรารีว่าจะใช้สัญลักษณ์ใด. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Why this matters:** ธง `EncodeTypes.Planet` จะทำการใช้ checksum และกฎการจัดวางที่ถูกต้องสำหรับ Planet postal barcode โดยอัตโนมัติ, ดังนั้นคุณไม่ต้องคำนวณด้วยตนเอง. + +## ขั้นตอนที่ 3 – ตั้งค่า X‑Dimension (ความกว้างของบาร์) + +เครื่องพิมพ์ส่วนใหญ่คาดหวังให้บาร์แต่ละบาร์มีจำนวนพิกเซลที่กำหนดไว้ ที่นี่เราตั้งค่า **XDimension pixels** เป็น `4`, ซึ่งเป็นค่าที่พบบ่อยสำหรับเครื่องพิมพ์ความร้อน 203 dpi. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Edge case:** หากคุณกำหนดเป้าหมายเป็นเครื่องพิมพ์ 300 dpi, คุณอาจต้องใช้ `3` หรือ `5` พิกเซลแทน. ปรับค่าตามเอกสารของอุปกรณ์ของคุณ. + +## ขั้นตอนที่ 4 – บันทึกเวอร์ชัน Filled‑Bar + +โดยค่าเริ่มต้น generator จะสร้าง **filled bars** (สี่เหลี่ยมสีดำทึบ). มาบันทึกลงดิสก์กัน: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +แทนที่ `YOUR_DIRECTORY` ด้วยพาธแบบ absolute หรือ relative ที่แอปของคุณสามารถเขียนได้. หลังจากบรรทัดนี้ทำงาน คุณจะพบไฟล์ PNG ที่ดูเหมือน Planet barcode คลาสสิก—เหมาะสำหรับการทดสอบกับสแกนเนอร์ไปรษณีย์. + +## ขั้นตอนที่ 5 – สลับเป็น Empty Bars + +บางครั้งบริการไปรษณีย์ต้องการสไตล์ “empty bars”, ซึ่งบาร์ถูกตัดออกจากพื้นหลังสีขาวแทนการทาสีดำ. ไลบรารีมีสวิตช์ง่าย ๆ ดังนี้: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +การตั้งค่า `FilledBars` เป็น `false` จะบอก renderer ให้กลับด้านตรรกะการเติมบาร์. ไม่จำเป็นต้องสร้าง `BarcodeGenerator` ใหม่; เราเพียงปรับ **BarcodeGenerator parameters** ที่มีอยู่. + +## ขั้นตอนที่ 6 – บันทึกเวอร์ชัน Empty‑Bar + +สุดท้าย ส่งออกภาพที่สอง: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +ตอนนี้คุณมีไฟล์ PNG สองไฟล์ที่แตกต่างกัน, แต่ละไฟล์สอดคล้องกับความต้องการด้านภาพที่แตกต่างกัน. + +## ตัวอย่างทำงานเต็มรูปแบบ + +รวมส่วนต่าง ๆ เข้าด้วยกัน นี่คือโปรแกรมที่พร้อมคัดลอกและวางเต็มรูปแบบ: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Expected output** (บนคอนโซล): + +``` +Both Planet barcode images have been generated successfully. +``` + +และใน `C:\Barcodes\` คุณจะเห็น: + +- `PostalPlanetFilledBars.png` – บาร์สีดำทึบ +- `PostalPlanetEmptyBars.png` – บาร์สีขาวพร้อมขอบสีดำ + +เปิดไฟล์เหล่านี้ในโปรแกรมดูรูปใดก็ได้; ทั้งสองควรสอดคล้องกับสเปค Planet. + +## คำถามทั่วไป & เคล็ดลับ + +### “ฉันสามารถเปลี่ยนรูปแบบภาพได้ไหม?” + +ได้เลย. เมธอด `Save` รองรับ `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` เป็นต้น. เพียงแทนที่ `BarCodeImageFormat.Png` ด้วยรูปแบบที่คุณต้องการ. + +### “ถ้าฉันต้องการความสูงของบาร์โค้ดที่ต่างออกไป?” + +ใช้ `planetBarcode.Parameters.Barcode.BarHeight` (หน่วย points) เพื่อเพิ่มหรือลดขนาดแนวตั้ง. ตัวอย่างเช่น: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “มีวิธีเพิ่มคำบรรยายที่มนุษย์อ่านได้หรือไม่?” + +มี. ตั้งค่า property `CodeText` บน `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “ฉันต้องทำการ dispose generator หรือไม่?” + +`BarcodeGenerator` implements `IDisposable`. ห่อไว้ในบล็อก `using` หากคุณสร้างบาร์โค้ดหลายรายการในลูป: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “ส่วนการจัดการข้อผิดพลาดล่ะ?” + +ใส่การเรียก `Save` ไว้ในบล็อก `try…catch` เพื่อจับ `IOException` (ปัญหาดิสก์) หรือ `ArgumentException` (พารามิเตอร์ไม่ถูกต้อง). ตัวอย่าง: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## สรุป + +เราได้ครอบคลุมทุกอย่างที่คุณต้องการเพื่อ **สร้าง planet barcode** รูปภาพใน C#: + +1. เริ่มต้น **Planet barcode generator** ด้วยข้อมูลของคุณ. +2. ปรับ **XDimension pixels** ให้ตรงกับสเปคของเครื่องพิมพ์. +3. บันทึก PNG **filled bars**. +4. สลับ `FilledBars` เพื่อสร้าง **empty bars**. +5. บันทึก PNG ที่สอง. + +จากนี้คุณสามารถสำรวจ **BarcodeGenerator parameters** เพิ่มเติม, ทดลองสัญลักษณ์อื่น (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, เป็นต้น), หรือรวมภาพเหล่านี้เข้าในกระบวนการส่งไปรษณีย์. + +--- + +**Ready for the next step?** ลองเพิ่ม QR code ลงในเอกสารเดียวกัน, หรือสร้างชุดของ Planet barcode จากรายการ CSV ด้วยลูป `foreach`. Aspose.BarCode API มีความยืดหยุ่นพอที่จะจัดการการทำงานแบบกลุ่ม, สีที่กำหนดเอง, และแม้กระทั่งการส่งออก SVG แบบเวกเตอร์. + +หากคุณเจอปัญหาใด ๆ, แสดงความคิดเห็นด้านล่างหรือดูเอกสาร Aspose.BarCode อย่างเป็นทางการเพื่อเรียนรู้ฟีเจอร์ขั้นสูงเพิ่มเติม. Happy coding! + +## สิ่งที่คุณควรเรียนต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดซึ่งต่อยอดจากเทคนิคที่แสดงในคู่มือนี้. แหล่งข้อมูลแต่ละรายการมีตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการทำงานแบบอื่นในโปรเจกต์ของคุณ. + +- [สร้างบาร์โค้ดด้วย Aspose - ตั้งค่า X & Y Dimensions ใน Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [วิธีสร้างภาพ code128 barcode ใน Java ด้วย Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [วิธีสร้าง code128 barcode ใน Java และตั้งค่าความสูงของบาร์](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/thai/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..aa2860c76 --- /dev/null +++ b/barcode/thai/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-07-18 +description: สร้างบาร์โค้ด RM4SCC ด้วย C# อย่างรวดเร็ว; เรียนรู้วิธีตั้งความสูงของบาร์โค้ดและยังสามารถสร้างบาร์โค้ด + Planet ด้วยขนาดที่กำหนดเองได้ +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: th +lastmod: 2026-07-18 +og_description: สร้างบาร์โค้ด RM4SCC ด้วย C# และค้นหาวิธีตั้งความสูงของบาร์โค้ด อีกทั้งดูวิธีสร้างบาร์โค้ด + Planet ด้วยไลบรารีเดียวกัน +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: สร้างบาร์โค้ด RM4SCC ด้วย C# – ตั้งค่าความสูงแบบกำหนดเองอย่างรวดเร็ว +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: สร้างบาร์โค้ด RM4SCC ด้วย C# – คู่มือเต็มสำหรับการตั้งความสูง +url: /th/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างบาร์โค้ด RM4SCC ด้วย C# – คู่มือเต็มสำหรับการตั้งความสูง + +เคยต้องการ **create RM4SCC barcode** ในแอป .NET แต่ไม่แน่ใจว่าจะควบคุมขนาดได้อย่างไร? คุณไม่ได้เป็นคนเดียว ไม่ว่าคุณจะสร้างระบบส่งจดหมายหรือแดชบอร์ดโลจิสติกส์ การได้ความสูงบาร์โค้ดที่เหมาะสมอาจเป็นความแตกต่างระหว่างการสแกนที่สำเร็จและที่ล้มเหลว + +ในบทแนะนำนี้ เราจะเดินผ่านกระบวนการทั้งหมด: ตั้งแต่การติดตั้งไลบรารี ไปจนถึง **generate Planet barcode** เป็นตัวอย่างข้างเคียง และสุดท้ายถึง **how to set barcode height** สำหรับทั้งสองประเภทของบาร์โค้ด เมื่อเสร็จคุณจะมีแอปคอนโซลที่พร้อมรันและสร้างไฟล์ PNG ที่มีขนาดตามที่คุณต้องการ + +--- + +## สิ่งที่คุณต้องการ + +- **.NET 6 SDK** (หรือเวอร์ชัน .NET ล่าสุดใดก็ได้) – โค้ดทำงานบน .NET Framework ได้เช่นกัน แต่ .NET 6 คือจุดที่เหมาะที่สุด +- **Aspose.BarCode for .NET** NuGet package – นี่คือไลบรารีที่ให้คลาส `BarcodeGenerator` +- ความรู้พื้นฐานเกี่ยวกับ C# เล็กน้อย – เราจะทำให้ไวยากรณ์เป็นมิตรต่อผู้เริ่มต้น +- IDE หรือโปรแกรมแก้ไขข้อความ (Visual Studio, VS Code, Rider—เลือกตามที่คุณชอบ) + +> **Pro tip:** หากคุณอยู่ใน pipeline ของ CI/CD ให้เพิ่มการอ้างอิง NuGet ในไฟล์ `.csproj` ของคุณเพื่อให้การสร้างไม่ลืมการพึ่งพา + +--- + +## ขั้นตอนที่ 1: ตั้งค่าโปรเจกต์ + +Open a terminal and create a new console project: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +เท่านี้—โปรเจกต์ของคุณจะอ้างอิงไลบรารีที่เป็นพื้นฐานให้กับทุกอย่างต่อไป + +### เพิ่ม Using Directives + +Open `Program.cs` and paste the following at the top: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +เนมสเปซเหล่านี้ทำให้เราสามารถเข้าถึง `BarcodeGenerator` และ enum ของรูปแบบภาพที่เราจะใช้ต่อไป + +--- + +## ขั้นตอนที่ 2: กำหนดเมธอดช่วยเหลือสำหรับการบันทึกรูปภาพ + +เพื่อหลีกเลี่ยงการทำซ้ำตรรกะการบันทึกเดียวกัน เราจะห่อมันไว้ในเมธอดเล็ก ๆ นี้ ซึ่งยังแสดงให้เห็น **how to set barcode height** ในภายหลัง + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Why this matters:** การรวมตรรกะการบันทึกไว้ในที่เดียวหมายความว่าคุณต้องเปลี่ยนรูปแบบหรือโฟลเดอร์เพียงที่เดียวหากความต้องการเปลี่ยนแปลง + +--- + +## ขั้นตอนที่ 3: สร้าง Planet Barcode (ส่วน “generate planet barcode”) + +ก่อนที่เราจะลงลึกในรายละเอียดของ RM4SCC เรามาเริ่มด้วย **Planet barcode** กันก่อน ซึ่งจะให้การตรวจสอบภาพอย่างรวดเร็วว่าห้องสมุดทำงานได้ + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Expected output:** จะมีไฟล์ PNG สองไฟล์ปรากฏในโฟลเดอร์ `output`—หนึ่งไฟล์ที่ความสูงคำนวณอัตโนมัติโดยไลบรารี, อีกไฟล์ที่ความสูง 100 px อย่างแม่นยำ + +--- + +## ขั้นตอนที่ 4: สร้าง RM4SCC Barcode – เป้าหมายหลัก + +ต่อไปคือส่วนสำคัญของการแสดง: **create RM4SCC barcode**. RM4SCC คือ Royal Mail 4‑State Code ที่ใช้กันอย่างแพร่หลายในระบบไปรษณีย์ของสหราชอาณาจักร + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**What you’ll see:** +- `RM4SCCDefault.png` – ไลบรารีกำหนดความสูงที่เหมาะสมตาม X‑dimension +- `RM4SCCHeight100.png` – บาร์โค้ดความสูง 100 พิกเซลที่คมชัดพร้อมพิมพ์บนซองจดหมาย + +> **Why set the height?** เครื่องพิมพ์ฉลากบางรุ่นต้องการความสูงบาร์ขั้นต่ำเพื่อการสแกนที่เชื่อถือได้ การกำหนดความสูงคงที่ช่วยให้คุณมั่นใจว่าตรงตามข้อกำหนดบนอุปกรณ์ทุกชนิด + +--- + +## ขั้นตอนที่ 5: ทำความเข้าใจการตั้งค่าความสูง (ตอบคำถาม “how to set barcode height”) + +Both the Planet and RM4SCC examples use the same property: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** คืออ็อบเจ็กต์ `BarHeight` ที่รวมหลายหน่วยวัด (พิกเซล, มิลลิเมตร, นิ้ว) +- **`.Pixels`** เป็นหน่วยที่ตรงไปตรงมาที่สุดสำหรับผลลัพธ์บนหน้าจอ, แต่คุณก็สามารถใช้ `.Millimeters` หรือ `.Inches` หากคุณมุ่งเป้าไปที่สื่อการพิมพ์ + +### กรณีขอบและเคล็ดลับ + +| Situation | Recommended Approach | +|-----------|----------------------| +| **X‑dimension เล็กมาก (เช่น 1 px)** | เพิ่ม `BarHeight` เพื่อให้บาร์โค้ดอ่านได้ | +| **พิมพ์บนเครื่องพิมพ์ฉลากความละเอียดสูง** | ใช้ `.Millimeters` เพื่อขนาดที่ไม่ขึ้นกับอุปกรณ์ | +| **บาร์โค้ดหลายประเภทในภาพเดียว** | ตั้งค่า `BarHeight` *หลังจาก* `XDimension` สำหรับแต่ละ generator เพื่อหลีกเลี่ยงการสืบทอดโดยบังเอิญ | +| **ข้อมูลแบบไดนามิก (เช่น รหัสที่ผู้ใช้ป้อน)** | ห่อการสร้าง generator ในเมธอดที่รับพารามิเตอร์ `code` และ `height` | + +--- + +## ขั้นตอนที่ 6: ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นโปรแกรมเดียวที่ทำงานอิสระซึ่งคุณสามารถคัดลอก‑วางลงใน `Program.cs` ได้ รวมทุกอย่างตั้งแต่การตั้งค่าโปรเจกต์จนถึงการบันทึกรูปภาพ + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Run it with: + +```bash +dotnet run +``` + +คุณควรเห็นผลลัพธ์ในคอนโซลที่ยืนยันการบันทึกแต่ละไฟล์ และโฟลเดอร์ `output` จะมี PNG สี่ไฟล์ที่ตรงกับชื่อที่แสดงด้านบน + +--- + +## สรุป + +ตอนนี้คุณรู้แล้วว่า **how to create RM4SCC barcode** ด้วย C# และควบคุมมิติของมันด้วยการกำหนดคุณสมบัติเพียงไม่กี่ค่า เรายังได้ครอบคลุม **generate planet barcode** เพื่อการตรวจสอบอย่างรวดเร็ว และสำรวจรายละเอียดของ **how to set barcode height** สำหรับสถานการณ์การพิมพ์ที่แตกต่างกัน + +ขั้นตอนต่อไป? ลองสลับ enum `EncodeTypes` เป็นสัญลักษณ์อื่น (Code128, QR, DataMatrix) และทดลองใช้ `BarHeight` ในหน่วยมิลลิเมตรสำหรับเครื่องพิมพ์ความละเอียดสูง หากคุณต้องการฝังบาร์โค้ดลงใน PDF ให้ใช้ Aspose.BarCode ร่วมกับ Aspose.PDF—อีกหนึ่งคอมโบที่ทรงพลัง + +มีคำถามหรืออยากแชร์การปรับแต่งของคุณ? ฝากคอมเมนต์ด้านล่าง แล้วขอให้เขียนโค้ดอย่างสนุกสนาน! + +## สิ่งที่คุณควรเรียนต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการนำไปใช้ทางเลือกในโปรเจกต์ของคุณ + +- [วิธีสร้างบาร์โค้ด Aztec ด้วยอัตราส่วนภาพที่กำหนดเองโดยใช้ Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [วิธีสร้าง Quiet Zone ของบาร์โค้ดสำหรับ ITF-14 โดยใช้ Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [วิธีสร้าง Quiet Zone ของบาร์โค้ดสำหรับ Code 16K โดยใช้ Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/thai/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..d90c697b5 --- /dev/null +++ b/barcode/thai/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-07-18 +description: เรียนรู้วิธีสร้างภาพบาร์โค้ดด้วยเครื่องสร้างบาร์โค้ด .net และเปลี่ยนความสูงของบาร์โค้ดได้อย่างง่ายดายสำหรับสัญลักษณ์ + GS1‑Databar Omni‑Directional. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: th +lastmod: 2026-07-18 +og_description: .NET barcode generator ช่วยให้คุณสร้างภาพบาร์โค้ดได้อย่างรวดเร็ว คู่มือนี้แสดงวิธีสร้างบาร์โค้ด + ปรับความสูงของบาร์ และบันทึกเป็นไฟล์ PNG. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: เปลี่ยนความสูงของบาร์โค้ดด้วยเครื่องสร้างบาร์โค้ด .net +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .net barcode generator – เปลี่ยนความสูงของบาร์โค้ด +url: /th/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – เปลี่ยนความสูงของบาร์โค้ด + +เคยสงสัยไหมว่า **วิธีสร้างภาพบาร์โค้ด** อย่างไรโดยไม่ต้องใช้เครื่องมือของบุคคลที่สามหลายสิบเครื่อง? ในโลก .NET มีวิธีที่ค่อนข้างเรียบง่ายและสำคัญคือ **.net barcode generator**. ด้วยเพียงไม่กี่บรรทัดของ C# คุณสามารถสร้างสัญลักษณ์ GS1‑Databar Omni‑Directional ปรับความสูงของบาร์ และบันทึกผลลัพธ์เป็นไฟล์ PNG ได้. + +หากคุณกำลังสร้างระบบจัดการสินค้าคงคลัง, เครื่องพิมพ์ฉลากจัดส่ง, หรือแอปใด ๆ ที่ต้องการรหัสที่สแกนได้, บทเรียนนี้จะพาคุณจากศูนย์สู่บาร์โค้ดที่ทำงานได้ในไม่กี่นาที. เราจะอธิบายโค้ดทั้งหมด, ทำไมแต่ละการตั้งค่าถึงสำคัญ, และแสดงวิธี **change barcode height** โดยไม่ทำให้สเปคเสียหาย. + +## สิ่งที่คุณต้องการ + +- .NET 6.0 หรือใหม่กว่า (API ทำงานเช่นเดียวกันบน .NET Framework 4.7+) +- การอ้างอิงไปยังไลบรารีบาร์โค้ด (เช่น Aspose.BarCode for .NET – คลาสเดียวกันนี้ใช้ในคิทเชิงพาณิชย์หลายชุด) +- สภาพแวดล้อมการพัฒนา (Visual Studio, Rider, หรือ VS Code พร้อมส่วนขยาย C#) +- โฟลเดอร์ที่คุณมีสิทธิ์เขียน – บทเรียนจะบันทึกไฟล์ PNG ลงในที่นั้น + +เท่านี้เอง. ไม่ต้องมีแพ็กเกจ NuGet เพิ่มเติมนอกจากไลบรารีบาร์โค้ดเอง. + +## การใช้ .net barcode generator เพื่อเปลี่ยนความสูงของบาร์โค้ด + +ด้านล่างเป็น **โปรแกรมคอนโซลที่สมบูรณ์และสามารถรันได้**. คัดลอกไปยังโปรเจกต์ C# ใหม่, ปรับโฟลเดอร์ผลลัพธ์, แล้วกด F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### ทำไมแต่ละบรรทัดจึงสำคัญ + +| บรรทัด | เหตุผล | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | สร้างอินสแตนซ์ของ **.net barcode generator** ด้วยสัญลักษณ์และข้อมูลที่ต้องการ. enum `EncodeTypes.DatabarOmniDirectional` บอกไลบรารีให้ใช้รูปแบบ GS1‑Databar Omni‑Directional. | +| `XDimension.Pixels = 2;` | X‑dimension คือความกว้างของบาร์ที่บางที่สุด. การตั้งค่าเป็น *2 pixels* ให้ภาพคมชัดบนจอส่วนใหญ่และทำให้ขนาดไฟล์เล็กลง. | +| `BarHeight.Pixels = 30;` | นี่คือขั้นตอน **change barcode height** ที่กำหนดความสูงของแต่ละบาร์. ความสูง 30 pixel เป็นค่าเริ่มต้นที่ดีสำหรับป้ายขนาดเล็ก. | +| `generator.Save(...);` | บันทึกบาร์โค้ดเป็นไฟล์ PNG. PNG เป็นรูปแบบ loss‑less ซึ่งหมายความว่าตัวสแกนจะเห็นรูปแบบที่คุณสร้างอย่างแม่นยำ. | +| `BarHeight.Pixels = 60;` | ที่นี่เราจะ **change barcode height** อีกครั้ง—ครั้งนี้เป็น 60 pixels. ไลบรารีจะรีเรนเดอร์สัญลักษณ์ใหม่โดยอัตโนมัติเมื่อคุณเรียก `Save` ครั้งที่สอง. | +| `Console.WriteLine(...);` | ให้ข้อมูลตอบกลับอย่างรวดเร็วว่ากระบวนการเสร็จสิ้นโดยไม่มีข้อยกเว้น. | + +> **Pro tip:** หากคุณต้องการผลลัพธ์ความละเอียดสูงสำหรับการพิมพ์, เปลี่ยน `BarCodeImageFormat.Png` เป็น `BarCodeImageFormat.Tiff` และเพิ่มค่า `Resolution` (เช่น `generator.Parameters.ImageResolution = 300;`). ความสูงของบาร์จะยังคงถูกนำไปใช้, เพียงแต่แสดงผลที่ DPI ที่ละเอียดกว่า. + +## วิธีสร้างภาพบาร์โค้ดด้วยการตั้งค่าต่าง ๆ + +ส่วนโค้ดข้างต้นครอบคลุมพื้นฐาน, แต่สถานการณ์จริงมักต้องการการปรับแต่งเพิ่มเติม: + +### ปรับ X‑dimension สำหรับการพิมพ์ขนาดใหญ่ +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +การเพิ่ม X‑dimension ทำให้บาร์โค้ดทั้งหมดใหญ่ขึ้นโดยไม่เปลี่ยนแปลงข้อมูลที่เข้ารหัส. นี้เป็นประโยชน์เมื่อคุณพิมพ์บนฉลากขนาดใหญ่. + +### เปลี่ยนรูปแบบการส่งออก +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG สามารถขยายได้ไม่จำกัด, เหมาะอย่างยิ่งสำหรับสแกนเนอร์บนเว็บที่ต้องการเวกเตอร์คมชัด. + +### เพิ่มข้อความที่อ่านได้โดยมนุษย์ +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +การเปิดใช้งาน `CodeTextVisible` จะเพิ่มข้อมูลดิบใต้บาร์โค้ด, มีประโยชน์สำหรับการตรวจสอบระหว่างการทดสอบ. + +## ข้อผิดพลาดทั่วไปเมื่อคุณ **change barcode height** + +1. **Height too small** – ตัวสแกนบางรุ่นต้องการความสูงบาร์ขั้นต่ำ (มักประมาณ 10 mm ในหน่วยจริง). หากตั้งค่า `BarHeight.Pixels` ต่ำเกินไป, ภาพที่สร้างอาจอ่านไม่ได้บนสแกนเนอร์จริง. ควรทดสอบกับฮาร์ดแวร์เป้าหมายเสมอ. +2. **Mismatched X‑dimension and height** – ความสูงบาร์ที่มากเกินไปร่วมกับ X‑dimension ที่เล็กเกินไปอาจทำให้บาร์ดูยืดและอาจทำให้การถอดรหัสล้มเหลว. ควรรักษาอัตราส่วนที่สมดุล (ประมาณ 3:1 ถึง 5:1) เว้นแต่สเปคจะกำหนดอย่างอื่น. +3. **Forgetting to reset parameters** – ตัวสร้างบาร์โค้ดจะเก็บสถานะระหว่างการบันทึก. หากคุณเปลี่ยน `BarHeight` สำหรับภาพหนึ่งแล้วใช้อินสแตนซ์เดียวกันสำหรับบาร์โค้ดอื่น, ความสูงก่อนหน้าจะยังคงอยู่. ให้รีเซ็ตคุณสมบัตินั้นหรือสร้าง `BarcodeGenerator` ใหม่สำหรับแต่ละบาร์โค้ดที่แตกต่างกัน. + +## ตัวอย่างเต็มขั้นตอน (รวมการติดตั้ง NuGet) + +หากคุณเริ่มจากศูนย์, ทำตามขั้นตอนเหล่านี้เพื่อให้โปรเจกต์ทำงานได้: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +แทนที่ `Program.cs` ที่สร้างอัตโนมัติด้วยโค้ดบล็อกที่แสดงก่อนหน้า, **อย่าลืมแทนที่ `YOUR_DIRECTORY`** ด้วยเส้นทางเช่น `Path.Combine(Environment.CurrentDirectory, "output")`. จากนั้น: + +```bash +dotnet run +``` + +คุณควรเห็นไฟล์ PNG สองไฟล์ในโฟลเดอร์ `output`: + +- `DatabarBarHeight30Pixels.png` – บาร์โค้ดความสูง 30 pixel แบบกะทัดรัด. +- `DatabarBarHeight60Pixels.png` – เวอร์ชันความสูง 60 pixel ที่สูงกว่า. + +ทั้งสองภาพจะดูคล้ายกัน, แต่ภาพที่สองจะมีบาร์ยาวกว่าอย่างชัดเจน, ทำให้สแกนเนอร์ความละเอียดต่ำอ่านได้ง่ายขึ้น. + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator แสดงผลลัพธ์ที่มีความสูงของบาร์ต่างกัน"} + +## สรุป & ขั้นตอนต่อไป + +เราได้อธิบายวิธี **generate barcode** ด้วย **.net barcode generator**, ปรับแต่งคุณสมบัติ **change barcode height** และบันทึกผลลัพธ์เป็น PNG. สิ่งที่ควรจำคือ: + +- สร้างอินสแตนซ์ของ generator ด้วย `EncodeTypes` ที่ถูกต้อง. +- ควบคุมขนาดภาพด้วย `XDimension` และ `BarHeight`. +- เรียก `Save` หลังจากแต่ละการเปลี่ยนแปลงเพื่อบันทึกภาพใหม่. +- ปรับความละเอียด, รูปแบบ, + +## สิ่งที่คุณควรเรียนต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้. แต่ละแหล่งรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการทำงานทางเลือกในโปรเจกต์ของคุณเอง. + +- [วิธีสร้างบาร์โค้ด Aztec ด้วยอัตราส่วนภาพที่กำหนดเองโดยใช้ Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [วิธีสร้าง dotcode พร้อมข้อความโค้ดขยายโดยใช้ Aspose.BarCode for .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-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/turkish/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/turkish/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..70f607d60 --- /dev/null +++ b/barcode/turkish/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-07-18 +description: Boyutları nasıl ayarlayacağınızı ve C#'ta DataBar Stacked Omni‑Directional + barkod görüntüsü oluşturmayı gösteren barkod oluşturucu örneği. Barkod kodlama türlerini + hızlıca öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: tr +lastmod: 2026-07-18 +og_description: Barkod oluşturucu örneği, boyutları nasıl ayarlayacağınızı, barkod + kodlama türlerini nasıl seçeceğinizi ve minimal kodla C# projelerinde barkod resmi + oluşturmayı adım adım gösterir. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Barkod Oluşturucu Örneği – C#'ta Hızlı DataBar Görüntüsü Oluşturma +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Barkod Üretici Örneği – C#'ta DataBar Görseli Oluştur +url: /tr/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barkod Üretici Örneği – C# ile DataBar Görüntüsü Oluşturma + +Gerçek bir barkodu sorunsuz bir şekilde üreten bir **barkod üretici örneği**'na hiç ihtiyaç duydunuz mu? Yalnız değilsiniz. Çoğu geliştirici, özellikle belgeler jargon yığınları arasında saklıyken, DataBar Stacked Omni‑Directional barkodunun **boyutları nasıl ayarlanır** sorusunu çözerken bir duvara çarpar. + +Bu öğreticide, **databar** görüntülerinin nasıl üretileceğini gösteren, doğru **barcode encode types**'ı seçen ve sonunda **create barcode image c#** dosyalarını herhangi bir projeye ekleyebileceğiniz tam çalışan bir C# programını adım adım inceleyeceğiz. Fazla söze gerek yok—kopyala‑yapıştır yapabileceğiniz kod ve her satırın ardındaki mantık. + +## Gereksinimler + +- **.NET 6** (veya daha yeni bir .NET sürümü) – kullandığımız API .NET Standard'ı hedeflediği için .NET Framework'te de çalışır. +- **Aspose.BarCode for .NET** – `BarcodeGenerator` sağlayan kütüphane. NuGet üzerinden `Install-Package Aspose.BarCode` ile edinebilirsiniz. +- Bir **C# IDE** – Visual Studio, Rider veya VS Code yeterli. +- PNG dosyalarının kaydedileceği bir klasör (kod `DatabarAspectRatio15.png` ve `DatabarAspectRatio30.png` dosyalarını oluşturur). + +Hepsi hazır mı? Harika—başlayalım. + +## Barkod Üretici Örneği – Üreteci Başlatma + +İlk iş olarak, **DataBar Stacked Omni‑Directional** sembolojisi için yapılandırılmış bir `BarcodeGenerator` örneğine ihtiyacımız var. Bu, çalışacağımız **barcode encode type**'dır. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Neden önemli?** `EncodeTypes.DatabarStackedOmniDirectional` Aspose'a hangi sembolojiyi oluşturacağını tam olarak söyler. Yanlış tip seçilirse, tarayıcı barkodu tanımaz, görüntü ne kadar güzel olursa olsun. + +## Barkod İçin Boyutları Nasıl Ayarlarsınız + +Bir barkodun okunabilirliği, **X‑dimension**'ına (en dar çubuğun genişliği) bağlıdır. Çoğu durumda 2 piksel değeri yeterli olur, ancak yazıcı ya da ekranınıza göre ayarlayabilirsiniz. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **İpucu:** Farklı bir barkod ailesi için **boyutları nasıl ayarlarsınız** sorusunu merak ederseniz, aynı özellik zinciri (`Parameters.Barcode.XDimension`) geçerlidir—sadece `Pixels` değerini değiştirin. + +## DataBar Stacked Omni‑Directional Barkod Nasıl Oluşturulur + +Üreteç hazır olduğuna göre, **aspect ratio** özelliğiyle oynayacağız. Bu, DataBar'ın yükseklik‑genişlik oranını kontrol eder ve kısa, kare bir sembol ya da uzun, dar bir sembol üretmenizi sağlar. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Ne oluyor?** `AspectRatio = 15` motorun çubukları genişliklerinin 15 katı kadar uzun yapmasını söyler. Oluşan PNG, çalıştırılabilir dosyanızın yanına kaydedilir. + +## Create Barcode Image C# – Aspect Ratio’yu Değiştirme + +Esnekliği göstermek için oranı 30’a değiştirip ikinci bir dosya kaydedelim. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +Programı çalıştırdığınızda iki PNG dosyası elde edeceksiniz: + +| Dosya | Aspect Ratio | Yaklaşık Boyut | +|------|--------------|----------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Herhangi bir görüntüleyicide açın—temiz ve taranabilir DataBar sembolleri görmelisiniz. + +## Barcode Encode Types Genel Bakışı (İsteğe Bağlı ama Faydalı) + +Aspose tarafından desteklenen diğer **barcode encode types** hakkında merak ettikleriniz varsa, işte hızlı bir özet: + +| EncodeTypes Enum | Açıklama | +|------------------|----------| +| `EncodeTypes.Code128` | Yüksek yoğunluklu alfanümerik | +| `EncodeTypes.QR` | 2‑D matris kod | +| `EncodeTypes.DatabarExpanded` | Perakende için GS1 DataBar | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Bizim odak noktamız** – kompakt, çok yönlü | + +Doğru enum’u bilmek, projeler arasında geçiş yaparken deneme‑yanılma süresini büyük ölçüde azaltır. + +## Yaygın Hatalar ve Önleme Yöntemleri + +- **NuGet paketi eksik** – `Aspose.BarCode` olmadan kod derlenmez. Önce `dotnet add package Aspose.BarCode` komutunu çalıştırın. +- **Yanlış dosya yolu** – Mutlak yol kullanıyorsanız, Windows'ta ters eğik çizgileri (`\\`) kontrol edin. Gösterildiği gibi göreli yollar taşınabilirliği artırır. +- **Aspect ratio çok aşırı** – 50’nin üzerindeki oranlar barkodu tipik tarayıcılar için çok uzun yapabilir. Çoğu senaryo için 15‑30 aralığını tercih edin. + +## Tam Kaynak Kodu (Kopyala‑Yapıştır Hazır) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Programı çalıştırın (`dotnet run` ya da Visual Studio’da **F5** tuşuna basın) ve konsolda dosyaların diskte oluşturulduğuna dair bir mesaj göreceksiniz. + +![Barcode generator example output showing DataBar barcode with aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Barkod üretici örnek çıktısı – Aspect Ratio 15 ile DataBar barkodu"} + +## Sonuç + +Bir **barkod üretici örneği** tamamladık; **boyutları nasıl ayarlarsınız**, doğru **barcode encode types**'ı seçer ve sonunda **create barcode image c#** dosyalarını istediğiniz yere ekleyebileceksiniz. Kod kısa, kavramlar net ve artık çözümü genişletmek için sağlam bir temele sahipsiniz—örneğin metin eklemek, görüntüyü döndürmek ya da farklı bir sembolojiye geçmek gibi. + +### Sırada Ne Var? + +- **Farklı X‑dimension** değerleriyle deneme yaparak tarayıcı toleransının nasıl değiştiğini gözlemleyin. +- `Code128` ya da `QR` gibi diğer **EncodeTypes**'ları deneyerek araç setinizi genişletin. +- Toplu üretim otomasyonu: bir CSV dosyasındaki ürün kimlikleri üzerinden döngü kurup her biri için PNG oluşturun. + +Bir sorunla karşılaşırsanız, aşağıya yorum bırakın ya da Aspose.BarCode dokümantasyonuna göz atın—burada da burada ele aldıklarımızı tamamlayan birçok örnek bulacaksınız. + +İyi kodlamalar, barkodlarınız ilk denemede taransın! + +## Bir Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanarak yakın konuları ele alır. Her kaynak, adım adım açıklamalar ve tam çalışan kod örnekleri içerir, böylece ek API özelliklerini öğrenebilir ve projelerinizde alternatif uygulama yaklaşımlarını keşfedebilirsiniz. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/turkish/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..6608dd3c3 --- /dev/null +++ b/barcode/turkish/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-07-18 +description: C# ile Planet barkodunu hızlıca oluşturun. Dolu ve boş çubukları nasıl + oluşturacağınızı, X‑boyutunu nasıl ayarlayacağınızı ve PNG görüntülerini nasıl kaydedeceğinizi + öğrenin – hepsi tek bir öğreticide. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: tr +lastmod: 2026-07-18 +og_description: Planet barkodunu anında oluşturun. Bu kılavuz, X‑boyutunu nasıl ayarlayacağınızı, + dolu ve boş çubuklar arasında nasıl geçiş yapacağınızı ve Aspose.BarCode ile PNG + dosyalarını nasıl dışa aktaracağınızı gösterir. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: C# ile Planet Barkod Oluşturma – Tam Programlama Rehberi +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: C#'ta Planet Barkod Oluşturma – Tam Adım Adım Rehber +url: /tr/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta Planet Barkod Oluşturma – Tam Adım‑Adım Kılavuz + +Hiç **planet barkod** görüntüleri oluşturmanız gerekti, ancak hangi özellikleri ayarlamanız gerektiğinden emin olmadınız mı? Yalnız değilsiniz. Birçok geliştirici, varsayılan dolu çubukların spesifikasyona uymadığı veya çubuk genişliğinin bir yazıcının DPI'sine eşit olması gerektiğinde bir engelle karşılaşıyor. + +Bu öğreticide, Aspose.BarCode kütüphanesini kullanarak **planet barkod** dosyalarını nasıl **oluşturacağınızı**, **XDimension piksel** değerini nasıl kontrol edeceğinizi ve **dolu çubuklar** ile **boş çubuklar** arasında kodu yeniden yazmadan nasıl geçiş yapacağınızı öğreneceksiniz. Sonunda, klasik Planet barkodunu bekleyen herhangi bir posta sistemine hazır, bir tanesi katı çubuklu, diğeri boş çubuklu iki PNG dosyanız olacak. + +## Prerequisites + +- .NET 6.0 veya daha yeni (kod .NET Framework 4.7 + üzerinde de çalışır) +- Aspose.BarCode for .NET NuGet paketi (`Install-Package Aspose.BarCode`) +- Temel C# bilgisi (`using` ifadelerini daha sonra neden kullandığımızı göreceksiniz) +- PNG'lerin kaydedileceği, yazılabilir bir klasör + +Bu gereksinimlere sahipseniz, doğrudan uygulamaya geçebiliriz. + +## Step 1 – Set Up the Project and Add the Library + +İlk olarak yeni bir console uygulaması (veya herhangi bir C# projesi) oluşturun ve **Planet barkod üreteci** kütüphanesine referans ekleyin. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Pro tip:** Visual Studio'da projeye sağ‑tıklayın → *Manage NuGet Packages* → **Aspose.BarCode** aratın ve *Install*'a tıklayın. Bu, `BarcodeGenerator` ve ihtiyacınız olacak tüm **BarcodeGenerator parameters**'a erişmenizi sağlar. + +## Step 2 – Initialise the Planet Barcode Generator + +Şimdi gerçekten **planet barkod** üreteci örneğini oluşturup kodlamak istediğimiz veriyi (`"123456"` bu örnekte) ona veriyoruz. `EncodeTypes.Planet` enum'u kütüphaneye hangi sembolojiyi kullanacağını bildirir. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Neden önemli:** `EncodeTypes.Planet` bayrağı, Planet posta barkodu için doğru kontrol toplamını ve yerleşim kurallarını otomatik olarak uygular, böylece bunları manuel olarak hesaplamanıza gerek kalmaz. + +## Step 3 – Configure X‑Dimension (Bar Width) + +Çoğu yazıcı, her çubuğun belirli bir piksel sayısına sahip olmasını bekler. Burada **XDimension piksel** değerini `4` olarak ayarlıyoruz; bu, 203 dpi termal yazıcılar için yaygın bir değerdir. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Köşe durumu:** 300 dpi bir yazıcı hedefliyorsanız, `3` veya `5` piksel gerekebilir. Bu değeri cihazınızın dokümantasyonuna göre ayarlayın. + +## Step 4 – Save the Filled‑Bar Version + +Varsayılan olarak üreteç **dolu çubuklar** (katı siyah dikdörtgenler) üretir. Bunu diske yazalım: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +`YOUR_DIRECTORY` ifadesini, uygulamanızın yazabileceği mutlak ya da göreli bir yol ile değiştirin. Bu satır çalıştıktan sonra klasik bir Planet barkodu gibi görünen bir PNG dosyası bulacaksınız—posta tarayıcısında test etmek için mükemmel. + +## Step 5 – Switch to Empty Bars + +Bazen posta hizmetleri, çubukların siyah olarak boyanması yerine beyaz bir arka plan üzerinden oyulmuş olduğu “boş çubuklar” stilini ister. Kütüphane basit bir anahtar sunar: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +`FilledBars` değerini `false` olarak ayarlamak, çubuk doldurma mantığını tersine çevirir. Yeni bir `BarcodeGenerator` örneği oluşturmanıza gerek yok; mevcut **BarcodeGenerator parameters**'ı sadece değiştiriyoruz. + +## Step 6 – Save the Empty‑Bar Version + +Son olarak ikinci görüntüyü dışa aktaralım: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Şimdi iki farklı görsel gereksinime uyan iki ayrı PNG dosyanız var. + +## Full Working Example + +Tüm parçaları bir araya getirerek, kopyala‑yapıştır‑hazır tam program aşağıdadır: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Beklenen çıktı** (konsolda): + +``` +Both Planet barcode images have been generated successfully. +``` + +Ve `C:\Barcodes\` içinde şunları göreceksiniz: + +- `PostalPlanetFilledBars.png` – katı siyah çubuklar +- `PostalPlanetEmptyBars.png` – siyah konturlu beyaz çubuklar + +Her iki dosyayı da herhangi bir görüntüleyicide açın; ikisi de Planet spesifikasyonuna uygun olmalıdır. + +## Common Questions & Tips + +### “Can I change the image format?” + +Kesinlikle. `Save` yöntemi `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif` vb. formatları kabul eder. `BarCodeImageFormat.Png` ifadesini istediğiniz formatla değiştirmeniz yeterlidir. + +### “What if I need a different barcode height?” + +Dikey boyutu artırmak ya da azaltmak için `planetBarcode.Parameters.Barcode.BarHeight` (puan cinsinden) özelliğini kullanın. Örneğin: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “Is there a way to add a human‑readable caption?” + +Evet. `planetBarcode.Parameters.Caption` üzerindeki `CodeText` özelliğini ayarlayın: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “Do I need to dispose the generator?” + +`BarcodeGenerator` `IDisposable` arayüzünü uygular. Döngü içinde birçok barkod oluşturuyorsanız, bir `using` bloğu içinde tutun: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “What about error handling?” + +`Save` çağrılarını `try…catch` bloğuna alarak `IOException` (disk sorunları) veya `ArgumentException` (geçersiz parametreler) gibi istisnaları yakalayabilirsiniz. Örnek: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Recap + +C#'ta **planet barkod** görüntüleri oluşturmak için ihtiyaç duyduğunuz her şeyi ele aldık: + +1. Verinizle **Planet barkod üretecini** başlatın. +2. Yazıcı özelliklerine uygun **XDimension piksel** değerini ayarlayın. +3. **Dolu çubuklar** PNG'sini kaydedin. +4. `FilledBars` değerini değiştirerek **boş çubuklar** üretin. +5. İkinci PNG'yi kaydedin. + +Buradan itibaren daha fazla **BarcodeGenerator parameters** keşfedebilir, diğer sembolojilerle (`EncodeTypes.Postnet`, `EncodeTypes.Code128` vb.) deneyler yapabilir veya görüntüleri posta iş akışınıza entegre edebilirsiniz. + +--- + +**Bir sonraki adıma hazır mısınız?** Aynı belgeye bir QR kodu eklemeyi deneyin ya da bir `foreach` döngüsü kullanarak CSV listesinden bir toplu Planet barkodları üretin. Aspose.BarCode API'si, toplu işlemler, özel renkler ve hatta vektör‑tabanlı SVG çıktısı gibi ihtiyaçları karşılayacak kadar esnektir. + +Herhangi bir sorunla karşılaşırsanız, aşağıya yorum bırakın ya da daha derinlemesine özellikler için resmi Aspose.BarCode dokümantasyonuna göz atın. Kodlamanın tadını çıkarın! + +## What Should You Learn Next? + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanan ve yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak tam çalışan kod örnekleri ve adım‑adım açıklamalar içerir. + +- [Aspose ile Barkod Oluşturma - Java'da X & Y Boyutlarını Ayarlama](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [Java'da Aspose.BarCode ile code128 barkod görüntüleri oluşturma](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [Java'da code128 barkod oluşturma ve çubuk yüksekliğini ayarlama](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/turkish/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..2f36093da --- /dev/null +++ b/barcode/turkish/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-07-18 +description: C#'ta RM4SCC barkodu hızlı bir şekilde oluşturun; barkod yüksekliğini + nasıl ayarlayacağınızı öğrenin ve ayrıca özel boyutlarla Planet barkodu üretin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: tr +lastmod: 2026-07-18 +og_description: C#'ta RM4SCC barkod oluşturun ve barkod yüksekliğini nasıl ayarlayacağınızı + keşfedin. Aynı kütüphane ile Planet barkodu nasıl oluşturacağınızı da görün. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: C#'de RM4SCC Barkod Oluştur – Özel Yüksekliği Hızlıca Ayarla +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: C#'ta RM4SCC Barkod Oluşturma – Yüksekliği Ayarlamak İçin Tam Kılavuz +url: /tr/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta RM4SCC Barkod Oluşturma – Yüksekliği Ayarlamak İçin Tam Kılavuz + +Bir .NET uygulamasında **create RM4SCC barcode** oluşturmanız gerektiğinde ancak boyutunu nasıl kontrol edeceğinizden emin olmadığınız oldu mu? Yalnız değilsiniz. Bir posta sistemi ya da bir lojistik kontrol paneli oluşturuyor olsanız da, doğru barkod yüksekliğini ayarlamak, çalışan bir tarama ile başarısız bir tarama arasındaki fark olabilir. + +Bu öğreticide, kütüphaneyi kurmaktan, **generate Planet barcode** yan yana örnek olarak göstermeye ve sonunda her iki barkod türü için **how to set barcode height**'ı göstermeye kadar tüm süreci adım adım anlatacağız. Sonunda, ihtiyacınız olan tam boyutlarda PNG dosyaları üreten, çalıştırmaya hazır bir konsol uygulamanız olacak. + +--- + +## İhtiyacınız Olanlar + +- **.NET 6 SDK** (veya herhangi bir yeni .NET sürümü) – kod .NET Framework'te de çalışır, ancak .NET 6 en uygun seçenektir. +- **Aspose.BarCode for .NET** NuGet paketi – bu, `BarcodeGenerator` sınıfını sağlayan kütüphanedir. +- Biraz C# bilgisi – sözdizimini yeni başlayanlar için dostane tutacağız. +- Bir IDE ya da metin düzenleyici (Visual Studio, VS Code, Rider—size uyanı seçin). + +> **Pro tip:** Bir CI/CD hattındaysanız, bağımlılığın unutulmaması için NuGet referansını `.csproj` dosyanıza ekleyin. + +## Adım 1: Projeyi Kurun + +Bir terminal açın ve yeni bir konsol projesi oluşturun: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +Hepsi bu—projeniz artık sonraki tüm işlemleri sağlayan kütüphaneye referans veriyor. + +### Using Direktiflerini Ekleyin + +`Program.cs` dosyasını açın ve aşağıdakileri en üstte yapıştırın: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +## Adım 2: Görüntüleri Kaydetmek İçin Yardımcı Bir Metod Tanımlayın + +Aynı kaydetme mantığını tekrarlamaktan kaçınmak için, bunu küçük bir metod içinde saracağız. Bu aynı zamanda daha sonra **how to set barcode height**'ı da gösterir. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Neden önemli:** Kaydetme mantığını merkezileştirerek, gereksinimler değiştiğinde formatı ya da klasörü sadece bir yerde değiştirmeniz yeterli olur. + +## Adım 3: Planet Barkodu Oluşturun ("generate planet barcode" bölümü) + +RM4SCC detaylarına girmeden önce bir **Planet barcode** oluşturalım. Bu, kütüphanenin çalıştığını hızlı bir görsel kontrol ile doğrulamanızı sağlar. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Beklenen çıktı:** `output` klasöründe iki PNG dosyası oluşur—biri kütüphanenin otomatik hesapladığı yükseklikte, diğeri tam 100 px yüksekliğinde. + +## Adım 4: RM4SCC Barkodu Oluşturun – Birincil Hedef + +Şimdi gösterinin yıldızı: **create RM4SCC barcode**. RM4SCC, Birleşik Krallık posta sisteminde yaygın olarak kullanılan Royal Mail 4‑State Code'dur. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**Gördükleriniz:** +- `RM4SCCDefault.png` – kütüphane X‑dimension'a göre uygun bir yükseklik belirler. +- `RM4SCCHeight100.png` – zarflara basım için hazır, net 100 piksel yüksekliğinde bir barkod. + +> **Neden yüksekliği ayarlamalısınız?** Bazı etiket yazıcıları güvenilir tarama için minimum çubuk yüksekliği ister. Yüksekliği sabitleyerek, cihazlar arasında uyumluluğu garantilersiniz. + +## Adım 5: Yükseklik Ayarlarını Anlamak ("how to set barcode height" sorusuna yanıt) + +Planet ve RM4SCC örneklerinin her ikisi de aynı özelliği kullanır: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** birden fazla ölçüm birimini (piksel, milimetre, inç) gruplandıran bir `BarHeight` nesnesidir. +- **`.Pixels`** ekran‑odaklı çıktı için en basit birimdir, ancak baskı medyası hedefliyorsanız `.Millimeters` veya `.Inches` da kullanabilirsiniz. + +### Kenar Durumları ve İpuçları + +| Durum | Önerilen Yaklaşım | +|-----------|----------------------| +| **Çok küçük X‑dimension (ör. 1 px)** | `BarHeight`'ı artırarak barkodun okunabilirliğini koruyun. | +| **Yüksek çözünürlüklü etiket yazıcılarında baskı** | Cihaz bağımsız boyutlandırma için `.Millimeters` kullanın. | +| **Tek bir görüntüde karışık barkod tipleri** | Her bir generator için `BarHeight`'ı `XDimension`'dan *sonra* ayarlayarak istemsiz kalıtımı önleyin. | +| **Dinamik veri (ör. kullanıcı girişi kodları)** | Generator oluşturmayı `code` ve `height` parametrelerini kabul eden bir metod içinde sarın. | + +## Adım 6: Tam Çalışan Örnek + +Aşağıda, `Program.cs` içine kopyalayıp yapıştırabileceğiniz tek bir, bağımsız program bulunmaktadır. Proje kurulumundan görüntü kaydetmeye kadar her şeyi içerir. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Şu şekilde çalıştırın: + +```bash +dotnet run +``` + +Her dosyanın kaydedildiğini onaylayan konsol çıktısını görmelisiniz ve `output` klasörü yukarıda gösterilen adlarla dört PNG içerecek. + +## Sonuç + +Artık C#'ta **how to create RM4SCC barcode** yapmayı ve sadece birkaç özellik atamasıyla boyutlarını kontrol etmeyi biliyorsunuz. Ayrıca **generate planet barcode**'ı hızlı bir doğrulama olarak ele aldık ve farklı baskı senaryoları için **how to set barcode height** inceliklerini keşfettik. + +Sonraki adımlar? `EncodeTypes` enum'ını diğer sembolojiler (Code128, QR, DataMatrix) ile değiştirin ve yüksek çözünürlüklü yazıcılar için `BarHeight`'ı milimetre cinsinden deneyin. Barkodu bir PDF'ye gömmek isterseniz, Aspose.BarCode'u Aspose.PDF ile birleştirin—başka bir güçlü kombinasyon. + +Sorularınız mı var ya da kendi ayarlamalarınızı paylaşmak mı istiyorsunuz? Aşağıya bir yorum bırakın, iyi kodlamalar! + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu rehberde 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. + +- [Aspose.BarCode for .NET kullanarak özel en‑boy oranı ile Aztec barkodu nasıl oluşturulur](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Aspose.BarCode for .NET kullanarak ITF-14 için Barkod Sessiz Bölgesi Nasıl Oluşturulur](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Aspose.BarCode for .NET kullanarak Code 16K için barkod sessiz bölgesi nasıl oluşturulur](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/turkish/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..21c654300 --- /dev/null +++ b/barcode/turkish/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-07-18 +description: Bir .net barkod üreteci ile barkod görüntüleri oluşturmayı öğrenin ve + GS1‑Databar Omni‑Directional sembolleri için barkod yüksekliğini kolayca değiştirin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: tr +lastmod: 2026-07-18 +og_description: .net barkod oluşturucu, barkod görüntülerini hızlı bir şekilde oluşturmanıza + olanak tanır. Bu kılavuz, barkod oluşturmayı, çubuk yüksekliğini ayarlamayı ve PNG + dosyalarını kaydetmeyi gösterir. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: .NET barkod jeneratörüyle barkod yüksekliğini değiştir +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET barkod oluşturucu – barkod yüksekliğini değiştir +url: /tr/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – çubuk yüksekliğini değiştir + +Hiç **barkod nasıl oluşturulur** diye merak ettiniz mi, onca üçüncü‑taraf aracıyla uğraşmadan? .NET dünyasında bunu yapmanın şaşırtıcı derecede temiz bir yolu var ve ana parça **.net barcode generator**. Sadece birkaç C# satırıyla bir GS1‑Databar Omni‑Directional sembolü oluşturabilir, çubuk yüksekliğini ayarlayabilir ve sonucu bir PNG dosyasına kaydedebilirsiniz. + +Bir envanter sistemi, nakliye etiketi yazıcı ya da taranabilir bir koda ihtiyaç duyan herhangi bir uygulama geliştiriyorsanız, bu öğretici sizi sıfırdan çalışan bir barkoda dakikalar içinde ulaştıracak. Tam kodu adım adım inceleyecek, her ayarın neden önemli olduğunu açıklayacak ve **barkod yüksekliğini değiştirme** işlemini spesifikasyona zarar vermeden nasıl yapacağınızı göstereceğiz. + +## Gereksinimler + +- .NET 6.0 veya üzeri (API, .NET Framework 4.7+ üzerinde aynı şekilde çalışır) +- Barkod kütüphanesine bir referans (örneğin, Aspose.BarCode for .NET – aynı sınıflar birçok ticari kit tarafından kullanılır) +- Bir geliştirme ortamı (Visual Studio, Rider veya C# uzantılı VS Code) +- Yazma izniniz olan bir klasör – öğretici PNG dosyalarını burada kaydedecek + +Hepsi bu kadar. Barkod kütüphanesinin dışında ekstra bir NuGet paketi gerekmez. + +## .net barcode generator kullanarak barkod yüksekliğini değiştirme + +Aşağıda **tam, çalıştırılabilir bir konsol programı** bulunmaktadır. Yeni bir C# projesine yapıştırın, çıktı klasörünü ayarlayın ve F5 tuşuna basın. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Her satırın önemi + +| Satır | Sebep | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | **.net barcode generator**'ı istenen semboloji ve veri yükü ile başlatır. `EncodeTypes.DatabarOmniDirectional` enum'u kütüphaneye GS1‑Databar Omni‑Directional formatını kullanmasını söyler. | +| `XDimension.Pixels = 2;` | X‑dimension, en ince çubuğun genişliğidir. *2 pixel* olarak ayarlamak, çoğu monitörde net bir görüntü sağlar ve dosya boyutunu düşük tutar. | +| `BarHeight.Pixels = 30;` | Bu, **barkod yüksekliğini değiştirme** adımıdır ve her çubuğun ne kadar yüksek olacağını belirler. 30 pixel yükseklik, küçük etiketler için iyi bir varsayılandır. | +| `generator.Save(...);` | Barkodu bir PNG dosyasına kaydeder. PNG kayıpsızdır, bu da tarayıcıların oluşturduğunuz tam deseni görmesi anlamına gelir. | +| `BarHeight.Pixels = 60;` | Burada **barkod yüksekliğini** tekrar değiştiriyoruz—bu sefer 60 pixel. Kütüphane, `Save` metodunu ikinci kez çağırdığınızda sembolü yeni boyutla otomatik olarak yeniden oluşturur. | +| `Console.WriteLine(...);` | İşlemin bir istisna fırlatmadan tamamlandığına dair hızlı bir geri bildirim verir. | + +> **Pro ipucu:** Yazdırma için daha yüksek çözünürlüklü çıktı gerekiyorsa, `BarCodeImageFormat.Png`'i `BarCodeImageFormat.Tiff` ile değiştirin ve `Resolution` özelliğini artırın (ör. `generator.Parameters.ImageResolution = 300;`). Çubuk yüksekliği hâlâ korunur, sadece daha ince DPI'da işlenir. + +## Farklı ayarlarla barkod görüntüleri oluşturma + +Yukarıdaki kod temel konuları kapsar, ancak gerçek dünyadaki senaryolar genellikle ekstra ayarlamalar gerektirir: + +### Daha büyük baskılar için X‑dimension ayarlama +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +X‑dimension'ı artırmak, kodlanmış veriyi değiştirmeden tüm barkodu daha büyük yapar. Büyük etiketlerde baskı alırken kullanışlıdır. + +### Çıktı formatlarını değiştirme +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG sınırsız ölçeklenir, bu da net vektörlere ihtiyaç duyan web‑tabanlı tarayıcılar için mükemmeldir. + +### İnsan tarafından okunabilir metin ekleme +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +`CodeTextVisible`'ı etkinleştirmek, barkodun altına ham veriyi ekler; test sırasında doğrulama için faydalıdır. + +## **Barkod yüksekliğini değiştirirken** yaygın tuzaklar + +1. **Yükseklik çok düşük** – Bazı tarayıcılar minimum çubuk yüksekliği gerektirir (genellikle fiziksel birim olarak 10 mm). `BarHeight.Pixels` değerini çok düşük ayarlarsanız, oluşturulan görüntü gerçek bir tarayıcıda okunamaz olabilir. Her zaman hedef donanımınızla test edin. +2. **Uyumsuz X‑dimension ve yükseklik** – Çok büyük bir çubuk yüksekliği, çok küçük bir X‑dimension ile birleştirildiğinde uzatılmış görünebilir ve çözümleme hatalarına yol açabilir. Spesifikasyon aksi belirtmedikçe, dengeli bir oran (yaklaşık 3:1 ila 5:1) hedefleyin. +3. **Parametreleri sıfırlamayı unutmak** – Üreteç, kaydetmeler arasında durumu korur. Bir görüntü için `BarHeight`'ı değiştirip aynı örneği başka bir barkod için yeniden kullanırsanız, önceki yükseklik kalır. Özelliği sıfırlayın ya da her farklı barkod için yeni bir `BarcodeGenerator` örneği oluşturun. + +## Baştan sona tam örnek (NuGet kurulumu dahil) + +Sıfırdan başlıyorsanız, projeyi çalıştırmak için şu adımları izleyin: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Otomatik oluşturulan `Program.cs` dosyasını önceki kod bloğuyla değiştirin, **`YOUR_DIRECTORY`'yi** `Path.Combine(Environment.CurrentDirectory, "output")` gibi bir şeyle değiştirmeyi unutmayın. Sonra: + +```bash +dotnet run +``` + +`output` klasöründe iki PNG dosyası görmelisiniz: + +- `DatabarBarHeight30Pixels.png` – kompakt 30 pixel yüksekliğinde bir barkod. +- `DatabarBarHeight60Pixels.png` – daha uzun 60 pixel versiyon. + +Her iki görüntü de benzer görünecek, ancak ikincisi belirgin şekilde daha uzun çubuklara sahip olacak, bu da düşük çözünürlüklü tarayıcıların okumasını kolaylaştırır. + +![Barcode height example](/images/barcode-height.png){alt=".net barcode generator çıktısı farklı çubuk yüksekliklerini gösteriyor"} + +## Özet ve sonraki adımlar + +**.net barcode generator** kullanarak **barkod** görüntüleri oluşturmayı, **barkod yüksekliğini değiştirme** özelliğini ince ayar yapmayı ve sonuçları PNG formatında kaydetmeyi ele aldık. Temel çıkarımlar şunlardır: + +- Doğru `EncodeTypes` ile üreteci başlatın. +- `XDimension` ve `BarHeight` ile görsel boyutu kontrol edin. +- Her değişiklikten sonra yeni bir görüntü kaydetmek için `Save` çağırın. +- Çözünürlüğü ve formatı ayarlayın, + +## Sonraki öğrenmeniz gerekenler + +Aşağıdaki öğreticiler, bu rehberde 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. + +- [Aspose.BarCode for .NET kullanarak özel en‑boy oranı ile Aztec barkod nasıl oluşturulur](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Aspose.BarCode for .NET ile dotcode genişletilmiş kod metni nasıl oluşturulur](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Aspose.BarCode for .NET ile DataMatrix Barkodları (ECC 200) nasıl oluşturulur](/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/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md b/barcode/vietnamese/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md new file mode 100644 index 000000000..206256ec9 --- /dev/null +++ b/barcode/vietnamese/python-java/general/barcode-generator-example-build-databar-image-in-c/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-07-18 +description: Ví dụ trình tạo mã vạch cho thấy cách đặt kích thước và tạo hình ảnh + mã vạch DataBar Stacked Omni‑Directional bằng C#. Nhanh chóng học các loại mã vạch. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to set dimensions +- how to generate databar +- barcode encode types +- create barcode image c# +language: vi +lastmod: 2026-07-18 +og_description: Ví dụ trình tạo mã vạch hướng dẫn bạn cách thiết lập kích thước, chọn + loại mã hoá, và tạo dự án C# để tạo hình ảnh mã vạch với mã tối thiểu. +og_image_alt: Barcode generator example output showing DataBar barcode with aspect + ratio 15 +og_title: Ví dụ Trình tạo Mã vạch – Tạo nhanh hình ảnh DataBar trong C# +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Barcode generator example showing how to set dimensions and generate + a DataBar Stacked Omni‑Directional barcode image in C#. Learn barcode encode types + quickly. + headline: Barcode Generator Example – Build DataBar Image in C# + type: TechArticle +tags: +- barcode +- C# +- Aspose +- image generation +title: Ví dụ Trình tạo Mã vạch – Xây dựng hình ảnh DataBar bằng C# +url: /vi/python-java/general/barcode-generator-example-build-databar-image-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ví dụ Trình tạo Mã vạch – Tạo hình ảnh DataBar trong C# + +Bạn đã bao giờ cần một **barcode generator example** thực sự tạo ra mã vạch thực tế mà không làm bạn phát điên không? Bạn không đơn độc. Hầu hết các nhà phát triển gặp khó khăn khi cố gắng tìm hiểu **how to set dimensions** cho mã vạch DataBar Stacked Omni‑Directional, đặc biệt khi tài liệu bị chôn sâu trong những thuật ngữ phức tạp. + +Trong hướng dẫn này, chúng ta sẽ đi qua một chương trình C# hoàn chỉnh, sẵn sàng chạy, cho thấy **how to generate databar** hình ảnh, chọn đúng **barcode encode types**, và cuối cùng **create barcode image c#** các tệp mà bạn có thể đưa vào bất kỳ dự án nào. Không có phần thừa—chỉ có mã bạn có thể sao chép‑dán, cùng với lý do đằng sau mỗi dòng. + +## Những gì bạn cần + +- **.NET 6** (hoặc bất kỳ phiên bản .NET gần đây nào) – API chúng ta dùng nhắm tới .NET Standard, vì vậy nó cũng hoạt động trên .NET Framework. +- **Aspose.BarCode for .NET** – thư viện cung cấp `BarcodeGenerator`. Bạn có thể tải nó từ NuGet bằng `Install-Package Aspose.BarCode`. +- Một **IDE C#** – Visual Studio, Rider, hoặc VS Code đều được. +- Một thư mục trên đĩa để lưu các tệp PNG (mã sẽ tạo `DatabarAspectRatio15.png` và `DatabarAspectRatio30.png`). + +Đã có tất cả? Tuyệt—cùng bắt đầu. + +## Barcode Generator Example – Khởi tạo Trình tạo + +Trước hết, chúng ta cần một thể hiện của `BarcodeGenerator` được cấu hình cho ký hiệu **DataBar Stacked Omni‑Directional**. Đây là **barcode encode type** mà chúng ta sẽ làm việc. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // Step 1: Create a DataBar Stacked Omni‑Directional barcode generator + // with the desired GTIN content. + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 example +``` + +> **Tại sao lại quan trọng:** `EncodeTypes.DatabarStackedOmniDirectional` nói với Aspose chính xác ký hiệu nào sẽ được vẽ. Nếu bạn chọn sai loại, máy quét sẽ không nhận dạng mã vạch, dù hình ảnh có đẹp đến đâu. + +## Cách thiết lập kích thước cho Mã vạch + +Độ đọc được của mã vạch phụ thuộc vào **X‑dimension** (chiều rộng của thanh hẹp nhất). Trong hầu hết các trường hợp, giá trị 2 pixel là ổn, nhưng bạn có thể điều chỉnh để phù hợp với máy in hoặc màn hình của mình. + +```csharp + // Step 2: Set a common X‑dimension (pixel width of the narrowest bar) + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +> **Mẹo chuyên nghiệp:** Nếu bạn muốn biết **how to set dimensions** cho một họ mã vạch khác, chuỗi thuộc tính (`Parameters.Barcode.XDimension`) vẫn áp dụng—chỉ cần thay đổi giá trị `Pixels`. + +## Cách tạo mã vạch DataBar Stacked Omni‑Directional + +Bây giờ trình tạo đã sẵn sàng, chúng ta sẽ chơi với thuộc tính **aspect ratio**. Thuộc tính này điều khiển tỷ lệ chiều cao‑so‑với‑chiều rộng của DataBar, cho phép bạn tạo một biểu tượng ngắn, vuông vức hoặc cao, hẹp. + +```csharp + // Step 3: Generate and save a barcode with aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); +``` + +> **Điều gì đang xảy ra?** `AspectRatio = 15` yêu cầu engine làm các thanh cao gấp 15 lần so với độ rộng. PNG kết quả sẽ được lưu ngay bên cạnh tệp thực thi của bạn. + +## Create Barcode Image C# – Thay đổi Aspect Ratio + +Hãy chứng minh tính linh hoạt bằng cách đổi tỷ lệ thành 30 và lưu một tệp thứ hai. + +```csharp + // Step 4: Change the aspect ratio to 30 and save another barcode + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been saved successfully."); + } +} +``` + +Khi bạn chạy chương trình, bạn sẽ có hai tệp PNG: + +| Tệp | Aspect Ratio | Kích thước xấp xỉ | +|------|--------------|-------------------| +| `DatabarAspectRatio15.png` | 15 | 120 × 180 px | +| `DatabarAspectRatio30.png` | 30 | 120 × 360 px | + +Mở chúng bằng bất kỳ trình xem ảnh nào—bạn sẽ thấy các biểu tượng DataBar sạch sẽ, có thể quét được. + +## Tổng quan về Barcode Encode Types (Tùy chọn nhưng hữu ích) + +Nếu bạn tò mò về các **barcode encode types** khác mà Aspose hỗ trợ, dưới đây là một bảng cheat‑sheet nhanh: + +| EncodeTypes Enum | Mô tả | +|------------------|-------| +| `EncodeTypes.Code128` | Alphanumeric mật độ cao | +| `EncodeTypes.QR` | Mã ma trận 2‑D | +| `EncodeTypes.DatabarExpanded` | GS1 DataBar cho bán lẻ | +| `EncodeTypes.DatabarStackedOmniDirectional` | **Mục tiêu của chúng ta** – gọn gàng, omnidirectional | + +Biết đúng enum sẽ giúp bạn tránh rất nhiều thử‑và‑sai khi chuyển dự án. + +## Những lỗi thường gặp & Cách tránh + +- **Thiếu gói NuGet** – Mã sẽ không biên dịch nếu không có `Aspose.BarCode`. Chạy `dotnet add package Aspose.BarCode` trước. +- **Đường dẫn tệp sai** – Nếu bạn dùng đường dẫn tuyệt đối, hãy kiểm tra lại các dấu gạch chéo ngược (`\\`) trên Windows. Đường dẫn tương đối (như trong ví dụ) giúp dự án di động hơn. +- **Aspect ratio quá cực đoan** – Tỷ lệ trên 50 có thể làm mã vạch quá cao đối với các máy quét thông thường. Giữ trong khoảng 15‑30 cho hầu hết các trường hợp. + +## Mã nguồn đầy đủ (Sẵn sàng sao chép‑dán) + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +class Program +{ + static void Main() + { + // 1️⃣ Initialize generator with DataBar Stacked Omni‑Directional type + var generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); // GTIN‑14 sample + + // 2️⃣ Set X‑dimension (how to set dimensions) – 2 pixels is a safe default + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ First barcode: aspect ratio 15 + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + generator.Save("DatabarAspectRatio15.png", BarCodeImageFormat.Png); + + // 4️⃣ Second barcode: aspect ratio 30 + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + generator.Save("DatabarAspectRatio30.png", BarCodeImageFormat.Png); + + Console.WriteLine("✅ Two barcode images saved – check your project folder."); + } +} +``` + +Chạy chương trình (`dotnet run` hoặc nhấn **F5** trong Visual Studio) và bạn sẽ thấy thông báo console xác nhận các tệp đã được lưu trên đĩa. + +![Ví dụ đầu ra của trình tạo mã vạch hiển thị DataBar với aspect ratio 15](placeholder/path/to/image.png){: .align-center alt="Ví dụ đầu ra của trình tạo mã vạch hiển thị DataBar với aspect ratio 15"} + +## Kết luận + +Chúng ta vừa hoàn thành một **barcode generator example** minh họa **how to set dimensions**, chọn đúng **barcode encode types**, và cuối cùng **create barcode image c#** các tệp bạn có thể nhúng bất kỳ đâu. Mã rất ngắn, khái niệm rõ ràng, và bây giờ bạn đã có nền tảng vững chắc để mở rộng giải pháp—có thể thêm chú thích văn bản, xoay ảnh, hoặc chuyển sang ký hiệu khác. + +### Bước tiếp theo là gì? + +- Thử nghiệm với **các X‑dimension** khác nhau để xem độ chịu lỗi của máy quét thay đổi như thế nào. +- Thử các **EncodeTypes** khác như `Code128` hoặc `QR` để mở rộng công cụ của bạn. +- Tự động tạo hàng loạt: lặp qua một CSV chứa các ID sản phẩm và tạo PNG cho mỗi mục. + +Nếu gặp khó khăn, hãy để lại bình luận bên dưới hoặc kiểm tra tài liệu Aspose.BarCode—nó chứa rất nhiều ví dụ bổ sung cho những gì chúng ta đã đề cập. + +Chúc lập trình vui vẻ, và hy vọng mã vạch của bạn luôn quét được ngay lần đầu! + +## 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ẽ, 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 hoạt động đầy đủ với các giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [Create barcode image C# – GS1 DataMatrix Example](/barcode/english/net/gs1-barcode-encoding/gs1-datamatrix-example/) +- [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/vietnamese/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md b/barcode/vietnamese/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md new file mode 100644 index 000000000..647e5e7a5 --- /dev/null +++ b/barcode/vietnamese/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-07-18 +description: Tạo mã vạch Planet nhanh chóng với C#. Tìm hiểu cách tạo các thanh đầy + và trống, thiết lập kích thước X, và lưu ảnh PNG – tất cả trong một hướng dẫn. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create planet barcode +- Planet barcode generator +- BarcodeGenerator parameters +- XDimension pixels +- filled bars vs empty bars +language: vi +lastmod: 2026-07-18 +og_description: Tạo mã vạch Planet ngay lập tức. Hướng dẫn này chỉ cho bạn cách thiết + lập kích thước X, chuyển đổi giữa các thanh đầy và trống, và xuất tệp PNG bằng Aspose.BarCode. +og_image_alt: Screenshot of a generated Planet barcode saved as PNG +og_title: Tạo Mã Vạch Hành Tinh bằng C# – Hướng Dẫn Lập Trình Toàn Diện +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + headline: Create Planet Barcode in C# – Full Step‑by‑Step Guide + type: TechArticle +- description: Create Planet barcode quickly with C#. Learn how to generate filled + and empty bars, set X‑dimension, and save PNG images – all in one tutorial. + name: Create Planet Barcode in C# – Full Step‑by‑Step Guide + steps: + - name: “Can I change the image format?” + text: Absolutely. The `Save` method accepts `BarCodeImageFormat.Jpeg`, `Bmp`, + `Gif`, etc. Just replace `BarCodeImageFormat.Png` with your desired format. + - name: “What if I need a different barcode height?” + text: 'Use `planetBarcode.Parameters.Barcode.BarHeight` (in points) to increase + or decrease the vertical size. For example:' + - name: “Is there a way to add a human‑readable caption?” + text: 'Yes. Set the `CodeText` property on `planetBarcode.Parameters.Caption`:' + - name: “Do I need to dispose the generator?” + text: 'The `BarcodeGenerator` implements `IDisposable`. Wrap it in a `using` block + if you’re creating many barcodes in a loop:' + - name: “What about error handling?” + text: 'Enclose the `Save` calls in a `try…catch` block to capture `IOException` + (disk issues) or `ArgumentException` (invalid parameters). Example:' + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Tạo Mã Vạch Hành Tinh trong C# – Hướng Dẫn Chi Tiết Từng Bước +url: /vi/python-java/general/create-planet-barcode-in-c-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo Planet Barcode trong C# – Hướng Dẫn Chi Tiết Từng Bước + +Bạn đã bao giờ cần **tạo planet barcode** nhưng không chắc thuộc tính nào cần điều chỉnh? Bạn không đơn độc. Nhiều nhà phát triển gặp khó khăn khi các thanh đã được điền mặc định không đáp ứng yêu cầu của tiêu chuẩn, hoặc khi độ rộng của thanh phải khớp với DPI của máy in. + +Trong hướng dẫn này, bạn sẽ học cách **tạo planet barcode** bằng thư viện Aspose.BarCode, cách kiểm soát **XDimension pixels**, và cách chuyển đổi giữa **filled bars** và **empty bars** mà không cần viết lại bất kỳ mã nào. Khi hoàn thành, bạn sẽ có hai tệp PNG — một với các thanh đặc và một với các thanh rỗng — sẵn sàng cho bất kỳ hệ thống bưu chính nào yêu cầu ký hiệu Planet. + +## Yêu cầu trước + +- .NET 6.0 hoặc cao hơn (mã cũng hoạt động trên .NET Framework 4.7 +) +- Gói NuGet Aspose.BarCode for .NET (`Install-Package Aspose.BarCode`) +- Kiến thức cơ bản về C# (bạn sẽ thấy lý do chúng ta dùng câu lệnh `using` sau này) +- Một thư mục có quyền ghi trên đĩa để lưu các tệp PNG + +Nếu đã có những thứ trên, chúng ta có thể bắt đầu triển khai ngay. + +## Bước 1 – Thiết lập dự án và thêm thư viện + +Đầu tiên, tạo một ứng dụng console mới (hoặc bất kỳ dự án C# nào) và tham chiếu thư viện **Planet barcode generator**. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // The rest of the code lives here + } + } +} +``` + +> **Mẹo chuyên nghiệp:** Trong Visual Studio, nhấp chuột phải vào dự án → *Manage NuGet Packages* → tìm **Aspose.BarCode** và nhấn *Install*. Điều này sẽ cung cấp cho bạn `BarcodeGenerator` và tất cả các **BarcodeGenerator parameters** cần thiết. + +## Bước 2 – Khởi tạo Planet Barcode Generator + +Bây giờ chúng ta thực sự **tạo planet barcode** bằng cách khởi tạo một thể hiện của generator và cung cấp dữ liệu cần mã hoá (`"123456"` trong ví dụ này). Enum `EncodeTypes.Planet` cho thư viện biết sẽ sử dụng ký hiệu nào. + +```csharp +// Step 2: Initialise the generator with Planet symbology and data +BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +> **Tại sao điều này quan trọng:** Cờ `EncodeTypes.Planet` tự động áp dụng checksum và quy tắc bố trí đúng cho mã bưu chính Planet, vì vậy bạn không cần tính toán chúng thủ công. + +## Bước 3 – Cấu hình X‑Dimension (Độ rộng thanh) + +Hầu hết các máy in yêu cầu mỗi thanh có một số pixel cố định. Ở đây chúng ta đặt **XDimension pixels** thành `4`, một giá trị phổ biến cho máy in nhiệt 203 dpi. + +```csharp +// Step 3: Set the width of each bar (X‑dimension) to 4 pixels +planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; +``` + +> **Trường hợp đặc biệt:** Nếu bạn đang hướng tới máy in 300 dpi, có thể cần `3` hoặc `5` pixel thay vì `4`. Điều chỉnh giá trị này dựa trên tài liệu của thiết bị. + +## Bước 4 – Lưu phiên bản Filled‑Bar + +Mặc định, generator tạo ra **filled bars** (hình chữ nhật đen đặc). Hãy ghi chúng ra đĩa: + +```csharp +// Step 4: Save the barcode with default (filled) bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetFilledBars.png", BarCodeImageFormat.Png); +``` + +Thay `YOUR_DIRECTORY` bằng đường dẫn tuyệt đối hoặc tương đối mà ứng dụng của bạn có thể ghi vào. Sau khi dòng này chạy, bạn sẽ thấy một tệp PNG trông giống như mã Planet truyền thống — hoàn hảo để kiểm tra với máy quét bưu chính. + +## Bước 5 – Chuyển sang Empty Bars + +Đôi khi các dịch vụ bưu chính yêu cầu kiểu “empty bars”, nơi các thanh được khắc trên nền trắng thay vì tô đen. Thư viện cung cấp một công tắc đơn giản: + +```csharp +// Step 5: Re‑configure the generator to produce empty bars +planetBarcode.Parameters.Barcode.FilledBars = false; +``` + +Đặt `FilledBars` thành `false` sẽ khiến renderer đảo ngược logic tô màu thanh. Không cần tạo một `BarcodeGenerator` mới; chúng ta chỉ cần điều chỉnh **BarcodeGenerator parameters** hiện có. + +## Bước 6 – Lưu phiên bản Empty‑Bar + +Cuối cùng, xuất hình ảnh thứ hai: + +```csharp +// Step 6: Save the barcode with empty bars +planetBarcode.Save("YOUR_DIRECTORY/PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); +``` + +Bây giờ bạn có hai tệp PNG riêng biệt, mỗi tệp đáp ứng một yêu cầu hiển thị khác nhau. + +## Ví dụ Hoạt động Đầy đủ + +Kết hợp tất cả các phần lại, đây là chương trình hoàn chỉnh, sẵn sàng sao chép‑dán: + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace PlanetBarcodeDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise the Planet barcode generator with data + BarcodeGenerator planetBarcode = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + + // Configure bar width (X‑dimension) – 4 pixels works for most 203 dpi printers + planetBarcode.Parameters.Barcode.XDimension.Pixels = 4; + + // Save the default filled‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetFilledBars.png", BarCodeImageFormat.Png); + + // Switch to empty‑bars style + planetBarcode.Parameters.Barcode.FilledBars = false; + + // Save the empty‑bars version + planetBarcode.Save(@"C:\Barcodes\PostalPlanetEmptyBars.png", BarCodeImageFormat.Png); + + Console.WriteLine("Both Planet barcode images have been generated successfully."); + } + } +} +``` + +**Kết quả mong đợi** (trên console): + +``` +Both Planet barcode images have been generated successfully. +``` + +Và trong `C:\Barcodes\` bạn sẽ thấy: + +- `PostalPlanetFilledBars.png` – các thanh đen đặc +- `PostalPlanetEmptyBars.png` – các thanh trắng với viền đen + +Mở chúng bằng bất kỳ trình xem ảnh nào; cả hai đều phải tuân thủ đặc tả Planet. + +## Câu hỏi Thường gặp & Mẹo + +### “Có thể thay đổi định dạng ảnh không?” + +Chắc chắn. Phương thức `Save` chấp nhận `BarCodeImageFormat.Jpeg`, `Bmp`, `Gif`, v.v. Chỉ cần thay `BarCodeImageFormat.Png` bằng định dạng bạn muốn. + +### “Nếu tôi cần chiều cao mã vạch khác?” + +Sử dụng `planetBarcode.Parameters.Barcode.BarHeight` (đơn vị point) để tăng hoặc giảm kích thước dọc. Ví dụ: + +```csharp +planetBarcode.Parameters.Barcode.BarHeight = 30; // 30 points tall +``` + +### “Có cách thêm chú thích dạng văn bản đọc được không?” + +Có. Đặt thuộc tính `CodeText` trên `planetBarcode.Parameters.Caption`: + +```csharp +planetBarcode.Parameters.Caption.Visible = true; +planetBarcode.Parameters.Caption.TopMargin = 5; // space between barcode and text +planetBarcode.Parameters.Caption.Text = "123456"; +``` + +### “Có cần giải phóng generator không?” + +`BarcodeGenerator` triển khai `IDisposable`. Bao nó trong khối `using` nếu bạn tạo nhiều mã vạch trong một vòng lặp: + +```csharp +using (BarcodeGenerator gen = new BarcodeGenerator(...)) +{ + // configure and save +} +``` + +### “Còn về xử lý lỗi thì sao?” + +Bao các lời gọi `Save` trong khối `try…catch` để bắt `IOException` (vấn đề đĩa) hoặc `ArgumentException` (tham số không hợp lệ). Ví dụ: + +```csharp +try +{ + planetBarcode.Save(path, BarCodeImageFormat.Png); +} +catch (Exception ex) +{ + Console.Error.WriteLine($"Failed to save barcode: {ex.Message}"); +} +``` + +## Tóm tắt + +Chúng ta đã bao phủ mọi thứ bạn cần để **tạo planet barcode** trong C#: + +1. Khởi tạo **Planet barcode generator** với dữ liệu của bạn. +2. Điều chỉnh **XDimension pixels** cho phù hợp với thông số máy in. +3. Lưu một PNG **filled bars**. +4. Đổi `FilledBars` để tạo **empty bars**. +5. Lưu PNG thứ hai. + +Từ đây, bạn có thể khám phá thêm **BarcodeGenerator parameters**, thử nghiệm các ký hiệu khác (`EncodeTypes.Postnet`, `EncodeTypes.Code128`, v.v.), hoặc tích hợp các hình ảnh vào quy trình gửi thư. + +--- + +**Sẵn sàng cho bước tiếp theo?** Hãy thử thêm một QR code vào cùng tài liệu, hoặc tạo một loạt Planet barcode từ danh sách CSV bằng vòng lặp `foreach`. API Aspose.BarCode đủ linh hoạt để xử lý các thao tác bulk, màu tùy chỉnh, và thậm chí xuất ra SVG dạng vector. + +Nếu gặp khó khăn, hãy để lại bình luận bên dưới hoặc tham khảo tài liệu chính thức của Aspose.BarCode để tìm hiểu sâu hơn về các tính năng nâng cao. 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ẽ, 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 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. + +- [Create Barcode with Aspose - Set X & Y Dimensions in Java](/barcode/english/java/barcode-configuration/managing-x-y-dimension-barcode/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /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/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md b/barcode/vietnamese/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md new file mode 100644 index 000000000..6b95a7936 --- /dev/null +++ b/barcode/vietnamese/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/_index.md @@ -0,0 +1,290 @@ +--- +category: general +date: 2026-07-18 +description: Tạo mã vạch RM4SCC trong C# nhanh chóng; học cách đặt chiều cao mã vạch + và cũng tạo mã vạch Planet với kích thước tùy chỉnh. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create rm4scc barcode +- generate planet barcode +- how to set barcode height +language: vi +lastmod: 2026-07-18 +og_description: Tạo mã vạch RM4SCC trong C# và khám phá cách đặt chiều cao mã vạch. + Cũng xem cách tạo mã vạch Planet bằng cùng thư viện. +og_image_alt: Screenshot of a generated RM4SCC barcode with custom height in C# +og_title: Tạo mã vạch RM4SCC trong C# – Đặt chiều cao tùy chỉnh nhanh +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Create RM4SCC barcode in C# quickly; learn how to set barcode height + and also generate Planet barcode with custom dimensions. + headline: Create RM4SCC Barcode in C# – Full Guide to Set Height + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Tạo mã vạch RM4SCC trong C# – Hướng dẫn đầy đủ để thiết lập chiều cao +url: /vi/python-java/general/create-rm4scc-barcode-in-c-full-guide-to-set-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo Mã vạch RM4SCC trong C# – Hướng dẫn đầy đủ để Đặt chiều cao + +Bạn đã bao giờ cần **create RM4SCC barcode** trong một ứng dụng .NET nhưng không chắc cách kiểm soát kích thước của nó? Bạn không phải là người duy nhất. Dù bạn đang xây dựng hệ thống gửi thư hay bảng điều khiển logistics, việc có chiều cao mã vạch đúng có thể là sự khác biệt giữa một lần quét thành công và một lần quét thất bại. + +Trong hướng dẫn này, chúng ta sẽ đi qua toàn bộ quy trình: từ cài đặt thư viện, đến **generate Planet barcode** như một ví dụ song song, và cuối cùng là **how to set barcode height** cho cả hai loại mã vạch. Khi kết thúc, bạn sẽ có một ứng dụng console sẵn sàng chạy và xuất các tệp PNG với kích thước chính xác mà bạn cần. + +--- + +## What You’ll Need + +- **.NET 6 SDK** (hoặc bất kỳ phiên bản .NET gần đây nào) – mã hoạt động trên .NET Framework cũng được, nhưng .NET 6 là lựa chọn tối ưu. +- **Aspose.BarCode for .NET** gói NuGet – đây là thư viện cung cấp lớp `BarcodeGenerator`. +- Một chút kiến thức về C# – chúng tôi sẽ giữ cú pháp thân thiện với người mới bắt đầu. +- Một IDE hoặc trình soạn thảo văn bản (Visual Studio, VS Code, Rider—chọn tùy thích). + +> **Pro tip:** Nếu bạn đang sử dụng pipeline CI/CD, hãy thêm tham chiếu NuGet vào file `.csproj` của bạn để quá trình build không bao giờ quên phụ thuộc. + +--- + +## Step 1: Set Up the Project + +Open a terminal and create a new console project: + +```bash +dotnet new console -n BarcodeDemo +cd BarcodeDemo +dotnet add package Aspose.BarCode +``` + +Xong—dự án của bạn hiện đã tham chiếu thư viện cung cấp mọi chức năng phía sau. + +### Add the Using Directives + +Thêm các chỉ thị Using + +Open `Program.cs` và paste the following at the top: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; // optional, for clarity +``` + +Các không gian tên này cho phép chúng ta truy cập `BarcodeGenerator` và enum định dạng ảnh mà chúng ta sẽ sử dụng sau. + +--- + +## Step 2: Define a Helper Method for Saving Images + +Định nghĩa phương thức trợ giúp để lưu ảnh + +Để tránh lặp lại cùng một logic lưu, chúng ta sẽ gói nó trong một phương thức nhỏ. Điều này cũng minh họa **how to set barcode height** sau này. + +```csharp +static void SaveBarcode(BarcodeGenerator generator, string fileName) +{ + // Ensure the output directory exists + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + // Save as PNG – you can switch to JPEG, BMP, etc. + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); +} +``` + +> **Why this matters:** Việc tập trung logic lưu có nghĩa là bạn chỉ cần thay đổi định dạng hoặc thư mục ở một nơi duy nhất nếu yêu cầu thay đổi. + +--- + +## Step 3: Generate a Planet Barcode (the “generate planet barcode” part) + +Tạo mã vạch Planet (phần “generate planet barcode”) + +Trước khi chúng ta đi sâu vào chi tiết RM4SCC, hãy tạo một **Planet barcode**. Điều này cung cấp cho bạn một kiểm tra nhanh về việc thư viện đang hoạt động. + +```csharp +// Create a Planet barcode with default height +var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + // X‑dimension controls the narrow bar width; 4 px is a good default + XDimension = { Pixels = 4 } +}; +SaveBarcode(planetDefault, "output/PlanetDefault.png"); + +// Create a Planet barcode with an explicit 100‑pixel height +var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(planetFixed, "output/PlanetHeight100.png"); +``` + +**Expected output:** Hai tệp PNG xuất hiện trong thư mục `output`—một với chiều cao tự động tính của thư viện, và một khác có chiều cao chính xác 100 px. + +--- + +## Step 4: Create RM4SCC Barcode – Primary Goal + +Tạo mã vạch RM4SCC – Mục tiêu chính + +Bây giờ là phần quan trọng nhất: **create RM4SCC barcode**. RM4SCC là Royal Mail 4‑State Code, được sử dụng rộng rãi trong hệ thống bưu chính Vương quốc Anh. + +```csharp +// RM4SCC with default (auto) height +var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 } +}; +SaveBarcode(rm4sccDefault, "output/RM4SCCDefault.png"); + +// RM4SCC with an explicit 100‑pixel height +var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") +{ + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // <-- how to set barcode height +}; +SaveBarcode(rm4sccFixed, "output/RM4SCCHeight100.png"); +``` + +**What you’ll see:** +- `RM4SCCDefault.png` – thư viện quyết định chiều cao phù hợp dựa trên X‑dimension. +- `RM4SCCHeight100.png` – một mã vạch sắc nét cao 100 pixel, sẵn sàng in lên phong bì. + +> **Why set the height?** Một số máy in nhãn yêu cầu chiều cao thanh tối thiểu để quét đáng tin cậy. Bằng cách cố định chiều cao, bạn đảm bảo tuân thủ trên mọi thiết bị. + +--- + +## Step 5: Understanding the Height Settings (Answering “how to set barcode height”) + +Hiểu về cài đặt chiều cao (Trả lời “how to set barcode height”) + +Both the Planet and RM4SCC examples use the same property: + +```csharp +generator.BarHeight.Pixels = ; +``` + +- **`BarHeight`** là một đối tượng `BarHeight` nhóm một số đơn vị đo (pixels, millimetres, inches). +- **`.Pixels`** là đơn vị đơn giản nhất cho đầu ra hướng màn hình, nhưng bạn cũng có thể sử dụng `.Millimeters` hoặc `.Inches` nếu bạn đang hướng tới phương tiện in. + +### Edge Cases & Tips + +Trường hợp đặc biệt & Mẹo + +| Tình huống | Cách tiếp cận đề xuất | +|-----------|----------------------| +| **X‑dimension rất nhỏ (ví dụ: 1 px)** | Tăng `BarHeight` để mã vạch vẫn đọc được. | +| **In trên máy in nhãn độ phân giải cao** | Sử dụng `.Millimeters` để kích thước không phụ thuộc vào thiết bị. | +| **Kết hợp nhiều loại mã vạch trong một hình ảnh** | Đặt `BarHeight` *sau* `XDimension` cho mỗi generator để tránh kế thừa không mong muốn. | +| **Dữ liệu động (ví dụ: mã do người dùng nhập)** | Gói việc tạo generator trong một phương thức nhận các tham số `code` và `height`. | + +--- + +## Step 6: Full Working Example + +Ví dụ Hoạt động đầy đủ + +Below is a single, self‑contained program you can copy‑paste into `Program.cs`. It includes everything from project setup to saving the images. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +class Program +{ + static void Main() + { + string outputDir = "output/"; + + // Helper ensures folder exists and logs the save + void Save(BarcodeGenerator gen, string file) => SaveBarcode(gen, file); + + // ---------- Planet barcode ---------- + var planetDefault = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(planetDefault, $"{outputDir}PlanetDefault.png"); + + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(planetFixed, $"{outputDir}PlanetHeight100.png"); + + // ---------- RM4SCC barcode ---------- + var rm4sccDefault = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 } + }; + Save(rm4sccDefault, $"{outputDir}RM4SCCDefault.png"); + + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456") + { + XDimension = { Pixels = 4 }, + BarHeight = { Pixels = 100 } // how to set barcode height + }; + Save(rm4sccFixed, $"{outputDir}RM4SCCHeight100.png"); + + Console.WriteLine("All barcodes generated!"); + } + + static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + var dir = System.IO.Path.GetDirectoryName(fileName); + if (!System.IO.Directory.Exists(dir)) + System.IO.Directory.CreateDirectory(dir); + + generator.Save(fileName, BarCodeImageFormat.Png); + Console.WriteLine($"Saved: {fileName}"); + } +} +``` + +Run it with: + +```bash +dotnet run +``` + +Bạn sẽ thấy đầu ra console xác nhận mỗi tệp đã được lưu, và thư mục `output` sẽ chứa bốn PNG khớp với các tên đã nêu ở trên. + +--- + +## Conclusion + +Kết luận + +Bạn giờ đã biết **how to create RM4SCC barcode** trong C# và kiểm soát kích thước của nó chỉ với một vài lệnh gán thuộc tính. Chúng tôi cũng đã đề cập **generate planet barcode** như một kiểm tra nhanh, và khám phá các chi tiết của **how to set barcode height** cho các kịch bản in khác nhau. + +Bước tiếp theo? Hãy thử thay thế enum `EncodeTypes` bằng các ký hiệu khác (Code128, QR, DataMatrix) và thử nghiệm `BarHeight` bằng millimetres cho máy in độ phân giải cao. Nếu bạn cần nhúng mã vạch vào PDF, kết hợp Aspose.BarCode với Aspose.PDF—một cặp mạnh mẽ khác. + +Có câu hỏi hoặc muốn chia sẻ các điều chỉnh của bạn? Để lại bình luận bên dưới, và chúc bạn lập trình vui vẻ! + +## What Should You Learn Next? + +Bạn nên học gì tiếp theo? + +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. + +- [Cách tạo mã vạch Aztec với tỷ lệ khung tùy chỉnh bằng Aspose.BarCode cho .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Cách tạo vùng yên tĩnh cho mã vạch ITF-14 bằng Aspose.BarCode cho .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) +- [Cách tạo vùng yên tĩnh cho mã vạch Code 16K bằng Aspose.BarCode cho .NET](/barcode/english/net/code-16k-encoding/code-16k-quiet-zone-settings/) + +{{< /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/python-java/general/net-barcode-generator-change-barcode-height/_index.md b/barcode/vietnamese/python-java/general/net-barcode-generator-change-barcode-height/_index.md new file mode 100644 index 000000000..4a060ed47 --- /dev/null +++ b/barcode/vietnamese/python-java/general/net-barcode-generator-change-barcode-height/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-07-18 +description: Tìm hiểu cách tạo hình ảnh mã vạch bằng trình tạo mã vạch .net và dễ + dàng thay đổi chiều cao mã vạch cho các ký hiệu GS1‑Databar Omni‑Directional. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- .net barcode generator +- how to generate barcode +- change barcode height +- GS1‑Databar Omni‑Directional +- barcode image export +language: vi +lastmod: 2026-07-18 +og_description: Trình tạo mã vạch .net cho phép bạn nhanh chóng tạo hình ảnh mã vạch. + Hướng dẫn này chỉ cách tạo mã vạch, điều chỉnh chiều cao thanh và lưu file PNG. +og_image_alt: Screenshot of a .net barcode generator output showing different bar + heights +og_title: Thay đổi chiều cao mã vạch bằng trình tạo mã vạch .net +schemas: +- author: Aspose + dateModified: '2026-07-18' + description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + headline: .net barcode generator – change barcode height + type: TechArticle +- description: Learn how to generate barcode images with a .net barcode generator + and easily change barcode height for GS1‑Databar Omni‑Directional symbols. + name: .net barcode generator – change barcode height + steps: + - name: Why each line matters + text: '| Line | Reason | |------|--------| | `BarcodeGenerator generator = new + BarcodeGenerator(...);` | Instantiates the **.net barcode generator** with the + desired symbology and data payload. The `EncodeTypes.DatabarOmniDirectional` + enum tells the library to use the GS1‑Databar Omni‑Directional format. |' + - name: Adjusting the X‑dimension for larger prints + text: '```csharp generator.Parameters.Barcode.XDimension.Pixels = 4; // Double + the narrow bar width ``` Increasing the X‑dimension makes the whole barcode + larger without altering the encoded data. This is handy when you print on large + labels.' + - name: Switching output formats + text: '```csharp generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); + ``` SVG scales infinitely, which is perfect for web‑based scanners that need + crisp vectors.' + - name: Adding human‑readable text + text: '```csharp generator.Parameters.Barcode.CodeTextVisible = true; generator.Parameters.Barcode.CodeTextAlignment + = CodeLocation.Below; ``` Enabling `CodeTextVisible` appends the raw data under + the barcode, useful for verification during testing.' + type: HowTo +tags: +- barcode +- .net +- image export +title: .NET barcode generator – thay đổi chiều cao mã vạch +url: /vi/python-java/general/net-barcode-generator-change-barcode-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# .net barcode generator – thay đổi chiều cao mã vạch + +Bạn đã bao giờ tự hỏi **cách tạo mã vạch** mà không phải dùng hàng tá công cụ bên thứ ba chưa? Trong thế giới .NET có một cách khá gọn gàng để làm điều này, và thành phần then chốt là **.net barcode generator**. Chỉ với vài dòng C# bạn có thể tạo ra một ký hiệu GS1‑Databar Omni‑Directional, điều chỉnh chiều cao các thanh, và lưu kết quả thành file PNG. + +Nếu bạn đang xây dựng một hệ thống quản lý tồn kho, máy in nhãn vận chuyển, hoặc bất kỳ ứng dụng nào cần mã có thể quét, hướng dẫn này sẽ đưa bạn từ không biết gì đến một mã vạch hoạt động trong vài phút. Chúng tôi sẽ đi qua toàn bộ mã, giải thích tại sao mỗi thiết lập quan trọng, và chỉ cho bạn cách **thay đổi chiều cao mã vạch** mà không vi phạm tiêu chuẩn. + +## Những gì bạn cần + +- .NET 6.0 hoặc mới hơn (API hoạt động tương tự trên .NET Framework 4.7+) +- Tham chiếu tới thư viện mã vạch (ví dụ, Aspose.BarCode for .NET – các lớp này được nhiều bộ công cụ thương mại sử dụng) +- Môi trường phát triển (Visual Studio, Rider, hoặc VS Code với phần mở rộng C#) +- Thư mục có quyền ghi – hướng dẫn sẽ lưu các file PNG vào đó + +Chỉ vậy thôi. Không cần gói NuGet bổ sung nào ngoài thư viện mã vạch. + +## Sử dụng .net barcode generator để thay đổi chiều cao mã vạch + +Dưới đây là một **chương trình console đầy đủ, có thể chạy**. Dán nó vào một dự án C# mới, điều chỉnh thư mục đầu ra, và nhấn F5. + +```csharp +using System; +using Aspose.BarCode.Generation; // Namespace for the barcode generator +using Aspose.BarCode; // For BarCodeImageFormat enum + +namespace BarcodeHeightDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Create a barcode generator for a GS1‑Databar Omni‑Directional symbol. + // The string "(01)12345678901231" follows the GS1 Application Identifier syntax. + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // 2️⃣ Define common visual parameters. + // X‑dimension controls the width of the narrowest bar; 2 pixels works well for screen display. + generator.Parameters.Barcode.XDimension.Pixels = 2; + + // 3️⃣ Set the initial bar height to 30 pixels. + generator.Parameters.Barcode.BarHeight.Pixels = 30; + + // 4️⃣ Save the first image – a compact barcode. + string outFolder = @"YOUR_DIRECTORY"; // ← replace with a real path + generator.Save($"{outFolder}/DatabarBarHeight30Pixels.png", BarCodeImageFormat.Png); + + // 5️⃣ Increase the bar height to 60 pixels for a larger, more readable code. + generator.Parameters.Barcode.BarHeight.Pixels = 60; + + // 6️⃣ Save the second image – a taller barcode. + generator.Save($"{outFolder}/DatabarBarHeight60Pixels.png", BarCodeImageFormat.Png); + + Console.WriteLine("Two barcode images have been generated successfully."); + } + } +} +``` + +### Tại sao mỗi dòng lại quan trọng + +| Line | Reason | +|------|--------| +| `BarcodeGenerator generator = new BarcodeGenerator(...);` | Khởi tạo **.net barcode generator** với ký hiệu và dữ liệu mong muốn. Enum `EncodeTypes.DatabarOmniDirectional` cho thư viện biết sử dụng định dạng GS1‑Databar Omni‑Directional. | +| `XDimension.Pixels = 2;` | X‑dimension là độ rộng của thanh mỏng nhất. Đặt nó thành *2 pixel* tạo hình ảnh sắc nét trên hầu hết màn hình đồng thời giữ kích thước file nhỏ. | +| `BarHeight.Pixels = 30;` | Đây là bước **thay đổi chiều cao mã vạch** xác định độ cao của mỗi thanh. Chiều cao 30 pixel là mặc định tốt cho nhãn nhỏ. | +| `generator.Save(...);` | Lưu mã vạch vào file PNG. PNG không mất dữ liệu, có nghĩa là máy quét sẽ thấy đúng mẫu bạn tạo. | +| `BarHeight.Pixels = 60;` | Ở đây chúng ta **thay đổi chiều cao mã vạch** một lần nữa—lần này thành 60 pixel. Thư viện sẽ tự động vẽ lại ký hiệu với kích thước mới khi bạn gọi `Save` lần thứ hai. | +| `Console.WriteLine(...);` | Cung cấp phản hồi nhanh rằng quá trình đã hoàn thành mà không ném ngoại lệ. | + +> **Mẹo chuyên nghiệp:** Nếu bạn cần đầu ra độ phân giải cao hơn cho việc in, chuyển `BarCodeImageFormat.Png` sang `BarCodeImageFormat.Tiff` và tăng thuộc tính `Resolution` (ví dụ, `generator.Parameters.ImageResolution = 300;`). Chiều cao thanh vẫn được giữ, chỉ được vẽ ở DPI mịn hơn. + +## Cách tạo ảnh mã vạch với các thiết lập khác nhau + +Đoạn mã trên bao quát các kiến thức cơ bản, nhưng trong thực tế thường cần các điều chỉnh bổ sung: + +### Điều chỉnh X‑dimension cho bản in lớn hơn +```csharp +generator.Parameters.Barcode.XDimension.Pixels = 4; // Double the narrow bar width +``` +Tăng X‑dimension làm toàn bộ mã vạch lớn hơn mà không thay đổi dữ liệu đã mã hoá. Điều này hữu ích khi bạn in trên nhãn lớn. + +### Chuyển đổi định dạng đầu ra +```csharp +generator.Save($"{outFolder}/Databar.svg", BarCodeImageFormat.Svg); +``` +SVG có thể phóng to vô hạn, rất phù hợp cho các máy quét dựa trên web cần vector sắc nét. + +### Thêm văn bản có thể đọc được bởi con người +```csharp +generator.Parameters.Barcode.CodeTextVisible = true; +generator.Parameters.Barcode.CodeTextAlignment = CodeLocation.Below; +``` +Bật `CodeTextVisible` sẽ thêm dữ liệu thô dưới mã vạch, hữu ích cho việc kiểm tra trong quá trình thử nghiệm. + +## Những lỗi thường gặp khi bạn **thay đổi chiều cao mã vạch** + +1. **Chiều cao quá nhỏ** – Một số máy quét yêu cầu chiều cao thanh tối thiểu (thường là 10 mm trong đơn vị vật lý). Nếu bạn đặt `BarHeight.Pixels` quá thấp, ảnh tạo ra có thể không đọc được trên máy quét thực tế. Luôn kiểm tra với phần cứng mục tiêu. +2. **X‑dimension và chiều cao không phù hợp** – Chiều cao thanh quá lớn kết hợp với X‑dimension quá nhỏ có thể trông bị kéo dài và gây lỗi giải mã. Hãy nhắm tới tỉ lệ cân bằng (khoảng 3:1 đến 5:1) trừ khi tiêu chuẩn quy định khác. +3. **Quên đặt lại tham số** – Trình tạo giữ trạng thái giữa các lần lưu. Nếu bạn thay đổi `BarHeight` cho một ảnh và sau đó dùng lại cùng một instance cho mã vạch khác, chiều cao trước sẽ vẫn còn. Hãy đặt lại thuộc tính hoặc khởi tạo một `BarcodeGenerator` mới cho mỗi mã vạch riêng biệt. + +## Ví dụ toàn diện từ đầu đến cuối (kèm cài đặt NuGet) + +Nếu bạn bắt đầu từ đầu, hãy làm theo các bước sau để dự án chạy được: + +```bash +dotnet new console -n BarcodeHeightDemo +cd BarcodeHeightDemo +dotnet add package Aspose.BarCode +``` + +Thay thế `Program.cs` được tạo tự động bằng khối mã đã hiển thị ở trên, **nhớ thay `YOUR_DIRECTORY`** bằng một đường dẫn như `Path.Combine(Environment.CurrentDirectory, "output")`. Sau đó: + +```bash +dotnet run +``` + +Bạn sẽ thấy hai file PNG trong thư mục `output`: + +- `DatabarBarHeight30Pixels.png` – mã vạch cao 30 pixel gọn gàng. +- `DatabarBarHeight60Pixels.png` – phiên bản cao 60 pixel hơn. + +Cả hai ảnh sẽ trông tương tự, nhưng ảnh thứ hai có các thanh dài hơn đáng kể, giúp các máy quét độ phân giải thấp dễ đọc hơn. + +![Ví dụ chiều cao mã vạch](/images/barcode-height.png){alt=".net barcode generator output hiển thị các chiều cao thanh khác nhau"} + +## Tóm tắt & các bước tiếp theo + +Chúng tôi đã trình bày cách **tạo ảnh mã vạch** bằng **.net barcode generator**, tinh chỉnh thuộc tính **thay đổi chiều cao mã vạch**, và lưu kết quả ở định dạng PNG. Những điểm chính cần nhớ là: + +- Khởi tạo trình tạo với `EncodeTypes` phù hợp. +- Kiểm soát kích thước hiển thị bằng `XDimension` và `BarHeight`. +- Gọi `Save` sau mỗi lần thay đổi để lưu ảnh mới. +- Điều chỉnh độ phân giải, định dạng, + +## 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ẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh với giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Cách tạo mã vạch Aztec với tỷ lệ khung tùy chỉnh bằng Aspose.BarCode cho .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Cách tạo dotcode với văn bản mở rộng bằng Aspose.BarCode cho .NET](/barcode/english/net/dotcode-barcode-configuration/dotcode-extended-code-text-configuration/) +- [Cách tạo mã DataMatrix (ECC 200) bằng 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